]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
Merge bmake-20170510
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaDecl.cpp
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50
51 using namespace clang;
52 using namespace sema;
53
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62
63 namespace {
64
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74   }
75
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91
92 } // end anonymous namespace
93
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125
126   default:
127     break;
128   }
129
130   return false;
131 }
132
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197
198   return FoundTypeDecl;
199 }
200
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              IdentifierInfo **CorrectedII) {
256   // Determine where we will perform name lookup.
257   DeclContext *LookupCtx = nullptr;
258   if (ObjectTypePtr) {
259     QualType ObjectType = ObjectTypePtr.get();
260     if (ObjectType->isRecordType())
261       LookupCtx = computeDeclContext(ObjectType);
262   } else if (SS && SS->isNotEmpty()) {
263     LookupCtx = computeDeclContext(*SS, false);
264
265     if (!LookupCtx) {
266       if (isDependentScopeSpecifier(*SS)) {
267         // C++ [temp.res]p3:
268         //   A qualified-id that refers to a type and in which the
269         //   nested-name-specifier depends on a template-parameter (14.6.2)
270         //   shall be prefixed by the keyword typename to indicate that the
271         //   qualified-id denotes a type, forming an
272         //   elaborated-type-specifier (7.1.5.3).
273         //
274         // We therefore do not perform any name lookup if the result would
275         // refer to a member of an unknown specialization.
276         if (!isClassName && !IsCtorOrDtorName)
277           return nullptr;
278
279         // We know from the grammar that this name refers to a type,
280         // so build a dependent node to describe the type.
281         if (WantNontrivialTypeSourceInfo)
282           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
283
284         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
285         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
286                                        II, NameLoc);
287         return ParsedType::make(T);
288       }
289
290       return nullptr;
291     }
292
293     if (!LookupCtx->isDependentContext() &&
294         RequireCompleteDeclContext(*SS, LookupCtx))
295       return nullptr;
296   }
297
298   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
299   // lookup for class-names.
300   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
301                                       LookupOrdinaryName;
302   LookupResult Result(*this, &II, NameLoc, Kind);
303   if (LookupCtx) {
304     // Perform "qualified" name lookup into the declaration context we
305     // computed, which is either the type of the base of a member access
306     // expression or the declaration context associated with a prior
307     // nested-name-specifier.
308     LookupQualifiedName(Result, LookupCtx);
309
310     if (ObjectTypePtr && Result.empty()) {
311       // C++ [basic.lookup.classref]p3:
312       //   If the unqualified-id is ~type-name, the type-name is looked up
313       //   in the context of the entire postfix-expression. If the type T of
314       //   the object expression is of a class type C, the type-name is also
315       //   looked up in the scope of class C. At least one of the lookups shall
316       //   find a name that refers to (possibly cv-qualified) T.
317       LookupName(Result, S);
318     }
319   } else {
320     // Perform unqualified name lookup.
321     LookupName(Result, S);
322
323     // For unqualified lookup in a class template in MSVC mode, look into
324     // dependent base classes where the primary class template is known.
325     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
326       if (ParsedType TypeInBase =
327               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
328         return TypeInBase;
329     }
330   }
331
332   NamedDecl *IIDecl = nullptr;
333   switch (Result.getResultKind()) {
334   case LookupResult::NotFound:
335   case LookupResult::NotFoundInCurrentInstantiation:
336     if (CorrectedII) {
337       TypoCorrection Correction = CorrectTypo(
338           Result.getLookupNameInfo(), Kind, S, SS,
339           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
340           CTK_ErrorRecovery);
341       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
342       TemplateTy Template;
343       bool MemberOfUnknownSpecialization;
344       UnqualifiedId TemplateName;
345       TemplateName.setIdentifier(NewII, NameLoc);
346       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
347       CXXScopeSpec NewSS, *NewSSPtr = SS;
348       if (SS && NNS) {
349         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
350         NewSSPtr = &NewSS;
351       }
352       if (Correction && (NNS || NewII != &II) &&
353           // Ignore a correction to a template type as the to-be-corrected
354           // identifier is not a template (typo correction for template names
355           // is handled elsewhere).
356           !(getLangOpts().CPlusPlus && NewSSPtr &&
357             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
358                            Template, MemberOfUnknownSpecialization))) {
359         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
360                                     isClassName, HasTrailingDot, ObjectTypePtr,
361                                     IsCtorOrDtorName,
362                                     WantNontrivialTypeSourceInfo);
363         if (Ty) {
364           diagnoseTypo(Correction,
365                        PDiag(diag::err_unknown_type_or_class_name_suggest)
366                          << Result.getLookupName() << isClassName);
367           if (SS && NNS)
368             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
369           *CorrectedII = NewII;
370           return Ty;
371         }
372       }
373     }
374     // If typo correction failed or was not performed, fall through
375   case LookupResult::FoundOverloaded:
376   case LookupResult::FoundUnresolvedValue:
377     Result.suppressDiagnostics();
378     return nullptr;
379
380   case LookupResult::Ambiguous:
381     // Recover from type-hiding ambiguities by hiding the type.  We'll
382     // do the lookup again when looking for an object, and we can
383     // diagnose the error then.  If we don't do this, then the error
384     // about hiding the type will be immediately followed by an error
385     // that only makes sense if the identifier was treated like a type.
386     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
387       Result.suppressDiagnostics();
388       return nullptr;
389     }
390
391     // Look to see if we have a type anywhere in the list of results.
392     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
393          Res != ResEnd; ++Res) {
394       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
395         if (!IIDecl ||
396             (*Res)->getLocation().getRawEncoding() <
397               IIDecl->getLocation().getRawEncoding())
398           IIDecl = *Res;
399       }
400     }
401
402     if (!IIDecl) {
403       // None of the entities we found is a type, so there is no way
404       // to even assume that the result is a type. In this case, don't
405       // complain about the ambiguity. The parser will either try to
406       // perform this lookup again (e.g., as an object name), which
407       // will produce the ambiguity, or will complain that it expected
408       // a type name.
409       Result.suppressDiagnostics();
410       return nullptr;
411     }
412
413     // We found a type within the ambiguous lookup; diagnose the
414     // ambiguity and then return that type. This might be the right
415     // answer, or it might not be, but it suppresses any attempt to
416     // perform the name lookup again.
417     break;
418
419   case LookupResult::Found:
420     IIDecl = Result.getFoundDecl();
421     break;
422   }
423
424   assert(IIDecl && "Didn't find decl");
425
426   QualType T;
427   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
428     DiagnoseUseOfDecl(IIDecl, NameLoc);
429
430     T = Context.getTypeDeclType(TD);
431     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
432
433     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
434     // constructor or destructor name (in such a case, the scope specifier
435     // will be attached to the enclosing Expr or Decl node).
436     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
437       if (WantNontrivialTypeSourceInfo) {
438         // Construct a type with type-source information.
439         TypeLocBuilder Builder;
440         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
441
442         T = getElaboratedType(ETK_None, *SS, T);
443         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
444         ElabTL.setElaboratedKeywordLoc(SourceLocation());
445         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
446         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
447       } else {
448         T = getElaboratedType(ETK_None, *SS, T);
449       }
450     }
451   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
452     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
453     if (!HasTrailingDot)
454       T = Context.getObjCInterfaceType(IDecl);
455   }
456
457   if (T.isNull()) {
458     // If it's not plausibly a type, suppress diagnostics.
459     Result.suppressDiagnostics();
460     return nullptr;
461   }
462   return ParsedType::make(T);
463 }
464
465 // Builds a fake NNS for the given decl context.
466 static NestedNameSpecifier *
467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
468   for (;; DC = DC->getLookupParent()) {
469     DC = DC->getPrimaryContext();
470     auto *ND = dyn_cast<NamespaceDecl>(DC);
471     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
472       return NestedNameSpecifier::Create(Context, nullptr, ND);
473     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
474       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
475                                          RD->getTypeForDecl());
476     else if (isa<TranslationUnitDecl>(DC))
477       return NestedNameSpecifier::GlobalSpecifier(Context);
478   }
479   llvm_unreachable("something isn't in TU scope?");
480 }
481
482 /// Find the parent class with dependent bases of the innermost enclosing method
483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
484 /// up allowing unqualified dependent type names at class-level, which MSVC
485 /// correctly rejects.
486 static const CXXRecordDecl *
487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
488   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
489     DC = DC->getPrimaryContext();
490     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
491       if (MD->getParent()->hasAnyDependentBases())
492         return MD->getParent();
493   }
494   return nullptr;
495 }
496
497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
498                                           SourceLocation NameLoc,
499                                           bool IsTemplateTypeArg) {
500   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
501
502   NestedNameSpecifier *NNS = nullptr;
503   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
504     // If we weren't able to parse a default template argument, delay lookup
505     // until instantiation time by making a non-dependent DependentTypeName. We
506     // pretend we saw a NestedNameSpecifier referring to the current scope, and
507     // lookup is retried.
508     // FIXME: This hurts our diagnostic quality, since we get errors like "no
509     // type named 'Foo' in 'current_namespace'" when the user didn't write any
510     // name specifiers.
511     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
512     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
513   } else if (const CXXRecordDecl *RD =
514                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
515     // Build a DependentNameType that will perform lookup into RD at
516     // instantiation time.
517     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
518                                       RD->getTypeForDecl());
519
520     // Diagnose that this identifier was undeclared, and retry the lookup during
521     // template instantiation.
522     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
523                                                                       << RD;
524   } else {
525     // This is not a situation that we should recover from.
526     return ParsedType();
527   }
528
529   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
530
531   // Build type location information.  We synthesized the qualifier, so we have
532   // to build a fake NestedNameSpecifierLoc.
533   NestedNameSpecifierLocBuilder NNSLocBuilder;
534   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
535   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
536
537   TypeLocBuilder Builder;
538   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
539   DepTL.setNameLoc(NameLoc);
540   DepTL.setElaboratedKeywordLoc(SourceLocation());
541   DepTL.setQualifierLoc(QualifierLoc);
542   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
543 }
544
545 /// isTagName() - This method is called *for error recovery purposes only*
546 /// to determine if the specified name is a valid tag name ("struct foo").  If
547 /// so, this returns the TST for the tag corresponding to it (TST_enum,
548 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
549 /// cases in C where the user forgot to specify the tag.
550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
551   // Do a tag name lookup in this scope.
552   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
553   LookupName(R, S, false);
554   R.suppressDiagnostics();
555   if (R.getResultKind() == LookupResult::Found)
556     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
557       switch (TD->getTagKind()) {
558       case TTK_Struct: return DeclSpec::TST_struct;
559       case TTK_Interface: return DeclSpec::TST_interface;
560       case TTK_Union:  return DeclSpec::TST_union;
561       case TTK_Class:  return DeclSpec::TST_class;
562       case TTK_Enum:   return DeclSpec::TST_enum;
563       }
564     }
565
566   return DeclSpec::TST_unspecified;
567 }
568
569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
571 /// then downgrade the missing typename error to a warning.
572 /// This is needed for MSVC compatibility; Example:
573 /// @code
574 /// template<class T> class A {
575 /// public:
576 ///   typedef int TYPE;
577 /// };
578 /// template<class T> class B : public A<T> {
579 /// public:
580 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
581 /// };
582 /// @endcode
583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
584   if (CurContext->isRecord()) {
585     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
586       return true;
587
588     const Type *Ty = SS->getScopeRep()->getAsType();
589
590     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
591     for (const auto &Base : RD->bases())
592       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
593         return true;
594     return S->isFunctionPrototypeScope();
595   }
596   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
597 }
598
599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
600                                    SourceLocation IILoc,
601                                    Scope *S,
602                                    CXXScopeSpec *SS,
603                                    ParsedType &SuggestedType,
604                                    bool AllowClassTemplates) {
605   // We don't have anything to suggest (yet).
606   SuggestedType = nullptr;
607
608   // There may have been a typo in the name of the type. Look up typo
609   // results, in case we have something that we can suggest.
610   if (TypoCorrection Corrected =
611           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
612                       llvm::make_unique<TypeNameValidatorCCC>(
613                           false, false, AllowClassTemplates),
614                       CTK_ErrorRecovery)) {
615     if (Corrected.isKeyword()) {
616       // We corrected to a keyword.
617       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
618       II = Corrected.getCorrectionAsIdentifierInfo();
619     } else {
620       // We found a similarly-named type or interface; suggest that.
621       if (!SS || !SS->isSet()) {
622         diagnoseTypo(Corrected,
623                      PDiag(diag::err_unknown_typename_suggest) << II);
624       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
625         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
626         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
627                                 II->getName().equals(CorrectedStr);
628         diagnoseTypo(Corrected,
629                      PDiag(diag::err_unknown_nested_typename_suggest)
630                        << II << DC << DroppedSpecifier << SS->getRange());
631       } else {
632         llvm_unreachable("could not have corrected a typo here");
633       }
634
635       CXXScopeSpec tmpSS;
636       if (Corrected.getCorrectionSpecifier())
637         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
638                           SourceRange(IILoc));
639       SuggestedType =
640           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
641                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
642                       /*IsCtorOrDtorName=*/false,
643                       /*NonTrivialTypeSourceInfo=*/true);
644     }
645     return;
646   }
647
648   if (getLangOpts().CPlusPlus) {
649     // See if II is a class template that the user forgot to pass arguments to.
650     UnqualifiedId Name;
651     Name.setIdentifier(II, IILoc);
652     CXXScopeSpec EmptySS;
653     TemplateTy TemplateResult;
654     bool MemberOfUnknownSpecialization;
655     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
656                        Name, nullptr, true, TemplateResult,
657                        MemberOfUnknownSpecialization) == TNK_Type_template) {
658       TemplateName TplName = TemplateResult.get();
659       Diag(IILoc, diag::err_template_missing_args) << TplName;
660       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
661         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
662           << TplDecl->getTemplateParameters()->getSourceRange();
663       }
664       return;
665     }
666   }
667
668   // FIXME: Should we move the logic that tries to recover from a missing tag
669   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
670
671   if (!SS || (!SS->isSet() && !SS->isInvalid()))
672     Diag(IILoc, diag::err_unknown_typename) << II;
673   else if (DeclContext *DC = computeDeclContext(*SS, false))
674     Diag(IILoc, diag::err_typename_nested_not_found)
675       << II << DC << SS->getRange();
676   else if (isDependentScopeSpecifier(*SS)) {
677     unsigned DiagID = diag::err_typename_missing;
678     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
679       DiagID = diag::ext_typename_missing;
680
681     Diag(SS->getRange().getBegin(), DiagID)
682       << SS->getScopeRep() << II->getName()
683       << SourceRange(SS->getRange().getBegin(), IILoc)
684       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
685     SuggestedType = ActOnTypenameType(S, SourceLocation(),
686                                       *SS, *II, IILoc).get();
687   } else {
688     assert(SS && SS->isInvalid() &&
689            "Invalid scope specifier has already been diagnosed");
690   }
691 }
692
693 /// \brief Determine whether the given result set contains either a type name
694 /// or
695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
696   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
697                        NextToken.is(tok::less);
698
699   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
700     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
701       return true;
702
703     if (CheckTemplate && isa<TemplateDecl>(*I))
704       return true;
705   }
706
707   return false;
708 }
709
710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
711                                     Scope *S, CXXScopeSpec &SS,
712                                     IdentifierInfo *&Name,
713                                     SourceLocation NameLoc) {
714   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
715   SemaRef.LookupParsedName(R, S, &SS);
716   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
717     StringRef FixItTagName;
718     switch (Tag->getTagKind()) {
719       case TTK_Class:
720         FixItTagName = "class ";
721         break;
722
723       case TTK_Enum:
724         FixItTagName = "enum ";
725         break;
726
727       case TTK_Struct:
728         FixItTagName = "struct ";
729         break;
730
731       case TTK_Interface:
732         FixItTagName = "__interface ";
733         break;
734
735       case TTK_Union:
736         FixItTagName = "union ";
737         break;
738     }
739
740     StringRef TagName = FixItTagName.drop_back();
741     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
742       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
743       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
744
745     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
746          I != IEnd; ++I)
747       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
748         << Name << TagName;
749
750     // Replace lookup results with just the tag decl.
751     Result.clear(Sema::LookupTagName);
752     SemaRef.LookupParsedName(Result, S, &SS);
753     return true;
754   }
755
756   return false;
757 }
758
759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
761                                   QualType T, SourceLocation NameLoc) {
762   ASTContext &Context = S.Context;
763
764   TypeLocBuilder Builder;
765   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
766
767   T = S.getElaboratedType(ETK_None, SS, T);
768   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
769   ElabTL.setElaboratedKeywordLoc(SourceLocation());
770   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
771   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
772 }
773
774 Sema::NameClassification
775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
776                    SourceLocation NameLoc, const Token &NextToken,
777                    bool IsAddressOfOperand,
778                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
779   DeclarationNameInfo NameInfo(Name, NameLoc);
780   ObjCMethodDecl *CurMethod = getCurMethodDecl();
781
782   if (NextToken.is(tok::coloncolon)) {
783     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
784     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
785   }
786
787   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
788   LookupParsedName(Result, S, &SS, !CurMethod);
789
790   // For unqualified lookup in a class template in MSVC mode, look into
791   // dependent base classes where the primary class template is known.
792   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
793     if (ParsedType TypeInBase =
794             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
795       return TypeInBase;
796   }
797
798   // Perform lookup for Objective-C instance variables (including automatically
799   // synthesized instance variables), if we're in an Objective-C method.
800   // FIXME: This lookup really, really needs to be folded in to the normal
801   // unqualified lookup mechanism.
802   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
803     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
804     if (E.get() || E.isInvalid())
805       return E;
806   }
807
808   bool SecondTry = false;
809   bool IsFilteredTemplateName = false;
810
811 Corrected:
812   switch (Result.getResultKind()) {
813   case LookupResult::NotFound:
814     // If an unqualified-id is followed by a '(', then we have a function
815     // call.
816     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
817       // In C++, this is an ADL-only call.
818       // FIXME: Reference?
819       if (getLangOpts().CPlusPlus)
820         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
821
822       // C90 6.3.2.2:
823       //   If the expression that precedes the parenthesized argument list in a
824       //   function call consists solely of an identifier, and if no
825       //   declaration is visible for this identifier, the identifier is
826       //   implicitly declared exactly as if, in the innermost block containing
827       //   the function call, the declaration
828       //
829       //     extern int identifier ();
830       //
831       //   appeared.
832       //
833       // We also allow this in C99 as an extension.
834       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
835         Result.addDecl(D);
836         Result.resolveKind();
837         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
838       }
839     }
840
841     // In C, we first see whether there is a tag type by the same name, in
842     // which case it's likely that the user just forgot to write "enum",
843     // "struct", or "union".
844     if (!getLangOpts().CPlusPlus && !SecondTry &&
845         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
846       break;
847     }
848
849     // Perform typo correction to determine if there is another name that is
850     // close to this name.
851     if (!SecondTry && CCC) {
852       SecondTry = true;
853       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
854                                                  Result.getLookupKind(), S,
855                                                  &SS, std::move(CCC),
856                                                  CTK_ErrorRecovery)) {
857         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
858         unsigned QualifiedDiag = diag::err_no_member_suggest;
859
860         NamedDecl *FirstDecl = Corrected.getFoundDecl();
861         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
862         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
863             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
864           UnqualifiedDiag = diag::err_no_template_suggest;
865           QualifiedDiag = diag::err_no_member_template_suggest;
866         } else if (UnderlyingFirstDecl &&
867                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
868                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
869                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
870           UnqualifiedDiag = diag::err_unknown_typename_suggest;
871           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
872         }
873
874         if (SS.isEmpty()) {
875           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
876         } else {// FIXME: is this even reachable? Test it.
877           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
878           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
879                                   Name->getName().equals(CorrectedStr);
880           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
881                                     << Name << computeDeclContext(SS, false)
882                                     << DroppedSpecifier << SS.getRange());
883         }
884
885         // Update the name, so that the caller has the new name.
886         Name = Corrected.getCorrectionAsIdentifierInfo();
887
888         // Typo correction corrected to a keyword.
889         if (Corrected.isKeyword())
890           return Name;
891
892         // Also update the LookupResult...
893         // FIXME: This should probably go away at some point
894         Result.clear();
895         Result.setLookupName(Corrected.getCorrection());
896         if (FirstDecl)
897           Result.addDecl(FirstDecl);
898
899         // If we found an Objective-C instance variable, let
900         // LookupInObjCMethod build the appropriate expression to
901         // reference the ivar.
902         // FIXME: This is a gross hack.
903         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
904           Result.clear();
905           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
906           return E;
907         }
908
909         goto Corrected;
910       }
911     }
912
913     // We failed to correct; just fall through and let the parser deal with it.
914     Result.suppressDiagnostics();
915     return NameClassification::Unknown();
916
917   case LookupResult::NotFoundInCurrentInstantiation: {
918     // We performed name lookup into the current instantiation, and there were
919     // dependent bases, so we treat this result the same way as any other
920     // dependent nested-name-specifier.
921
922     // C++ [temp.res]p2:
923     //   A name used in a template declaration or definition and that is
924     //   dependent on a template-parameter is assumed not to name a type
925     //   unless the applicable name lookup finds a type name or the name is
926     //   qualified by the keyword typename.
927     //
928     // FIXME: If the next token is '<', we might want to ask the parser to
929     // perform some heroics to see if we actually have a
930     // template-argument-list, which would indicate a missing 'template'
931     // keyword here.
932     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
933                                       NameInfo, IsAddressOfOperand,
934                                       /*TemplateArgs=*/nullptr);
935   }
936
937   case LookupResult::Found:
938   case LookupResult::FoundOverloaded:
939   case LookupResult::FoundUnresolvedValue:
940     break;
941
942   case LookupResult::Ambiguous:
943     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
944         hasAnyAcceptableTemplateNames(Result)) {
945       // C++ [temp.local]p3:
946       //   A lookup that finds an injected-class-name (10.2) can result in an
947       //   ambiguity in certain cases (for example, if it is found in more than
948       //   one base class). If all of the injected-class-names that are found
949       //   refer to specializations of the same class template, and if the name
950       //   is followed by a template-argument-list, the reference refers to the
951       //   class template itself and not a specialization thereof, and is not
952       //   ambiguous.
953       //
954       // This filtering can make an ambiguous result into an unambiguous one,
955       // so try again after filtering out template names.
956       FilterAcceptableTemplateNames(Result);
957       if (!Result.isAmbiguous()) {
958         IsFilteredTemplateName = true;
959         break;
960       }
961     }
962
963     // Diagnose the ambiguity and return an error.
964     return NameClassification::Error();
965   }
966
967   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
968       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
969     // C++ [temp.names]p3:
970     //   After name lookup (3.4) finds that a name is a template-name or that
971     //   an operator-function-id or a literal- operator-id refers to a set of
972     //   overloaded functions any member of which is a function template if
973     //   this is followed by a <, the < is always taken as the delimiter of a
974     //   template-argument-list and never as the less-than operator.
975     if (!IsFilteredTemplateName)
976       FilterAcceptableTemplateNames(Result);
977
978     if (!Result.empty()) {
979       bool IsFunctionTemplate;
980       bool IsVarTemplate;
981       TemplateName Template;
982       if (Result.end() - Result.begin() > 1) {
983         IsFunctionTemplate = true;
984         Template = Context.getOverloadedTemplateName(Result.begin(),
985                                                      Result.end());
986       } else {
987         TemplateDecl *TD
988           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
989         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
990         IsVarTemplate = isa<VarTemplateDecl>(TD);
991
992         if (SS.isSet() && !SS.isInvalid())
993           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
994                                                     /*TemplateKeyword=*/false,
995                                                       TD);
996         else
997           Template = TemplateName(TD);
998       }
999
1000       if (IsFunctionTemplate) {
1001         // Function templates always go through overload resolution, at which
1002         // point we'll perform the various checks (e.g., accessibility) we need
1003         // to based on which function we selected.
1004         Result.suppressDiagnostics();
1005
1006         return NameClassification::FunctionTemplate(Template);
1007       }
1008
1009       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1010                            : NameClassification::TypeTemplate(Template);
1011     }
1012   }
1013
1014   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1015   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1018     QualType T = Context.getTypeDeclType(Type);
1019     if (SS.isNotEmpty())
1020       return buildNestedType(*this, SS, T, NameLoc);
1021     return ParsedType::make(T);
1022   }
1023
1024   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1025   if (!Class) {
1026     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1027     if (ObjCCompatibleAliasDecl *Alias =
1028             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1029       Class = Alias->getClassInterface();
1030   }
1031
1032   if (Class) {
1033     DiagnoseUseOfDecl(Class, NameLoc);
1034
1035     if (NextToken.is(tok::period)) {
1036       // Interface. <something> is parsed as a property reference expression.
1037       // Just return "unknown" as a fall-through for now.
1038       Result.suppressDiagnostics();
1039       return NameClassification::Unknown();
1040     }
1041
1042     QualType T = Context.getObjCInterfaceType(Class);
1043     return ParsedType::make(T);
1044   }
1045
1046   // We can have a type template here if we're classifying a template argument.
1047   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1048       !isa<VarTemplateDecl>(FirstDecl))
1049     return NameClassification::TypeTemplate(
1050         TemplateName(cast<TemplateDecl>(FirstDecl)));
1051
1052   // Check for a tag type hidden by a non-type decl in a few cases where it
1053   // seems likely a type is wanted instead of the non-type that was found.
1054   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1055   if ((NextToken.is(tok::identifier) ||
1056        (NextIsOp &&
1057         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1058       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1059     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1060     DiagnoseUseOfDecl(Type, NameLoc);
1061     QualType T = Context.getTypeDeclType(Type);
1062     if (SS.isNotEmpty())
1063       return buildNestedType(*this, SS, T, NameLoc);
1064     return ParsedType::make(T);
1065   }
1066
1067   if (FirstDecl->isCXXClassMember())
1068     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1069                                            nullptr, S);
1070
1071   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1072   return BuildDeclarationNameExpr(SS, Result, ADL);
1073 }
1074
1075 // Determines the context to return to after temporarily entering a
1076 // context.  This depends in an unnecessarily complicated way on the
1077 // exact ordering of callbacks from the parser.
1078 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1079
1080   // Functions defined inline within classes aren't parsed until we've
1081   // finished parsing the top-level class, so the top-level class is
1082   // the context we'll need to return to.
1083   // A Lambda call operator whose parent is a class must not be treated
1084   // as an inline member function.  A Lambda can be used legally
1085   // either as an in-class member initializer or a default argument.  These
1086   // are parsed once the class has been marked complete and so the containing
1087   // context would be the nested class (when the lambda is defined in one);
1088   // If the class is not complete, then the lambda is being used in an
1089   // ill-formed fashion (such as to specify the width of a bit-field, or
1090   // in an array-bound) - in which case we still want to return the
1091   // lexically containing DC (which could be a nested class).
1092   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1093     DC = DC->getLexicalParent();
1094
1095     // A function not defined within a class will always return to its
1096     // lexical context.
1097     if (!isa<CXXRecordDecl>(DC))
1098       return DC;
1099
1100     // A C++ inline method/friend is parsed *after* the topmost class
1101     // it was declared in is fully parsed ("complete");  the topmost
1102     // class is the context we need to return to.
1103     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1104       DC = RD;
1105
1106     // Return the declaration context of the topmost class the inline method is
1107     // declared in.
1108     return DC;
1109   }
1110
1111   return DC->getLexicalParent();
1112 }
1113
1114 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1115   assert(getContainingDC(DC) == CurContext &&
1116       "The next DeclContext should be lexically contained in the current one.");
1117   CurContext = DC;
1118   S->setEntity(DC);
1119 }
1120
1121 void Sema::PopDeclContext() {
1122   assert(CurContext && "DeclContext imbalance!");
1123
1124   CurContext = getContainingDC(CurContext);
1125   assert(CurContext && "Popped translation unit!");
1126 }
1127
1128 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1129                                                                     Decl *D) {
1130   // Unlike PushDeclContext, the context to which we return is not necessarily
1131   // the containing DC of TD, because the new context will be some pre-existing
1132   // TagDecl definition instead of a fresh one.
1133   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1134   CurContext = cast<TagDecl>(D)->getDefinition();
1135   assert(CurContext && "skipping definition of undefined tag");
1136   // Start lookups from the parent of the current context; we don't want to look
1137   // into the pre-existing complete definition.
1138   S->setEntity(CurContext->getLookupParent());
1139   return Result;
1140 }
1141
1142 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1143   CurContext = static_cast<decltype(CurContext)>(Context);
1144 }
1145
1146 /// EnterDeclaratorContext - Used when we must lookup names in the context
1147 /// of a declarator's nested name specifier.
1148 ///
1149 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1150   // C++0x [basic.lookup.unqual]p13:
1151   //   A name used in the definition of a static data member of class
1152   //   X (after the qualified-id of the static member) is looked up as
1153   //   if the name was used in a member function of X.
1154   // C++0x [basic.lookup.unqual]p14:
1155   //   If a variable member of a namespace is defined outside of the
1156   //   scope of its namespace then any name used in the definition of
1157   //   the variable member (after the declarator-id) is looked up as
1158   //   if the definition of the variable member occurred in its
1159   //   namespace.
1160   // Both of these imply that we should push a scope whose context
1161   // is the semantic context of the declaration.  We can't use
1162   // PushDeclContext here because that context is not necessarily
1163   // lexically contained in the current context.  Fortunately,
1164   // the containing scope should have the appropriate information.
1165
1166   assert(!S->getEntity() && "scope already has entity");
1167
1168 #ifndef NDEBUG
1169   Scope *Ancestor = S->getParent();
1170   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1171   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1172 #endif
1173
1174   CurContext = DC;
1175   S->setEntity(DC);
1176 }
1177
1178 void Sema::ExitDeclaratorContext(Scope *S) {
1179   assert(S->getEntity() == CurContext && "Context imbalance!");
1180
1181   // Switch back to the lexical context.  The safety of this is
1182   // enforced by an assert in EnterDeclaratorContext.
1183   Scope *Ancestor = S->getParent();
1184   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1185   CurContext = Ancestor->getEntity();
1186
1187   // We don't need to do anything with the scope, which is going to
1188   // disappear.
1189 }
1190
1191 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1192   // We assume that the caller has already called
1193   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1194   FunctionDecl *FD = D->getAsFunction();
1195   if (!FD)
1196     return;
1197
1198   // Same implementation as PushDeclContext, but enters the context
1199   // from the lexical parent, rather than the top-level class.
1200   assert(CurContext == FD->getLexicalParent() &&
1201     "The next DeclContext should be lexically contained in the current one.");
1202   CurContext = FD;
1203   S->setEntity(CurContext);
1204
1205   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1206     ParmVarDecl *Param = FD->getParamDecl(P);
1207     // If the parameter has an identifier, then add it to the scope
1208     if (Param->getIdentifier()) {
1209       S->AddDecl(Param);
1210       IdResolver.AddDecl(Param);
1211     }
1212   }
1213 }
1214
1215 void Sema::ActOnExitFunctionContext() {
1216   // Same implementation as PopDeclContext, but returns to the lexical parent,
1217   // rather than the top-level class.
1218   assert(CurContext && "DeclContext imbalance!");
1219   CurContext = CurContext->getLexicalParent();
1220   assert(CurContext && "Popped translation unit!");
1221 }
1222
1223 /// \brief Determine whether we allow overloading of the function
1224 /// PrevDecl with another declaration.
1225 ///
1226 /// This routine determines whether overloading is possible, not
1227 /// whether some new function is actually an overload. It will return
1228 /// true in C++ (where we can always provide overloads) or, as an
1229 /// extension, in C when the previous function is already an
1230 /// overloaded function declaration or has the "overloadable"
1231 /// attribute.
1232 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1233                                        ASTContext &Context) {
1234   if (Context.getLangOpts().CPlusPlus)
1235     return true;
1236
1237   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1238     return true;
1239
1240   return (Previous.getResultKind() == LookupResult::Found
1241           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1242 }
1243
1244 /// Add this decl to the scope shadowed decl chains.
1245 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1246   // Move up the scope chain until we find the nearest enclosing
1247   // non-transparent context. The declaration will be introduced into this
1248   // scope.
1249   while (S->getEntity() && S->getEntity()->isTransparentContext())
1250     S = S->getParent();
1251
1252   // Add scoped declarations into their context, so that they can be
1253   // found later. Declarations without a context won't be inserted
1254   // into any context.
1255   if (AddToContext)
1256     CurContext->addDecl(D);
1257
1258   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1259   // are function-local declarations.
1260   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1261       !D->getDeclContext()->getRedeclContext()->Equals(
1262         D->getLexicalDeclContext()->getRedeclContext()) &&
1263       !D->getLexicalDeclContext()->isFunctionOrMethod())
1264     return;
1265
1266   // Template instantiations should also not be pushed into scope.
1267   if (isa<FunctionDecl>(D) &&
1268       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1269     return;
1270
1271   // If this replaces anything in the current scope,
1272   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1273                                IEnd = IdResolver.end();
1274   for (; I != IEnd; ++I) {
1275     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1276       S->RemoveDecl(*I);
1277       IdResolver.RemoveDecl(*I);
1278
1279       // Should only need to replace one decl.
1280       break;
1281     }
1282   }
1283
1284   S->AddDecl(D);
1285
1286   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1287     // Implicitly-generated labels may end up getting generated in an order that
1288     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1289     // the label at the appropriate place in the identifier chain.
1290     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1291       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1292       if (IDC == CurContext) {
1293         if (!S->isDeclScope(*I))
1294           continue;
1295       } else if (IDC->Encloses(CurContext))
1296         break;
1297     }
1298
1299     IdResolver.InsertDeclAfter(I, D);
1300   } else {
1301     IdResolver.AddDecl(D);
1302   }
1303 }
1304
1305 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1306   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1307     TUScope->AddDecl(D);
1308 }
1309
1310 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1311                          bool AllowInlineNamespace) {
1312   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1313 }
1314
1315 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1316   DeclContext *TargetDC = DC->getPrimaryContext();
1317   do {
1318     if (DeclContext *ScopeDC = S->getEntity())
1319       if (ScopeDC->getPrimaryContext() == TargetDC)
1320         return S;
1321   } while ((S = S->getParent()));
1322
1323   return nullptr;
1324 }
1325
1326 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1327                                             DeclContext*,
1328                                             ASTContext&);
1329
1330 /// Filters out lookup results that don't fall within the given scope
1331 /// as determined by isDeclInScope.
1332 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1333                                 bool ConsiderLinkage,
1334                                 bool AllowInlineNamespace) {
1335   LookupResult::Filter F = R.makeFilter();
1336   while (F.hasNext()) {
1337     NamedDecl *D = F.next();
1338
1339     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1340       continue;
1341
1342     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1343       continue;
1344
1345     F.erase();
1346   }
1347
1348   F.done();
1349 }
1350
1351 static bool isUsingDecl(NamedDecl *D) {
1352   return isa<UsingShadowDecl>(D) ||
1353          isa<UnresolvedUsingTypenameDecl>(D) ||
1354          isa<UnresolvedUsingValueDecl>(D);
1355 }
1356
1357 /// Removes using shadow declarations from the lookup results.
1358 static void RemoveUsingDecls(LookupResult &R) {
1359   LookupResult::Filter F = R.makeFilter();
1360   while (F.hasNext())
1361     if (isUsingDecl(F.next()))
1362       F.erase();
1363
1364   F.done();
1365 }
1366
1367 /// \brief Check for this common pattern:
1368 /// @code
1369 /// class S {
1370 ///   S(const S&); // DO NOT IMPLEMENT
1371 ///   void operator=(const S&); // DO NOT IMPLEMENT
1372 /// };
1373 /// @endcode
1374 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1375   // FIXME: Should check for private access too but access is set after we get
1376   // the decl here.
1377   if (D->doesThisDeclarationHaveABody())
1378     return false;
1379
1380   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1381     return CD->isCopyConstructor();
1382   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1383     return Method->isCopyAssignmentOperator();
1384   return false;
1385 }
1386
1387 // We need this to handle
1388 //
1389 // typedef struct {
1390 //   void *foo() { return 0; }
1391 // } A;
1392 //
1393 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1394 // for example. If 'A', foo will have external linkage. If we have '*A',
1395 // foo will have no linkage. Since we can't know until we get to the end
1396 // of the typedef, this function finds out if D might have non-external linkage.
1397 // Callers should verify at the end of the TU if it D has external linkage or
1398 // not.
1399 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1400   const DeclContext *DC = D->getDeclContext();
1401   while (!DC->isTranslationUnit()) {
1402     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1403       if (!RD->hasNameForLinkage())
1404         return true;
1405     }
1406     DC = DC->getParent();
1407   }
1408
1409   return !D->isExternallyVisible();
1410 }
1411
1412 // FIXME: This needs to be refactored; some other isInMainFile users want
1413 // these semantics.
1414 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1415   if (S.TUKind != TU_Complete)
1416     return false;
1417   return S.SourceMgr.isInMainFile(Loc);
1418 }
1419
1420 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1421   assert(D);
1422
1423   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1424     return false;
1425
1426   // Ignore all entities declared within templates, and out-of-line definitions
1427   // of members of class templates.
1428   if (D->getDeclContext()->isDependentContext() ||
1429       D->getLexicalDeclContext()->isDependentContext())
1430     return false;
1431
1432   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1433     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1434       return false;
1435
1436     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1437       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1438         return false;
1439     } else {
1440       // 'static inline' functions are defined in headers; don't warn.
1441       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1442         return false;
1443     }
1444
1445     if (FD->doesThisDeclarationHaveABody() &&
1446         Context.DeclMustBeEmitted(FD))
1447       return false;
1448   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1449     // Constants and utility variables are defined in headers with internal
1450     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1451     // like "inline".)
1452     if (!isMainFileLoc(*this, VD->getLocation()))
1453       return false;
1454
1455     if (Context.DeclMustBeEmitted(VD))
1456       return false;
1457
1458     if (VD->isStaticDataMember() &&
1459         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1460       return false;
1461
1462     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1463       return false;
1464   } else {
1465     return false;
1466   }
1467
1468   // Only warn for unused decls internal to the translation unit.
1469   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1470   // for inline functions defined in the main source file, for instance.
1471   return mightHaveNonExternalLinkage(D);
1472 }
1473
1474 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1475   if (!D)
1476     return;
1477
1478   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1479     const FunctionDecl *First = FD->getFirstDecl();
1480     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1481       return; // First should already be in the vector.
1482   }
1483
1484   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1485     const VarDecl *First = VD->getFirstDecl();
1486     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1487       return; // First should already be in the vector.
1488   }
1489
1490   if (ShouldWarnIfUnusedFileScopedDecl(D))
1491     UnusedFileScopedDecls.push_back(D);
1492 }
1493
1494 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1495   if (D->isInvalidDecl())
1496     return false;
1497
1498   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1499       D->hasAttr<ObjCPreciseLifetimeAttr>())
1500     return false;
1501
1502   if (isa<LabelDecl>(D))
1503     return true;
1504
1505   // Except for labels, we only care about unused decls that are local to
1506   // functions.
1507   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1508   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1509     // For dependent types, the diagnostic is deferred.
1510     WithinFunction =
1511         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1512   if (!WithinFunction)
1513     return false;
1514
1515   if (isa<TypedefNameDecl>(D))
1516     return true;
1517
1518   // White-list anything that isn't a local variable.
1519   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1520     return false;
1521
1522   // Types of valid local variables should be complete, so this should succeed.
1523   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1524
1525     // White-list anything with an __attribute__((unused)) type.
1526     const auto *Ty = VD->getType().getTypePtr();
1527
1528     // Only look at the outermost level of typedef.
1529     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1530       if (TT->getDecl()->hasAttr<UnusedAttr>())
1531         return false;
1532     }
1533
1534     // If we failed to complete the type for some reason, or if the type is
1535     // dependent, don't diagnose the variable.
1536     if (Ty->isIncompleteType() || Ty->isDependentType())
1537       return false;
1538
1539     // Look at the element type to ensure that the warning behaviour is
1540     // consistent for both scalars and arrays.
1541     Ty = Ty->getBaseElementTypeUnsafe();
1542
1543     if (const TagType *TT = Ty->getAs<TagType>()) {
1544       const TagDecl *Tag = TT->getDecl();
1545       if (Tag->hasAttr<UnusedAttr>())
1546         return false;
1547
1548       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1549         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1550           return false;
1551
1552         if (const Expr *Init = VD->getInit()) {
1553           if (const ExprWithCleanups *Cleanups =
1554                   dyn_cast<ExprWithCleanups>(Init))
1555             Init = Cleanups->getSubExpr();
1556           const CXXConstructExpr *Construct =
1557             dyn_cast<CXXConstructExpr>(Init);
1558           if (Construct && !Construct->isElidable()) {
1559             CXXConstructorDecl *CD = Construct->getConstructor();
1560             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1561               return false;
1562           }
1563         }
1564       }
1565     }
1566
1567     // TODO: __attribute__((unused)) templates?
1568   }
1569
1570   return true;
1571 }
1572
1573 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1574                                      FixItHint &Hint) {
1575   if (isa<LabelDecl>(D)) {
1576     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1577                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1578     if (AfterColon.isInvalid())
1579       return;
1580     Hint = FixItHint::CreateRemoval(CharSourceRange::
1581                                     getCharRange(D->getLocStart(), AfterColon));
1582   }
1583 }
1584
1585 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1586   if (D->getTypeForDecl()->isDependentType())
1587     return;
1588
1589   for (auto *TmpD : D->decls()) {
1590     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1591       DiagnoseUnusedDecl(T);
1592     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1593       DiagnoseUnusedNestedTypedefs(R);
1594   }
1595 }
1596
1597 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1598 /// unless they are marked attr(unused).
1599 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1600   if (!ShouldDiagnoseUnusedDecl(D))
1601     return;
1602
1603   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1604     // typedefs can be referenced later on, so the diagnostics are emitted
1605     // at end-of-translation-unit.
1606     UnusedLocalTypedefNameCandidates.insert(TD);
1607     return;
1608   }
1609
1610   FixItHint Hint;
1611   GenerateFixForUnusedDecl(D, Context, Hint);
1612
1613   unsigned DiagID;
1614   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1615     DiagID = diag::warn_unused_exception_param;
1616   else if (isa<LabelDecl>(D))
1617     DiagID = diag::warn_unused_label;
1618   else
1619     DiagID = diag::warn_unused_variable;
1620
1621   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1622 }
1623
1624 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1625   // Verify that we have no forward references left.  If so, there was a goto
1626   // or address of a label taken, but no definition of it.  Label fwd
1627   // definitions are indicated with a null substmt which is also not a resolved
1628   // MS inline assembly label name.
1629   bool Diagnose = false;
1630   if (L->isMSAsmLabel())
1631     Diagnose = !L->isResolvedMSAsmLabel();
1632   else
1633     Diagnose = L->getStmt() == nullptr;
1634   if (Diagnose)
1635     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1636 }
1637
1638 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1639   S->mergeNRVOIntoParent();
1640
1641   if (S->decl_empty()) return;
1642   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1643          "Scope shouldn't contain decls!");
1644
1645   for (auto *TmpD : S->decls()) {
1646     assert(TmpD && "This decl didn't get pushed??");
1647
1648     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1649     NamedDecl *D = cast<NamedDecl>(TmpD);
1650
1651     if (!D->getDeclName()) continue;
1652
1653     // Diagnose unused variables in this scope.
1654     if (!S->hasUnrecoverableErrorOccurred()) {
1655       DiagnoseUnusedDecl(D);
1656       if (const auto *RD = dyn_cast<RecordDecl>(D))
1657         DiagnoseUnusedNestedTypedefs(RD);
1658     }
1659
1660     // If this was a forward reference to a label, verify it was defined.
1661     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1662       CheckPoppedLabel(LD, *this);
1663
1664     // Remove this name from our lexical scope, and warn on it if we haven't
1665     // already.
1666     IdResolver.RemoveDecl(D);
1667     auto ShadowI = ShadowingDecls.find(D);
1668     if (ShadowI != ShadowingDecls.end()) {
1669       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1670         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1671             << D << FD << FD->getParent();
1672         Diag(FD->getLocation(), diag::note_previous_declaration);
1673       }
1674       ShadowingDecls.erase(ShadowI);
1675     }
1676   }
1677 }
1678
1679 /// \brief Look for an Objective-C class in the translation unit.
1680 ///
1681 /// \param Id The name of the Objective-C class we're looking for. If
1682 /// typo-correction fixes this name, the Id will be updated
1683 /// to the fixed name.
1684 ///
1685 /// \param IdLoc The location of the name in the translation unit.
1686 ///
1687 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1688 /// if there is no class with the given name.
1689 ///
1690 /// \returns The declaration of the named Objective-C class, or NULL if the
1691 /// class could not be found.
1692 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1693                                               SourceLocation IdLoc,
1694                                               bool DoTypoCorrection) {
1695   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1696   // creation from this context.
1697   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1698
1699   if (!IDecl && DoTypoCorrection) {
1700     // Perform typo correction at the given location, but only if we
1701     // find an Objective-C class name.
1702     if (TypoCorrection C = CorrectTypo(
1703             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1704             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1705             CTK_ErrorRecovery)) {
1706       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1707       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1708       Id = IDecl->getIdentifier();
1709     }
1710   }
1711   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1712   // This routine must always return a class definition, if any.
1713   if (Def && Def->getDefinition())
1714       Def = Def->getDefinition();
1715   return Def;
1716 }
1717
1718 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1719 /// from S, where a non-field would be declared. This routine copes
1720 /// with the difference between C and C++ scoping rules in structs and
1721 /// unions. For example, the following code is well-formed in C but
1722 /// ill-formed in C++:
1723 /// @code
1724 /// struct S6 {
1725 ///   enum { BAR } e;
1726 /// };
1727 ///
1728 /// void test_S6() {
1729 ///   struct S6 a;
1730 ///   a.e = BAR;
1731 /// }
1732 /// @endcode
1733 /// For the declaration of BAR, this routine will return a different
1734 /// scope. The scope S will be the scope of the unnamed enumeration
1735 /// within S6. In C++, this routine will return the scope associated
1736 /// with S6, because the enumeration's scope is a transparent
1737 /// context but structures can contain non-field names. In C, this
1738 /// routine will return the translation unit scope, since the
1739 /// enumeration's scope is a transparent context and structures cannot
1740 /// contain non-field names.
1741 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1742   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1743          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1744          (S->isClassScope() && !getLangOpts().CPlusPlus))
1745     S = S->getParent();
1746   return S;
1747 }
1748
1749 /// \brief Looks up the declaration of "struct objc_super" and
1750 /// saves it for later use in building builtin declaration of
1751 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1752 /// pre-existing declaration exists no action takes place.
1753 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1754                                         IdentifierInfo *II) {
1755   if (!II->isStr("objc_msgSendSuper"))
1756     return;
1757   ASTContext &Context = ThisSema.Context;
1758
1759   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1760                       SourceLocation(), Sema::LookupTagName);
1761   ThisSema.LookupName(Result, S);
1762   if (Result.getResultKind() == LookupResult::Found)
1763     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1764       Context.setObjCSuperType(Context.getTagDeclType(TD));
1765 }
1766
1767 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1768   switch (Error) {
1769   case ASTContext::GE_None:
1770     return "";
1771   case ASTContext::GE_Missing_stdio:
1772     return "stdio.h";
1773   case ASTContext::GE_Missing_setjmp:
1774     return "setjmp.h";
1775   case ASTContext::GE_Missing_ucontext:
1776     return "ucontext.h";
1777   }
1778   llvm_unreachable("unhandled error kind");
1779 }
1780
1781 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1782 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1783 /// if we're creating this built-in in anticipation of redeclaring the
1784 /// built-in.
1785 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1786                                      Scope *S, bool ForRedeclaration,
1787                                      SourceLocation Loc) {
1788   LookupPredefedObjCSuperType(*this, S, II);
1789
1790   ASTContext::GetBuiltinTypeError Error;
1791   QualType R = Context.GetBuiltinType(ID, Error);
1792   if (Error) {
1793     if (ForRedeclaration)
1794       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1795           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1796     return nullptr;
1797   }
1798
1799   if (!ForRedeclaration &&
1800       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1801        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1802     Diag(Loc, diag::ext_implicit_lib_function_decl)
1803         << Context.BuiltinInfo.getName(ID) << R;
1804     if (Context.BuiltinInfo.getHeaderName(ID) &&
1805         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1806       Diag(Loc, diag::note_include_header_or_declare)
1807           << Context.BuiltinInfo.getHeaderName(ID)
1808           << Context.BuiltinInfo.getName(ID);
1809   }
1810
1811   if (R.isNull())
1812     return nullptr;
1813
1814   DeclContext *Parent = Context.getTranslationUnitDecl();
1815   if (getLangOpts().CPlusPlus) {
1816     LinkageSpecDecl *CLinkageDecl =
1817         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1818                                 LinkageSpecDecl::lang_c, false);
1819     CLinkageDecl->setImplicit();
1820     Parent->addDecl(CLinkageDecl);
1821     Parent = CLinkageDecl;
1822   }
1823
1824   FunctionDecl *New = FunctionDecl::Create(Context,
1825                                            Parent,
1826                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1827                                            SC_Extern,
1828                                            false,
1829                                            R->isFunctionProtoType());
1830   New->setImplicit();
1831
1832   // Create Decl objects for each parameter, adding them to the
1833   // FunctionDecl.
1834   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1835     SmallVector<ParmVarDecl*, 16> Params;
1836     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1837       ParmVarDecl *parm =
1838           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1839                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1840                               SC_None, nullptr);
1841       parm->setScopeInfo(0, i);
1842       Params.push_back(parm);
1843     }
1844     New->setParams(Params);
1845   }
1846
1847   AddKnownFunctionAttributes(New);
1848   RegisterLocallyScopedExternCDecl(New, S);
1849
1850   // TUScope is the translation-unit scope to insert this function into.
1851   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1852   // relate Scopes to DeclContexts, and probably eliminate CurContext
1853   // entirely, but we're not there yet.
1854   DeclContext *SavedContext = CurContext;
1855   CurContext = Parent;
1856   PushOnScopeChains(New, TUScope);
1857   CurContext = SavedContext;
1858   return New;
1859 }
1860
1861 /// Typedef declarations don't have linkage, but they still denote the same
1862 /// entity if their types are the same.
1863 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1864 /// isSameEntity.
1865 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1866                                                      TypedefNameDecl *Decl,
1867                                                      LookupResult &Previous) {
1868   // This is only interesting when modules are enabled.
1869   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1870     return;
1871
1872   // Empty sets are uninteresting.
1873   if (Previous.empty())
1874     return;
1875
1876   LookupResult::Filter Filter = Previous.makeFilter();
1877   while (Filter.hasNext()) {
1878     NamedDecl *Old = Filter.next();
1879
1880     // Non-hidden declarations are never ignored.
1881     if (S.isVisible(Old))
1882       continue;
1883
1884     // Declarations of the same entity are not ignored, even if they have
1885     // different linkages.
1886     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1887       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1888                                 Decl->getUnderlyingType()))
1889         continue;
1890
1891       // If both declarations give a tag declaration a typedef name for linkage
1892       // purposes, then they declare the same entity.
1893       if (S.getLangOpts().CPlusPlus &&
1894           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1895           Decl->getAnonDeclWithTypedefName())
1896         continue;
1897     }
1898
1899     Filter.erase();
1900   }
1901
1902   Filter.done();
1903 }
1904
1905 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1906   QualType OldType;
1907   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1908     OldType = OldTypedef->getUnderlyingType();
1909   else
1910     OldType = Context.getTypeDeclType(Old);
1911   QualType NewType = New->getUnderlyingType();
1912
1913   if (NewType->isVariablyModifiedType()) {
1914     // Must not redefine a typedef with a variably-modified type.
1915     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1916     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1917       << Kind << NewType;
1918     if (Old->getLocation().isValid())
1919       Diag(Old->getLocation(), diag::note_previous_definition);
1920     New->setInvalidDecl();
1921     return true;
1922   }
1923
1924   if (OldType != NewType &&
1925       !OldType->isDependentType() &&
1926       !NewType->isDependentType() &&
1927       !Context.hasSameType(OldType, NewType)) {
1928     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1929     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1930       << Kind << NewType << OldType;
1931     if (Old->getLocation().isValid())
1932       Diag(Old->getLocation(), diag::note_previous_definition);
1933     New->setInvalidDecl();
1934     return true;
1935   }
1936   return false;
1937 }
1938
1939 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1940 /// same name and scope as a previous declaration 'Old'.  Figure out
1941 /// how to resolve this situation, merging decls or emitting
1942 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1943 ///
1944 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1945                                 LookupResult &OldDecls) {
1946   // If the new decl is known invalid already, don't bother doing any
1947   // merging checks.
1948   if (New->isInvalidDecl()) return;
1949
1950   // Allow multiple definitions for ObjC built-in typedefs.
1951   // FIXME: Verify the underlying types are equivalent!
1952   if (getLangOpts().ObjC1) {
1953     const IdentifierInfo *TypeID = New->getIdentifier();
1954     switch (TypeID->getLength()) {
1955     default: break;
1956     case 2:
1957       {
1958         if (!TypeID->isStr("id"))
1959           break;
1960         QualType T = New->getUnderlyingType();
1961         if (!T->isPointerType())
1962           break;
1963         if (!T->isVoidPointerType()) {
1964           QualType PT = T->getAs<PointerType>()->getPointeeType();
1965           if (!PT->isStructureType())
1966             break;
1967         }
1968         Context.setObjCIdRedefinitionType(T);
1969         // Install the built-in type for 'id', ignoring the current definition.
1970         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1971         return;
1972       }
1973     case 5:
1974       if (!TypeID->isStr("Class"))
1975         break;
1976       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1977       // Install the built-in type for 'Class', ignoring the current definition.
1978       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1979       return;
1980     case 3:
1981       if (!TypeID->isStr("SEL"))
1982         break;
1983       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1984       // Install the built-in type for 'SEL', ignoring the current definition.
1985       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1986       return;
1987     }
1988     // Fall through - the typedef name was not a builtin type.
1989   }
1990
1991   // Verify the old decl was also a type.
1992   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1993   if (!Old) {
1994     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1995       << New->getDeclName();
1996
1997     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1998     if (OldD->getLocation().isValid())
1999       Diag(OldD->getLocation(), diag::note_previous_definition);
2000
2001     return New->setInvalidDecl();
2002   }
2003
2004   // If the old declaration is invalid, just give up here.
2005   if (Old->isInvalidDecl())
2006     return New->setInvalidDecl();
2007
2008   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2009     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2010     auto *NewTag = New->getAnonDeclWithTypedefName();
2011     NamedDecl *Hidden = nullptr;
2012     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2013         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2014         !hasVisibleDefinition(OldTag, &Hidden)) {
2015       // There is a definition of this tag, but it is not visible. Use it
2016       // instead of our tag.
2017       New->setTypeForDecl(OldTD->getTypeForDecl());
2018       if (OldTD->isModed())
2019         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2020                                     OldTD->getUnderlyingType());
2021       else
2022         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2023
2024       // Make the old tag definition visible.
2025       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2026
2027       // If this was an unscoped enumeration, yank all of its enumerators
2028       // out of the scope.
2029       if (isa<EnumDecl>(NewTag)) {
2030         Scope *EnumScope = getNonFieldDeclScope(S);
2031         for (auto *D : NewTag->decls()) {
2032           auto *ED = cast<EnumConstantDecl>(D);
2033           assert(EnumScope->isDeclScope(ED));
2034           EnumScope->RemoveDecl(ED);
2035           IdResolver.RemoveDecl(ED);
2036           ED->getLexicalDeclContext()->removeDecl(ED);
2037         }
2038       }
2039     }
2040   }
2041
2042   // If the typedef types are not identical, reject them in all languages and
2043   // with any extensions enabled.
2044   if (isIncompatibleTypedef(Old, New))
2045     return;
2046
2047   // The types match.  Link up the redeclaration chain and merge attributes if
2048   // the old declaration was a typedef.
2049   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2050     New->setPreviousDecl(Typedef);
2051     mergeDeclAttributes(New, Old);
2052   }
2053
2054   if (getLangOpts().MicrosoftExt)
2055     return;
2056
2057   if (getLangOpts().CPlusPlus) {
2058     // C++ [dcl.typedef]p2:
2059     //   In a given non-class scope, a typedef specifier can be used to
2060     //   redefine the name of any type declared in that scope to refer
2061     //   to the type to which it already refers.
2062     if (!isa<CXXRecordDecl>(CurContext))
2063       return;
2064
2065     // C++0x [dcl.typedef]p4:
2066     //   In a given class scope, a typedef specifier can be used to redefine
2067     //   any class-name declared in that scope that is not also a typedef-name
2068     //   to refer to the type to which it already refers.
2069     //
2070     // This wording came in via DR424, which was a correction to the
2071     // wording in DR56, which accidentally banned code like:
2072     //
2073     //   struct S {
2074     //     typedef struct A { } A;
2075     //   };
2076     //
2077     // in the C++03 standard. We implement the C++0x semantics, which
2078     // allow the above but disallow
2079     //
2080     //   struct S {
2081     //     typedef int I;
2082     //     typedef int I;
2083     //   };
2084     //
2085     // since that was the intent of DR56.
2086     if (!isa<TypedefNameDecl>(Old))
2087       return;
2088
2089     Diag(New->getLocation(), diag::err_redefinition)
2090       << New->getDeclName();
2091     Diag(Old->getLocation(), diag::note_previous_definition);
2092     return New->setInvalidDecl();
2093   }
2094
2095   // Modules always permit redefinition of typedefs, as does C11.
2096   if (getLangOpts().Modules || getLangOpts().C11)
2097     return;
2098
2099   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2100   // is normally mapped to an error, but can be controlled with
2101   // -Wtypedef-redefinition.  If either the original or the redefinition is
2102   // in a system header, don't emit this for compatibility with GCC.
2103   if (getDiagnostics().getSuppressSystemWarnings() &&
2104       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2105        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2106     return;
2107
2108   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2109     << New->getDeclName();
2110   Diag(Old->getLocation(), diag::note_previous_definition);
2111 }
2112
2113 /// DeclhasAttr - returns true if decl Declaration already has the target
2114 /// attribute.
2115 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2116   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2117   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2118   for (const auto *i : D->attrs())
2119     if (i->getKind() == A->getKind()) {
2120       if (Ann) {
2121         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2122           return true;
2123         continue;
2124       }
2125       // FIXME: Don't hardcode this check
2126       if (OA && isa<OwnershipAttr>(i))
2127         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2128       return true;
2129     }
2130
2131   return false;
2132 }
2133
2134 static bool isAttributeTargetADefinition(Decl *D) {
2135   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2136     return VD->isThisDeclarationADefinition();
2137   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2138     return TD->isCompleteDefinition() || TD->isBeingDefined();
2139   return true;
2140 }
2141
2142 /// Merge alignment attributes from \p Old to \p New, taking into account the
2143 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2144 ///
2145 /// \return \c true if any attributes were added to \p New.
2146 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2147   // Look for alignas attributes on Old, and pick out whichever attribute
2148   // specifies the strictest alignment requirement.
2149   AlignedAttr *OldAlignasAttr = nullptr;
2150   AlignedAttr *OldStrictestAlignAttr = nullptr;
2151   unsigned OldAlign = 0;
2152   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2153     // FIXME: We have no way of representing inherited dependent alignments
2154     // in a case like:
2155     //   template<int A, int B> struct alignas(A) X;
2156     //   template<int A, int B> struct alignas(B) X {};
2157     // For now, we just ignore any alignas attributes which are not on the
2158     // definition in such a case.
2159     if (I->isAlignmentDependent())
2160       return false;
2161
2162     if (I->isAlignas())
2163       OldAlignasAttr = I;
2164
2165     unsigned Align = I->getAlignment(S.Context);
2166     if (Align > OldAlign) {
2167       OldAlign = Align;
2168       OldStrictestAlignAttr = I;
2169     }
2170   }
2171
2172   // Look for alignas attributes on New.
2173   AlignedAttr *NewAlignasAttr = nullptr;
2174   unsigned NewAlign = 0;
2175   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2176     if (I->isAlignmentDependent())
2177       return false;
2178
2179     if (I->isAlignas())
2180       NewAlignasAttr = I;
2181
2182     unsigned Align = I->getAlignment(S.Context);
2183     if (Align > NewAlign)
2184       NewAlign = Align;
2185   }
2186
2187   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2188     // Both declarations have 'alignas' attributes. We require them to match.
2189     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2190     // fall short. (If two declarations both have alignas, they must both match
2191     // every definition, and so must match each other if there is a definition.)
2192
2193     // If either declaration only contains 'alignas(0)' specifiers, then it
2194     // specifies the natural alignment for the type.
2195     if (OldAlign == 0 || NewAlign == 0) {
2196       QualType Ty;
2197       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2198         Ty = VD->getType();
2199       else
2200         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2201
2202       if (OldAlign == 0)
2203         OldAlign = S.Context.getTypeAlign(Ty);
2204       if (NewAlign == 0)
2205         NewAlign = S.Context.getTypeAlign(Ty);
2206     }
2207
2208     if (OldAlign != NewAlign) {
2209       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2210         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2211         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2212       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2213     }
2214   }
2215
2216   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2217     // C++11 [dcl.align]p6:
2218     //   if any declaration of an entity has an alignment-specifier,
2219     //   every defining declaration of that entity shall specify an
2220     //   equivalent alignment.
2221     // C11 6.7.5/7:
2222     //   If the definition of an object does not have an alignment
2223     //   specifier, any other declaration of that object shall also
2224     //   have no alignment specifier.
2225     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2226       << OldAlignasAttr;
2227     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2228       << OldAlignasAttr;
2229   }
2230
2231   bool AnyAdded = false;
2232
2233   // Ensure we have an attribute representing the strictest alignment.
2234   if (OldAlign > NewAlign) {
2235     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2236     Clone->setInherited(true);
2237     New->addAttr(Clone);
2238     AnyAdded = true;
2239   }
2240
2241   // Ensure we have an alignas attribute if the old declaration had one.
2242   if (OldAlignasAttr && !NewAlignasAttr &&
2243       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2244     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2245     Clone->setInherited(true);
2246     New->addAttr(Clone);
2247     AnyAdded = true;
2248   }
2249
2250   return AnyAdded;
2251 }
2252
2253 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2254                                const InheritableAttr *Attr,
2255                                Sema::AvailabilityMergeKind AMK) {
2256   // This function copies an attribute Attr from a previous declaration to the
2257   // new declaration D if the new declaration doesn't itself have that attribute
2258   // yet or if that attribute allows duplicates.
2259   // If you're adding a new attribute that requires logic different from
2260   // "use explicit attribute on decl if present, else use attribute from
2261   // previous decl", for example if the attribute needs to be consistent
2262   // between redeclarations, you need to call a custom merge function here.
2263   InheritableAttr *NewAttr = nullptr;
2264   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2265   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2266     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2267                                       AA->isImplicit(), AA->getIntroduced(),
2268                                       AA->getDeprecated(),
2269                                       AA->getObsoleted(), AA->getUnavailable(),
2270                                       AA->getMessage(), AA->getStrict(),
2271                                       AA->getReplacement(), AMK,
2272                                       AttrSpellingListIndex);
2273   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2274     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2275                                     AttrSpellingListIndex);
2276   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2277     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2278                                         AttrSpellingListIndex);
2279   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2280     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2281                                    AttrSpellingListIndex);
2282   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2283     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2284                                    AttrSpellingListIndex);
2285   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2286     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2287                                 FA->getFormatIdx(), FA->getFirstArg(),
2288                                 AttrSpellingListIndex);
2289   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2290     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2291                                  AttrSpellingListIndex);
2292   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2293     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2294                                        AttrSpellingListIndex,
2295                                        IA->getSemanticSpelling());
2296   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2297     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2298                                       &S.Context.Idents.get(AA->getSpelling()),
2299                                       AttrSpellingListIndex);
2300   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2301            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2302             isa<CUDAGlobalAttr>(Attr))) {
2303     // CUDA target attributes are part of function signature for
2304     // overloading purposes and must not be merged.
2305     return false;
2306   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2307     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2308   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2309     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2310   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2311     NewAttr = S.mergeInternalLinkageAttr(
2312         D, InternalLinkageA->getRange(),
2313         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2314         AttrSpellingListIndex);
2315   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2316     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2317                                 &S.Context.Idents.get(CommonA->getSpelling()),
2318                                 AttrSpellingListIndex);
2319   else if (isa<AlignedAttr>(Attr))
2320     // AlignedAttrs are handled separately, because we need to handle all
2321     // such attributes on a declaration at the same time.
2322     NewAttr = nullptr;
2323   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2324            (AMK == Sema::AMK_Override ||
2325             AMK == Sema::AMK_ProtocolImplementation))
2326     NewAttr = nullptr;
2327   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2328     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2329                               UA->getGuid());
2330   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2331     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2332
2333   if (NewAttr) {
2334     NewAttr->setInherited(true);
2335     D->addAttr(NewAttr);
2336     if (isa<MSInheritanceAttr>(NewAttr))
2337       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2338     return true;
2339   }
2340
2341   return false;
2342 }
2343
2344 static const Decl *getDefinition(const Decl *D) {
2345   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2346     return TD->getDefinition();
2347   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2348     const VarDecl *Def = VD->getDefinition();
2349     if (Def)
2350       return Def;
2351     return VD->getActingDefinition();
2352   }
2353   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2354     return FD->getDefinition();
2355   return nullptr;
2356 }
2357
2358 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2359   for (const auto *Attribute : D->attrs())
2360     if (Attribute->getKind() == Kind)
2361       return true;
2362   return false;
2363 }
2364
2365 /// checkNewAttributesAfterDef - If we already have a definition, check that
2366 /// there are no new attributes in this declaration.
2367 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2368   if (!New->hasAttrs())
2369     return;
2370
2371   const Decl *Def = getDefinition(Old);
2372   if (!Def || Def == New)
2373     return;
2374
2375   AttrVec &NewAttributes = New->getAttrs();
2376   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2377     const Attr *NewAttribute = NewAttributes[I];
2378
2379     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2380       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2381         Sema::SkipBodyInfo SkipBody;
2382         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2383
2384         // If we're skipping this definition, drop the "alias" attribute.
2385         if (SkipBody.ShouldSkip) {
2386           NewAttributes.erase(NewAttributes.begin() + I);
2387           --E;
2388           continue;
2389         }
2390       } else {
2391         VarDecl *VD = cast<VarDecl>(New);
2392         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2393                                 VarDecl::TentativeDefinition
2394                             ? diag::err_alias_after_tentative
2395                             : diag::err_redefinition;
2396         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2397         S.Diag(Def->getLocation(), diag::note_previous_definition);
2398         VD->setInvalidDecl();
2399       }
2400       ++I;
2401       continue;
2402     }
2403
2404     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2405       // Tentative definitions are only interesting for the alias check above.
2406       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2407         ++I;
2408         continue;
2409       }
2410     }
2411
2412     if (hasAttribute(Def, NewAttribute->getKind())) {
2413       ++I;
2414       continue; // regular attr merging will take care of validating this.
2415     }
2416
2417     if (isa<C11NoReturnAttr>(NewAttribute)) {
2418       // C's _Noreturn is allowed to be added to a function after it is defined.
2419       ++I;
2420       continue;
2421     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2422       if (AA->isAlignas()) {
2423         // C++11 [dcl.align]p6:
2424         //   if any declaration of an entity has an alignment-specifier,
2425         //   every defining declaration of that entity shall specify an
2426         //   equivalent alignment.
2427         // C11 6.7.5/7:
2428         //   If the definition of an object does not have an alignment
2429         //   specifier, any other declaration of that object shall also
2430         //   have no alignment specifier.
2431         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2432           << AA;
2433         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2434           << AA;
2435         NewAttributes.erase(NewAttributes.begin() + I);
2436         --E;
2437         continue;
2438       }
2439     }
2440
2441     S.Diag(NewAttribute->getLocation(),
2442            diag::warn_attribute_precede_definition);
2443     S.Diag(Def->getLocation(), diag::note_previous_definition);
2444     NewAttributes.erase(NewAttributes.begin() + I);
2445     --E;
2446   }
2447 }
2448
2449 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2450 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2451                                AvailabilityMergeKind AMK) {
2452   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2453     UsedAttr *NewAttr = OldAttr->clone(Context);
2454     NewAttr->setInherited(true);
2455     New->addAttr(NewAttr);
2456   }
2457
2458   if (!Old->hasAttrs() && !New->hasAttrs())
2459     return;
2460
2461   // Attributes declared post-definition are currently ignored.
2462   checkNewAttributesAfterDef(*this, New, Old);
2463
2464   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2465     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2466       if (OldA->getLabel() != NewA->getLabel()) {
2467         // This redeclaration changes __asm__ label.
2468         Diag(New->getLocation(), diag::err_different_asm_label);
2469         Diag(OldA->getLocation(), diag::note_previous_declaration);
2470       }
2471     } else if (Old->isUsed()) {
2472       // This redeclaration adds an __asm__ label to a declaration that has
2473       // already been ODR-used.
2474       Diag(New->getLocation(), diag::err_late_asm_label_name)
2475         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2476     }
2477   }
2478
2479   // Re-declaration cannot add abi_tag's.
2480   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2481     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2482       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2483         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2484                       NewTag) == OldAbiTagAttr->tags_end()) {
2485           Diag(NewAbiTagAttr->getLocation(),
2486                diag::err_new_abi_tag_on_redeclaration)
2487               << NewTag;
2488           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2489         }
2490       }
2491     } else {
2492       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2493       Diag(Old->getLocation(), diag::note_previous_declaration);
2494     }
2495   }
2496
2497   if (!Old->hasAttrs())
2498     return;
2499
2500   bool foundAny = New->hasAttrs();
2501
2502   // Ensure that any moving of objects within the allocated map is done before
2503   // we process them.
2504   if (!foundAny) New->setAttrs(AttrVec());
2505
2506   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2507     // Ignore deprecated/unavailable/availability attributes if requested.
2508     AvailabilityMergeKind LocalAMK = AMK_None;
2509     if (isa<DeprecatedAttr>(I) ||
2510         isa<UnavailableAttr>(I) ||
2511         isa<AvailabilityAttr>(I)) {
2512       switch (AMK) {
2513       case AMK_None:
2514         continue;
2515
2516       case AMK_Redeclaration:
2517       case AMK_Override:
2518       case AMK_ProtocolImplementation:
2519         LocalAMK = AMK;
2520         break;
2521       }
2522     }
2523
2524     // Already handled.
2525     if (isa<UsedAttr>(I))
2526       continue;
2527
2528     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2529       foundAny = true;
2530   }
2531
2532   if (mergeAlignedAttrs(*this, New, Old))
2533     foundAny = true;
2534
2535   if (!foundAny) New->dropAttrs();
2536 }
2537
2538 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2539 /// to the new one.
2540 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2541                                      const ParmVarDecl *oldDecl,
2542                                      Sema &S) {
2543   // C++11 [dcl.attr.depend]p2:
2544   //   The first declaration of a function shall specify the
2545   //   carries_dependency attribute for its declarator-id if any declaration
2546   //   of the function specifies the carries_dependency attribute.
2547   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2548   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2549     S.Diag(CDA->getLocation(),
2550            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2551     // Find the first declaration of the parameter.
2552     // FIXME: Should we build redeclaration chains for function parameters?
2553     const FunctionDecl *FirstFD =
2554       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2555     const ParmVarDecl *FirstVD =
2556       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2557     S.Diag(FirstVD->getLocation(),
2558            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2559   }
2560
2561   if (!oldDecl->hasAttrs())
2562     return;
2563
2564   bool foundAny = newDecl->hasAttrs();
2565
2566   // Ensure that any moving of objects within the allocated map is
2567   // done before we process them.
2568   if (!foundAny) newDecl->setAttrs(AttrVec());
2569
2570   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2571     if (!DeclHasAttr(newDecl, I)) {
2572       InheritableAttr *newAttr =
2573         cast<InheritableParamAttr>(I->clone(S.Context));
2574       newAttr->setInherited(true);
2575       newDecl->addAttr(newAttr);
2576       foundAny = true;
2577     }
2578   }
2579
2580   if (!foundAny) newDecl->dropAttrs();
2581 }
2582
2583 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2584                                 const ParmVarDecl *OldParam,
2585                                 Sema &S) {
2586   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2587     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2588       if (*Oldnullability != *Newnullability) {
2589         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2590           << DiagNullabilityKind(
2591                *Newnullability,
2592                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2593                 != 0))
2594           << DiagNullabilityKind(
2595                *Oldnullability,
2596                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2597                 != 0));
2598         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2599       }
2600     } else {
2601       QualType NewT = NewParam->getType();
2602       NewT = S.Context.getAttributedType(
2603                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2604                          NewT, NewT);
2605       NewParam->setType(NewT);
2606     }
2607   }
2608 }
2609
2610 namespace {
2611
2612 /// Used in MergeFunctionDecl to keep track of function parameters in
2613 /// C.
2614 struct GNUCompatibleParamWarning {
2615   ParmVarDecl *OldParm;
2616   ParmVarDecl *NewParm;
2617   QualType PromotedType;
2618 };
2619
2620 } // end anonymous namespace
2621
2622 /// getSpecialMember - get the special member enum for a method.
2623 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2624   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2625     if (Ctor->isDefaultConstructor())
2626       return Sema::CXXDefaultConstructor;
2627
2628     if (Ctor->isCopyConstructor())
2629       return Sema::CXXCopyConstructor;
2630
2631     if (Ctor->isMoveConstructor())
2632       return Sema::CXXMoveConstructor;
2633   } else if (isa<CXXDestructorDecl>(MD)) {
2634     return Sema::CXXDestructor;
2635   } else if (MD->isCopyAssignmentOperator()) {
2636     return Sema::CXXCopyAssignment;
2637   } else if (MD->isMoveAssignmentOperator()) {
2638     return Sema::CXXMoveAssignment;
2639   }
2640
2641   return Sema::CXXInvalid;
2642 }
2643
2644 // Determine whether the previous declaration was a definition, implicit
2645 // declaration, or a declaration.
2646 template <typename T>
2647 static std::pair<diag::kind, SourceLocation>
2648 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2649   diag::kind PrevDiag;
2650   SourceLocation OldLocation = Old->getLocation();
2651   if (Old->isThisDeclarationADefinition())
2652     PrevDiag = diag::note_previous_definition;
2653   else if (Old->isImplicit()) {
2654     PrevDiag = diag::note_previous_implicit_declaration;
2655     if (OldLocation.isInvalid())
2656       OldLocation = New->getLocation();
2657   } else
2658     PrevDiag = diag::note_previous_declaration;
2659   return std::make_pair(PrevDiag, OldLocation);
2660 }
2661
2662 /// canRedefineFunction - checks if a function can be redefined. Currently,
2663 /// only extern inline functions can be redefined, and even then only in
2664 /// GNU89 mode.
2665 static bool canRedefineFunction(const FunctionDecl *FD,
2666                                 const LangOptions& LangOpts) {
2667   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2668           !LangOpts.CPlusPlus &&
2669           FD->isInlineSpecified() &&
2670           FD->getStorageClass() == SC_Extern);
2671 }
2672
2673 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2674   const AttributedType *AT = T->getAs<AttributedType>();
2675   while (AT && !AT->isCallingConv())
2676     AT = AT->getModifiedType()->getAs<AttributedType>();
2677   return AT;
2678 }
2679
2680 template <typename T>
2681 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2682   const DeclContext *DC = Old->getDeclContext();
2683   if (DC->isRecord())
2684     return false;
2685
2686   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2687   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2688     return true;
2689   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2690     return true;
2691   return false;
2692 }
2693
2694 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2695 static bool isExternC(VarTemplateDecl *) { return false; }
2696
2697 /// \brief Check whether a redeclaration of an entity introduced by a
2698 /// using-declaration is valid, given that we know it's not an overload
2699 /// (nor a hidden tag declaration).
2700 template<typename ExpectedDecl>
2701 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2702                                    ExpectedDecl *New) {
2703   // C++11 [basic.scope.declarative]p4:
2704   //   Given a set of declarations in a single declarative region, each of
2705   //   which specifies the same unqualified name,
2706   //   -- they shall all refer to the same entity, or all refer to functions
2707   //      and function templates; or
2708   //   -- exactly one declaration shall declare a class name or enumeration
2709   //      name that is not a typedef name and the other declarations shall all
2710   //      refer to the same variable or enumerator, or all refer to functions
2711   //      and function templates; in this case the class name or enumeration
2712   //      name is hidden (3.3.10).
2713
2714   // C++11 [namespace.udecl]p14:
2715   //   If a function declaration in namespace scope or block scope has the
2716   //   same name and the same parameter-type-list as a function introduced
2717   //   by a using-declaration, and the declarations do not declare the same
2718   //   function, the program is ill-formed.
2719
2720   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2721   if (Old &&
2722       !Old->getDeclContext()->getRedeclContext()->Equals(
2723           New->getDeclContext()->getRedeclContext()) &&
2724       !(isExternC(Old) && isExternC(New)))
2725     Old = nullptr;
2726
2727   if (!Old) {
2728     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2729     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2730     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2731     return true;
2732   }
2733   return false;
2734 }
2735
2736 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2737                                             const FunctionDecl *B) {
2738   assert(A->getNumParams() == B->getNumParams());
2739
2740   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2741     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2742     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2743     if (AttrA == AttrB)
2744       return true;
2745     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2746   };
2747
2748   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2749 }
2750
2751 /// MergeFunctionDecl - We just parsed a function 'New' from
2752 /// declarator D which has the same name and scope as a previous
2753 /// declaration 'Old'.  Figure out how to resolve this situation,
2754 /// merging decls or emitting diagnostics as appropriate.
2755 ///
2756 /// In C++, New and Old must be declarations that are not
2757 /// overloaded. Use IsOverload to determine whether New and Old are
2758 /// overloaded, and to select the Old declaration that New should be
2759 /// merged with.
2760 ///
2761 /// Returns true if there was an error, false otherwise.
2762 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2763                              Scope *S, bool MergeTypeWithOld) {
2764   // Verify the old decl was also a function.
2765   FunctionDecl *Old = OldD->getAsFunction();
2766   if (!Old) {
2767     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2768       if (New->getFriendObjectKind()) {
2769         Diag(New->getLocation(), diag::err_using_decl_friend);
2770         Diag(Shadow->getTargetDecl()->getLocation(),
2771              diag::note_using_decl_target);
2772         Diag(Shadow->getUsingDecl()->getLocation(),
2773              diag::note_using_decl) << 0;
2774         return true;
2775       }
2776
2777       // Check whether the two declarations might declare the same function.
2778       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2779         return true;
2780       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2781     } else {
2782       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2783         << New->getDeclName();
2784       Diag(OldD->getLocation(), diag::note_previous_definition);
2785       return true;
2786     }
2787   }
2788
2789   // If the old declaration is invalid, just give up here.
2790   if (Old->isInvalidDecl())
2791     return true;
2792
2793   diag::kind PrevDiag;
2794   SourceLocation OldLocation;
2795   std::tie(PrevDiag, OldLocation) =
2796       getNoteDiagForInvalidRedeclaration(Old, New);
2797
2798   // Don't complain about this if we're in GNU89 mode and the old function
2799   // is an extern inline function.
2800   // Don't complain about specializations. They are not supposed to have
2801   // storage classes.
2802   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2803       New->getStorageClass() == SC_Static &&
2804       Old->hasExternalFormalLinkage() &&
2805       !New->getTemplateSpecializationInfo() &&
2806       !canRedefineFunction(Old, getLangOpts())) {
2807     if (getLangOpts().MicrosoftExt) {
2808       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2809       Diag(OldLocation, PrevDiag);
2810     } else {
2811       Diag(New->getLocation(), diag::err_static_non_static) << New;
2812       Diag(OldLocation, PrevDiag);
2813       return true;
2814     }
2815   }
2816
2817   if (New->hasAttr<InternalLinkageAttr>() &&
2818       !Old->hasAttr<InternalLinkageAttr>()) {
2819     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2820         << New->getDeclName();
2821     Diag(Old->getLocation(), diag::note_previous_definition);
2822     New->dropAttr<InternalLinkageAttr>();
2823   }
2824
2825   // If a function is first declared with a calling convention, but is later
2826   // declared or defined without one, all following decls assume the calling
2827   // convention of the first.
2828   //
2829   // It's OK if a function is first declared without a calling convention,
2830   // but is later declared or defined with the default calling convention.
2831   //
2832   // To test if either decl has an explicit calling convention, we look for
2833   // AttributedType sugar nodes on the type as written.  If they are missing or
2834   // were canonicalized away, we assume the calling convention was implicit.
2835   //
2836   // Note also that we DO NOT return at this point, because we still have
2837   // other tests to run.
2838   QualType OldQType = Context.getCanonicalType(Old->getType());
2839   QualType NewQType = Context.getCanonicalType(New->getType());
2840   const FunctionType *OldType = cast<FunctionType>(OldQType);
2841   const FunctionType *NewType = cast<FunctionType>(NewQType);
2842   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2843   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2844   bool RequiresAdjustment = false;
2845
2846   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2847     FunctionDecl *First = Old->getFirstDecl();
2848     const FunctionType *FT =
2849         First->getType().getCanonicalType()->castAs<FunctionType>();
2850     FunctionType::ExtInfo FI = FT->getExtInfo();
2851     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2852     if (!NewCCExplicit) {
2853       // Inherit the CC from the previous declaration if it was specified
2854       // there but not here.
2855       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2856       RequiresAdjustment = true;
2857     } else {
2858       // Calling conventions aren't compatible, so complain.
2859       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2860       Diag(New->getLocation(), diag::err_cconv_change)
2861         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2862         << !FirstCCExplicit
2863         << (!FirstCCExplicit ? "" :
2864             FunctionType::getNameForCallConv(FI.getCC()));
2865
2866       // Put the note on the first decl, since it is the one that matters.
2867       Diag(First->getLocation(), diag::note_previous_declaration);
2868       return true;
2869     }
2870   }
2871
2872   // FIXME: diagnose the other way around?
2873   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2874     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2875     RequiresAdjustment = true;
2876   }
2877
2878   // Merge regparm attribute.
2879   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2880       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2881     if (NewTypeInfo.getHasRegParm()) {
2882       Diag(New->getLocation(), diag::err_regparm_mismatch)
2883         << NewType->getRegParmType()
2884         << OldType->getRegParmType();
2885       Diag(OldLocation, diag::note_previous_declaration);
2886       return true;
2887     }
2888
2889     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2890     RequiresAdjustment = true;
2891   }
2892
2893   // Merge ns_returns_retained attribute.
2894   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2895     if (NewTypeInfo.getProducesResult()) {
2896       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2897       Diag(OldLocation, diag::note_previous_declaration);
2898       return true;
2899     }
2900
2901     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2902     RequiresAdjustment = true;
2903   }
2904
2905   if (RequiresAdjustment) {
2906     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2907     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2908     New->setType(QualType(AdjustedType, 0));
2909     NewQType = Context.getCanonicalType(New->getType());
2910     NewType = cast<FunctionType>(NewQType);
2911   }
2912
2913   // If this redeclaration makes the function inline, we may need to add it to
2914   // UndefinedButUsed.
2915   if (!Old->isInlined() && New->isInlined() &&
2916       !New->hasAttr<GNUInlineAttr>() &&
2917       !getLangOpts().GNUInline &&
2918       Old->isUsed(false) &&
2919       !Old->isDefined() && !New->isThisDeclarationADefinition())
2920     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2921                                            SourceLocation()));
2922
2923   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2924   // about it.
2925   if (New->hasAttr<GNUInlineAttr>() &&
2926       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2927     UndefinedButUsed.erase(Old->getCanonicalDecl());
2928   }
2929
2930   // If pass_object_size params don't match up perfectly, this isn't a valid
2931   // redeclaration.
2932   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2933       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2934     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2935         << New->getDeclName();
2936     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2937     return true;
2938   }
2939
2940   if (getLangOpts().CPlusPlus) {
2941     // C++1z [over.load]p2
2942     //   Certain function declarations cannot be overloaded:
2943     //     -- Function declarations that differ only in the return type,
2944     //        the exception specification, or both cannot be overloaded.
2945
2946     // Check the exception specifications match. This may recompute the type of
2947     // both Old and New if it resolved exception specifications, so grab the
2948     // types again after this. Because this updates the type, we do this before
2949     // any of the other checks below, which may update the "de facto" NewQType
2950     // but do not necessarily update the type of New.
2951     if (CheckEquivalentExceptionSpec(Old, New))
2952       return true;
2953     OldQType = Context.getCanonicalType(Old->getType());
2954     NewQType = Context.getCanonicalType(New->getType());
2955
2956     // Go back to the type source info to compare the declared return types,
2957     // per C++1y [dcl.type.auto]p13:
2958     //   Redeclarations or specializations of a function or function template
2959     //   with a declared return type that uses a placeholder type shall also
2960     //   use that placeholder, not a deduced type.
2961     QualType OldDeclaredReturnType =
2962         (Old->getTypeSourceInfo()
2963              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2964              : OldType)->getReturnType();
2965     QualType NewDeclaredReturnType =
2966         (New->getTypeSourceInfo()
2967              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2968              : NewType)->getReturnType();
2969     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2970         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2971           New->isLocalExternDecl())) {
2972       QualType ResQT;
2973       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2974           OldDeclaredReturnType->isObjCObjectPointerType())
2975         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2976       if (ResQT.isNull()) {
2977         if (New->isCXXClassMember() && New->isOutOfLine())
2978           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2979               << New << New->getReturnTypeSourceRange();
2980         else
2981           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2982               << New->getReturnTypeSourceRange();
2983         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2984                                     << Old->getReturnTypeSourceRange();
2985         return true;
2986       }
2987       else
2988         NewQType = ResQT;
2989     }
2990
2991     QualType OldReturnType = OldType->getReturnType();
2992     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2993     if (OldReturnType != NewReturnType) {
2994       // If this function has a deduced return type and has already been
2995       // defined, copy the deduced value from the old declaration.
2996       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2997       if (OldAT && OldAT->isDeduced()) {
2998         New->setType(
2999             SubstAutoType(New->getType(),
3000                           OldAT->isDependentType() ? Context.DependentTy
3001                                                    : OldAT->getDeducedType()));
3002         NewQType = Context.getCanonicalType(
3003             SubstAutoType(NewQType,
3004                           OldAT->isDependentType() ? Context.DependentTy
3005                                                    : OldAT->getDeducedType()));
3006       }
3007     }
3008
3009     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3010     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3011     if (OldMethod && NewMethod) {
3012       // Preserve triviality.
3013       NewMethod->setTrivial(OldMethod->isTrivial());
3014
3015       // MSVC allows explicit template specialization at class scope:
3016       // 2 CXXMethodDecls referring to the same function will be injected.
3017       // We don't want a redeclaration error.
3018       bool IsClassScopeExplicitSpecialization =
3019                               OldMethod->isFunctionTemplateSpecialization() &&
3020                               NewMethod->isFunctionTemplateSpecialization();
3021       bool isFriend = NewMethod->getFriendObjectKind();
3022
3023       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3024           !IsClassScopeExplicitSpecialization) {
3025         //    -- Member function declarations with the same name and the
3026         //       same parameter types cannot be overloaded if any of them
3027         //       is a static member function declaration.
3028         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3029           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3030           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3031           return true;
3032         }
3033
3034         // C++ [class.mem]p1:
3035         //   [...] A member shall not be declared twice in the
3036         //   member-specification, except that a nested class or member
3037         //   class template can be declared and then later defined.
3038         if (ActiveTemplateInstantiations.empty()) {
3039           unsigned NewDiag;
3040           if (isa<CXXConstructorDecl>(OldMethod))
3041             NewDiag = diag::err_constructor_redeclared;
3042           else if (isa<CXXDestructorDecl>(NewMethod))
3043             NewDiag = diag::err_destructor_redeclared;
3044           else if (isa<CXXConversionDecl>(NewMethod))
3045             NewDiag = diag::err_conv_function_redeclared;
3046           else
3047             NewDiag = diag::err_member_redeclared;
3048
3049           Diag(New->getLocation(), NewDiag);
3050         } else {
3051           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3052             << New << New->getType();
3053         }
3054         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3055         return true;
3056
3057       // Complain if this is an explicit declaration of a special
3058       // member that was initially declared implicitly.
3059       //
3060       // As an exception, it's okay to befriend such methods in order
3061       // to permit the implicit constructor/destructor/operator calls.
3062       } else if (OldMethod->isImplicit()) {
3063         if (isFriend) {
3064           NewMethod->setImplicit();
3065         } else {
3066           Diag(NewMethod->getLocation(),
3067                diag::err_definition_of_implicitly_declared_member)
3068             << New << getSpecialMember(OldMethod);
3069           return true;
3070         }
3071       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3072         Diag(NewMethod->getLocation(),
3073              diag::err_definition_of_explicitly_defaulted_member)
3074           << getSpecialMember(OldMethod);
3075         return true;
3076       }
3077     }
3078
3079     // C++11 [dcl.attr.noreturn]p1:
3080     //   The first declaration of a function shall specify the noreturn
3081     //   attribute if any declaration of that function specifies the noreturn
3082     //   attribute.
3083     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3084     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3085       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3086       Diag(Old->getFirstDecl()->getLocation(),
3087            diag::note_noreturn_missing_first_decl);
3088     }
3089
3090     // C++11 [dcl.attr.depend]p2:
3091     //   The first declaration of a function shall specify the
3092     //   carries_dependency attribute for its declarator-id if any declaration
3093     //   of the function specifies the carries_dependency attribute.
3094     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3095     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3096       Diag(CDA->getLocation(),
3097            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3098       Diag(Old->getFirstDecl()->getLocation(),
3099            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3100     }
3101
3102     // (C++98 8.3.5p3):
3103     //   All declarations for a function shall agree exactly in both the
3104     //   return type and the parameter-type-list.
3105     // We also want to respect all the extended bits except noreturn.
3106
3107     // noreturn should now match unless the old type info didn't have it.
3108     QualType OldQTypeForComparison = OldQType;
3109     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3110       auto *OldType = OldQType->castAs<FunctionProtoType>();
3111       const FunctionType *OldTypeForComparison
3112         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3113       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3114       assert(OldQTypeForComparison.isCanonical());
3115     }
3116
3117     if (haveIncompatibleLanguageLinkages(Old, New)) {
3118       // As a special case, retain the language linkage from previous
3119       // declarations of a friend function as an extension.
3120       //
3121       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3122       // and is useful because there's otherwise no way to specify language
3123       // linkage within class scope.
3124       //
3125       // Check cautiously as the friend object kind isn't yet complete.
3126       if (New->getFriendObjectKind() != Decl::FOK_None) {
3127         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3128         Diag(OldLocation, PrevDiag);
3129       } else {
3130         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3131         Diag(OldLocation, PrevDiag);
3132         return true;
3133       }
3134     }
3135
3136     if (OldQTypeForComparison == NewQType)
3137       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3138
3139     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3140         New->isLocalExternDecl()) {
3141       // It's OK if we couldn't merge types for a local function declaraton
3142       // if either the old or new type is dependent. We'll merge the types
3143       // when we instantiate the function.
3144       return false;
3145     }
3146
3147     // Fall through for conflicting redeclarations and redefinitions.
3148   }
3149
3150   // C: Function types need to be compatible, not identical. This handles
3151   // duplicate function decls like "void f(int); void f(enum X);" properly.
3152   if (!getLangOpts().CPlusPlus &&
3153       Context.typesAreCompatible(OldQType, NewQType)) {
3154     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3155     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3156     const FunctionProtoType *OldProto = nullptr;
3157     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3158         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3159       // The old declaration provided a function prototype, but the
3160       // new declaration does not. Merge in the prototype.
3161       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3162       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3163       NewQType =
3164           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3165                                   OldProto->getExtProtoInfo());
3166       New->setType(NewQType);
3167       New->setHasInheritedPrototype();
3168
3169       // Synthesize parameters with the same types.
3170       SmallVector<ParmVarDecl*, 16> Params;
3171       for (const auto &ParamType : OldProto->param_types()) {
3172         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3173                                                  SourceLocation(), nullptr,
3174                                                  ParamType, /*TInfo=*/nullptr,
3175                                                  SC_None, nullptr);
3176         Param->setScopeInfo(0, Params.size());
3177         Param->setImplicit();
3178         Params.push_back(Param);
3179       }
3180
3181       New->setParams(Params);
3182     }
3183
3184     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3185   }
3186
3187   // GNU C permits a K&R definition to follow a prototype declaration
3188   // if the declared types of the parameters in the K&R definition
3189   // match the types in the prototype declaration, even when the
3190   // promoted types of the parameters from the K&R definition differ
3191   // from the types in the prototype. GCC then keeps the types from
3192   // the prototype.
3193   //
3194   // If a variadic prototype is followed by a non-variadic K&R definition,
3195   // the K&R definition becomes variadic.  This is sort of an edge case, but
3196   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3197   // C99 6.9.1p8.
3198   if (!getLangOpts().CPlusPlus &&
3199       Old->hasPrototype() && !New->hasPrototype() &&
3200       New->getType()->getAs<FunctionProtoType>() &&
3201       Old->getNumParams() == New->getNumParams()) {
3202     SmallVector<QualType, 16> ArgTypes;
3203     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3204     const FunctionProtoType *OldProto
3205       = Old->getType()->getAs<FunctionProtoType>();
3206     const FunctionProtoType *NewProto
3207       = New->getType()->getAs<FunctionProtoType>();
3208
3209     // Determine whether this is the GNU C extension.
3210     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3211                                                NewProto->getReturnType());
3212     bool LooseCompatible = !MergedReturn.isNull();
3213     for (unsigned Idx = 0, End = Old->getNumParams();
3214          LooseCompatible && Idx != End; ++Idx) {
3215       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3216       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3217       if (Context.typesAreCompatible(OldParm->getType(),
3218                                      NewProto->getParamType(Idx))) {
3219         ArgTypes.push_back(NewParm->getType());
3220       } else if (Context.typesAreCompatible(OldParm->getType(),
3221                                             NewParm->getType(),
3222                                             /*CompareUnqualified=*/true)) {
3223         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3224                                            NewProto->getParamType(Idx) };
3225         Warnings.push_back(Warn);
3226         ArgTypes.push_back(NewParm->getType());
3227       } else
3228         LooseCompatible = false;
3229     }
3230
3231     if (LooseCompatible) {
3232       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3233         Diag(Warnings[Warn].NewParm->getLocation(),
3234              diag::ext_param_promoted_not_compatible_with_prototype)
3235           << Warnings[Warn].PromotedType
3236           << Warnings[Warn].OldParm->getType();
3237         if (Warnings[Warn].OldParm->getLocation().isValid())
3238           Diag(Warnings[Warn].OldParm->getLocation(),
3239                diag::note_previous_declaration);
3240       }
3241
3242       if (MergeTypeWithOld)
3243         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3244                                              OldProto->getExtProtoInfo()));
3245       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3246     }
3247
3248     // Fall through to diagnose conflicting types.
3249   }
3250
3251   // A function that has already been declared has been redeclared or
3252   // defined with a different type; show an appropriate diagnostic.
3253
3254   // If the previous declaration was an implicitly-generated builtin
3255   // declaration, then at the very least we should use a specialized note.
3256   unsigned BuiltinID;
3257   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3258     // If it's actually a library-defined builtin function like 'malloc'
3259     // or 'printf', just warn about the incompatible redeclaration.
3260     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3261       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3262       Diag(OldLocation, diag::note_previous_builtin_declaration)
3263         << Old << Old->getType();
3264
3265       // If this is a global redeclaration, just forget hereafter
3266       // about the "builtin-ness" of the function.
3267       //
3268       // Doing this for local extern declarations is problematic.  If
3269       // the builtin declaration remains visible, a second invalid
3270       // local declaration will produce a hard error; if it doesn't
3271       // remain visible, a single bogus local redeclaration (which is
3272       // actually only a warning) could break all the downstream code.
3273       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3274         New->getIdentifier()->revertBuiltin();
3275
3276       return false;
3277     }
3278
3279     PrevDiag = diag::note_previous_builtin_declaration;
3280   }
3281
3282   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3283   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3284   return true;
3285 }
3286
3287 /// \brief Completes the merge of two function declarations that are
3288 /// known to be compatible.
3289 ///
3290 /// This routine handles the merging of attributes and other
3291 /// properties of function declarations from the old declaration to
3292 /// the new declaration, once we know that New is in fact a
3293 /// redeclaration of Old.
3294 ///
3295 /// \returns false
3296 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3297                                         Scope *S, bool MergeTypeWithOld) {
3298   // Merge the attributes
3299   mergeDeclAttributes(New, Old);
3300
3301   // Merge "pure" flag.
3302   if (Old->isPure())
3303     New->setPure();
3304
3305   // Merge "used" flag.
3306   if (Old->getMostRecentDecl()->isUsed(false))
3307     New->setIsUsed();
3308
3309   // Merge attributes from the parameters.  These can mismatch with K&R
3310   // declarations.
3311   if (New->getNumParams() == Old->getNumParams())
3312       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3313         ParmVarDecl *NewParam = New->getParamDecl(i);
3314         ParmVarDecl *OldParam = Old->getParamDecl(i);
3315         mergeParamDeclAttributes(NewParam, OldParam, *this);
3316         mergeParamDeclTypes(NewParam, OldParam, *this);
3317       }
3318
3319   if (getLangOpts().CPlusPlus)
3320     return MergeCXXFunctionDecl(New, Old, S);
3321
3322   // Merge the function types so the we get the composite types for the return
3323   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3324   // was visible.
3325   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3326   if (!Merged.isNull() && MergeTypeWithOld)
3327     New->setType(Merged);
3328
3329   return false;
3330 }
3331
3332 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3333                                 ObjCMethodDecl *oldMethod) {
3334   // Merge the attributes, including deprecated/unavailable
3335   AvailabilityMergeKind MergeKind =
3336     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3337       ? AMK_ProtocolImplementation
3338       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3339                                                        : AMK_Override;
3340
3341   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3342
3343   // Merge attributes from the parameters.
3344   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3345                                        oe = oldMethod->param_end();
3346   for (ObjCMethodDecl::param_iterator
3347          ni = newMethod->param_begin(), ne = newMethod->param_end();
3348        ni != ne && oi != oe; ++ni, ++oi)
3349     mergeParamDeclAttributes(*ni, *oi, *this);
3350
3351   CheckObjCMethodOverride(newMethod, oldMethod);
3352 }
3353
3354 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3355   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3356
3357   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3358          ? diag::err_redefinition_different_type
3359          : diag::err_redeclaration_different_type)
3360     << New->getDeclName() << New->getType() << Old->getType();
3361
3362   diag::kind PrevDiag;
3363   SourceLocation OldLocation;
3364   std::tie(PrevDiag, OldLocation)
3365     = getNoteDiagForInvalidRedeclaration(Old, New);
3366   S.Diag(OldLocation, PrevDiag);
3367   New->setInvalidDecl();
3368 }
3369
3370 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3371 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3372 /// emitting diagnostics as appropriate.
3373 ///
3374 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3375 /// to here in AddInitializerToDecl. We can't check them before the initializer
3376 /// is attached.
3377 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3378                              bool MergeTypeWithOld) {
3379   if (New->isInvalidDecl() || Old->isInvalidDecl())
3380     return;
3381
3382   QualType MergedT;
3383   if (getLangOpts().CPlusPlus) {
3384     if (New->getType()->isUndeducedType()) {
3385       // We don't know what the new type is until the initializer is attached.
3386       return;
3387     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3388       // These could still be something that needs exception specs checked.
3389       return MergeVarDeclExceptionSpecs(New, Old);
3390     }
3391     // C++ [basic.link]p10:
3392     //   [...] the types specified by all declarations referring to a given
3393     //   object or function shall be identical, except that declarations for an
3394     //   array object can specify array types that differ by the presence or
3395     //   absence of a major array bound (8.3.4).
3396     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3397       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3398       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3399
3400       // We are merging a variable declaration New into Old. If it has an array
3401       // bound, and that bound differs from Old's bound, we should diagnose the
3402       // mismatch.
3403       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3404         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3405              PrevVD = PrevVD->getPreviousDecl()) {
3406           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3407           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3408             continue;
3409
3410           if (!Context.hasSameType(NewArray, PrevVDTy))
3411             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3412         }
3413       }
3414
3415       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3416         if (Context.hasSameType(OldArray->getElementType(),
3417                                 NewArray->getElementType()))
3418           MergedT = New->getType();
3419       }
3420       // FIXME: Check visibility. New is hidden but has a complete type. If New
3421       // has no array bound, it should not inherit one from Old, if Old is not
3422       // visible.
3423       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3424         if (Context.hasSameType(OldArray->getElementType(),
3425                                 NewArray->getElementType()))
3426           MergedT = Old->getType();
3427       }
3428     }
3429     else if (New->getType()->isObjCObjectPointerType() &&
3430                Old->getType()->isObjCObjectPointerType()) {
3431       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3432                                               Old->getType());
3433     }
3434   } else {
3435     // C 6.2.7p2:
3436     //   All declarations that refer to the same object or function shall have
3437     //   compatible type.
3438     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3439   }
3440   if (MergedT.isNull()) {
3441     // It's OK if we couldn't merge types if either type is dependent, for a
3442     // block-scope variable. In other cases (static data members of class
3443     // templates, variable templates, ...), we require the types to be
3444     // equivalent.
3445     // FIXME: The C++ standard doesn't say anything about this.
3446     if ((New->getType()->isDependentType() ||
3447          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3448       // If the old type was dependent, we can't merge with it, so the new type
3449       // becomes dependent for now. We'll reproduce the original type when we
3450       // instantiate the TypeSourceInfo for the variable.
3451       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3452         New->setType(Context.DependentTy);
3453       return;
3454     }
3455     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3456   }
3457
3458   // Don't actually update the type on the new declaration if the old
3459   // declaration was an extern declaration in a different scope.
3460   if (MergeTypeWithOld)
3461     New->setType(MergedT);
3462 }
3463
3464 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3465                                   LookupResult &Previous) {
3466   // C11 6.2.7p4:
3467   //   For an identifier with internal or external linkage declared
3468   //   in a scope in which a prior declaration of that identifier is
3469   //   visible, if the prior declaration specifies internal or
3470   //   external linkage, the type of the identifier at the later
3471   //   declaration becomes the composite type.
3472   //
3473   // If the variable isn't visible, we do not merge with its type.
3474   if (Previous.isShadowed())
3475     return false;
3476
3477   if (S.getLangOpts().CPlusPlus) {
3478     // C++11 [dcl.array]p3:
3479     //   If there is a preceding declaration of the entity in the same
3480     //   scope in which the bound was specified, an omitted array bound
3481     //   is taken to be the same as in that earlier declaration.
3482     return NewVD->isPreviousDeclInSameBlockScope() ||
3483            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3484             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3485   } else {
3486     // If the old declaration was function-local, don't merge with its
3487     // type unless we're in the same function.
3488     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3489            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3490   }
3491 }
3492
3493 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3494 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3495 /// situation, merging decls or emitting diagnostics as appropriate.
3496 ///
3497 /// Tentative definition rules (C99 6.9.2p2) are checked by
3498 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3499 /// definitions here, since the initializer hasn't been attached.
3500 ///
3501 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3502   // If the new decl is already invalid, don't do any other checking.
3503   if (New->isInvalidDecl())
3504     return;
3505
3506   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3507     return;
3508
3509   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3510
3511   // Verify the old decl was also a variable or variable template.
3512   VarDecl *Old = nullptr;
3513   VarTemplateDecl *OldTemplate = nullptr;
3514   if (Previous.isSingleResult()) {
3515     if (NewTemplate) {
3516       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3517       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3518
3519       if (auto *Shadow =
3520               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3521         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3522           return New->setInvalidDecl();
3523     } else {
3524       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3525
3526       if (auto *Shadow =
3527               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3528         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3529           return New->setInvalidDecl();
3530     }
3531   }
3532   if (!Old) {
3533     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3534       << New->getDeclName();
3535     Diag(Previous.getRepresentativeDecl()->getLocation(),
3536          diag::note_previous_definition);
3537     return New->setInvalidDecl();
3538   }
3539
3540   // Ensure the template parameters are compatible.
3541   if (NewTemplate &&
3542       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3543                                       OldTemplate->getTemplateParameters(),
3544                                       /*Complain=*/true, TPL_TemplateMatch))
3545     return New->setInvalidDecl();
3546
3547   // C++ [class.mem]p1:
3548   //   A member shall not be declared twice in the member-specification [...]
3549   //
3550   // Here, we need only consider static data members.
3551   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3552     Diag(New->getLocation(), diag::err_duplicate_member)
3553       << New->getIdentifier();
3554     Diag(Old->getLocation(), diag::note_previous_declaration);
3555     New->setInvalidDecl();
3556   }
3557
3558   mergeDeclAttributes(New, Old);
3559   // Warn if an already-declared variable is made a weak_import in a subsequent
3560   // declaration
3561   if (New->hasAttr<WeakImportAttr>() &&
3562       Old->getStorageClass() == SC_None &&
3563       !Old->hasAttr<WeakImportAttr>()) {
3564     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3565     Diag(Old->getLocation(), diag::note_previous_definition);
3566     // Remove weak_import attribute on new declaration.
3567     New->dropAttr<WeakImportAttr>();
3568   }
3569
3570   if (New->hasAttr<InternalLinkageAttr>() &&
3571       !Old->hasAttr<InternalLinkageAttr>()) {
3572     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3573         << New->getDeclName();
3574     Diag(Old->getLocation(), diag::note_previous_definition);
3575     New->dropAttr<InternalLinkageAttr>();
3576   }
3577
3578   // Merge the types.
3579   VarDecl *MostRecent = Old->getMostRecentDecl();
3580   if (MostRecent != Old) {
3581     MergeVarDeclTypes(New, MostRecent,
3582                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3583     if (New->isInvalidDecl())
3584       return;
3585   }
3586
3587   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3588   if (New->isInvalidDecl())
3589     return;
3590
3591   diag::kind PrevDiag;
3592   SourceLocation OldLocation;
3593   std::tie(PrevDiag, OldLocation) =
3594       getNoteDiagForInvalidRedeclaration(Old, New);
3595
3596   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3597   if (New->getStorageClass() == SC_Static &&
3598       !New->isStaticDataMember() &&
3599       Old->hasExternalFormalLinkage()) {
3600     if (getLangOpts().MicrosoftExt) {
3601       Diag(New->getLocation(), diag::ext_static_non_static)
3602           << New->getDeclName();
3603       Diag(OldLocation, PrevDiag);
3604     } else {
3605       Diag(New->getLocation(), diag::err_static_non_static)
3606           << New->getDeclName();
3607       Diag(OldLocation, PrevDiag);
3608       return New->setInvalidDecl();
3609     }
3610   }
3611   // C99 6.2.2p4:
3612   //   For an identifier declared with the storage-class specifier
3613   //   extern in a scope in which a prior declaration of that
3614   //   identifier is visible,23) if the prior declaration specifies
3615   //   internal or external linkage, the linkage of the identifier at
3616   //   the later declaration is the same as the linkage specified at
3617   //   the prior declaration. If no prior declaration is visible, or
3618   //   if the prior declaration specifies no linkage, then the
3619   //   identifier has external linkage.
3620   if (New->hasExternalStorage() && Old->hasLinkage())
3621     /* Okay */;
3622   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3623            !New->isStaticDataMember() &&
3624            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3625     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3626     Diag(OldLocation, PrevDiag);
3627     return New->setInvalidDecl();
3628   }
3629
3630   // Check if extern is followed by non-extern and vice-versa.
3631   if (New->hasExternalStorage() &&
3632       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3633     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3634     Diag(OldLocation, PrevDiag);
3635     return New->setInvalidDecl();
3636   }
3637   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3638       !New->hasExternalStorage()) {
3639     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3640     Diag(OldLocation, PrevDiag);
3641     return New->setInvalidDecl();
3642   }
3643
3644   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3645
3646   // FIXME: The test for external storage here seems wrong? We still
3647   // need to check for mismatches.
3648   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3649       // Don't complain about out-of-line definitions of static members.
3650       !(Old->getLexicalDeclContext()->isRecord() &&
3651         !New->getLexicalDeclContext()->isRecord())) {
3652     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3653     Diag(OldLocation, PrevDiag);
3654     return New->setInvalidDecl();
3655   }
3656
3657   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3658     if (VarDecl *Def = Old->getDefinition()) {
3659       // C++1z [dcl.fcn.spec]p4:
3660       //   If the definition of a variable appears in a translation unit before
3661       //   its first declaration as inline, the program is ill-formed.
3662       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3663       Diag(Def->getLocation(), diag::note_previous_definition);
3664     }
3665   }
3666
3667   // If this redeclaration makes the function inline, we may need to add it to
3668   // UndefinedButUsed.
3669   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3670       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3671     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3672                                            SourceLocation()));
3673
3674   if (New->getTLSKind() != Old->getTLSKind()) {
3675     if (!Old->getTLSKind()) {
3676       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3677       Diag(OldLocation, PrevDiag);
3678     } else if (!New->getTLSKind()) {
3679       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3680       Diag(OldLocation, PrevDiag);
3681     } else {
3682       // Do not allow redeclaration to change the variable between requiring
3683       // static and dynamic initialization.
3684       // FIXME: GCC allows this, but uses the TLS keyword on the first
3685       // declaration to determine the kind. Do we need to be compatible here?
3686       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3687         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3688       Diag(OldLocation, PrevDiag);
3689     }
3690   }
3691
3692   // C++ doesn't have tentative definitions, so go right ahead and check here.
3693   if (getLangOpts().CPlusPlus &&
3694       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3695     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3696         Old->getCanonicalDecl()->isConstexpr()) {
3697       // This definition won't be a definition any more once it's been merged.
3698       Diag(New->getLocation(),
3699            diag::warn_deprecated_redundant_constexpr_static_def);
3700     } else if (VarDecl *Def = Old->getDefinition()) {
3701       if (checkVarDeclRedefinition(Def, New))
3702         return;
3703     }
3704   }
3705
3706   if (haveIncompatibleLanguageLinkages(Old, New)) {
3707     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3708     Diag(OldLocation, PrevDiag);
3709     New->setInvalidDecl();
3710     return;
3711   }
3712
3713   // Merge "used" flag.
3714   if (Old->getMostRecentDecl()->isUsed(false))
3715     New->setIsUsed();
3716
3717   // Keep a chain of previous declarations.
3718   New->setPreviousDecl(Old);
3719   if (NewTemplate)
3720     NewTemplate->setPreviousDecl(OldTemplate);
3721
3722   // Inherit access appropriately.
3723   New->setAccess(Old->getAccess());
3724   if (NewTemplate)
3725     NewTemplate->setAccess(New->getAccess());
3726
3727   if (Old->isInline())
3728     New->setImplicitlyInline();
3729 }
3730
3731 /// We've just determined that \p Old and \p New both appear to be definitions
3732 /// of the same variable. Either diagnose or fix the problem.
3733 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3734   if (!hasVisibleDefinition(Old) &&
3735       (New->getFormalLinkage() == InternalLinkage ||
3736        New->isInline() ||
3737        New->getDescribedVarTemplate() ||
3738        New->getNumTemplateParameterLists() ||
3739        New->getDeclContext()->isDependentContext())) {
3740     // The previous definition is hidden, and multiple definitions are
3741     // permitted (in separate TUs). Demote this to a declaration.
3742     New->demoteThisDefinitionToDeclaration();
3743
3744     // Make the canonical definition visible.
3745     if (auto *OldTD = Old->getDescribedVarTemplate())
3746       makeMergedDefinitionVisible(OldTD, New->getLocation());
3747     makeMergedDefinitionVisible(Old, New->getLocation());
3748     return false;
3749   } else {
3750     Diag(New->getLocation(), diag::err_redefinition) << New;
3751     Diag(Old->getLocation(), diag::note_previous_definition);
3752     New->setInvalidDecl();
3753     return true;
3754   }
3755 }
3756
3757 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3758 /// no declarator (e.g. "struct foo;") is parsed.
3759 Decl *
3760 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3761                                  RecordDecl *&AnonRecord) {
3762   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3763                                     AnonRecord);
3764 }
3765
3766 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3767 // disambiguate entities defined in different scopes.
3768 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3769 // compatibility.
3770 // We will pick our mangling number depending on which version of MSVC is being
3771 // targeted.
3772 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3773   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3774              ? S->getMSCurManglingNumber()
3775              : S->getMSLastManglingNumber();
3776 }
3777
3778 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3779   if (!Context.getLangOpts().CPlusPlus)
3780     return;
3781
3782   if (isa<CXXRecordDecl>(Tag->getParent())) {
3783     // If this tag is the direct child of a class, number it if
3784     // it is anonymous.
3785     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3786       return;
3787     MangleNumberingContext &MCtx =
3788         Context.getManglingNumberContext(Tag->getParent());
3789     Context.setManglingNumber(
3790         Tag, MCtx.getManglingNumber(
3791                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3792     return;
3793   }
3794
3795   // If this tag isn't a direct child of a class, number it if it is local.
3796   Decl *ManglingContextDecl;
3797   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3798           Tag->getDeclContext(), ManglingContextDecl)) {
3799     Context.setManglingNumber(
3800         Tag, MCtx->getManglingNumber(
3801                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3802   }
3803 }
3804
3805 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3806                                         TypedefNameDecl *NewTD) {
3807   if (TagFromDeclSpec->isInvalidDecl())
3808     return;
3809
3810   // Do nothing if the tag already has a name for linkage purposes.
3811   if (TagFromDeclSpec->hasNameForLinkage())
3812     return;
3813
3814   // A well-formed anonymous tag must always be a TUK_Definition.
3815   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3816
3817   // The type must match the tag exactly;  no qualifiers allowed.
3818   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3819                            Context.getTagDeclType(TagFromDeclSpec))) {
3820     if (getLangOpts().CPlusPlus)
3821       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3822     return;
3823   }
3824
3825   // If we've already computed linkage for the anonymous tag, then
3826   // adding a typedef name for the anonymous decl can change that
3827   // linkage, which might be a serious problem.  Diagnose this as
3828   // unsupported and ignore the typedef name.  TODO: we should
3829   // pursue this as a language defect and establish a formal rule
3830   // for how to handle it.
3831   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3832     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3833
3834     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3835     tagLoc = getLocForEndOfToken(tagLoc);
3836
3837     llvm::SmallString<40> textToInsert;
3838     textToInsert += ' ';
3839     textToInsert += NewTD->getIdentifier()->getName();
3840     Diag(tagLoc, diag::note_typedef_changes_linkage)
3841         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3842     return;
3843   }
3844
3845   // Otherwise, set this is the anon-decl typedef for the tag.
3846   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3847 }
3848
3849 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3850   switch (T) {
3851   case DeclSpec::TST_class:
3852     return 0;
3853   case DeclSpec::TST_struct:
3854     return 1;
3855   case DeclSpec::TST_interface:
3856     return 2;
3857   case DeclSpec::TST_union:
3858     return 3;
3859   case DeclSpec::TST_enum:
3860     return 4;
3861   default:
3862     llvm_unreachable("unexpected type specifier");
3863   }
3864 }
3865
3866 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3867 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3868 /// parameters to cope with template friend declarations.
3869 Decl *
3870 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3871                                  MultiTemplateParamsArg TemplateParams,
3872                                  bool IsExplicitInstantiation,
3873                                  RecordDecl *&AnonRecord) {
3874   Decl *TagD = nullptr;
3875   TagDecl *Tag = nullptr;
3876   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3877       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3878       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3879       DS.getTypeSpecType() == DeclSpec::TST_union ||
3880       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3881     TagD = DS.getRepAsDecl();
3882
3883     if (!TagD) // We probably had an error
3884       return nullptr;
3885
3886     // Note that the above type specs guarantee that the
3887     // type rep is a Decl, whereas in many of the others
3888     // it's a Type.
3889     if (isa<TagDecl>(TagD))
3890       Tag = cast<TagDecl>(TagD);
3891     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3892       Tag = CTD->getTemplatedDecl();
3893   }
3894
3895   if (Tag) {
3896     handleTagNumbering(Tag, S);
3897     Tag->setFreeStanding();
3898     if (Tag->isInvalidDecl())
3899       return Tag;
3900   }
3901
3902   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3903     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3904     // or incomplete types shall not be restrict-qualified."
3905     if (TypeQuals & DeclSpec::TQ_restrict)
3906       Diag(DS.getRestrictSpecLoc(),
3907            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3908            << DS.getSourceRange();
3909   }
3910
3911   if (DS.isInlineSpecified())
3912     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3913         << getLangOpts().CPlusPlus1z;
3914
3915   if (DS.isConstexprSpecified()) {
3916     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3917     // and definitions of functions and variables.
3918     if (Tag)
3919       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3920           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3921     else
3922       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3923     // Don't emit warnings after this error.
3924     return TagD;
3925   }
3926
3927   if (DS.isConceptSpecified()) {
3928     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3929     // either a function concept and its definition or a variable concept and
3930     // its initializer.
3931     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3932     return TagD;
3933   }
3934
3935   DiagnoseFunctionSpecifiers(DS);
3936
3937   if (DS.isFriendSpecified()) {
3938     // If we're dealing with a decl but not a TagDecl, assume that
3939     // whatever routines created it handled the friendship aspect.
3940     if (TagD && !Tag)
3941       return nullptr;
3942     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3943   }
3944
3945   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3946   bool IsExplicitSpecialization =
3947     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3948   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3949       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3950       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3951     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3952     // nested-name-specifier unless it is an explicit instantiation
3953     // or an explicit specialization.
3954     //
3955     // FIXME: We allow class template partial specializations here too, per the
3956     // obvious intent of DR1819.
3957     //
3958     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3959     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3960         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3961     return nullptr;
3962   }
3963
3964   // Track whether this decl-specifier declares anything.
3965   bool DeclaresAnything = true;
3966
3967   // Handle anonymous struct definitions.
3968   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3969     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3970         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3971       if (getLangOpts().CPlusPlus ||
3972           Record->getDeclContext()->isRecord()) {
3973         // If CurContext is a DeclContext that can contain statements,
3974         // RecursiveASTVisitor won't visit the decls that
3975         // BuildAnonymousStructOrUnion() will put into CurContext.
3976         // Also store them here so that they can be part of the
3977         // DeclStmt that gets created in this case.
3978         // FIXME: Also return the IndirectFieldDecls created by
3979         // BuildAnonymousStructOr union, for the same reason?
3980         if (CurContext->isFunctionOrMethod())
3981           AnonRecord = Record;
3982         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3983                                            Context.getPrintingPolicy());
3984       }
3985
3986       DeclaresAnything = false;
3987     }
3988   }
3989
3990   // C11 6.7.2.1p2:
3991   //   A struct-declaration that does not declare an anonymous structure or
3992   //   anonymous union shall contain a struct-declarator-list.
3993   //
3994   // This rule also existed in C89 and C99; the grammar for struct-declaration
3995   // did not permit a struct-declaration without a struct-declarator-list.
3996   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3997       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3998     // Check for Microsoft C extension: anonymous struct/union member.
3999     // Handle 2 kinds of anonymous struct/union:
4000     //   struct STRUCT;
4001     //   union UNION;
4002     // and
4003     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4004     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4005     if ((Tag && Tag->getDeclName()) ||
4006         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4007       RecordDecl *Record = nullptr;
4008       if (Tag)
4009         Record = dyn_cast<RecordDecl>(Tag);
4010       else if (const RecordType *RT =
4011                    DS.getRepAsType().get()->getAsStructureType())
4012         Record = RT->getDecl();
4013       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4014         Record = UT->getDecl();
4015
4016       if (Record && getLangOpts().MicrosoftExt) {
4017         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4018           << Record->isUnion() << DS.getSourceRange();
4019         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4020       }
4021
4022       DeclaresAnything = false;
4023     }
4024   }
4025
4026   // Skip all the checks below if we have a type error.
4027   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4028       (TagD && TagD->isInvalidDecl()))
4029     return TagD;
4030
4031   if (getLangOpts().CPlusPlus &&
4032       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4033     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4034       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4035           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4036         DeclaresAnything = false;
4037
4038   if (!DS.isMissingDeclaratorOk()) {
4039     // Customize diagnostic for a typedef missing a name.
4040     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4041       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4042         << DS.getSourceRange();
4043     else
4044       DeclaresAnything = false;
4045   }
4046
4047   if (DS.isModulePrivateSpecified() &&
4048       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4049     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4050       << Tag->getTagKind()
4051       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4052
4053   ActOnDocumentableDecl(TagD);
4054
4055   // C 6.7/2:
4056   //   A declaration [...] shall declare at least a declarator [...], a tag,
4057   //   or the members of an enumeration.
4058   // C++ [dcl.dcl]p3:
4059   //   [If there are no declarators], and except for the declaration of an
4060   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4061   //   names into the program, or shall redeclare a name introduced by a
4062   //   previous declaration.
4063   if (!DeclaresAnything) {
4064     // In C, we allow this as a (popular) extension / bug. Don't bother
4065     // producing further diagnostics for redundant qualifiers after this.
4066     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4067     return TagD;
4068   }
4069
4070   // C++ [dcl.stc]p1:
4071   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4072   //   init-declarator-list of the declaration shall not be empty.
4073   // C++ [dcl.fct.spec]p1:
4074   //   If a cv-qualifier appears in a decl-specifier-seq, the
4075   //   init-declarator-list of the declaration shall not be empty.
4076   //
4077   // Spurious qualifiers here appear to be valid in C.
4078   unsigned DiagID = diag::warn_standalone_specifier;
4079   if (getLangOpts().CPlusPlus)
4080     DiagID = diag::ext_standalone_specifier;
4081
4082   // Note that a linkage-specification sets a storage class, but
4083   // 'extern "C" struct foo;' is actually valid and not theoretically
4084   // useless.
4085   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4086     if (SCS == DeclSpec::SCS_mutable)
4087       // Since mutable is not a viable storage class specifier in C, there is
4088       // no reason to treat it as an extension. Instead, diagnose as an error.
4089       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4090     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4091       Diag(DS.getStorageClassSpecLoc(), DiagID)
4092         << DeclSpec::getSpecifierName(SCS);
4093   }
4094
4095   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4096     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4097       << DeclSpec::getSpecifierName(TSCS);
4098   if (DS.getTypeQualifiers()) {
4099     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4100       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4101     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4102       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4103     // Restrict is covered above.
4104     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4105       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4106     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4107       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4108   }
4109
4110   // Warn about ignored type attributes, for example:
4111   // __attribute__((aligned)) struct A;
4112   // Attributes should be placed after tag to apply to type declaration.
4113   if (!DS.getAttributes().empty()) {
4114     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4115     if (TypeSpecType == DeclSpec::TST_class ||
4116         TypeSpecType == DeclSpec::TST_struct ||
4117         TypeSpecType == DeclSpec::TST_interface ||
4118         TypeSpecType == DeclSpec::TST_union ||
4119         TypeSpecType == DeclSpec::TST_enum) {
4120       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4121            attrs = attrs->getNext())
4122         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4123             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4124     }
4125   }
4126
4127   return TagD;
4128 }
4129
4130 /// We are trying to inject an anonymous member into the given scope;
4131 /// check if there's an existing declaration that can't be overloaded.
4132 ///
4133 /// \return true if this is a forbidden redeclaration
4134 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4135                                          Scope *S,
4136                                          DeclContext *Owner,
4137                                          DeclarationName Name,
4138                                          SourceLocation NameLoc,
4139                                          bool IsUnion) {
4140   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4141                  Sema::ForRedeclaration);
4142   if (!SemaRef.LookupName(R, S)) return false;
4143
4144   // Pick a representative declaration.
4145   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4146   assert(PrevDecl && "Expected a non-null Decl");
4147
4148   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4149     return false;
4150
4151   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4152     << IsUnion << Name;
4153   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4154
4155   return true;
4156 }
4157
4158 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4159 /// anonymous struct or union AnonRecord into the owning context Owner
4160 /// and scope S. This routine will be invoked just after we realize
4161 /// that an unnamed union or struct is actually an anonymous union or
4162 /// struct, e.g.,
4163 ///
4164 /// @code
4165 /// union {
4166 ///   int i;
4167 ///   float f;
4168 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4169 ///    // f into the surrounding scope.x
4170 /// @endcode
4171 ///
4172 /// This routine is recursive, injecting the names of nested anonymous
4173 /// structs/unions into the owning context and scope as well.
4174 static bool
4175 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4176                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4177                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4178   bool Invalid = false;
4179
4180   // Look every FieldDecl and IndirectFieldDecl with a name.
4181   for (auto *D : AnonRecord->decls()) {
4182     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4183         cast<NamedDecl>(D)->getDeclName()) {
4184       ValueDecl *VD = cast<ValueDecl>(D);
4185       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4186                                        VD->getLocation(),
4187                                        AnonRecord->isUnion())) {
4188         // C++ [class.union]p2:
4189         //   The names of the members of an anonymous union shall be
4190         //   distinct from the names of any other entity in the
4191         //   scope in which the anonymous union is declared.
4192         Invalid = true;
4193       } else {
4194         // C++ [class.union]p2:
4195         //   For the purpose of name lookup, after the anonymous union
4196         //   definition, the members of the anonymous union are
4197         //   considered to have been defined in the scope in which the
4198         //   anonymous union is declared.
4199         unsigned OldChainingSize = Chaining.size();
4200         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4201           Chaining.append(IF->chain_begin(), IF->chain_end());
4202         else
4203           Chaining.push_back(VD);
4204
4205         assert(Chaining.size() >= 2);
4206         NamedDecl **NamedChain =
4207           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4208         for (unsigned i = 0; i < Chaining.size(); i++)
4209           NamedChain[i] = Chaining[i];
4210
4211         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4212             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4213             VD->getType(), {NamedChain, Chaining.size()});
4214
4215         for (const auto *Attr : VD->attrs())
4216           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4217
4218         IndirectField->setAccess(AS);
4219         IndirectField->setImplicit();
4220         SemaRef.PushOnScopeChains(IndirectField, S);
4221
4222         // That includes picking up the appropriate access specifier.
4223         if (AS != AS_none) IndirectField->setAccess(AS);
4224
4225         Chaining.resize(OldChainingSize);
4226       }
4227     }
4228   }
4229
4230   return Invalid;
4231 }
4232
4233 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4234 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4235 /// illegal input values are mapped to SC_None.
4236 static StorageClass
4237 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4238   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4239   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4240          "Parser allowed 'typedef' as storage class VarDecl.");
4241   switch (StorageClassSpec) {
4242   case DeclSpec::SCS_unspecified:    return SC_None;
4243   case DeclSpec::SCS_extern:
4244     if (DS.isExternInLinkageSpec())
4245       return SC_None;
4246     return SC_Extern;
4247   case DeclSpec::SCS_static:         return SC_Static;
4248   case DeclSpec::SCS_auto:           return SC_Auto;
4249   case DeclSpec::SCS_register:       return SC_Register;
4250   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4251     // Illegal SCSs map to None: error reporting is up to the caller.
4252   case DeclSpec::SCS_mutable:        // Fall through.
4253   case DeclSpec::SCS_typedef:        return SC_None;
4254   }
4255   llvm_unreachable("unknown storage class specifier");
4256 }
4257
4258 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4259   assert(Record->hasInClassInitializer());
4260
4261   for (const auto *I : Record->decls()) {
4262     const auto *FD = dyn_cast<FieldDecl>(I);
4263     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4264       FD = IFD->getAnonField();
4265     if (FD && FD->hasInClassInitializer())
4266       return FD->getLocation();
4267   }
4268
4269   llvm_unreachable("couldn't find in-class initializer");
4270 }
4271
4272 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4273                                       SourceLocation DefaultInitLoc) {
4274   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4275     return;
4276
4277   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4278   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4279 }
4280
4281 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4282                                       CXXRecordDecl *AnonUnion) {
4283   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4284     return;
4285
4286   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4287 }
4288
4289 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4290 /// anonymous structure or union. Anonymous unions are a C++ feature
4291 /// (C++ [class.union]) and a C11 feature; anonymous structures
4292 /// are a C11 feature and GNU C++ extension.
4293 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4294                                         AccessSpecifier AS,
4295                                         RecordDecl *Record,
4296                                         const PrintingPolicy &Policy) {
4297   DeclContext *Owner = Record->getDeclContext();
4298
4299   // Diagnose whether this anonymous struct/union is an extension.
4300   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4301     Diag(Record->getLocation(), diag::ext_anonymous_union);
4302   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4303     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4304   else if (!Record->isUnion() && !getLangOpts().C11)
4305     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4306
4307   // C and C++ require different kinds of checks for anonymous
4308   // structs/unions.
4309   bool Invalid = false;
4310   if (getLangOpts().CPlusPlus) {
4311     const char *PrevSpec = nullptr;
4312     unsigned DiagID;
4313     if (Record->isUnion()) {
4314       // C++ [class.union]p6:
4315       //   Anonymous unions declared in a named namespace or in the
4316       //   global namespace shall be declared static.
4317       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4318           (isa<TranslationUnitDecl>(Owner) ||
4319            (isa<NamespaceDecl>(Owner) &&
4320             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4321         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4322           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4323
4324         // Recover by adding 'static'.
4325         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4326                                PrevSpec, DiagID, Policy);
4327       }
4328       // C++ [class.union]p6:
4329       //   A storage class is not allowed in a declaration of an
4330       //   anonymous union in a class scope.
4331       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4332                isa<RecordDecl>(Owner)) {
4333         Diag(DS.getStorageClassSpecLoc(),
4334              diag::err_anonymous_union_with_storage_spec)
4335           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4336
4337         // Recover by removing the storage specifier.
4338         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4339                                SourceLocation(),
4340                                PrevSpec, DiagID, Context.getPrintingPolicy());
4341       }
4342     }
4343
4344     // Ignore const/volatile/restrict qualifiers.
4345     if (DS.getTypeQualifiers()) {
4346       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4347         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4348           << Record->isUnion() << "const"
4349           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4350       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4351         Diag(DS.getVolatileSpecLoc(),
4352              diag::ext_anonymous_struct_union_qualified)
4353           << Record->isUnion() << "volatile"
4354           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4355       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4356         Diag(DS.getRestrictSpecLoc(),
4357              diag::ext_anonymous_struct_union_qualified)
4358           << Record->isUnion() << "restrict"
4359           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4360       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4361         Diag(DS.getAtomicSpecLoc(),
4362              diag::ext_anonymous_struct_union_qualified)
4363           << Record->isUnion() << "_Atomic"
4364           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4365       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4366         Diag(DS.getUnalignedSpecLoc(),
4367              diag::ext_anonymous_struct_union_qualified)
4368           << Record->isUnion() << "__unaligned"
4369           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4370
4371       DS.ClearTypeQualifiers();
4372     }
4373
4374     // C++ [class.union]p2:
4375     //   The member-specification of an anonymous union shall only
4376     //   define non-static data members. [Note: nested types and
4377     //   functions cannot be declared within an anonymous union. ]
4378     for (auto *Mem : Record->decls()) {
4379       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4380         // C++ [class.union]p3:
4381         //   An anonymous union shall not have private or protected
4382         //   members (clause 11).
4383         assert(FD->getAccess() != AS_none);
4384         if (FD->getAccess() != AS_public) {
4385           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4386             << Record->isUnion() << (FD->getAccess() == AS_protected);
4387           Invalid = true;
4388         }
4389
4390         // C++ [class.union]p1
4391         //   An object of a class with a non-trivial constructor, a non-trivial
4392         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4393         //   assignment operator cannot be a member of a union, nor can an
4394         //   array of such objects.
4395         if (CheckNontrivialField(FD))
4396           Invalid = true;
4397       } else if (Mem->isImplicit()) {
4398         // Any implicit members are fine.
4399       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4400         // This is a type that showed up in an
4401         // elaborated-type-specifier inside the anonymous struct or
4402         // union, but which actually declares a type outside of the
4403         // anonymous struct or union. It's okay.
4404       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4405         if (!MemRecord->isAnonymousStructOrUnion() &&
4406             MemRecord->getDeclName()) {
4407           // Visual C++ allows type definition in anonymous struct or union.
4408           if (getLangOpts().MicrosoftExt)
4409             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4410               << Record->isUnion();
4411           else {
4412             // This is a nested type declaration.
4413             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4414               << Record->isUnion();
4415             Invalid = true;
4416           }
4417         } else {
4418           // This is an anonymous type definition within another anonymous type.
4419           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4420           // not part of standard C++.
4421           Diag(MemRecord->getLocation(),
4422                diag::ext_anonymous_record_with_anonymous_type)
4423             << Record->isUnion();
4424         }
4425       } else if (isa<AccessSpecDecl>(Mem)) {
4426         // Any access specifier is fine.
4427       } else if (isa<StaticAssertDecl>(Mem)) {
4428         // In C++1z, static_assert declarations are also fine.
4429       } else {
4430         // We have something that isn't a non-static data
4431         // member. Complain about it.
4432         unsigned DK = diag::err_anonymous_record_bad_member;
4433         if (isa<TypeDecl>(Mem))
4434           DK = diag::err_anonymous_record_with_type;
4435         else if (isa<FunctionDecl>(Mem))
4436           DK = diag::err_anonymous_record_with_function;
4437         else if (isa<VarDecl>(Mem))
4438           DK = diag::err_anonymous_record_with_static;
4439
4440         // Visual C++ allows type definition in anonymous struct or union.
4441         if (getLangOpts().MicrosoftExt &&
4442             DK == diag::err_anonymous_record_with_type)
4443           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4444             << Record->isUnion();
4445         else {
4446           Diag(Mem->getLocation(), DK) << Record->isUnion();
4447           Invalid = true;
4448         }
4449       }
4450     }
4451
4452     // C++11 [class.union]p8 (DR1460):
4453     //   At most one variant member of a union may have a
4454     //   brace-or-equal-initializer.
4455     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4456         Owner->isRecord())
4457       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4458                                 cast<CXXRecordDecl>(Record));
4459   }
4460
4461   if (!Record->isUnion() && !Owner->isRecord()) {
4462     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4463       << getLangOpts().CPlusPlus;
4464     Invalid = true;
4465   }
4466
4467   // Mock up a declarator.
4468   Declarator Dc(DS, Declarator::MemberContext);
4469   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4470   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4471
4472   // Create a declaration for this anonymous struct/union.
4473   NamedDecl *Anon = nullptr;
4474   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4475     Anon = FieldDecl::Create(Context, OwningClass,
4476                              DS.getLocStart(),
4477                              Record->getLocation(),
4478                              /*IdentifierInfo=*/nullptr,
4479                              Context.getTypeDeclType(Record),
4480                              TInfo,
4481                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4482                              /*InitStyle=*/ICIS_NoInit);
4483     Anon->setAccess(AS);
4484     if (getLangOpts().CPlusPlus)
4485       FieldCollector->Add(cast<FieldDecl>(Anon));
4486   } else {
4487     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4488     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4489     if (SCSpec == DeclSpec::SCS_mutable) {
4490       // mutable can only appear on non-static class members, so it's always
4491       // an error here
4492       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4493       Invalid = true;
4494       SC = SC_None;
4495     }
4496
4497     Anon = VarDecl::Create(Context, Owner,
4498                            DS.getLocStart(),
4499                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4500                            Context.getTypeDeclType(Record),
4501                            TInfo, SC);
4502
4503     // Default-initialize the implicit variable. This initialization will be
4504     // trivial in almost all cases, except if a union member has an in-class
4505     // initializer:
4506     //   union { int n = 0; };
4507     ActOnUninitializedDecl(Anon);
4508   }
4509   Anon->setImplicit();
4510
4511   // Mark this as an anonymous struct/union type.
4512   Record->setAnonymousStructOrUnion(true);
4513
4514   // Add the anonymous struct/union object to the current
4515   // context. We'll be referencing this object when we refer to one of
4516   // its members.
4517   Owner->addDecl(Anon);
4518
4519   // Inject the members of the anonymous struct/union into the owning
4520   // context and into the identifier resolver chain for name lookup
4521   // purposes.
4522   SmallVector<NamedDecl*, 2> Chain;
4523   Chain.push_back(Anon);
4524
4525   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4526     Invalid = true;
4527
4528   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4529     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4530       Decl *ManglingContextDecl;
4531       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4532               NewVD->getDeclContext(), ManglingContextDecl)) {
4533         Context.setManglingNumber(
4534             NewVD, MCtx->getManglingNumber(
4535                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4536         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4537       }
4538     }
4539   }
4540
4541   if (Invalid)
4542     Anon->setInvalidDecl();
4543
4544   return Anon;
4545 }
4546
4547 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4548 /// Microsoft C anonymous structure.
4549 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4550 /// Example:
4551 ///
4552 /// struct A { int a; };
4553 /// struct B { struct A; int b; };
4554 ///
4555 /// void foo() {
4556 ///   B var;
4557 ///   var.a = 3;
4558 /// }
4559 ///
4560 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4561                                            RecordDecl *Record) {
4562   assert(Record && "expected a record!");
4563
4564   // Mock up a declarator.
4565   Declarator Dc(DS, Declarator::TypeNameContext);
4566   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4567   assert(TInfo && "couldn't build declarator info for anonymous struct");
4568
4569   auto *ParentDecl = cast<RecordDecl>(CurContext);
4570   QualType RecTy = Context.getTypeDeclType(Record);
4571
4572   // Create a declaration for this anonymous struct.
4573   NamedDecl *Anon = FieldDecl::Create(Context,
4574                              ParentDecl,
4575                              DS.getLocStart(),
4576                              DS.getLocStart(),
4577                              /*IdentifierInfo=*/nullptr,
4578                              RecTy,
4579                              TInfo,
4580                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4581                              /*InitStyle=*/ICIS_NoInit);
4582   Anon->setImplicit();
4583
4584   // Add the anonymous struct object to the current context.
4585   CurContext->addDecl(Anon);
4586
4587   // Inject the members of the anonymous struct into the current
4588   // context and into the identifier resolver chain for name lookup
4589   // purposes.
4590   SmallVector<NamedDecl*, 2> Chain;
4591   Chain.push_back(Anon);
4592
4593   RecordDecl *RecordDef = Record->getDefinition();
4594   if (RequireCompleteType(Anon->getLocation(), RecTy,
4595                           diag::err_field_incomplete) ||
4596       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4597                                           AS_none, Chain)) {
4598     Anon->setInvalidDecl();
4599     ParentDecl->setInvalidDecl();
4600   }
4601
4602   return Anon;
4603 }
4604
4605 /// GetNameForDeclarator - Determine the full declaration name for the
4606 /// given Declarator.
4607 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4608   return GetNameFromUnqualifiedId(D.getName());
4609 }
4610
4611 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4612 DeclarationNameInfo
4613 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4614   DeclarationNameInfo NameInfo;
4615   NameInfo.setLoc(Name.StartLocation);
4616
4617   switch (Name.getKind()) {
4618
4619   case UnqualifiedId::IK_ImplicitSelfParam:
4620   case UnqualifiedId::IK_Identifier:
4621     NameInfo.setName(Name.Identifier);
4622     NameInfo.setLoc(Name.StartLocation);
4623     return NameInfo;
4624
4625   case UnqualifiedId::IK_OperatorFunctionId:
4626     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4627                                            Name.OperatorFunctionId.Operator));
4628     NameInfo.setLoc(Name.StartLocation);
4629     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4630       = Name.OperatorFunctionId.SymbolLocations[0];
4631     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4632       = Name.EndLocation.getRawEncoding();
4633     return NameInfo;
4634
4635   case UnqualifiedId::IK_LiteralOperatorId:
4636     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4637                                                            Name.Identifier));
4638     NameInfo.setLoc(Name.StartLocation);
4639     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4640     return NameInfo;
4641
4642   case UnqualifiedId::IK_ConversionFunctionId: {
4643     TypeSourceInfo *TInfo;
4644     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4645     if (Ty.isNull())
4646       return DeclarationNameInfo();
4647     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4648                                                Context.getCanonicalType(Ty)));
4649     NameInfo.setLoc(Name.StartLocation);
4650     NameInfo.setNamedTypeInfo(TInfo);
4651     return NameInfo;
4652   }
4653
4654   case UnqualifiedId::IK_ConstructorName: {
4655     TypeSourceInfo *TInfo;
4656     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4657     if (Ty.isNull())
4658       return DeclarationNameInfo();
4659     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4660                                               Context.getCanonicalType(Ty)));
4661     NameInfo.setLoc(Name.StartLocation);
4662     NameInfo.setNamedTypeInfo(TInfo);
4663     return NameInfo;
4664   }
4665
4666   case UnqualifiedId::IK_ConstructorTemplateId: {
4667     // In well-formed code, we can only have a constructor
4668     // template-id that refers to the current context, so go there
4669     // to find the actual type being constructed.
4670     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4671     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4672       return DeclarationNameInfo();
4673
4674     // Determine the type of the class being constructed.
4675     QualType CurClassType = Context.getTypeDeclType(CurClass);
4676
4677     // FIXME: Check two things: that the template-id names the same type as
4678     // CurClassType, and that the template-id does not occur when the name
4679     // was qualified.
4680
4681     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4682                                     Context.getCanonicalType(CurClassType)));
4683     NameInfo.setLoc(Name.StartLocation);
4684     // FIXME: should we retrieve TypeSourceInfo?
4685     NameInfo.setNamedTypeInfo(nullptr);
4686     return NameInfo;
4687   }
4688
4689   case UnqualifiedId::IK_DestructorName: {
4690     TypeSourceInfo *TInfo;
4691     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4692     if (Ty.isNull())
4693       return DeclarationNameInfo();
4694     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4695                                               Context.getCanonicalType(Ty)));
4696     NameInfo.setLoc(Name.StartLocation);
4697     NameInfo.setNamedTypeInfo(TInfo);
4698     return NameInfo;
4699   }
4700
4701   case UnqualifiedId::IK_TemplateId: {
4702     TemplateName TName = Name.TemplateId->Template.get();
4703     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4704     return Context.getNameForTemplate(TName, TNameLoc);
4705   }
4706
4707   } // switch (Name.getKind())
4708
4709   llvm_unreachable("Unknown name kind");
4710 }
4711
4712 static QualType getCoreType(QualType Ty) {
4713   do {
4714     if (Ty->isPointerType() || Ty->isReferenceType())
4715       Ty = Ty->getPointeeType();
4716     else if (Ty->isArrayType())
4717       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4718     else
4719       return Ty.withoutLocalFastQualifiers();
4720   } while (true);
4721 }
4722
4723 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4724 /// and Definition have "nearly" matching parameters. This heuristic is
4725 /// used to improve diagnostics in the case where an out-of-line function
4726 /// definition doesn't match any declaration within the class or namespace.
4727 /// Also sets Params to the list of indices to the parameters that differ
4728 /// between the declaration and the definition. If hasSimilarParameters
4729 /// returns true and Params is empty, then all of the parameters match.
4730 static bool hasSimilarParameters(ASTContext &Context,
4731                                      FunctionDecl *Declaration,
4732                                      FunctionDecl *Definition,
4733                                      SmallVectorImpl<unsigned> &Params) {
4734   Params.clear();
4735   if (Declaration->param_size() != Definition->param_size())
4736     return false;
4737   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4738     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4739     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4740
4741     // The parameter types are identical
4742     if (Context.hasSameType(DefParamTy, DeclParamTy))
4743       continue;
4744
4745     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4746     QualType DefParamBaseTy = getCoreType(DefParamTy);
4747     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4748     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4749
4750     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4751         (DeclTyName && DeclTyName == DefTyName))
4752       Params.push_back(Idx);
4753     else  // The two parameters aren't even close
4754       return false;
4755   }
4756
4757   return true;
4758 }
4759
4760 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4761 /// declarator needs to be rebuilt in the current instantiation.
4762 /// Any bits of declarator which appear before the name are valid for
4763 /// consideration here.  That's specifically the type in the decl spec
4764 /// and the base type in any member-pointer chunks.
4765 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4766                                                     DeclarationName Name) {
4767   // The types we specifically need to rebuild are:
4768   //   - typenames, typeofs, and decltypes
4769   //   - types which will become injected class names
4770   // Of course, we also need to rebuild any type referencing such a
4771   // type.  It's safest to just say "dependent", but we call out a
4772   // few cases here.
4773
4774   DeclSpec &DS = D.getMutableDeclSpec();
4775   switch (DS.getTypeSpecType()) {
4776   case DeclSpec::TST_typename:
4777   case DeclSpec::TST_typeofType:
4778   case DeclSpec::TST_underlyingType:
4779   case DeclSpec::TST_atomic: {
4780     // Grab the type from the parser.
4781     TypeSourceInfo *TSI = nullptr;
4782     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4783     if (T.isNull() || !T->isDependentType()) break;
4784
4785     // Make sure there's a type source info.  This isn't really much
4786     // of a waste; most dependent types should have type source info
4787     // attached already.
4788     if (!TSI)
4789       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4790
4791     // Rebuild the type in the current instantiation.
4792     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4793     if (!TSI) return true;
4794
4795     // Store the new type back in the decl spec.
4796     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4797     DS.UpdateTypeRep(LocType);
4798     break;
4799   }
4800
4801   case DeclSpec::TST_decltype:
4802   case DeclSpec::TST_typeofExpr: {
4803     Expr *E = DS.getRepAsExpr();
4804     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4805     if (Result.isInvalid()) return true;
4806     DS.UpdateExprRep(Result.get());
4807     break;
4808   }
4809
4810   default:
4811     // Nothing to do for these decl specs.
4812     break;
4813   }
4814
4815   // It doesn't matter what order we do this in.
4816   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4817     DeclaratorChunk &Chunk = D.getTypeObject(I);
4818
4819     // The only type information in the declarator which can come
4820     // before the declaration name is the base type of a member
4821     // pointer.
4822     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4823       continue;
4824
4825     // Rebuild the scope specifier in-place.
4826     CXXScopeSpec &SS = Chunk.Mem.Scope();
4827     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4828       return true;
4829   }
4830
4831   return false;
4832 }
4833
4834 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4835   D.setFunctionDefinitionKind(FDK_Declaration);
4836   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4837
4838   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4839       Dcl && Dcl->getDeclContext()->isFileContext())
4840     Dcl->setTopLevelDeclInObjCContainer();
4841
4842   if (getLangOpts().OpenCL)
4843     setCurrentOpenCLExtensionForDecl(Dcl);
4844
4845   return Dcl;
4846 }
4847
4848 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4849 ///   If T is the name of a class, then each of the following shall have a
4850 ///   name different from T:
4851 ///     - every static data member of class T;
4852 ///     - every member function of class T
4853 ///     - every member of class T that is itself a type;
4854 /// \returns true if the declaration name violates these rules.
4855 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4856                                    DeclarationNameInfo NameInfo) {
4857   DeclarationName Name = NameInfo.getName();
4858
4859   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4860   while (Record && Record->isAnonymousStructOrUnion())
4861     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4862   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4863     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4864     return true;
4865   }
4866
4867   return false;
4868 }
4869
4870 /// \brief Diagnose a declaration whose declarator-id has the given
4871 /// nested-name-specifier.
4872 ///
4873 /// \param SS The nested-name-specifier of the declarator-id.
4874 ///
4875 /// \param DC The declaration context to which the nested-name-specifier
4876 /// resolves.
4877 ///
4878 /// \param Name The name of the entity being declared.
4879 ///
4880 /// \param Loc The location of the name of the entity being declared.
4881 ///
4882 /// \returns true if we cannot safely recover from this error, false otherwise.
4883 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4884                                         DeclarationName Name,
4885                                         SourceLocation Loc) {
4886   DeclContext *Cur = CurContext;
4887   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4888     Cur = Cur->getParent();
4889
4890   // If the user provided a superfluous scope specifier that refers back to the
4891   // class in which the entity is already declared, diagnose and ignore it.
4892   //
4893   // class X {
4894   //   void X::f();
4895   // };
4896   //
4897   // Note, it was once ill-formed to give redundant qualification in all
4898   // contexts, but that rule was removed by DR482.
4899   if (Cur->Equals(DC)) {
4900     if (Cur->isRecord()) {
4901       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4902                                       : diag::err_member_extra_qualification)
4903         << Name << FixItHint::CreateRemoval(SS.getRange());
4904       SS.clear();
4905     } else {
4906       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4907     }
4908     return false;
4909   }
4910
4911   // Check whether the qualifying scope encloses the scope of the original
4912   // declaration.
4913   if (!Cur->Encloses(DC)) {
4914     if (Cur->isRecord())
4915       Diag(Loc, diag::err_member_qualification)
4916         << Name << SS.getRange();
4917     else if (isa<TranslationUnitDecl>(DC))
4918       Diag(Loc, diag::err_invalid_declarator_global_scope)
4919         << Name << SS.getRange();
4920     else if (isa<FunctionDecl>(Cur))
4921       Diag(Loc, diag::err_invalid_declarator_in_function)
4922         << Name << SS.getRange();
4923     else if (isa<BlockDecl>(Cur))
4924       Diag(Loc, diag::err_invalid_declarator_in_block)
4925         << Name << SS.getRange();
4926     else
4927       Diag(Loc, diag::err_invalid_declarator_scope)
4928       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4929
4930     return true;
4931   }
4932
4933   if (Cur->isRecord()) {
4934     // Cannot qualify members within a class.
4935     Diag(Loc, diag::err_member_qualification)
4936       << Name << SS.getRange();
4937     SS.clear();
4938
4939     // C++ constructors and destructors with incorrect scopes can break
4940     // our AST invariants by having the wrong underlying types. If
4941     // that's the case, then drop this declaration entirely.
4942     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4943          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4944         !Context.hasSameType(Name.getCXXNameType(),
4945                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4946       return true;
4947
4948     return false;
4949   }
4950
4951   // C++11 [dcl.meaning]p1:
4952   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4953   //   not begin with a decltype-specifer"
4954   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4955   while (SpecLoc.getPrefix())
4956     SpecLoc = SpecLoc.getPrefix();
4957   if (dyn_cast_or_null<DecltypeType>(
4958         SpecLoc.getNestedNameSpecifier()->getAsType()))
4959     Diag(Loc, diag::err_decltype_in_declarator)
4960       << SpecLoc.getTypeLoc().getSourceRange();
4961
4962   return false;
4963 }
4964
4965 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4966                                   MultiTemplateParamsArg TemplateParamLists) {
4967   // TODO: consider using NameInfo for diagnostic.
4968   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4969   DeclarationName Name = NameInfo.getName();
4970
4971   // All of these full declarators require an identifier.  If it doesn't have
4972   // one, the ParsedFreeStandingDeclSpec action should be used.
4973   if (D.isDecompositionDeclarator()) {
4974     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
4975   } else if (!Name) {
4976     if (!D.isInvalidType())  // Reject this if we think it is valid.
4977       Diag(D.getDeclSpec().getLocStart(),
4978            diag::err_declarator_need_ident)
4979         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4980     return nullptr;
4981   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4982     return nullptr;
4983
4984   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4985   // we find one that is.
4986   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4987          (S->getFlags() & Scope::TemplateParamScope) != 0)
4988     S = S->getParent();
4989
4990   DeclContext *DC = CurContext;
4991   if (D.getCXXScopeSpec().isInvalid())
4992     D.setInvalidType();
4993   else if (D.getCXXScopeSpec().isSet()) {
4994     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4995                                         UPPC_DeclarationQualifier))
4996       return nullptr;
4997
4998     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4999     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5000     if (!DC || isa<EnumDecl>(DC)) {
5001       // If we could not compute the declaration context, it's because the
5002       // declaration context is dependent but does not refer to a class,
5003       // class template, or class template partial specialization. Complain
5004       // and return early, to avoid the coming semantic disaster.
5005       Diag(D.getIdentifierLoc(),
5006            diag::err_template_qualified_declarator_no_match)
5007         << D.getCXXScopeSpec().getScopeRep()
5008         << D.getCXXScopeSpec().getRange();
5009       return nullptr;
5010     }
5011     bool IsDependentContext = DC->isDependentContext();
5012
5013     if (!IsDependentContext &&
5014         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5015       return nullptr;
5016
5017     // If a class is incomplete, do not parse entities inside it.
5018     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5019       Diag(D.getIdentifierLoc(),
5020            diag::err_member_def_undefined_record)
5021         << Name << DC << D.getCXXScopeSpec().getRange();
5022       return nullptr;
5023     }
5024     if (!D.getDeclSpec().isFriendSpecified()) {
5025       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5026                                       Name, D.getIdentifierLoc())) {
5027         if (DC->isRecord())
5028           return nullptr;
5029
5030         D.setInvalidType();
5031       }
5032     }
5033
5034     // Check whether we need to rebuild the type of the given
5035     // declaration in the current instantiation.
5036     if (EnteringContext && IsDependentContext &&
5037         TemplateParamLists.size() != 0) {
5038       ContextRAII SavedContext(*this, DC);
5039       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5040         D.setInvalidType();
5041     }
5042   }
5043
5044   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5045   QualType R = TInfo->getType();
5046
5047   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5048     // If this is a typedef, we'll end up spewing multiple diagnostics.
5049     // Just return early; it's safer. If this is a function, let the
5050     // "constructor cannot have a return type" diagnostic handle it.
5051     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5052       return nullptr;
5053
5054   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5055                                       UPPC_DeclarationType))
5056     D.setInvalidType();
5057
5058   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5059                         ForRedeclaration);
5060
5061   // See if this is a redefinition of a variable in the same scope.
5062   if (!D.getCXXScopeSpec().isSet()) {
5063     bool IsLinkageLookup = false;
5064     bool CreateBuiltins = false;
5065
5066     // If the declaration we're planning to build will be a function
5067     // or object with linkage, then look for another declaration with
5068     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5069     //
5070     // If the declaration we're planning to build will be declared with
5071     // external linkage in the translation unit, create any builtin with
5072     // the same name.
5073     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5074       /* Do nothing*/;
5075     else if (CurContext->isFunctionOrMethod() &&
5076              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5077               R->isFunctionType())) {
5078       IsLinkageLookup = true;
5079       CreateBuiltins =
5080           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5081     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5082                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5083       CreateBuiltins = true;
5084
5085     if (IsLinkageLookup)
5086       Previous.clear(LookupRedeclarationWithLinkage);
5087
5088     LookupName(Previous, S, CreateBuiltins);
5089   } else { // Something like "int foo::x;"
5090     LookupQualifiedName(Previous, DC);
5091
5092     // C++ [dcl.meaning]p1:
5093     //   When the declarator-id is qualified, the declaration shall refer to a
5094     //  previously declared member of the class or namespace to which the
5095     //  qualifier refers (or, in the case of a namespace, of an element of the
5096     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5097     //  thereof; [...]
5098     //
5099     // Note that we already checked the context above, and that we do not have
5100     // enough information to make sure that Previous contains the declaration
5101     // we want to match. For example, given:
5102     //
5103     //   class X {
5104     //     void f();
5105     //     void f(float);
5106     //   };
5107     //
5108     //   void X::f(int) { } // ill-formed
5109     //
5110     // In this case, Previous will point to the overload set
5111     // containing the two f's declared in X, but neither of them
5112     // matches.
5113
5114     // C++ [dcl.meaning]p1:
5115     //   [...] the member shall not merely have been introduced by a
5116     //   using-declaration in the scope of the class or namespace nominated by
5117     //   the nested-name-specifier of the declarator-id.
5118     RemoveUsingDecls(Previous);
5119   }
5120
5121   if (Previous.isSingleResult() &&
5122       Previous.getFoundDecl()->isTemplateParameter()) {
5123     // Maybe we will complain about the shadowed template parameter.
5124     if (!D.isInvalidType())
5125       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5126                                       Previous.getFoundDecl());
5127
5128     // Just pretend that we didn't see the previous declaration.
5129     Previous.clear();
5130   }
5131
5132   // In C++, the previous declaration we find might be a tag type
5133   // (class or enum). In this case, the new declaration will hide the
5134   // tag type. Note that this does does not apply if we're declaring a
5135   // typedef (C++ [dcl.typedef]p4).
5136   if (Previous.isSingleTagDecl() &&
5137       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5138     Previous.clear();
5139
5140   // Check that there are no default arguments other than in the parameters
5141   // of a function declaration (C++ only).
5142   if (getLangOpts().CPlusPlus)
5143     CheckExtraCXXDefaultArguments(D);
5144
5145   if (D.getDeclSpec().isConceptSpecified()) {
5146     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5147     // applied only to the definition of a function template or variable
5148     // template, declared in namespace scope
5149     if (!TemplateParamLists.size()) {
5150       Diag(D.getDeclSpec().getConceptSpecLoc(),
5151            diag:: err_concept_wrong_decl_kind);
5152       return nullptr;
5153     }
5154
5155     if (!DC->getRedeclContext()->isFileContext()) {
5156       Diag(D.getIdentifierLoc(),
5157            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5158       return nullptr;
5159     }
5160   }
5161
5162   NamedDecl *New;
5163
5164   bool AddToScope = true;
5165   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5166     if (TemplateParamLists.size()) {
5167       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5168       return nullptr;
5169     }
5170
5171     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5172   } else if (R->isFunctionType()) {
5173     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5174                                   TemplateParamLists,
5175                                   AddToScope);
5176   } else {
5177     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5178                                   AddToScope);
5179   }
5180
5181   if (!New)
5182     return nullptr;
5183
5184   // If this has an identifier and is not a function template specialization,
5185   // add it to the scope stack.
5186   if (New->getDeclName() && AddToScope) {
5187     // Only make a locally-scoped extern declaration visible if it is the first
5188     // declaration of this entity. Qualified lookup for such an entity should
5189     // only find this declaration if there is no visible declaration of it.
5190     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5191     PushOnScopeChains(New, S, AddToContext);
5192     if (!AddToContext)
5193       CurContext->addHiddenDecl(New);
5194   }
5195
5196   if (isInOpenMPDeclareTargetContext())
5197     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5198
5199   return New;
5200 }
5201
5202 /// Helper method to turn variable array types into constant array
5203 /// types in certain situations which would otherwise be errors (for
5204 /// GCC compatibility).
5205 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5206                                                     ASTContext &Context,
5207                                                     bool &SizeIsNegative,
5208                                                     llvm::APSInt &Oversized) {
5209   // This method tries to turn a variable array into a constant
5210   // array even when the size isn't an ICE.  This is necessary
5211   // for compatibility with code that depends on gcc's buggy
5212   // constant expression folding, like struct {char x[(int)(char*)2];}
5213   SizeIsNegative = false;
5214   Oversized = 0;
5215
5216   if (T->isDependentType())
5217     return QualType();
5218
5219   QualifierCollector Qs;
5220   const Type *Ty = Qs.strip(T);
5221
5222   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5223     QualType Pointee = PTy->getPointeeType();
5224     QualType FixedType =
5225         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5226                                             Oversized);
5227     if (FixedType.isNull()) return FixedType;
5228     FixedType = Context.getPointerType(FixedType);
5229     return Qs.apply(Context, FixedType);
5230   }
5231   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5232     QualType Inner = PTy->getInnerType();
5233     QualType FixedType =
5234         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5235                                             Oversized);
5236     if (FixedType.isNull()) return FixedType;
5237     FixedType = Context.getParenType(FixedType);
5238     return Qs.apply(Context, FixedType);
5239   }
5240
5241   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5242   if (!VLATy)
5243     return QualType();
5244   // FIXME: We should probably handle this case
5245   if (VLATy->getElementType()->isVariablyModifiedType())
5246     return QualType();
5247
5248   llvm::APSInt Res;
5249   if (!VLATy->getSizeExpr() ||
5250       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5251     return QualType();
5252
5253   // Check whether the array size is negative.
5254   if (Res.isSigned() && Res.isNegative()) {
5255     SizeIsNegative = true;
5256     return QualType();
5257   }
5258
5259   // Check whether the array is too large to be addressed.
5260   unsigned ActiveSizeBits
5261     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5262                                               Res);
5263   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5264     Oversized = Res;
5265     return QualType();
5266   }
5267
5268   return Context.getConstantArrayType(VLATy->getElementType(),
5269                                       Res, ArrayType::Normal, 0);
5270 }
5271
5272 static void
5273 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5274   SrcTL = SrcTL.getUnqualifiedLoc();
5275   DstTL = DstTL.getUnqualifiedLoc();
5276   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5277     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5278     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5279                                       DstPTL.getPointeeLoc());
5280     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5281     return;
5282   }
5283   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5284     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5285     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5286                                       DstPTL.getInnerLoc());
5287     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5288     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5289     return;
5290   }
5291   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5292   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5293   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5294   TypeLoc DstElemTL = DstATL.getElementLoc();
5295   DstElemTL.initializeFullCopy(SrcElemTL);
5296   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5297   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5298   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5299 }
5300
5301 /// Helper method to turn variable array types into constant array
5302 /// types in certain situations which would otherwise be errors (for
5303 /// GCC compatibility).
5304 static TypeSourceInfo*
5305 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5306                                               ASTContext &Context,
5307                                               bool &SizeIsNegative,
5308                                               llvm::APSInt &Oversized) {
5309   QualType FixedTy
5310     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5311                                           SizeIsNegative, Oversized);
5312   if (FixedTy.isNull())
5313     return nullptr;
5314   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5315   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5316                                     FixedTInfo->getTypeLoc());
5317   return FixedTInfo;
5318 }
5319
5320 /// \brief Register the given locally-scoped extern "C" declaration so
5321 /// that it can be found later for redeclarations. We include any extern "C"
5322 /// declaration that is not visible in the translation unit here, not just
5323 /// function-scope declarations.
5324 void
5325 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5326   if (!getLangOpts().CPlusPlus &&
5327       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5328     // Don't need to track declarations in the TU in C.
5329     return;
5330
5331   // Note that we have a locally-scoped external with this name.
5332   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5333 }
5334
5335 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5336   // FIXME: We can have multiple results via __attribute__((overloadable)).
5337   auto Result = Context.getExternCContextDecl()->lookup(Name);
5338   return Result.empty() ? nullptr : *Result.begin();
5339 }
5340
5341 /// \brief Diagnose function specifiers on a declaration of an identifier that
5342 /// does not identify a function.
5343 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5344   // FIXME: We should probably indicate the identifier in question to avoid
5345   // confusion for constructs like "virtual int a(), b;"
5346   if (DS.isVirtualSpecified())
5347     Diag(DS.getVirtualSpecLoc(),
5348          diag::err_virtual_non_function);
5349
5350   if (DS.isExplicitSpecified())
5351     Diag(DS.getExplicitSpecLoc(),
5352          diag::err_explicit_non_function);
5353
5354   if (DS.isNoreturnSpecified())
5355     Diag(DS.getNoreturnSpecLoc(),
5356          diag::err_noreturn_non_function);
5357 }
5358
5359 NamedDecl*
5360 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5361                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5362   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5363   if (D.getCXXScopeSpec().isSet()) {
5364     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5365       << D.getCXXScopeSpec().getRange();
5366     D.setInvalidType();
5367     // Pretend we didn't see the scope specifier.
5368     DC = CurContext;
5369     Previous.clear();
5370   }
5371
5372   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5373
5374   if (D.getDeclSpec().isInlineSpecified())
5375     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5376         << getLangOpts().CPlusPlus1z;
5377   if (D.getDeclSpec().isConstexprSpecified())
5378     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5379       << 1;
5380   if (D.getDeclSpec().isConceptSpecified())
5381     Diag(D.getDeclSpec().getConceptSpecLoc(),
5382          diag::err_concept_wrong_decl_kind);
5383
5384   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5385     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5386       << D.getName().getSourceRange();
5387     return nullptr;
5388   }
5389
5390   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5391   if (!NewTD) return nullptr;
5392
5393   // Handle attributes prior to checking for duplicates in MergeVarDecl
5394   ProcessDeclAttributes(S, NewTD, D);
5395
5396   CheckTypedefForVariablyModifiedType(S, NewTD);
5397
5398   bool Redeclaration = D.isRedeclaration();
5399   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5400   D.setRedeclaration(Redeclaration);
5401   return ND;
5402 }
5403
5404 void
5405 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5406   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5407   // then it shall have block scope.
5408   // Note that variably modified types must be fixed before merging the decl so
5409   // that redeclarations will match.
5410   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5411   QualType T = TInfo->getType();
5412   if (T->isVariablyModifiedType()) {
5413     getCurFunction()->setHasBranchProtectedScope();
5414
5415     if (S->getFnParent() == nullptr) {
5416       bool SizeIsNegative;
5417       llvm::APSInt Oversized;
5418       TypeSourceInfo *FixedTInfo =
5419         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5420                                                       SizeIsNegative,
5421                                                       Oversized);
5422       if (FixedTInfo) {
5423         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5424         NewTD->setTypeSourceInfo(FixedTInfo);
5425       } else {
5426         if (SizeIsNegative)
5427           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5428         else if (T->isVariableArrayType())
5429           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5430         else if (Oversized.getBoolValue())
5431           Diag(NewTD->getLocation(), diag::err_array_too_large)
5432             << Oversized.toString(10);
5433         else
5434           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5435         NewTD->setInvalidDecl();
5436       }
5437     }
5438   }
5439 }
5440
5441 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5442 /// declares a typedef-name, either using the 'typedef' type specifier or via
5443 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5444 NamedDecl*
5445 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5446                            LookupResult &Previous, bool &Redeclaration) {
5447   // Merge the decl with the existing one if appropriate. If the decl is
5448   // in an outer scope, it isn't the same thing.
5449   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5450                        /*AllowInlineNamespace*/false);
5451   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5452   if (!Previous.empty()) {
5453     Redeclaration = true;
5454     MergeTypedefNameDecl(S, NewTD, Previous);
5455   }
5456
5457   // If this is the C FILE type, notify the AST context.
5458   if (IdentifierInfo *II = NewTD->getIdentifier())
5459     if (!NewTD->isInvalidDecl() &&
5460         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5461       if (II->isStr("FILE"))
5462         Context.setFILEDecl(NewTD);
5463       else if (II->isStr("jmp_buf"))
5464         Context.setjmp_bufDecl(NewTD);
5465       else if (II->isStr("sigjmp_buf"))
5466         Context.setsigjmp_bufDecl(NewTD);
5467       else if (II->isStr("ucontext_t"))
5468         Context.setucontext_tDecl(NewTD);
5469     }
5470
5471   return NewTD;
5472 }
5473
5474 /// \brief Determines whether the given declaration is an out-of-scope
5475 /// previous declaration.
5476 ///
5477 /// This routine should be invoked when name lookup has found a
5478 /// previous declaration (PrevDecl) that is not in the scope where a
5479 /// new declaration by the same name is being introduced. If the new
5480 /// declaration occurs in a local scope, previous declarations with
5481 /// linkage may still be considered previous declarations (C99
5482 /// 6.2.2p4-5, C++ [basic.link]p6).
5483 ///
5484 /// \param PrevDecl the previous declaration found by name
5485 /// lookup
5486 ///
5487 /// \param DC the context in which the new declaration is being
5488 /// declared.
5489 ///
5490 /// \returns true if PrevDecl is an out-of-scope previous declaration
5491 /// for a new delcaration with the same name.
5492 static bool
5493 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5494                                 ASTContext &Context) {
5495   if (!PrevDecl)
5496     return false;
5497
5498   if (!PrevDecl->hasLinkage())
5499     return false;
5500
5501   if (Context.getLangOpts().CPlusPlus) {
5502     // C++ [basic.link]p6:
5503     //   If there is a visible declaration of an entity with linkage
5504     //   having the same name and type, ignoring entities declared
5505     //   outside the innermost enclosing namespace scope, the block
5506     //   scope declaration declares that same entity and receives the
5507     //   linkage of the previous declaration.
5508     DeclContext *OuterContext = DC->getRedeclContext();
5509     if (!OuterContext->isFunctionOrMethod())
5510       // This rule only applies to block-scope declarations.
5511       return false;
5512
5513     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5514     if (PrevOuterContext->isRecord())
5515       // We found a member function: ignore it.
5516       return false;
5517
5518     // Find the innermost enclosing namespace for the new and
5519     // previous declarations.
5520     OuterContext = OuterContext->getEnclosingNamespaceContext();
5521     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5522
5523     // The previous declaration is in a different namespace, so it
5524     // isn't the same function.
5525     if (!OuterContext->Equals(PrevOuterContext))
5526       return false;
5527   }
5528
5529   return true;
5530 }
5531
5532 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5533   CXXScopeSpec &SS = D.getCXXScopeSpec();
5534   if (!SS.isSet()) return;
5535   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5536 }
5537
5538 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5539   QualType type = decl->getType();
5540   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5541   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5542     // Various kinds of declaration aren't allowed to be __autoreleasing.
5543     unsigned kind = -1U;
5544     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5545       if (var->hasAttr<BlocksAttr>())
5546         kind = 0; // __block
5547       else if (!var->hasLocalStorage())
5548         kind = 1; // global
5549     } else if (isa<ObjCIvarDecl>(decl)) {
5550       kind = 3; // ivar
5551     } else if (isa<FieldDecl>(decl)) {
5552       kind = 2; // field
5553     }
5554
5555     if (kind != -1U) {
5556       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5557         << kind;
5558     }
5559   } else if (lifetime == Qualifiers::OCL_None) {
5560     // Try to infer lifetime.
5561     if (!type->isObjCLifetimeType())
5562       return false;
5563
5564     lifetime = type->getObjCARCImplicitLifetime();
5565     type = Context.getLifetimeQualifiedType(type, lifetime);
5566     decl->setType(type);
5567   }
5568
5569   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5570     // Thread-local variables cannot have lifetime.
5571     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5572         var->getTLSKind()) {
5573       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5574         << var->getType();
5575       return true;
5576     }
5577   }
5578
5579   return false;
5580 }
5581
5582 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5583   // Ensure that an auto decl is deduced otherwise the checks below might cache
5584   // the wrong linkage.
5585   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5586
5587   // 'weak' only applies to declarations with external linkage.
5588   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5589     if (!ND.isExternallyVisible()) {
5590       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5591       ND.dropAttr<WeakAttr>();
5592     }
5593   }
5594   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5595     if (ND.isExternallyVisible()) {
5596       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5597       ND.dropAttr<WeakRefAttr>();
5598       ND.dropAttr<AliasAttr>();
5599     }
5600   }
5601
5602   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5603     if (VD->hasInit()) {
5604       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5605         assert(VD->isThisDeclarationADefinition() &&
5606                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5607         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5608         VD->dropAttr<AliasAttr>();
5609       }
5610     }
5611   }
5612
5613   // 'selectany' only applies to externally visible variable declarations.
5614   // It does not apply to functions.
5615   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5616     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5617       S.Diag(Attr->getLocation(),
5618              diag::err_attribute_selectany_non_extern_data);
5619       ND.dropAttr<SelectAnyAttr>();
5620     }
5621   }
5622
5623   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5624     // dll attributes require external linkage. Static locals may have external
5625     // linkage but still cannot be explicitly imported or exported.
5626     auto *VD = dyn_cast<VarDecl>(&ND);
5627     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5628       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5629         << &ND << Attr;
5630       ND.setInvalidDecl();
5631     }
5632   }
5633
5634   // Virtual functions cannot be marked as 'notail'.
5635   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5636     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5637       if (MD->isVirtual()) {
5638         S.Diag(ND.getLocation(),
5639                diag::err_invalid_attribute_on_virtual_function)
5640             << Attr;
5641         ND.dropAttr<NotTailCalledAttr>();
5642       }
5643 }
5644
5645 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5646                                            NamedDecl *NewDecl,
5647                                            bool IsSpecialization,
5648                                            bool IsDefinition) {
5649   if (OldDecl->isInvalidDecl())
5650     return;
5651
5652   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5653     OldDecl = OldTD->getTemplatedDecl();
5654     if (!IsSpecialization)
5655       IsDefinition = false;
5656   }
5657   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5658     NewDecl = NewTD->getTemplatedDecl();
5659
5660   if (!OldDecl || !NewDecl)
5661     return;
5662
5663   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5664   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5665   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5666   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5667
5668   // dllimport and dllexport are inheritable attributes so we have to exclude
5669   // inherited attribute instances.
5670   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5671                     (NewExportAttr && !NewExportAttr->isInherited());
5672
5673   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5674   // the only exception being explicit specializations.
5675   // Implicitly generated declarations are also excluded for now because there
5676   // is no other way to switch these to use dllimport or dllexport.
5677   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5678
5679   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5680     // Allow with a warning for free functions and global variables.
5681     bool JustWarn = false;
5682     if (!OldDecl->isCXXClassMember()) {
5683       auto *VD = dyn_cast<VarDecl>(OldDecl);
5684       if (VD && !VD->getDescribedVarTemplate())
5685         JustWarn = true;
5686       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5687       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5688         JustWarn = true;
5689     }
5690
5691     // We cannot change a declaration that's been used because IR has already
5692     // been emitted. Dllimported functions will still work though (modulo
5693     // address equality) as they can use the thunk.
5694     if (OldDecl->isUsed())
5695       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5696         JustWarn = false;
5697
5698     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5699                                : diag::err_attribute_dll_redeclaration;
5700     S.Diag(NewDecl->getLocation(), DiagID)
5701         << NewDecl
5702         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5703     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5704     if (!JustWarn) {
5705       NewDecl->setInvalidDecl();
5706       return;
5707     }
5708   }
5709
5710   // A redeclaration is not allowed to drop a dllimport attribute, the only
5711   // exceptions being inline function definitions, local extern declarations,
5712   // qualified friend declarations or special MSVC extension: in the last case,
5713   // the declaration is treated as if it were marked dllexport.
5714   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5715   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5716   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5717     // Ignore static data because out-of-line definitions are diagnosed
5718     // separately.
5719     IsStaticDataMember = VD->isStaticDataMember();
5720     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5721                    VarDecl::DeclarationOnly;
5722   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5723     IsInline = FD->isInlined();
5724     IsQualifiedFriend = FD->getQualifier() &&
5725                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5726   }
5727
5728   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5729       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5730     if (IsMicrosoft && IsDefinition) {
5731       S.Diag(NewDecl->getLocation(),
5732              diag::warn_redeclaration_without_import_attribute)
5733           << NewDecl;
5734       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5735       NewDecl->dropAttr<DLLImportAttr>();
5736       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5737           NewImportAttr->getRange(), S.Context,
5738           NewImportAttr->getSpellingListIndex()));
5739     } else {
5740       S.Diag(NewDecl->getLocation(),
5741              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5742           << NewDecl << OldImportAttr;
5743       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5744       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5745       OldDecl->dropAttr<DLLImportAttr>();
5746       NewDecl->dropAttr<DLLImportAttr>();
5747     }
5748   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5749     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5750     OldDecl->dropAttr<DLLImportAttr>();
5751     NewDecl->dropAttr<DLLImportAttr>();
5752     S.Diag(NewDecl->getLocation(),
5753            diag::warn_dllimport_dropped_from_inline_function)
5754         << NewDecl << OldImportAttr;
5755   }
5756 }
5757
5758 /// Given that we are within the definition of the given function,
5759 /// will that definition behave like C99's 'inline', where the
5760 /// definition is discarded except for optimization purposes?
5761 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5762   // Try to avoid calling GetGVALinkageForFunction.
5763
5764   // All cases of this require the 'inline' keyword.
5765   if (!FD->isInlined()) return false;
5766
5767   // This is only possible in C++ with the gnu_inline attribute.
5768   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5769     return false;
5770
5771   // Okay, go ahead and call the relatively-more-expensive function.
5772   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5773 }
5774
5775 /// Determine whether a variable is extern "C" prior to attaching
5776 /// an initializer. We can't just call isExternC() here, because that
5777 /// will also compute and cache whether the declaration is externally
5778 /// visible, which might change when we attach the initializer.
5779 ///
5780 /// This can only be used if the declaration is known to not be a
5781 /// redeclaration of an internal linkage declaration.
5782 ///
5783 /// For instance:
5784 ///
5785 ///   auto x = []{};
5786 ///
5787 /// Attaching the initializer here makes this declaration not externally
5788 /// visible, because its type has internal linkage.
5789 ///
5790 /// FIXME: This is a hack.
5791 template<typename T>
5792 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5793   if (S.getLangOpts().CPlusPlus) {
5794     // In C++, the overloadable attribute negates the effects of extern "C".
5795     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5796       return false;
5797
5798     // So do CUDA's host/device attributes.
5799     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5800                                  D->template hasAttr<CUDAHostAttr>()))
5801       return false;
5802   }
5803   return D->isExternC();
5804 }
5805
5806 static bool shouldConsiderLinkage(const VarDecl *VD) {
5807   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5808   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5809     return VD->hasExternalStorage();
5810   if (DC->isFileContext())
5811     return true;
5812   if (DC->isRecord())
5813     return false;
5814   llvm_unreachable("Unexpected context");
5815 }
5816
5817 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5818   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5819   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5820       isa<OMPDeclareReductionDecl>(DC))
5821     return true;
5822   if (DC->isRecord())
5823     return false;
5824   llvm_unreachable("Unexpected context");
5825 }
5826
5827 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5828                           AttributeList::Kind Kind) {
5829   for (const AttributeList *L = AttrList; L; L = L->getNext())
5830     if (L->getKind() == Kind)
5831       return true;
5832   return false;
5833 }
5834
5835 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5836                           AttributeList::Kind Kind) {
5837   // Check decl attributes on the DeclSpec.
5838   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5839     return true;
5840
5841   // Walk the declarator structure, checking decl attributes that were in a type
5842   // position to the decl itself.
5843   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5844     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5845       return true;
5846   }
5847
5848   // Finally, check attributes on the decl itself.
5849   return hasParsedAttr(S, PD.getAttributes(), Kind);
5850 }
5851
5852 /// Adjust the \c DeclContext for a function or variable that might be a
5853 /// function-local external declaration.
5854 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5855   if (!DC->isFunctionOrMethod())
5856     return false;
5857
5858   // If this is a local extern function or variable declared within a function
5859   // template, don't add it into the enclosing namespace scope until it is
5860   // instantiated; it might have a dependent type right now.
5861   if (DC->isDependentContext())
5862     return true;
5863
5864   // C++11 [basic.link]p7:
5865   //   When a block scope declaration of an entity with linkage is not found to
5866   //   refer to some other declaration, then that entity is a member of the
5867   //   innermost enclosing namespace.
5868   //
5869   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5870   // semantically-enclosing namespace, not a lexically-enclosing one.
5871   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5872     DC = DC->getParent();
5873   return true;
5874 }
5875
5876 /// \brief Returns true if given declaration has external C language linkage.
5877 static bool isDeclExternC(const Decl *D) {
5878   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5879     return FD->isExternC();
5880   if (const auto *VD = dyn_cast<VarDecl>(D))
5881     return VD->isExternC();
5882
5883   llvm_unreachable("Unknown type of decl!");
5884 }
5885
5886 NamedDecl *Sema::ActOnVariableDeclarator(
5887     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5888     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5889     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5890   QualType R = TInfo->getType();
5891   DeclarationName Name = GetNameForDeclarator(D).getName();
5892
5893   IdentifierInfo *II = Name.getAsIdentifierInfo();
5894
5895   if (D.isDecompositionDeclarator()) {
5896     AddToScope = false;
5897     // Take the name of the first declarator as our name for diagnostic
5898     // purposes.
5899     auto &Decomp = D.getDecompositionDeclarator();
5900     if (!Decomp.bindings().empty()) {
5901       II = Decomp.bindings()[0].Name;
5902       Name = II;
5903     }
5904   } else if (!II) {
5905     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5906       << Name;
5907     return nullptr;
5908   }
5909
5910   if (getLangOpts().OpenCL) {
5911     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5912     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5913     // argument.
5914     if (R->isImageType() || R->isPipeType()) {
5915       Diag(D.getIdentifierLoc(),
5916            diag::err_opencl_type_can_only_be_used_as_function_parameter)
5917           << R;
5918       D.setInvalidType();
5919       return nullptr;
5920     }
5921
5922     // OpenCL v1.2 s6.9.r:
5923     // The event type cannot be used to declare a program scope variable.
5924     // OpenCL v2.0 s6.9.q:
5925     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
5926     if (NULL == S->getParent()) {
5927       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
5928         Diag(D.getIdentifierLoc(),
5929              diag::err_invalid_type_for_program_scope_var) << R;
5930         D.setInvalidType();
5931         return nullptr;
5932       }
5933     }
5934
5935     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5936     QualType NR = R;
5937     while (NR->isPointerType()) {
5938       if (NR->isFunctionPointerType()) {
5939         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5940         D.setInvalidType();
5941         break;
5942       }
5943       NR = NR->getPointeeType();
5944     }
5945
5946     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
5947       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5948       // half array type (unless the cl_khr_fp16 extension is enabled).
5949       if (Context.getBaseElementType(R)->isHalfType()) {
5950         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5951         D.setInvalidType();
5952       }
5953     }
5954
5955     // OpenCL v1.2 s6.9.b p4:
5956     // The sampler type cannot be used with the __local and __global address
5957     // space qualifiers.
5958     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5959       R.getAddressSpace() == LangAS::opencl_global)) {
5960       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5961     }
5962
5963     // OpenCL v1.2 s6.9.r:
5964     // The event type cannot be used with the __local, __constant and __global
5965     // address space qualifiers.
5966     if (R->isEventT()) {
5967       if (R.getAddressSpace()) {
5968         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5969         D.setInvalidType();
5970       }
5971     }
5972   }
5973
5974   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5975   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5976
5977   // dllimport globals without explicit storage class are treated as extern. We
5978   // have to change the storage class this early to get the right DeclContext.
5979   if (SC == SC_None && !DC->isRecord() &&
5980       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5981       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5982     SC = SC_Extern;
5983
5984   DeclContext *OriginalDC = DC;
5985   bool IsLocalExternDecl = SC == SC_Extern &&
5986                            adjustContextForLocalExternDecl(DC);
5987
5988   if (SCSpec == DeclSpec::SCS_mutable) {
5989     // mutable can only appear on non-static class members, so it's always
5990     // an error here
5991     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5992     D.setInvalidType();
5993     SC = SC_None;
5994   }
5995
5996   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5997       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5998                               D.getDeclSpec().getStorageClassSpecLoc())) {
5999     // In C++11, the 'register' storage class specifier is deprecated.
6000     // Suppress the warning in system macros, it's used in macros in some
6001     // popular C system headers, such as in glibc's htonl() macro.
6002     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6003          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6004                                    : diag::warn_deprecated_register)
6005       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6006   }
6007
6008   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6009
6010   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6011     // C99 6.9p2: The storage-class specifiers auto and register shall not
6012     // appear in the declaration specifiers in an external declaration.
6013     // Global Register+Asm is a GNU extension we support.
6014     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6015       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6016       D.setInvalidType();
6017     }
6018   }
6019
6020   bool IsExplicitSpecialization = false;
6021   bool IsVariableTemplateSpecialization = false;
6022   bool IsPartialSpecialization = false;
6023   bool IsVariableTemplate = false;
6024   VarDecl *NewVD = nullptr;
6025   VarTemplateDecl *NewTemplate = nullptr;
6026   TemplateParameterList *TemplateParams = nullptr;
6027   if (!getLangOpts().CPlusPlus) {
6028     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6029                             D.getIdentifierLoc(), II,
6030                             R, TInfo, SC);
6031
6032     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6033       ParsingInitForAutoVars.insert(NewVD);
6034
6035     if (D.isInvalidType())
6036       NewVD->setInvalidDecl();
6037   } else {
6038     bool Invalid = false;
6039
6040     if (DC->isRecord() && !CurContext->isRecord()) {
6041       // This is an out-of-line definition of a static data member.
6042       switch (SC) {
6043       case SC_None:
6044         break;
6045       case SC_Static:
6046         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6047              diag::err_static_out_of_line)
6048           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6049         break;
6050       case SC_Auto:
6051       case SC_Register:
6052       case SC_Extern:
6053         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6054         // to names of variables declared in a block or to function parameters.
6055         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6056         // of class members
6057
6058         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6059              diag::err_storage_class_for_static_member)
6060           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6061         break;
6062       case SC_PrivateExtern:
6063         llvm_unreachable("C storage class in c++!");
6064       }
6065     }
6066
6067     if (SC == SC_Static && CurContext->isRecord()) {
6068       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6069         if (RD->isLocalClass())
6070           Diag(D.getIdentifierLoc(),
6071                diag::err_static_data_member_not_allowed_in_local_class)
6072             << Name << RD->getDeclName();
6073
6074         // C++98 [class.union]p1: If a union contains a static data member,
6075         // the program is ill-formed. C++11 drops this restriction.
6076         if (RD->isUnion())
6077           Diag(D.getIdentifierLoc(),
6078                getLangOpts().CPlusPlus11
6079                  ? diag::warn_cxx98_compat_static_data_member_in_union
6080                  : diag::ext_static_data_member_in_union) << Name;
6081         // We conservatively disallow static data members in anonymous structs.
6082         else if (!RD->getDeclName())
6083           Diag(D.getIdentifierLoc(),
6084                diag::err_static_data_member_not_allowed_in_anon_struct)
6085             << Name << RD->isUnion();
6086       }
6087     }
6088
6089     // Match up the template parameter lists with the scope specifier, then
6090     // determine whether we have a template or a template specialization.
6091     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6092         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6093         D.getCXXScopeSpec(),
6094         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6095             ? D.getName().TemplateId
6096             : nullptr,
6097         TemplateParamLists,
6098         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6099
6100     if (TemplateParams) {
6101       if (!TemplateParams->size() &&
6102           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6103         // There is an extraneous 'template<>' for this variable. Complain
6104         // about it, but allow the declaration of the variable.
6105         Diag(TemplateParams->getTemplateLoc(),
6106              diag::err_template_variable_noparams)
6107           << II
6108           << SourceRange(TemplateParams->getTemplateLoc(),
6109                          TemplateParams->getRAngleLoc());
6110         TemplateParams = nullptr;
6111       } else {
6112         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6113           // This is an explicit specialization or a partial specialization.
6114           // FIXME: Check that we can declare a specialization here.
6115           IsVariableTemplateSpecialization = true;
6116           IsPartialSpecialization = TemplateParams->size() > 0;
6117         } else { // if (TemplateParams->size() > 0)
6118           // This is a template declaration.
6119           IsVariableTemplate = true;
6120
6121           // Check that we can declare a template here.
6122           if (CheckTemplateDeclScope(S, TemplateParams))
6123             return nullptr;
6124
6125           // Only C++1y supports variable templates (N3651).
6126           Diag(D.getIdentifierLoc(),
6127                getLangOpts().CPlusPlus14
6128                    ? diag::warn_cxx11_compat_variable_template
6129                    : diag::ext_variable_template);
6130         }
6131       }
6132     } else {
6133       assert(
6134           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6135           "should have a 'template<>' for this decl");
6136     }
6137
6138     if (IsVariableTemplateSpecialization) {
6139       SourceLocation TemplateKWLoc =
6140           TemplateParamLists.size() > 0
6141               ? TemplateParamLists[0]->getTemplateLoc()
6142               : SourceLocation();
6143       DeclResult Res = ActOnVarTemplateSpecialization(
6144           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6145           IsPartialSpecialization);
6146       if (Res.isInvalid())
6147         return nullptr;
6148       NewVD = cast<VarDecl>(Res.get());
6149       AddToScope = false;
6150     } else if (D.isDecompositionDeclarator()) {
6151       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6152                                         D.getIdentifierLoc(), R, TInfo, SC,
6153                                         Bindings);
6154     } else
6155       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6156                               D.getIdentifierLoc(), II, R, TInfo, SC);
6157
6158     // If this is supposed to be a variable template, create it as such.
6159     if (IsVariableTemplate) {
6160       NewTemplate =
6161           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6162                                   TemplateParams, NewVD);
6163       NewVD->setDescribedVarTemplate(NewTemplate);
6164     }
6165
6166     // If this decl has an auto type in need of deduction, make a note of the
6167     // Decl so we can diagnose uses of it in its own initializer.
6168     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6169       ParsingInitForAutoVars.insert(NewVD);
6170
6171     if (D.isInvalidType() || Invalid) {
6172       NewVD->setInvalidDecl();
6173       if (NewTemplate)
6174         NewTemplate->setInvalidDecl();
6175     }
6176
6177     SetNestedNameSpecifier(NewVD, D);
6178
6179     // If we have any template parameter lists that don't directly belong to
6180     // the variable (matching the scope specifier), store them.
6181     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6182     if (TemplateParamLists.size() > VDTemplateParamLists)
6183       NewVD->setTemplateParameterListsInfo(
6184           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6185
6186     if (D.getDeclSpec().isConstexprSpecified()) {
6187       NewVD->setConstexpr(true);
6188       // C++1z [dcl.spec.constexpr]p1:
6189       //   A static data member declared with the constexpr specifier is
6190       //   implicitly an inline variable.
6191       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6192         NewVD->setImplicitlyInline();
6193     }
6194
6195     if (D.getDeclSpec().isConceptSpecified()) {
6196       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6197         VTD->setConcept();
6198
6199       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6200       // be declared with the thread_local, inline, friend, or constexpr
6201       // specifiers, [...]
6202       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6203         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6204              diag::err_concept_decl_invalid_specifiers)
6205             << 0 << 0;
6206         NewVD->setInvalidDecl(true);
6207       }
6208
6209       if (D.getDeclSpec().isConstexprSpecified()) {
6210         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6211              diag::err_concept_decl_invalid_specifiers)
6212             << 0 << 3;
6213         NewVD->setInvalidDecl(true);
6214       }
6215
6216       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6217       // applied only to the definition of a function template or variable
6218       // template, declared in namespace scope.
6219       if (IsVariableTemplateSpecialization) {
6220         Diag(D.getDeclSpec().getConceptSpecLoc(),
6221              diag::err_concept_specified_specialization)
6222             << (IsPartialSpecialization ? 2 : 1);
6223       }
6224
6225       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6226       // following restrictions:
6227       // - The declared type shall have the type bool.
6228       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6229           !NewVD->isInvalidDecl()) {
6230         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6231         NewVD->setInvalidDecl(true);
6232       }
6233     }
6234   }
6235
6236   if (D.getDeclSpec().isInlineSpecified()) {
6237     if (!getLangOpts().CPlusPlus) {
6238       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6239           << 0;
6240     } else if (CurContext->isFunctionOrMethod()) {
6241       // 'inline' is not allowed on block scope variable declaration.
6242       Diag(D.getDeclSpec().getInlineSpecLoc(),
6243            diag::err_inline_declaration_block_scope) << Name
6244         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6245     } else {
6246       Diag(D.getDeclSpec().getInlineSpecLoc(),
6247            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6248                                      : diag::ext_inline_variable);
6249       NewVD->setInlineSpecified();
6250     }
6251   }
6252
6253   // Set the lexical context. If the declarator has a C++ scope specifier, the
6254   // lexical context will be different from the semantic context.
6255   NewVD->setLexicalDeclContext(CurContext);
6256   if (NewTemplate)
6257     NewTemplate->setLexicalDeclContext(CurContext);
6258
6259   if (IsLocalExternDecl) {
6260     if (D.isDecompositionDeclarator())
6261       for (auto *B : Bindings)
6262         B->setLocalExternDecl();
6263     else
6264       NewVD->setLocalExternDecl();
6265   }
6266
6267   bool EmitTLSUnsupportedError = false;
6268   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6269     // C++11 [dcl.stc]p4:
6270     //   When thread_local is applied to a variable of block scope the
6271     //   storage-class-specifier static is implied if it does not appear
6272     //   explicitly.
6273     // Core issue: 'static' is not implied if the variable is declared
6274     //   'extern'.
6275     if (NewVD->hasLocalStorage() &&
6276         (SCSpec != DeclSpec::SCS_unspecified ||
6277          TSCS != DeclSpec::TSCS_thread_local ||
6278          !DC->isFunctionOrMethod()))
6279       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6280            diag::err_thread_non_global)
6281         << DeclSpec::getSpecifierName(TSCS);
6282     else if (!Context.getTargetInfo().isTLSSupported()) {
6283       if (getLangOpts().CUDA) {
6284         // Postpone error emission until we've collected attributes required to
6285         // figure out whether it's a host or device variable and whether the
6286         // error should be ignored.
6287         EmitTLSUnsupportedError = true;
6288         // We still need to mark the variable as TLS so it shows up in AST with
6289         // proper storage class for other tools to use even if we're not going
6290         // to emit any code for it.
6291         NewVD->setTSCSpec(TSCS);
6292       } else
6293         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6294              diag::err_thread_unsupported);
6295     } else
6296       NewVD->setTSCSpec(TSCS);
6297   }
6298
6299   // C99 6.7.4p3
6300   //   An inline definition of a function with external linkage shall
6301   //   not contain a definition of a modifiable object with static or
6302   //   thread storage duration...
6303   // We only apply this when the function is required to be defined
6304   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6305   // that a local variable with thread storage duration still has to
6306   // be marked 'static'.  Also note that it's possible to get these
6307   // semantics in C++ using __attribute__((gnu_inline)).
6308   if (SC == SC_Static && S->getFnParent() != nullptr &&
6309       !NewVD->getType().isConstQualified()) {
6310     FunctionDecl *CurFD = getCurFunctionDecl();
6311     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6312       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6313            diag::warn_static_local_in_extern_inline);
6314       MaybeSuggestAddingStaticToDecl(CurFD);
6315     }
6316   }
6317
6318   if (D.getDeclSpec().isModulePrivateSpecified()) {
6319     if (IsVariableTemplateSpecialization)
6320       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6321           << (IsPartialSpecialization ? 1 : 0)
6322           << FixItHint::CreateRemoval(
6323                  D.getDeclSpec().getModulePrivateSpecLoc());
6324     else if (IsExplicitSpecialization)
6325       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6326         << 2
6327         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6328     else if (NewVD->hasLocalStorage())
6329       Diag(NewVD->getLocation(), diag::err_module_private_local)
6330         << 0 << NewVD->getDeclName()
6331         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6332         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6333     else {
6334       NewVD->setModulePrivate();
6335       if (NewTemplate)
6336         NewTemplate->setModulePrivate();
6337       for (auto *B : Bindings)
6338         B->setModulePrivate();
6339     }
6340   }
6341
6342   // Handle attributes prior to checking for duplicates in MergeVarDecl
6343   ProcessDeclAttributes(S, NewVD, D);
6344
6345   if (getLangOpts().CUDA) {
6346     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6347       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6348            diag::err_thread_unsupported);
6349     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6350     // storage [duration]."
6351     if (SC == SC_None && S->getFnParent() != nullptr &&
6352         (NewVD->hasAttr<CUDASharedAttr>() ||
6353          NewVD->hasAttr<CUDAConstantAttr>())) {
6354       NewVD->setStorageClass(SC_Static);
6355     }
6356   }
6357
6358   // Ensure that dllimport globals without explicit storage class are treated as
6359   // extern. The storage class is set above using parsed attributes. Now we can
6360   // check the VarDecl itself.
6361   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6362          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6363          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6364
6365   // In auto-retain/release, infer strong retension for variables of
6366   // retainable type.
6367   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6368     NewVD->setInvalidDecl();
6369
6370   // Handle GNU asm-label extension (encoded as an attribute).
6371   if (Expr *E = (Expr*)D.getAsmLabel()) {
6372     // The parser guarantees this is a string.
6373     StringLiteral *SE = cast<StringLiteral>(E);
6374     StringRef Label = SE->getString();
6375     if (S->getFnParent() != nullptr) {
6376       switch (SC) {
6377       case SC_None:
6378       case SC_Auto:
6379         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6380         break;
6381       case SC_Register:
6382         // Local Named register
6383         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6384             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6385           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6386         break;
6387       case SC_Static:
6388       case SC_Extern:
6389       case SC_PrivateExtern:
6390         break;
6391       }
6392     } else if (SC == SC_Register) {
6393       // Global Named register
6394       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6395         const auto &TI = Context.getTargetInfo();
6396         bool HasSizeMismatch;
6397
6398         if (!TI.isValidGCCRegisterName(Label))
6399           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6400         else if (!TI.validateGlobalRegisterVariable(Label,
6401                                                     Context.getTypeSize(R),
6402                                                     HasSizeMismatch))
6403           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6404         else if (HasSizeMismatch)
6405           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6406       }
6407
6408       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6409         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6410         NewVD->setInvalidDecl(true);
6411       }
6412     }
6413
6414     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6415                                                 Context, Label, 0));
6416   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6417     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6418       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6419     if (I != ExtnameUndeclaredIdentifiers.end()) {
6420       if (isDeclExternC(NewVD)) {
6421         NewVD->addAttr(I->second);
6422         ExtnameUndeclaredIdentifiers.erase(I);
6423       } else
6424         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6425             << /*Variable*/1 << NewVD;
6426     }
6427   }
6428
6429   // Find the shadowed declaration before filtering for scope.
6430   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6431                                 ? getShadowedDeclaration(NewVD, Previous)
6432                                 : nullptr;
6433
6434   // Don't consider existing declarations that are in a different
6435   // scope and are out-of-semantic-context declarations (if the new
6436   // declaration has linkage).
6437   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6438                        D.getCXXScopeSpec().isNotEmpty() ||
6439                        IsExplicitSpecialization ||
6440                        IsVariableTemplateSpecialization);
6441
6442   // Check whether the previous declaration is in the same block scope. This
6443   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6444   if (getLangOpts().CPlusPlus &&
6445       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6446     NewVD->setPreviousDeclInSameBlockScope(
6447         Previous.isSingleResult() && !Previous.isShadowed() &&
6448         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6449
6450   if (!getLangOpts().CPlusPlus) {
6451     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6452   } else {
6453     // If this is an explicit specialization of a static data member, check it.
6454     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6455         CheckMemberSpecialization(NewVD, Previous))
6456       NewVD->setInvalidDecl();
6457
6458     // Merge the decl with the existing one if appropriate.
6459     if (!Previous.empty()) {
6460       if (Previous.isSingleResult() &&
6461           isa<FieldDecl>(Previous.getFoundDecl()) &&
6462           D.getCXXScopeSpec().isSet()) {
6463         // The user tried to define a non-static data member
6464         // out-of-line (C++ [dcl.meaning]p1).
6465         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6466           << D.getCXXScopeSpec().getRange();
6467         Previous.clear();
6468         NewVD->setInvalidDecl();
6469       }
6470     } else if (D.getCXXScopeSpec().isSet()) {
6471       // No previous declaration in the qualifying scope.
6472       Diag(D.getIdentifierLoc(), diag::err_no_member)
6473         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6474         << D.getCXXScopeSpec().getRange();
6475       NewVD->setInvalidDecl();
6476     }
6477
6478     if (!IsVariableTemplateSpecialization)
6479       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6480
6481     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6482     // an explicit specialization (14.8.3) or a partial specialization of a
6483     // concept definition.
6484     if (IsVariableTemplateSpecialization &&
6485         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6486         Previous.isSingleResult()) {
6487       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6488       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6489         if (VarTmpl->isConcept()) {
6490           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6491               << 1                            /*variable*/
6492               << (IsPartialSpecialization ? 2 /*partially specialized*/
6493                                           : 1 /*explicitly specialized*/);
6494           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6495           NewVD->setInvalidDecl();
6496         }
6497       }
6498     }
6499
6500     if (NewTemplate) {
6501       VarTemplateDecl *PrevVarTemplate =
6502           NewVD->getPreviousDecl()
6503               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6504               : nullptr;
6505
6506       // Check the template parameter list of this declaration, possibly
6507       // merging in the template parameter list from the previous variable
6508       // template declaration.
6509       if (CheckTemplateParameterList(
6510               TemplateParams,
6511               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6512                               : nullptr,
6513               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6514                DC->isDependentContext())
6515                   ? TPC_ClassTemplateMember
6516                   : TPC_VarTemplate))
6517         NewVD->setInvalidDecl();
6518
6519       // If we are providing an explicit specialization of a static variable
6520       // template, make a note of that.
6521       if (PrevVarTemplate &&
6522           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6523         PrevVarTemplate->setMemberSpecialization();
6524     }
6525   }
6526
6527   // Diagnose shadowed variables iff this isn't a redeclaration.
6528   if (ShadowedDecl && !D.isRedeclaration())
6529     CheckShadow(NewVD, ShadowedDecl, Previous);
6530
6531   ProcessPragmaWeak(S, NewVD);
6532
6533   // If this is the first declaration of an extern C variable, update
6534   // the map of such variables.
6535   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6536       isIncompleteDeclExternC(*this, NewVD))
6537     RegisterLocallyScopedExternCDecl(NewVD, S);
6538
6539   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6540     Decl *ManglingContextDecl;
6541     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6542             NewVD->getDeclContext(), ManglingContextDecl)) {
6543       Context.setManglingNumber(
6544           NewVD, MCtx->getManglingNumber(
6545                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6546       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6547     }
6548   }
6549
6550   // Special handling of variable named 'main'.
6551   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6552       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6553       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6554
6555     // C++ [basic.start.main]p3
6556     // A program that declares a variable main at global scope is ill-formed.
6557     if (getLangOpts().CPlusPlus)
6558       Diag(D.getLocStart(), diag::err_main_global_variable);
6559
6560     // In C, and external-linkage variable named main results in undefined
6561     // behavior.
6562     else if (NewVD->hasExternalFormalLinkage())
6563       Diag(D.getLocStart(), diag::warn_main_redefined);
6564   }
6565
6566   if (D.isRedeclaration() && !Previous.empty()) {
6567     checkDLLAttributeRedeclaration(
6568         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6569         IsExplicitSpecialization, D.isFunctionDefinition());
6570   }
6571
6572   if (NewTemplate) {
6573     if (NewVD->isInvalidDecl())
6574       NewTemplate->setInvalidDecl();
6575     ActOnDocumentableDecl(NewTemplate);
6576     return NewTemplate;
6577   }
6578
6579   return NewVD;
6580 }
6581
6582 /// Enum describing the %select options in diag::warn_decl_shadow.
6583 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6584
6585 /// Determine what kind of declaration we're shadowing.
6586 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6587                                                 const DeclContext *OldDC) {
6588   if (isa<RecordDecl>(OldDC))
6589     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6590   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6591 }
6592
6593 /// Return the location of the capture if the given lambda captures the given
6594 /// variable \p VD, or an invalid source location otherwise.
6595 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6596                                          const VarDecl *VD) {
6597   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6598     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6599       return Capture.getLocation();
6600   }
6601   return SourceLocation();
6602 }
6603
6604 /// \brief Return the declaration shadowed by the given variable \p D, or null
6605 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6606 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6607                                         const LookupResult &R) {
6608   // Return if warning is ignored.
6609   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6610     return nullptr;
6611
6612   // Don't diagnose declarations at file scope.
6613   if (D->hasGlobalStorage())
6614     return nullptr;
6615
6616   // Only diagnose if we're shadowing an unambiguous field or variable.
6617   if (R.getResultKind() != LookupResult::Found)
6618     return nullptr;
6619
6620   NamedDecl *ShadowedDecl = R.getFoundDecl();
6621   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6622              ? ShadowedDecl
6623              : nullptr;
6624 }
6625
6626 /// \brief Diagnose variable or built-in function shadowing.  Implements
6627 /// -Wshadow.
6628 ///
6629 /// This method is called whenever a VarDecl is added to a "useful"
6630 /// scope.
6631 ///
6632 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6633 /// \param R the lookup of the name
6634 ///
6635 void Sema::CheckShadow(VarDecl *D, NamedDecl *ShadowedDecl,
6636                        const LookupResult &R) {
6637   DeclContext *NewDC = D->getDeclContext();
6638
6639   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6640     // Fields are not shadowed by variables in C++ static methods.
6641     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6642       if (MD->isStatic())
6643         return;
6644
6645     // Fields shadowed by constructor parameters are a special case. Usually
6646     // the constructor initializes the field with the parameter.
6647     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6648       // Remember that this was shadowed so we can either warn about its
6649       // modification or its existence depending on warning settings.
6650       D = D->getCanonicalDecl();
6651       ShadowingDecls.insert({D, FD});
6652       return;
6653     }
6654   }
6655
6656   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6657     if (shadowedVar->isExternC()) {
6658       // For shadowing external vars, make sure that we point to the global
6659       // declaration, not a locally scoped extern declaration.
6660       for (auto I : shadowedVar->redecls())
6661         if (I->isFileVarDecl()) {
6662           ShadowedDecl = I;
6663           break;
6664         }
6665     }
6666
6667   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6668
6669   unsigned WarningDiag = diag::warn_decl_shadow;
6670   SourceLocation CaptureLoc;
6671   if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) {
6672     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6673       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6674         if (RD->getLambdaCaptureDefault() == LCD_None) {
6675           // Try to avoid warnings for lambdas with an explicit capture list.
6676           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6677           // Warn only when the lambda captures the shadowed decl explicitly.
6678           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6679           if (CaptureLoc.isInvalid())
6680             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6681         } else {
6682           // Remember that this was shadowed so we can avoid the warning if the
6683           // shadowed decl isn't captured and the warning settings allow it.
6684           cast<LambdaScopeInfo>(getCurFunction())
6685               ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)});
6686           return;
6687         }
6688       }
6689     }
6690   }
6691
6692   // Only warn about certain kinds of shadowing for class members.
6693   if (NewDC && NewDC->isRecord()) {
6694     // In particular, don't warn about shadowing non-class members.
6695     if (!OldDC->isRecord())
6696       return;
6697
6698     // TODO: should we warn about static data members shadowing
6699     // static data members from base classes?
6700
6701     // TODO: don't diagnose for inaccessible shadowed members.
6702     // This is hard to do perfectly because we might friend the
6703     // shadowing context, but that's just a false negative.
6704   }
6705
6706
6707   DeclarationName Name = R.getLookupName();
6708
6709   // Emit warning and note.
6710   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6711     return;
6712   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6713   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6714   if (!CaptureLoc.isInvalid())
6715     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6716         << Name << /*explicitly*/ 1;
6717   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6718 }
6719
6720 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6721 /// when these variables are captured by the lambda.
6722 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6723   for (const auto &Shadow : LSI->ShadowingDecls) {
6724     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6725     // Try to avoid the warning when the shadowed decl isn't captured.
6726     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6727     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6728     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6729                                        ? diag::warn_decl_shadow_uncaptured_local
6730                                        : diag::warn_decl_shadow)
6731         << Shadow.VD->getDeclName()
6732         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6733     if (!CaptureLoc.isInvalid())
6734       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6735           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6736     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6737   }
6738 }
6739
6740 /// \brief Check -Wshadow without the advantage of a previous lookup.
6741 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6742   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6743     return;
6744
6745   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6746                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6747   LookupName(R, S);
6748   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6749     CheckShadow(D, ShadowedDecl, R);
6750 }
6751
6752 /// Check if 'E', which is an expression that is about to be modified, refers
6753 /// to a constructor parameter that shadows a field.
6754 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6755   // Quickly ignore expressions that can't be shadowing ctor parameters.
6756   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6757     return;
6758   E = E->IgnoreParenImpCasts();
6759   auto *DRE = dyn_cast<DeclRefExpr>(E);
6760   if (!DRE)
6761     return;
6762   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6763   auto I = ShadowingDecls.find(D);
6764   if (I == ShadowingDecls.end())
6765     return;
6766   const NamedDecl *ShadowedDecl = I->second;
6767   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6768   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6769   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6770   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6771
6772   // Avoid issuing multiple warnings about the same decl.
6773   ShadowingDecls.erase(I);
6774 }
6775
6776 /// Check for conflict between this global or extern "C" declaration and
6777 /// previous global or extern "C" declarations. This is only used in C++.
6778 template<typename T>
6779 static bool checkGlobalOrExternCConflict(
6780     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6781   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6782   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6783
6784   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6785     // The common case: this global doesn't conflict with any extern "C"
6786     // declaration.
6787     return false;
6788   }
6789
6790   if (Prev) {
6791     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6792       // Both the old and new declarations have C language linkage. This is a
6793       // redeclaration.
6794       Previous.clear();
6795       Previous.addDecl(Prev);
6796       return true;
6797     }
6798
6799     // This is a global, non-extern "C" declaration, and there is a previous
6800     // non-global extern "C" declaration. Diagnose if this is a variable
6801     // declaration.
6802     if (!isa<VarDecl>(ND))
6803       return false;
6804   } else {
6805     // The declaration is extern "C". Check for any declaration in the
6806     // translation unit which might conflict.
6807     if (IsGlobal) {
6808       // We have already performed the lookup into the translation unit.
6809       IsGlobal = false;
6810       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6811            I != E; ++I) {
6812         if (isa<VarDecl>(*I)) {
6813           Prev = *I;
6814           break;
6815         }
6816       }
6817     } else {
6818       DeclContext::lookup_result R =
6819           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6820       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6821            I != E; ++I) {
6822         if (isa<VarDecl>(*I)) {
6823           Prev = *I;
6824           break;
6825         }
6826         // FIXME: If we have any other entity with this name in global scope,
6827         // the declaration is ill-formed, but that is a defect: it breaks the
6828         // 'stat' hack, for instance. Only variables can have mangled name
6829         // clashes with extern "C" declarations, so only they deserve a
6830         // diagnostic.
6831       }
6832     }
6833
6834     if (!Prev)
6835       return false;
6836   }
6837
6838   // Use the first declaration's location to ensure we point at something which
6839   // is lexically inside an extern "C" linkage-spec.
6840   assert(Prev && "should have found a previous declaration to diagnose");
6841   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6842     Prev = FD->getFirstDecl();
6843   else
6844     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6845
6846   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6847     << IsGlobal << ND;
6848   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6849     << IsGlobal;
6850   return false;
6851 }
6852
6853 /// Apply special rules for handling extern "C" declarations. Returns \c true
6854 /// if we have found that this is a redeclaration of some prior entity.
6855 ///
6856 /// Per C++ [dcl.link]p6:
6857 ///   Two declarations [for a function or variable] with C language linkage
6858 ///   with the same name that appear in different scopes refer to the same
6859 ///   [entity]. An entity with C language linkage shall not be declared with
6860 ///   the same name as an entity in global scope.
6861 template<typename T>
6862 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6863                                                   LookupResult &Previous) {
6864   if (!S.getLangOpts().CPlusPlus) {
6865     // In C, when declaring a global variable, look for a corresponding 'extern'
6866     // variable declared in function scope. We don't need this in C++, because
6867     // we find local extern decls in the surrounding file-scope DeclContext.
6868     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6869       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6870         Previous.clear();
6871         Previous.addDecl(Prev);
6872         return true;
6873       }
6874     }
6875     return false;
6876   }
6877
6878   // A declaration in the translation unit can conflict with an extern "C"
6879   // declaration.
6880   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6881     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6882
6883   // An extern "C" declaration can conflict with a declaration in the
6884   // translation unit or can be a redeclaration of an extern "C" declaration
6885   // in another scope.
6886   if (isIncompleteDeclExternC(S,ND))
6887     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6888
6889   // Neither global nor extern "C": nothing to do.
6890   return false;
6891 }
6892
6893 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6894   // If the decl is already known invalid, don't check it.
6895   if (NewVD->isInvalidDecl())
6896     return;
6897
6898   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6899   QualType T = TInfo->getType();
6900
6901   // Defer checking an 'auto' type until its initializer is attached.
6902   if (T->isUndeducedType())
6903     return;
6904
6905   if (NewVD->hasAttrs())
6906     CheckAlignasUnderalignment(NewVD);
6907
6908   if (T->isObjCObjectType()) {
6909     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6910       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6911     T = Context.getObjCObjectPointerType(T);
6912     NewVD->setType(T);
6913   }
6914
6915   // Emit an error if an address space was applied to decl with local storage.
6916   // This includes arrays of objects with address space qualifiers, but not
6917   // automatic variables that point to other address spaces.
6918   // ISO/IEC TR 18037 S5.1.2
6919   if (!getLangOpts().OpenCL
6920       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6921     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6922     NewVD->setInvalidDecl();
6923     return;
6924   }
6925
6926   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6927   // scope.
6928   if (getLangOpts().OpenCLVersion == 120 &&
6929       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
6930       NewVD->isStaticLocal()) {
6931     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6932     NewVD->setInvalidDecl();
6933     return;
6934   }
6935
6936   if (getLangOpts().OpenCL) {
6937     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6938     if (NewVD->hasAttr<BlocksAttr>()) {
6939       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6940       return;
6941     }
6942
6943     if (T->isBlockPointerType()) {
6944       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6945       // can't use 'extern' storage class.
6946       if (!T.isConstQualified()) {
6947         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6948             << 0 /*const*/;
6949         NewVD->setInvalidDecl();
6950         return;
6951       }
6952       if (NewVD->hasExternalStorage()) {
6953         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6954         NewVD->setInvalidDecl();
6955         return;
6956       }
6957     }
6958     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6959     // __constant address space.
6960     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6961     // variables inside a function can also be declared in the global
6962     // address space.
6963     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6964         NewVD->hasExternalStorage()) {
6965       if (!T->isSamplerT() &&
6966           !(T.getAddressSpace() == LangAS::opencl_constant ||
6967             (T.getAddressSpace() == LangAS::opencl_global &&
6968              getLangOpts().OpenCLVersion == 200))) {
6969         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6970         if (getLangOpts().OpenCLVersion == 200)
6971           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6972               << Scope << "global or constant";
6973         else
6974           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6975               << Scope << "constant";
6976         NewVD->setInvalidDecl();
6977         return;
6978       }
6979     } else {
6980       if (T.getAddressSpace() == LangAS::opencl_global) {
6981         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6982             << 1 /*is any function*/ << "global";
6983         NewVD->setInvalidDecl();
6984         return;
6985       }
6986       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6987       // in functions.
6988       if (T.getAddressSpace() == LangAS::opencl_constant ||
6989           T.getAddressSpace() == LangAS::opencl_local) {
6990         FunctionDecl *FD = getCurFunctionDecl();
6991         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6992           if (T.getAddressSpace() == LangAS::opencl_constant)
6993             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6994                 << 0 /*non-kernel only*/ << "constant";
6995           else
6996             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6997                 << 0 /*non-kernel only*/ << "local";
6998           NewVD->setInvalidDecl();
6999           return;
7000         }
7001       }
7002     }
7003   }
7004
7005   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7006       && !NewVD->hasAttr<BlocksAttr>()) {
7007     if (getLangOpts().getGC() != LangOptions::NonGC)
7008       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7009     else {
7010       assert(!getLangOpts().ObjCAutoRefCount);
7011       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7012     }
7013   }
7014
7015   bool isVM = T->isVariablyModifiedType();
7016   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7017       NewVD->hasAttr<BlocksAttr>())
7018     getCurFunction()->setHasBranchProtectedScope();
7019
7020   if ((isVM && NewVD->hasLinkage()) ||
7021       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7022     bool SizeIsNegative;
7023     llvm::APSInt Oversized;
7024     TypeSourceInfo *FixedTInfo =
7025       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7026                                                     SizeIsNegative, Oversized);
7027     if (!FixedTInfo && T->isVariableArrayType()) {
7028       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7029       // FIXME: This won't give the correct result for
7030       // int a[10][n];
7031       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7032
7033       if (NewVD->isFileVarDecl())
7034         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7035         << SizeRange;
7036       else if (NewVD->isStaticLocal())
7037         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7038         << SizeRange;
7039       else
7040         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7041         << SizeRange;
7042       NewVD->setInvalidDecl();
7043       return;
7044     }
7045
7046     if (!FixedTInfo) {
7047       if (NewVD->isFileVarDecl())
7048         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7049       else
7050         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7051       NewVD->setInvalidDecl();
7052       return;
7053     }
7054
7055     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7056     NewVD->setType(FixedTInfo->getType());
7057     NewVD->setTypeSourceInfo(FixedTInfo);
7058   }
7059
7060   if (T->isVoidType()) {
7061     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7062     //                    of objects and functions.
7063     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7064       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7065         << T;
7066       NewVD->setInvalidDecl();
7067       return;
7068     }
7069   }
7070
7071   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7072     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7073     NewVD->setInvalidDecl();
7074     return;
7075   }
7076
7077   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7078     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7079     NewVD->setInvalidDecl();
7080     return;
7081   }
7082
7083   if (NewVD->isConstexpr() && !T->isDependentType() &&
7084       RequireLiteralType(NewVD->getLocation(), T,
7085                          diag::err_constexpr_var_non_literal)) {
7086     NewVD->setInvalidDecl();
7087     return;
7088   }
7089 }
7090
7091 /// \brief Perform semantic checking on a newly-created variable
7092 /// declaration.
7093 ///
7094 /// This routine performs all of the type-checking required for a
7095 /// variable declaration once it has been built. It is used both to
7096 /// check variables after they have been parsed and their declarators
7097 /// have been translated into a declaration, and to check variables
7098 /// that have been instantiated from a template.
7099 ///
7100 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7101 ///
7102 /// Returns true if the variable declaration is a redeclaration.
7103 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7104   CheckVariableDeclarationType(NewVD);
7105
7106   // If the decl is already known invalid, don't check it.
7107   if (NewVD->isInvalidDecl())
7108     return false;
7109
7110   // If we did not find anything by this name, look for a non-visible
7111   // extern "C" declaration with the same name.
7112   if (Previous.empty() &&
7113       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7114     Previous.setShadowed();
7115
7116   if (!Previous.empty()) {
7117     MergeVarDecl(NewVD, Previous);
7118     return true;
7119   }
7120   return false;
7121 }
7122
7123 namespace {
7124 struct FindOverriddenMethod {
7125   Sema *S;
7126   CXXMethodDecl *Method;
7127
7128   /// Member lookup function that determines whether a given C++
7129   /// method overrides a method in a base class, to be used with
7130   /// CXXRecordDecl::lookupInBases().
7131   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7132     RecordDecl *BaseRecord =
7133         Specifier->getType()->getAs<RecordType>()->getDecl();
7134
7135     DeclarationName Name = Method->getDeclName();
7136
7137     // FIXME: Do we care about other names here too?
7138     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7139       // We really want to find the base class destructor here.
7140       QualType T = S->Context.getTypeDeclType(BaseRecord);
7141       CanQualType CT = S->Context.getCanonicalType(T);
7142
7143       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7144     }
7145
7146     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7147          Path.Decls = Path.Decls.slice(1)) {
7148       NamedDecl *D = Path.Decls.front();
7149       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7150         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7151           return true;
7152       }
7153     }
7154
7155     return false;
7156   }
7157 };
7158
7159 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7160 } // end anonymous namespace
7161
7162 /// \brief Report an error regarding overriding, along with any relevant
7163 /// overriden methods.
7164 ///
7165 /// \param DiagID the primary error to report.
7166 /// \param MD the overriding method.
7167 /// \param OEK which overrides to include as notes.
7168 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7169                             OverrideErrorKind OEK = OEK_All) {
7170   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7171   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7172                                       E = MD->end_overridden_methods();
7173        I != E; ++I) {
7174     // This check (& the OEK parameter) could be replaced by a predicate, but
7175     // without lambdas that would be overkill. This is still nicer than writing
7176     // out the diag loop 3 times.
7177     if ((OEK == OEK_All) ||
7178         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7179         (OEK == OEK_Deleted && (*I)->isDeleted()))
7180       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7181   }
7182 }
7183
7184 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7185 /// and if so, check that it's a valid override and remember it.
7186 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7187   // Look for methods in base classes that this method might override.
7188   CXXBasePaths Paths;
7189   FindOverriddenMethod FOM;
7190   FOM.Method = MD;
7191   FOM.S = this;
7192   bool hasDeletedOverridenMethods = false;
7193   bool hasNonDeletedOverridenMethods = false;
7194   bool AddedAny = false;
7195   if (DC->lookupInBases(FOM, Paths)) {
7196     for (auto *I : Paths.found_decls()) {
7197       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7198         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7199         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7200             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7201             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7202             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7203           hasDeletedOverridenMethods |= OldMD->isDeleted();
7204           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7205           AddedAny = true;
7206         }
7207       }
7208     }
7209   }
7210
7211   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7212     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7213   }
7214   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7215     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7216   }
7217
7218   return AddedAny;
7219 }
7220
7221 namespace {
7222   // Struct for holding all of the extra arguments needed by
7223   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7224   struct ActOnFDArgs {
7225     Scope *S;
7226     Declarator &D;
7227     MultiTemplateParamsArg TemplateParamLists;
7228     bool AddToScope;
7229   };
7230 } // end anonymous namespace
7231
7232 namespace {
7233
7234 // Callback to only accept typo corrections that have a non-zero edit distance.
7235 // Also only accept corrections that have the same parent decl.
7236 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7237  public:
7238   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7239                             CXXRecordDecl *Parent)
7240       : Context(Context), OriginalFD(TypoFD),
7241         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7242
7243   bool ValidateCandidate(const TypoCorrection &candidate) override {
7244     if (candidate.getEditDistance() == 0)
7245       return false;
7246
7247     SmallVector<unsigned, 1> MismatchedParams;
7248     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7249                                           CDeclEnd = candidate.end();
7250          CDecl != CDeclEnd; ++CDecl) {
7251       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7252
7253       if (FD && !FD->hasBody() &&
7254           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7255         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7256           CXXRecordDecl *Parent = MD->getParent();
7257           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7258             return true;
7259         } else if (!ExpectedParent) {
7260           return true;
7261         }
7262       }
7263     }
7264
7265     return false;
7266   }
7267
7268  private:
7269   ASTContext &Context;
7270   FunctionDecl *OriginalFD;
7271   CXXRecordDecl *ExpectedParent;
7272 };
7273
7274 } // end anonymous namespace
7275
7276 /// \brief Generate diagnostics for an invalid function redeclaration.
7277 ///
7278 /// This routine handles generating the diagnostic messages for an invalid
7279 /// function redeclaration, including finding possible similar declarations
7280 /// or performing typo correction if there are no previous declarations with
7281 /// the same name.
7282 ///
7283 /// Returns a NamedDecl iff typo correction was performed and substituting in
7284 /// the new declaration name does not cause new errors.
7285 static NamedDecl *DiagnoseInvalidRedeclaration(
7286     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7287     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7288   DeclarationName Name = NewFD->getDeclName();
7289   DeclContext *NewDC = NewFD->getDeclContext();
7290   SmallVector<unsigned, 1> MismatchedParams;
7291   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7292   TypoCorrection Correction;
7293   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7294   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7295                                    : diag::err_member_decl_does_not_match;
7296   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7297                     IsLocalFriend ? Sema::LookupLocalFriendName
7298                                   : Sema::LookupOrdinaryName,
7299                     Sema::ForRedeclaration);
7300
7301   NewFD->setInvalidDecl();
7302   if (IsLocalFriend)
7303     SemaRef.LookupName(Prev, S);
7304   else
7305     SemaRef.LookupQualifiedName(Prev, NewDC);
7306   assert(!Prev.isAmbiguous() &&
7307          "Cannot have an ambiguity in previous-declaration lookup");
7308   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7309   if (!Prev.empty()) {
7310     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7311          Func != FuncEnd; ++Func) {
7312       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7313       if (FD &&
7314           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7315         // Add 1 to the index so that 0 can mean the mismatch didn't
7316         // involve a parameter
7317         unsigned ParamNum =
7318             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7319         NearMatches.push_back(std::make_pair(FD, ParamNum));
7320       }
7321     }
7322   // If the qualified name lookup yielded nothing, try typo correction
7323   } else if ((Correction = SemaRef.CorrectTypo(
7324                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7325                   &ExtraArgs.D.getCXXScopeSpec(),
7326                   llvm::make_unique<DifferentNameValidatorCCC>(
7327                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7328                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7329     // Set up everything for the call to ActOnFunctionDeclarator
7330     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7331                               ExtraArgs.D.getIdentifierLoc());
7332     Previous.clear();
7333     Previous.setLookupName(Correction.getCorrection());
7334     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7335                                     CDeclEnd = Correction.end();
7336          CDecl != CDeclEnd; ++CDecl) {
7337       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7338       if (FD && !FD->hasBody() &&
7339           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7340         Previous.addDecl(FD);
7341       }
7342     }
7343     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7344
7345     NamedDecl *Result;
7346     // Retry building the function declaration with the new previous
7347     // declarations, and with errors suppressed.
7348     {
7349       // Trap errors.
7350       Sema::SFINAETrap Trap(SemaRef);
7351
7352       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7353       // pieces need to verify the typo-corrected C++ declaration and hopefully
7354       // eliminate the need for the parameter pack ExtraArgs.
7355       Result = SemaRef.ActOnFunctionDeclarator(
7356           ExtraArgs.S, ExtraArgs.D,
7357           Correction.getCorrectionDecl()->getDeclContext(),
7358           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7359           ExtraArgs.AddToScope);
7360
7361       if (Trap.hasErrorOccurred())
7362         Result = nullptr;
7363     }
7364
7365     if (Result) {
7366       // Determine which correction we picked.
7367       Decl *Canonical = Result->getCanonicalDecl();
7368       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7369            I != E; ++I)
7370         if ((*I)->getCanonicalDecl() == Canonical)
7371           Correction.setCorrectionDecl(*I);
7372
7373       SemaRef.diagnoseTypo(
7374           Correction,
7375           SemaRef.PDiag(IsLocalFriend
7376                           ? diag::err_no_matching_local_friend_suggest
7377                           : diag::err_member_decl_does_not_match_suggest)
7378             << Name << NewDC << IsDefinition);
7379       return Result;
7380     }
7381
7382     // Pretend the typo correction never occurred
7383     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7384                               ExtraArgs.D.getIdentifierLoc());
7385     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7386     Previous.clear();
7387     Previous.setLookupName(Name);
7388   }
7389
7390   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7391       << Name << NewDC << IsDefinition << NewFD->getLocation();
7392
7393   bool NewFDisConst = false;
7394   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7395     NewFDisConst = NewMD->isConst();
7396
7397   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7398        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7399        NearMatch != NearMatchEnd; ++NearMatch) {
7400     FunctionDecl *FD = NearMatch->first;
7401     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7402     bool FDisConst = MD && MD->isConst();
7403     bool IsMember = MD || !IsLocalFriend;
7404
7405     // FIXME: These notes are poorly worded for the local friend case.
7406     if (unsigned Idx = NearMatch->second) {
7407       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7408       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7409       if (Loc.isInvalid()) Loc = FD->getLocation();
7410       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7411                                  : diag::note_local_decl_close_param_match)
7412         << Idx << FDParam->getType()
7413         << NewFD->getParamDecl(Idx - 1)->getType();
7414     } else if (FDisConst != NewFDisConst) {
7415       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7416           << NewFDisConst << FD->getSourceRange().getEnd();
7417     } else
7418       SemaRef.Diag(FD->getLocation(),
7419                    IsMember ? diag::note_member_def_close_match
7420                             : diag::note_local_decl_close_match);
7421   }
7422   return nullptr;
7423 }
7424
7425 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7426   switch (D.getDeclSpec().getStorageClassSpec()) {
7427   default: llvm_unreachable("Unknown storage class!");
7428   case DeclSpec::SCS_auto:
7429   case DeclSpec::SCS_register:
7430   case DeclSpec::SCS_mutable:
7431     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7432                  diag::err_typecheck_sclass_func);
7433     D.setInvalidType();
7434     break;
7435   case DeclSpec::SCS_unspecified: break;
7436   case DeclSpec::SCS_extern:
7437     if (D.getDeclSpec().isExternInLinkageSpec())
7438       return SC_None;
7439     return SC_Extern;
7440   case DeclSpec::SCS_static: {
7441     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7442       // C99 6.7.1p5:
7443       //   The declaration of an identifier for a function that has
7444       //   block scope shall have no explicit storage-class specifier
7445       //   other than extern
7446       // See also (C++ [dcl.stc]p4).
7447       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7448                    diag::err_static_block_func);
7449       break;
7450     } else
7451       return SC_Static;
7452   }
7453   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7454   }
7455
7456   // No explicit storage class has already been returned
7457   return SC_None;
7458 }
7459
7460 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7461                                            DeclContext *DC, QualType &R,
7462                                            TypeSourceInfo *TInfo,
7463                                            StorageClass SC,
7464                                            bool &IsVirtualOkay) {
7465   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7466   DeclarationName Name = NameInfo.getName();
7467
7468   FunctionDecl *NewFD = nullptr;
7469   bool isInline = D.getDeclSpec().isInlineSpecified();
7470
7471   if (!SemaRef.getLangOpts().CPlusPlus) {
7472     // Determine whether the function was written with a
7473     // prototype. This true when:
7474     //   - there is a prototype in the declarator, or
7475     //   - the type R of the function is some kind of typedef or other reference
7476     //     to a type name (which eventually refers to a function type).
7477     bool HasPrototype =
7478       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7479       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7480
7481     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7482                                  D.getLocStart(), NameInfo, R,
7483                                  TInfo, SC, isInline,
7484                                  HasPrototype, false);
7485     if (D.isInvalidType())
7486       NewFD->setInvalidDecl();
7487
7488     return NewFD;
7489   }
7490
7491   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7492   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7493
7494   // Check that the return type is not an abstract class type.
7495   // For record types, this is done by the AbstractClassUsageDiagnoser once
7496   // the class has been completely parsed.
7497   if (!DC->isRecord() &&
7498       SemaRef.RequireNonAbstractType(
7499           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7500           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7501     D.setInvalidType();
7502
7503   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7504     // This is a C++ constructor declaration.
7505     assert(DC->isRecord() &&
7506            "Constructors can only be declared in a member context");
7507
7508     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7509     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7510                                       D.getLocStart(), NameInfo,
7511                                       R, TInfo, isExplicit, isInline,
7512                                       /*isImplicitlyDeclared=*/false,
7513                                       isConstexpr);
7514
7515   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7516     // This is a C++ destructor declaration.
7517     if (DC->isRecord()) {
7518       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7519       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7520       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7521                                         SemaRef.Context, Record,
7522                                         D.getLocStart(),
7523                                         NameInfo, R, TInfo, isInline,
7524                                         /*isImplicitlyDeclared=*/false);
7525
7526       // If the class is complete, then we now create the implicit exception
7527       // specification. If the class is incomplete or dependent, we can't do
7528       // it yet.
7529       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7530           Record->getDefinition() && !Record->isBeingDefined() &&
7531           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7532         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7533       }
7534
7535       IsVirtualOkay = true;
7536       return NewDD;
7537
7538     } else {
7539       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7540       D.setInvalidType();
7541
7542       // Create a FunctionDecl to satisfy the function definition parsing
7543       // code path.
7544       return FunctionDecl::Create(SemaRef.Context, DC,
7545                                   D.getLocStart(),
7546                                   D.getIdentifierLoc(), Name, R, TInfo,
7547                                   SC, isInline,
7548                                   /*hasPrototype=*/true, isConstexpr);
7549     }
7550
7551   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7552     if (!DC->isRecord()) {
7553       SemaRef.Diag(D.getIdentifierLoc(),
7554            diag::err_conv_function_not_member);
7555       return nullptr;
7556     }
7557
7558     SemaRef.CheckConversionDeclarator(D, R, SC);
7559     IsVirtualOkay = true;
7560     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7561                                      D.getLocStart(), NameInfo,
7562                                      R, TInfo, isInline, isExplicit,
7563                                      isConstexpr, SourceLocation());
7564
7565   } else if (DC->isRecord()) {
7566     // If the name of the function is the same as the name of the record,
7567     // then this must be an invalid constructor that has a return type.
7568     // (The parser checks for a return type and makes the declarator a
7569     // constructor if it has no return type).
7570     if (Name.getAsIdentifierInfo() &&
7571         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7572       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7573         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7574         << SourceRange(D.getIdentifierLoc());
7575       return nullptr;
7576     }
7577
7578     // This is a C++ method declaration.
7579     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7580                                                cast<CXXRecordDecl>(DC),
7581                                                D.getLocStart(), NameInfo, R,
7582                                                TInfo, SC, isInline,
7583                                                isConstexpr, SourceLocation());
7584     IsVirtualOkay = !Ret->isStatic();
7585     return Ret;
7586   } else {
7587     bool isFriend =
7588         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7589     if (!isFriend && SemaRef.CurContext->isRecord())
7590       return nullptr;
7591
7592     // Determine whether the function was written with a
7593     // prototype. This true when:
7594     //   - we're in C++ (where every function has a prototype),
7595     return FunctionDecl::Create(SemaRef.Context, DC,
7596                                 D.getLocStart(),
7597                                 NameInfo, R, TInfo, SC, isInline,
7598                                 true/*HasPrototype*/, isConstexpr);
7599   }
7600 }
7601
7602 enum OpenCLParamType {
7603   ValidKernelParam,
7604   PtrPtrKernelParam,
7605   PtrKernelParam,
7606   InvalidAddrSpacePtrKernelParam,
7607   InvalidKernelParam,
7608   RecordKernelParam
7609 };
7610
7611 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7612   if (PT->isPointerType()) {
7613     QualType PointeeType = PT->getPointeeType();
7614     if (PointeeType->isPointerType())
7615       return PtrPtrKernelParam;
7616     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7617         PointeeType.getAddressSpace() == 0)
7618       return InvalidAddrSpacePtrKernelParam;
7619     return PtrKernelParam;
7620   }
7621
7622   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7623   // be used as builtin types.
7624
7625   if (PT->isImageType())
7626     return PtrKernelParam;
7627
7628   if (PT->isBooleanType())
7629     return InvalidKernelParam;
7630
7631   if (PT->isEventT())
7632     return InvalidKernelParam;
7633
7634   // OpenCL extension spec v1.2 s9.5:
7635   // This extension adds support for half scalar and vector types as built-in
7636   // types that can be used for arithmetic operations, conversions etc.
7637   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7638     return InvalidKernelParam;
7639
7640   if (PT->isRecordType())
7641     return RecordKernelParam;
7642
7643   return ValidKernelParam;
7644 }
7645
7646 static void checkIsValidOpenCLKernelParameter(
7647   Sema &S,
7648   Declarator &D,
7649   ParmVarDecl *Param,
7650   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7651   QualType PT = Param->getType();
7652
7653   // Cache the valid types we encounter to avoid rechecking structs that are
7654   // used again
7655   if (ValidTypes.count(PT.getTypePtr()))
7656     return;
7657
7658   switch (getOpenCLKernelParameterType(S, PT)) {
7659   case PtrPtrKernelParam:
7660     // OpenCL v1.2 s6.9.a:
7661     // A kernel function argument cannot be declared as a
7662     // pointer to a pointer type.
7663     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7664     D.setInvalidType();
7665     return;
7666
7667   case InvalidAddrSpacePtrKernelParam:
7668     // OpenCL v1.0 s6.5:
7669     // __kernel function arguments declared to be a pointer of a type can point
7670     // to one of the following address spaces only : __global, __local or
7671     // __constant.
7672     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7673     D.setInvalidType();
7674     return;
7675
7676     // OpenCL v1.2 s6.9.k:
7677     // Arguments to kernel functions in a program cannot be declared with the
7678     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7679     // uintptr_t or a struct and/or union that contain fields declared to be
7680     // one of these built-in scalar types.
7681
7682   case InvalidKernelParam:
7683     // OpenCL v1.2 s6.8 n:
7684     // A kernel function argument cannot be declared
7685     // of event_t type.
7686     // Do not diagnose half type since it is diagnosed as invalid argument
7687     // type for any function elsewhere.
7688     if (!PT->isHalfType())
7689       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7690     D.setInvalidType();
7691     return;
7692
7693   case PtrKernelParam:
7694   case ValidKernelParam:
7695     ValidTypes.insert(PT.getTypePtr());
7696     return;
7697
7698   case RecordKernelParam:
7699     break;
7700   }
7701
7702   // Track nested structs we will inspect
7703   SmallVector<const Decl *, 4> VisitStack;
7704
7705   // Track where we are in the nested structs. Items will migrate from
7706   // VisitStack to HistoryStack as we do the DFS for bad field.
7707   SmallVector<const FieldDecl *, 4> HistoryStack;
7708   HistoryStack.push_back(nullptr);
7709
7710   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7711   VisitStack.push_back(PD);
7712
7713   assert(VisitStack.back() && "First decl null?");
7714
7715   do {
7716     const Decl *Next = VisitStack.pop_back_val();
7717     if (!Next) {
7718       assert(!HistoryStack.empty());
7719       // Found a marker, we have gone up a level
7720       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7721         ValidTypes.insert(Hist->getType().getTypePtr());
7722
7723       continue;
7724     }
7725
7726     // Adds everything except the original parameter declaration (which is not a
7727     // field itself) to the history stack.
7728     const RecordDecl *RD;
7729     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7730       HistoryStack.push_back(Field);
7731       RD = Field->getType()->castAs<RecordType>()->getDecl();
7732     } else {
7733       RD = cast<RecordDecl>(Next);
7734     }
7735
7736     // Add a null marker so we know when we've gone back up a level
7737     VisitStack.push_back(nullptr);
7738
7739     for (const auto *FD : RD->fields()) {
7740       QualType QT = FD->getType();
7741
7742       if (ValidTypes.count(QT.getTypePtr()))
7743         continue;
7744
7745       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7746       if (ParamType == ValidKernelParam)
7747         continue;
7748
7749       if (ParamType == RecordKernelParam) {
7750         VisitStack.push_back(FD);
7751         continue;
7752       }
7753
7754       // OpenCL v1.2 s6.9.p:
7755       // Arguments to kernel functions that are declared to be a struct or union
7756       // do not allow OpenCL objects to be passed as elements of the struct or
7757       // union.
7758       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7759           ParamType == InvalidAddrSpacePtrKernelParam) {
7760         S.Diag(Param->getLocation(),
7761                diag::err_record_with_pointers_kernel_param)
7762           << PT->isUnionType()
7763           << PT;
7764       } else {
7765         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7766       }
7767
7768       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7769         << PD->getDeclName();
7770
7771       // We have an error, now let's go back up through history and show where
7772       // the offending field came from
7773       for (ArrayRef<const FieldDecl *>::const_iterator
7774                I = HistoryStack.begin() + 1,
7775                E = HistoryStack.end();
7776            I != E; ++I) {
7777         const FieldDecl *OuterField = *I;
7778         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7779           << OuterField->getType();
7780       }
7781
7782       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7783         << QT->isPointerType()
7784         << QT;
7785       D.setInvalidType();
7786       return;
7787     }
7788   } while (!VisitStack.empty());
7789 }
7790
7791 /// Find the DeclContext in which a tag is implicitly declared if we see an
7792 /// elaborated type specifier in the specified context, and lookup finds
7793 /// nothing.
7794 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7795   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7796     DC = DC->getParent();
7797   return DC;
7798 }
7799
7800 /// Find the Scope in which a tag is implicitly declared if we see an
7801 /// elaborated type specifier in the specified context, and lookup finds
7802 /// nothing.
7803 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7804   while (S->isClassScope() ||
7805          (LangOpts.CPlusPlus &&
7806           S->isFunctionPrototypeScope()) ||
7807          ((S->getFlags() & Scope::DeclScope) == 0) ||
7808          (S->getEntity() && S->getEntity()->isTransparentContext()))
7809     S = S->getParent();
7810   return S;
7811 }
7812
7813 NamedDecl*
7814 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7815                               TypeSourceInfo *TInfo, LookupResult &Previous,
7816                               MultiTemplateParamsArg TemplateParamLists,
7817                               bool &AddToScope) {
7818   QualType R = TInfo->getType();
7819
7820   assert(R.getTypePtr()->isFunctionType());
7821
7822   // TODO: consider using NameInfo for diagnostic.
7823   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7824   DeclarationName Name = NameInfo.getName();
7825   StorageClass SC = getFunctionStorageClass(*this, D);
7826
7827   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7828     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7829          diag::err_invalid_thread)
7830       << DeclSpec::getSpecifierName(TSCS);
7831
7832   if (D.isFirstDeclarationOfMember())
7833     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7834                            D.getIdentifierLoc());
7835
7836   bool isFriend = false;
7837   FunctionTemplateDecl *FunctionTemplate = nullptr;
7838   bool isExplicitSpecialization = false;
7839   bool isFunctionTemplateSpecialization = false;
7840
7841   bool isDependentClassScopeExplicitSpecialization = false;
7842   bool HasExplicitTemplateArgs = false;
7843   TemplateArgumentListInfo TemplateArgs;
7844
7845   bool isVirtualOkay = false;
7846
7847   DeclContext *OriginalDC = DC;
7848   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7849
7850   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7851                                               isVirtualOkay);
7852   if (!NewFD) return nullptr;
7853
7854   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7855     NewFD->setTopLevelDeclInObjCContainer();
7856
7857   // Set the lexical context. If this is a function-scope declaration, or has a
7858   // C++ scope specifier, or is the object of a friend declaration, the lexical
7859   // context will be different from the semantic context.
7860   NewFD->setLexicalDeclContext(CurContext);
7861
7862   if (IsLocalExternDecl)
7863     NewFD->setLocalExternDecl();
7864
7865   if (getLangOpts().CPlusPlus) {
7866     bool isInline = D.getDeclSpec().isInlineSpecified();
7867     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7868     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7869     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7870     bool isConcept = D.getDeclSpec().isConceptSpecified();
7871     isFriend = D.getDeclSpec().isFriendSpecified();
7872     if (isFriend && !isInline && D.isFunctionDefinition()) {
7873       // C++ [class.friend]p5
7874       //   A function can be defined in a friend declaration of a
7875       //   class . . . . Such a function is implicitly inline.
7876       NewFD->setImplicitlyInline();
7877     }
7878
7879     // If this is a method defined in an __interface, and is not a constructor
7880     // or an overloaded operator, then set the pure flag (isVirtual will already
7881     // return true).
7882     if (const CXXRecordDecl *Parent =
7883           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7884       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7885         NewFD->setPure(true);
7886
7887       // C++ [class.union]p2
7888       //   A union can have member functions, but not virtual functions.
7889       if (isVirtual && Parent->isUnion())
7890         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7891     }
7892
7893     SetNestedNameSpecifier(NewFD, D);
7894     isExplicitSpecialization = false;
7895     isFunctionTemplateSpecialization = false;
7896     if (D.isInvalidType())
7897       NewFD->setInvalidDecl();
7898
7899     // Match up the template parameter lists with the scope specifier, then
7900     // determine whether we have a template or a template specialization.
7901     bool Invalid = false;
7902     if (TemplateParameterList *TemplateParams =
7903             MatchTemplateParametersToScopeSpecifier(
7904                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7905                 D.getCXXScopeSpec(),
7906                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7907                     ? D.getName().TemplateId
7908                     : nullptr,
7909                 TemplateParamLists, isFriend, isExplicitSpecialization,
7910                 Invalid)) {
7911       if (TemplateParams->size() > 0) {
7912         // This is a function template
7913
7914         // Check that we can declare a template here.
7915         if (CheckTemplateDeclScope(S, TemplateParams))
7916           NewFD->setInvalidDecl();
7917
7918         // A destructor cannot be a template.
7919         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7920           Diag(NewFD->getLocation(), diag::err_destructor_template);
7921           NewFD->setInvalidDecl();
7922         }
7923
7924         // If we're adding a template to a dependent context, we may need to
7925         // rebuilding some of the types used within the template parameter list,
7926         // now that we know what the current instantiation is.
7927         if (DC->isDependentContext()) {
7928           ContextRAII SavedContext(*this, DC);
7929           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7930             Invalid = true;
7931         }
7932
7933         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7934                                                         NewFD->getLocation(),
7935                                                         Name, TemplateParams,
7936                                                         NewFD);
7937         FunctionTemplate->setLexicalDeclContext(CurContext);
7938         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7939
7940         // For source fidelity, store the other template param lists.
7941         if (TemplateParamLists.size() > 1) {
7942           NewFD->setTemplateParameterListsInfo(Context,
7943                                                TemplateParamLists.drop_back(1));
7944         }
7945       } else {
7946         // This is a function template specialization.
7947         isFunctionTemplateSpecialization = true;
7948         // For source fidelity, store all the template param lists.
7949         if (TemplateParamLists.size() > 0)
7950           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7951
7952         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7953         if (isFriend) {
7954           // We want to remove the "template<>", found here.
7955           SourceRange RemoveRange = TemplateParams->getSourceRange();
7956
7957           // If we remove the template<> and the name is not a
7958           // template-id, we're actually silently creating a problem:
7959           // the friend declaration will refer to an untemplated decl,
7960           // and clearly the user wants a template specialization.  So
7961           // we need to insert '<>' after the name.
7962           SourceLocation InsertLoc;
7963           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7964             InsertLoc = D.getName().getSourceRange().getEnd();
7965             InsertLoc = getLocForEndOfToken(InsertLoc);
7966           }
7967
7968           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7969             << Name << RemoveRange
7970             << FixItHint::CreateRemoval(RemoveRange)
7971             << FixItHint::CreateInsertion(InsertLoc, "<>");
7972         }
7973       }
7974     }
7975     else {
7976       // All template param lists were matched against the scope specifier:
7977       // this is NOT (an explicit specialization of) a template.
7978       if (TemplateParamLists.size() > 0)
7979         // For source fidelity, store all the template param lists.
7980         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7981     }
7982
7983     if (Invalid) {
7984       NewFD->setInvalidDecl();
7985       if (FunctionTemplate)
7986         FunctionTemplate->setInvalidDecl();
7987     }
7988
7989     // C++ [dcl.fct.spec]p5:
7990     //   The virtual specifier shall only be used in declarations of
7991     //   nonstatic class member functions that appear within a
7992     //   member-specification of a class declaration; see 10.3.
7993     //
7994     if (isVirtual && !NewFD->isInvalidDecl()) {
7995       if (!isVirtualOkay) {
7996         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7997              diag::err_virtual_non_function);
7998       } else if (!CurContext->isRecord()) {
7999         // 'virtual' was specified outside of the class.
8000         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8001              diag::err_virtual_out_of_class)
8002           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8003       } else if (NewFD->getDescribedFunctionTemplate()) {
8004         // C++ [temp.mem]p3:
8005         //  A member function template shall not be virtual.
8006         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8007              diag::err_virtual_member_function_template)
8008           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8009       } else {
8010         // Okay: Add virtual to the method.
8011         NewFD->setVirtualAsWritten(true);
8012       }
8013
8014       if (getLangOpts().CPlusPlus14 &&
8015           NewFD->getReturnType()->isUndeducedType())
8016         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8017     }
8018
8019     if (getLangOpts().CPlusPlus14 &&
8020         (NewFD->isDependentContext() ||
8021          (isFriend && CurContext->isDependentContext())) &&
8022         NewFD->getReturnType()->isUndeducedType()) {
8023       // If the function template is referenced directly (for instance, as a
8024       // member of the current instantiation), pretend it has a dependent type.
8025       // This is not really justified by the standard, but is the only sane
8026       // thing to do.
8027       // FIXME: For a friend function, we have not marked the function as being
8028       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8029       const FunctionProtoType *FPT =
8030           NewFD->getType()->castAs<FunctionProtoType>();
8031       QualType Result =
8032           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8033       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8034                                              FPT->getExtProtoInfo()));
8035     }
8036
8037     // C++ [dcl.fct.spec]p3:
8038     //  The inline specifier shall not appear on a block scope function
8039     //  declaration.
8040     if (isInline && !NewFD->isInvalidDecl()) {
8041       if (CurContext->isFunctionOrMethod()) {
8042         // 'inline' is not allowed on block scope function declaration.
8043         Diag(D.getDeclSpec().getInlineSpecLoc(),
8044              diag::err_inline_declaration_block_scope) << Name
8045           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8046       }
8047     }
8048
8049     // C++ [dcl.fct.spec]p6:
8050     //  The explicit specifier shall be used only in the declaration of a
8051     //  constructor or conversion function within its class definition;
8052     //  see 12.3.1 and 12.3.2.
8053     if (isExplicit && !NewFD->isInvalidDecl()) {
8054       if (!CurContext->isRecord()) {
8055         // 'explicit' was specified outside of the class.
8056         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8057              diag::err_explicit_out_of_class)
8058           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8059       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8060                  !isa<CXXConversionDecl>(NewFD)) {
8061         // 'explicit' was specified on a function that wasn't a constructor
8062         // or conversion function.
8063         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8064              diag::err_explicit_non_ctor_or_conv_function)
8065           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8066       }
8067     }
8068
8069     if (isConstexpr) {
8070       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8071       // are implicitly inline.
8072       NewFD->setImplicitlyInline();
8073
8074       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8075       // be either constructors or to return a literal type. Therefore,
8076       // destructors cannot be declared constexpr.
8077       if (isa<CXXDestructorDecl>(NewFD))
8078         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8079     }
8080
8081     if (isConcept) {
8082       // This is a function concept.
8083       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8084         FTD->setConcept();
8085
8086       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8087       // applied only to the definition of a function template [...]
8088       if (!D.isFunctionDefinition()) {
8089         Diag(D.getDeclSpec().getConceptSpecLoc(),
8090              diag::err_function_concept_not_defined);
8091         NewFD->setInvalidDecl();
8092       }
8093
8094       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8095       // have no exception-specification and is treated as if it were specified
8096       // with noexcept(true) (15.4). [...]
8097       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8098         if (FPT->hasExceptionSpec()) {
8099           SourceRange Range;
8100           if (D.isFunctionDeclarator())
8101             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8102           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8103               << FixItHint::CreateRemoval(Range);
8104           NewFD->setInvalidDecl();
8105         } else {
8106           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8107         }
8108
8109         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8110         // following restrictions:
8111         // - The declared return type shall have the type bool.
8112         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8113           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8114           NewFD->setInvalidDecl();
8115         }
8116
8117         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8118         // following restrictions:
8119         // - The declaration's parameter list shall be equivalent to an empty
8120         //   parameter list.
8121         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8122           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8123       }
8124
8125       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8126       // implicity defined to be a constexpr declaration (implicitly inline)
8127       NewFD->setImplicitlyInline();
8128
8129       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8130       // be declared with the thread_local, inline, friend, or constexpr
8131       // specifiers, [...]
8132       if (isInline) {
8133         Diag(D.getDeclSpec().getInlineSpecLoc(),
8134              diag::err_concept_decl_invalid_specifiers)
8135             << 1 << 1;
8136         NewFD->setInvalidDecl(true);
8137       }
8138
8139       if (isFriend) {
8140         Diag(D.getDeclSpec().getFriendSpecLoc(),
8141              diag::err_concept_decl_invalid_specifiers)
8142             << 1 << 2;
8143         NewFD->setInvalidDecl(true);
8144       }
8145
8146       if (isConstexpr) {
8147         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8148              diag::err_concept_decl_invalid_specifiers)
8149             << 1 << 3;
8150         NewFD->setInvalidDecl(true);
8151       }
8152
8153       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8154       // applied only to the definition of a function template or variable
8155       // template, declared in namespace scope.
8156       if (isFunctionTemplateSpecialization) {
8157         Diag(D.getDeclSpec().getConceptSpecLoc(),
8158              diag::err_concept_specified_specialization) << 1;
8159         NewFD->setInvalidDecl(true);
8160         return NewFD;
8161       }
8162     }
8163
8164     // If __module_private__ was specified, mark the function accordingly.
8165     if (D.getDeclSpec().isModulePrivateSpecified()) {
8166       if (isFunctionTemplateSpecialization) {
8167         SourceLocation ModulePrivateLoc
8168           = D.getDeclSpec().getModulePrivateSpecLoc();
8169         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8170           << 0
8171           << FixItHint::CreateRemoval(ModulePrivateLoc);
8172       } else {
8173         NewFD->setModulePrivate();
8174         if (FunctionTemplate)
8175           FunctionTemplate->setModulePrivate();
8176       }
8177     }
8178
8179     if (isFriend) {
8180       if (FunctionTemplate) {
8181         FunctionTemplate->setObjectOfFriendDecl();
8182         FunctionTemplate->setAccess(AS_public);
8183       }
8184       NewFD->setObjectOfFriendDecl();
8185       NewFD->setAccess(AS_public);
8186     }
8187
8188     // If a function is defined as defaulted or deleted, mark it as such now.
8189     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8190     // definition kind to FDK_Definition.
8191     switch (D.getFunctionDefinitionKind()) {
8192       case FDK_Declaration:
8193       case FDK_Definition:
8194         break;
8195
8196       case FDK_Defaulted:
8197         NewFD->setDefaulted();
8198         break;
8199
8200       case FDK_Deleted:
8201         NewFD->setDeletedAsWritten();
8202         break;
8203     }
8204
8205     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8206         D.isFunctionDefinition()) {
8207       // C++ [class.mfct]p2:
8208       //   A member function may be defined (8.4) in its class definition, in
8209       //   which case it is an inline member function (7.1.2)
8210       NewFD->setImplicitlyInline();
8211     }
8212
8213     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8214         !CurContext->isRecord()) {
8215       // C++ [class.static]p1:
8216       //   A data or function member of a class may be declared static
8217       //   in a class definition, in which case it is a static member of
8218       //   the class.
8219
8220       // Complain about the 'static' specifier if it's on an out-of-line
8221       // member function definition.
8222       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8223            diag::err_static_out_of_line)
8224         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8225     }
8226
8227     // C++11 [except.spec]p15:
8228     //   A deallocation function with no exception-specification is treated
8229     //   as if it were specified with noexcept(true).
8230     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8231     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8232          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8233         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8234       NewFD->setType(Context.getFunctionType(
8235           FPT->getReturnType(), FPT->getParamTypes(),
8236           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8237   }
8238
8239   // Filter out previous declarations that don't match the scope.
8240   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8241                        D.getCXXScopeSpec().isNotEmpty() ||
8242                        isExplicitSpecialization ||
8243                        isFunctionTemplateSpecialization);
8244
8245   // Handle GNU asm-label extension (encoded as an attribute).
8246   if (Expr *E = (Expr*) D.getAsmLabel()) {
8247     // The parser guarantees this is a string.
8248     StringLiteral *SE = cast<StringLiteral>(E);
8249     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8250                                                 SE->getString(), 0));
8251   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8252     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8253       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8254     if (I != ExtnameUndeclaredIdentifiers.end()) {
8255       if (isDeclExternC(NewFD)) {
8256         NewFD->addAttr(I->second);
8257         ExtnameUndeclaredIdentifiers.erase(I);
8258       } else
8259         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8260             << /*Variable*/0 << NewFD;
8261     }
8262   }
8263
8264   // Copy the parameter declarations from the declarator D to the function
8265   // declaration NewFD, if they are available.  First scavenge them into Params.
8266   SmallVector<ParmVarDecl*, 16> Params;
8267   unsigned FTIIdx;
8268   if (D.isFunctionDeclarator(FTIIdx)) {
8269     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8270
8271     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8272     // function that takes no arguments, not a function that takes a
8273     // single void argument.
8274     // We let through "const void" here because Sema::GetTypeForDeclarator
8275     // already checks for that case.
8276     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8277       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8278         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8279         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8280         Param->setDeclContext(NewFD);
8281         Params.push_back(Param);
8282
8283         if (Param->isInvalidDecl())
8284           NewFD->setInvalidDecl();
8285       }
8286     }
8287
8288     if (!getLangOpts().CPlusPlus) {
8289       // In C, find all the tag declarations from the prototype and move them
8290       // into the function DeclContext. Remove them from the surrounding tag
8291       // injection context of the function, which is typically but not always
8292       // the TU.
8293       DeclContext *PrototypeTagContext =
8294           getTagInjectionContext(NewFD->getLexicalDeclContext());
8295       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8296         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8297
8298         // We don't want to reparent enumerators. Look at their parent enum
8299         // instead.
8300         if (!TD) {
8301           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8302             TD = cast<EnumDecl>(ECD->getDeclContext());
8303         }
8304         if (!TD)
8305           continue;
8306         DeclContext *TagDC = TD->getLexicalDeclContext();
8307         if (!TagDC->containsDecl(TD))
8308           continue;
8309         TagDC->removeDecl(TD);
8310         TD->setDeclContext(NewFD);
8311         NewFD->addDecl(TD);
8312
8313         // Preserve the lexical DeclContext if it is not the surrounding tag
8314         // injection context of the FD. In this example, the semantic context of
8315         // E will be f and the lexical context will be S, while both the
8316         // semantic and lexical contexts of S will be f:
8317         //   void f(struct S { enum E { a } f; } s);
8318         if (TagDC != PrototypeTagContext)
8319           TD->setLexicalDeclContext(TagDC);
8320       }
8321     }
8322   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8323     // When we're declaring a function with a typedef, typeof, etc as in the
8324     // following example, we'll need to synthesize (unnamed)
8325     // parameters for use in the declaration.
8326     //
8327     // @code
8328     // typedef void fn(int);
8329     // fn f;
8330     // @endcode
8331
8332     // Synthesize a parameter for each argument type.
8333     for (const auto &AI : FT->param_types()) {
8334       ParmVarDecl *Param =
8335           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8336       Param->setScopeInfo(0, Params.size());
8337       Params.push_back(Param);
8338     }
8339   } else {
8340     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8341            "Should not need args for typedef of non-prototype fn");
8342   }
8343
8344   // Finally, we know we have the right number of parameters, install them.
8345   NewFD->setParams(Params);
8346
8347   if (D.getDeclSpec().isNoreturnSpecified())
8348     NewFD->addAttr(
8349         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8350                                        Context, 0));
8351
8352   // Functions returning a variably modified type violate C99 6.7.5.2p2
8353   // because all functions have linkage.
8354   if (!NewFD->isInvalidDecl() &&
8355       NewFD->getReturnType()->isVariablyModifiedType()) {
8356     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8357     NewFD->setInvalidDecl();
8358   }
8359
8360   // Apply an implicit SectionAttr if #pragma code_seg is active.
8361   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8362       !NewFD->hasAttr<SectionAttr>()) {
8363     NewFD->addAttr(
8364         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8365                                     CodeSegStack.CurrentValue->getString(),
8366                                     CodeSegStack.CurrentPragmaLocation));
8367     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8368                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8369                          ASTContext::PSF_Read,
8370                      NewFD))
8371       NewFD->dropAttr<SectionAttr>();
8372   }
8373
8374   // Handle attributes.
8375   ProcessDeclAttributes(S, NewFD, D);
8376
8377   if (getLangOpts().OpenCL) {
8378     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8379     // type declaration will generate a compilation error.
8380     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8381     if (AddressSpace == LangAS::opencl_local ||
8382         AddressSpace == LangAS::opencl_global ||
8383         AddressSpace == LangAS::opencl_constant) {
8384       Diag(NewFD->getLocation(),
8385            diag::err_opencl_return_value_with_address_space);
8386       NewFD->setInvalidDecl();
8387     }
8388   }
8389
8390   if (!getLangOpts().CPlusPlus) {
8391     // Perform semantic checking on the function declaration.
8392     bool isExplicitSpecialization=false;
8393     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8394       CheckMain(NewFD, D.getDeclSpec());
8395
8396     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8397       CheckMSVCRTEntryPoint(NewFD);
8398
8399     if (!NewFD->isInvalidDecl())
8400       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8401                                                   isExplicitSpecialization));
8402     else if (!Previous.empty())
8403       // Recover gracefully from an invalid redeclaration.
8404       D.setRedeclaration(true);
8405     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8406             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8407            "previous declaration set still overloaded");
8408
8409     // Diagnose no-prototype function declarations with calling conventions that
8410     // don't support variadic calls. Only do this in C and do it after merging
8411     // possibly prototyped redeclarations.
8412     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8413     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8414       CallingConv CC = FT->getExtInfo().getCC();
8415       if (!supportsVariadicCall(CC)) {
8416         // Windows system headers sometimes accidentally use stdcall without
8417         // (void) parameters, so we relax this to a warning.
8418         int DiagID =
8419             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8420         Diag(NewFD->getLocation(), DiagID)
8421             << FunctionType::getNameForCallConv(CC);
8422       }
8423     }
8424   } else {
8425     // C++11 [replacement.functions]p3:
8426     //  The program's definitions shall not be specified as inline.
8427     //
8428     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8429     //
8430     // Suppress the diagnostic if the function is __attribute__((used)), since
8431     // that forces an external definition to be emitted.
8432     if (D.getDeclSpec().isInlineSpecified() &&
8433         NewFD->isReplaceableGlobalAllocationFunction() &&
8434         !NewFD->hasAttr<UsedAttr>())
8435       Diag(D.getDeclSpec().getInlineSpecLoc(),
8436            diag::ext_operator_new_delete_declared_inline)
8437         << NewFD->getDeclName();
8438
8439     // If the declarator is a template-id, translate the parser's template
8440     // argument list into our AST format.
8441     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8442       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8443       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8444       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8445       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8446                                          TemplateId->NumArgs);
8447       translateTemplateArguments(TemplateArgsPtr,
8448                                  TemplateArgs);
8449
8450       HasExplicitTemplateArgs = true;
8451
8452       if (NewFD->isInvalidDecl()) {
8453         HasExplicitTemplateArgs = false;
8454       } else if (FunctionTemplate) {
8455         // Function template with explicit template arguments.
8456         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8457           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8458
8459         HasExplicitTemplateArgs = false;
8460       } else {
8461         assert((isFunctionTemplateSpecialization ||
8462                 D.getDeclSpec().isFriendSpecified()) &&
8463                "should have a 'template<>' for this decl");
8464         // "friend void foo<>(int);" is an implicit specialization decl.
8465         isFunctionTemplateSpecialization = true;
8466       }
8467     } else if (isFriend && isFunctionTemplateSpecialization) {
8468       // This combination is only possible in a recovery case;  the user
8469       // wrote something like:
8470       //   template <> friend void foo(int);
8471       // which we're recovering from as if the user had written:
8472       //   friend void foo<>(int);
8473       // Go ahead and fake up a template id.
8474       HasExplicitTemplateArgs = true;
8475       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8476       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8477     }
8478
8479     // We do not add HD attributes to specializations here because
8480     // they may have different constexpr-ness compared to their
8481     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8482     // may end up with different effective targets. Instead, a
8483     // specialization inherits its target attributes from its template
8484     // in the CheckFunctionTemplateSpecialization() call below.
8485     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8486       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8487
8488     // If it's a friend (and only if it's a friend), it's possible
8489     // that either the specialized function type or the specialized
8490     // template is dependent, and therefore matching will fail.  In
8491     // this case, don't check the specialization yet.
8492     bool InstantiationDependent = false;
8493     if (isFunctionTemplateSpecialization && isFriend &&
8494         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8495          TemplateSpecializationType::anyDependentTemplateArguments(
8496             TemplateArgs,
8497             InstantiationDependent))) {
8498       assert(HasExplicitTemplateArgs &&
8499              "friend function specialization without template args");
8500       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8501                                                        Previous))
8502         NewFD->setInvalidDecl();
8503     } else if (isFunctionTemplateSpecialization) {
8504       if (CurContext->isDependentContext() && CurContext->isRecord()
8505           && !isFriend) {
8506         isDependentClassScopeExplicitSpecialization = true;
8507         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8508           diag::ext_function_specialization_in_class :
8509           diag::err_function_specialization_in_class)
8510           << NewFD->getDeclName();
8511       } else if (CheckFunctionTemplateSpecialization(NewFD,
8512                                   (HasExplicitTemplateArgs ? &TemplateArgs
8513                                                            : nullptr),
8514                                                      Previous))
8515         NewFD->setInvalidDecl();
8516
8517       // C++ [dcl.stc]p1:
8518       //   A storage-class-specifier shall not be specified in an explicit
8519       //   specialization (14.7.3)
8520       FunctionTemplateSpecializationInfo *Info =
8521           NewFD->getTemplateSpecializationInfo();
8522       if (Info && SC != SC_None) {
8523         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8524           Diag(NewFD->getLocation(),
8525                diag::err_explicit_specialization_inconsistent_storage_class)
8526             << SC
8527             << FixItHint::CreateRemoval(
8528                                       D.getDeclSpec().getStorageClassSpecLoc());
8529
8530         else
8531           Diag(NewFD->getLocation(),
8532                diag::ext_explicit_specialization_storage_class)
8533             << FixItHint::CreateRemoval(
8534                                       D.getDeclSpec().getStorageClassSpecLoc());
8535       }
8536     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8537       if (CheckMemberSpecialization(NewFD, Previous))
8538           NewFD->setInvalidDecl();
8539     }
8540
8541     // Perform semantic checking on the function declaration.
8542     if (!isDependentClassScopeExplicitSpecialization) {
8543       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8544         CheckMain(NewFD, D.getDeclSpec());
8545
8546       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8547         CheckMSVCRTEntryPoint(NewFD);
8548
8549       if (!NewFD->isInvalidDecl())
8550         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8551                                                     isExplicitSpecialization));
8552       else if (!Previous.empty())
8553         // Recover gracefully from an invalid redeclaration.
8554         D.setRedeclaration(true);
8555     }
8556
8557     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8558             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8559            "previous declaration set still overloaded");
8560
8561     NamedDecl *PrincipalDecl = (FunctionTemplate
8562                                 ? cast<NamedDecl>(FunctionTemplate)
8563                                 : NewFD);
8564
8565     if (isFriend && NewFD->getPreviousDecl()) {
8566       AccessSpecifier Access = AS_public;
8567       if (!NewFD->isInvalidDecl())
8568         Access = NewFD->getPreviousDecl()->getAccess();
8569
8570       NewFD->setAccess(Access);
8571       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8572     }
8573
8574     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8575         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8576       PrincipalDecl->setNonMemberOperator();
8577
8578     // If we have a function template, check the template parameter
8579     // list. This will check and merge default template arguments.
8580     if (FunctionTemplate) {
8581       FunctionTemplateDecl *PrevTemplate =
8582                                      FunctionTemplate->getPreviousDecl();
8583       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8584                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8585                                     : nullptr,
8586                             D.getDeclSpec().isFriendSpecified()
8587                               ? (D.isFunctionDefinition()
8588                                    ? TPC_FriendFunctionTemplateDefinition
8589                                    : TPC_FriendFunctionTemplate)
8590                               : (D.getCXXScopeSpec().isSet() &&
8591                                  DC && DC->isRecord() &&
8592                                  DC->isDependentContext())
8593                                   ? TPC_ClassTemplateMember
8594                                   : TPC_FunctionTemplate);
8595     }
8596
8597     if (NewFD->isInvalidDecl()) {
8598       // Ignore all the rest of this.
8599     } else if (!D.isRedeclaration()) {
8600       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8601                                        AddToScope };
8602       // Fake up an access specifier if it's supposed to be a class member.
8603       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8604         NewFD->setAccess(AS_public);
8605
8606       // Qualified decls generally require a previous declaration.
8607       if (D.getCXXScopeSpec().isSet()) {
8608         // ...with the major exception of templated-scope or
8609         // dependent-scope friend declarations.
8610
8611         // TODO: we currently also suppress this check in dependent
8612         // contexts because (1) the parameter depth will be off when
8613         // matching friend templates and (2) we might actually be
8614         // selecting a friend based on a dependent factor.  But there
8615         // are situations where these conditions don't apply and we
8616         // can actually do this check immediately.
8617         if (isFriend &&
8618             (TemplateParamLists.size() ||
8619              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8620              CurContext->isDependentContext())) {
8621           // ignore these
8622         } else {
8623           // The user tried to provide an out-of-line definition for a
8624           // function that is a member of a class or namespace, but there
8625           // was no such member function declared (C++ [class.mfct]p2,
8626           // C++ [namespace.memdef]p2). For example:
8627           //
8628           // class X {
8629           //   void f() const;
8630           // };
8631           //
8632           // void X::f() { } // ill-formed
8633           //
8634           // Complain about this problem, and attempt to suggest close
8635           // matches (e.g., those that differ only in cv-qualifiers and
8636           // whether the parameter types are references).
8637
8638           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8639                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8640             AddToScope = ExtraArgs.AddToScope;
8641             return Result;
8642           }
8643         }
8644
8645         // Unqualified local friend declarations are required to resolve
8646         // to something.
8647       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8648         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8649                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8650           AddToScope = ExtraArgs.AddToScope;
8651           return Result;
8652         }
8653       }
8654     } else if (!D.isFunctionDefinition() &&
8655                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8656                !isFriend && !isFunctionTemplateSpecialization &&
8657                !isExplicitSpecialization) {
8658       // An out-of-line member function declaration must also be a
8659       // definition (C++ [class.mfct]p2).
8660       // Note that this is not the case for explicit specializations of
8661       // function templates or member functions of class templates, per
8662       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8663       // extension for compatibility with old SWIG code which likes to
8664       // generate them.
8665       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8666         << D.getCXXScopeSpec().getRange();
8667     }
8668   }
8669
8670   ProcessPragmaWeak(S, NewFD);
8671   checkAttributesAfterMerging(*this, *NewFD);
8672
8673   AddKnownFunctionAttributes(NewFD);
8674
8675   if (NewFD->hasAttr<OverloadableAttr>() &&
8676       !NewFD->getType()->getAs<FunctionProtoType>()) {
8677     Diag(NewFD->getLocation(),
8678          diag::err_attribute_overloadable_no_prototype)
8679       << NewFD;
8680
8681     // Turn this into a variadic function with no parameters.
8682     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8683     FunctionProtoType::ExtProtoInfo EPI(
8684         Context.getDefaultCallingConvention(true, false));
8685     EPI.Variadic = true;
8686     EPI.ExtInfo = FT->getExtInfo();
8687
8688     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8689     NewFD->setType(R);
8690   }
8691
8692   // If there's a #pragma GCC visibility in scope, and this isn't a class
8693   // member, set the visibility of this function.
8694   if (!DC->isRecord() && NewFD->isExternallyVisible())
8695     AddPushedVisibilityAttribute(NewFD);
8696
8697   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8698   // marking the function.
8699   AddCFAuditedAttribute(NewFD);
8700
8701   // If this is a function definition, check if we have to apply optnone due to
8702   // a pragma.
8703   if(D.isFunctionDefinition())
8704     AddRangeBasedOptnone(NewFD);
8705
8706   // If this is the first declaration of an extern C variable, update
8707   // the map of such variables.
8708   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8709       isIncompleteDeclExternC(*this, NewFD))
8710     RegisterLocallyScopedExternCDecl(NewFD, S);
8711
8712   // Set this FunctionDecl's range up to the right paren.
8713   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8714
8715   if (D.isRedeclaration() && !Previous.empty()) {
8716     checkDLLAttributeRedeclaration(
8717         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8718         isExplicitSpecialization || isFunctionTemplateSpecialization,
8719         D.isFunctionDefinition());
8720   }
8721
8722   if (getLangOpts().CUDA) {
8723     IdentifierInfo *II = NewFD->getIdentifier();
8724     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8725         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8726       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8727         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8728
8729       Context.setcudaConfigureCallDecl(NewFD);
8730     }
8731
8732     // Variadic functions, other than a *declaration* of printf, are not allowed
8733     // in device-side CUDA code, unless someone passed
8734     // -fcuda-allow-variadic-functions.
8735     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8736         (NewFD->hasAttr<CUDADeviceAttr>() ||
8737          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8738         !(II && II->isStr("printf") && NewFD->isExternC() &&
8739           !D.isFunctionDefinition())) {
8740       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8741     }
8742   }
8743
8744   if (getLangOpts().CPlusPlus) {
8745     if (FunctionTemplate) {
8746       if (NewFD->isInvalidDecl())
8747         FunctionTemplate->setInvalidDecl();
8748       return FunctionTemplate;
8749     }
8750   }
8751
8752   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8753     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8754     if ((getLangOpts().OpenCLVersion >= 120)
8755         && (SC == SC_Static)) {
8756       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8757       D.setInvalidType();
8758     }
8759
8760     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8761     if (!NewFD->getReturnType()->isVoidType()) {
8762       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8763       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8764           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8765                                 : FixItHint());
8766       D.setInvalidType();
8767     }
8768
8769     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8770     for (auto Param : NewFD->parameters())
8771       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8772   }
8773   for (const ParmVarDecl *Param : NewFD->parameters()) {
8774     QualType PT = Param->getType();
8775
8776     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8777     // types.
8778     if (getLangOpts().OpenCLVersion >= 200) {
8779       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8780         QualType ElemTy = PipeTy->getElementType();
8781           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8782             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8783             D.setInvalidType();
8784           }
8785       }
8786     }
8787   }
8788
8789   MarkUnusedFileScopedDecl(NewFD);
8790
8791   // Here we have an function template explicit specialization at class scope.
8792   // The actually specialization will be postponed to template instatiation
8793   // time via the ClassScopeFunctionSpecializationDecl node.
8794   if (isDependentClassScopeExplicitSpecialization) {
8795     ClassScopeFunctionSpecializationDecl *NewSpec =
8796                          ClassScopeFunctionSpecializationDecl::Create(
8797                                 Context, CurContext, SourceLocation(),
8798                                 cast<CXXMethodDecl>(NewFD),
8799                                 HasExplicitTemplateArgs, TemplateArgs);
8800     CurContext->addDecl(NewSpec);
8801     AddToScope = false;
8802   }
8803
8804   return NewFD;
8805 }
8806
8807 /// \brief Checks if the new declaration declared in dependent context must be
8808 /// put in the same redeclaration chain as the specified declaration.
8809 ///
8810 /// \param D Declaration that is checked.
8811 /// \param PrevDecl Previous declaration found with proper lookup method for the
8812 ///                 same declaration name.
8813 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8814 ///          belongs to.
8815 ///
8816 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8817   // Any declarations should be put into redeclaration chains except for
8818   // friend declaration in a dependent context that names a function in
8819   // namespace scope.
8820   //
8821   // This allows to compile code like:
8822   //
8823   //       void func();
8824   //       template<typename T> class C1 { friend void func() { } };
8825   //       template<typename T> class C2 { friend void func() { } };
8826   //
8827   // This code snippet is a valid code unless both templates are instantiated.
8828   return !(D->getLexicalDeclContext()->isDependentContext() &&
8829            D->getDeclContext()->isFileContext() &&
8830            D->getFriendObjectKind() != Decl::FOK_None);
8831 }
8832
8833 /// \brief Perform semantic checking of a new function declaration.
8834 ///
8835 /// Performs semantic analysis of the new function declaration
8836 /// NewFD. This routine performs all semantic checking that does not
8837 /// require the actual declarator involved in the declaration, and is
8838 /// used both for the declaration of functions as they are parsed
8839 /// (called via ActOnDeclarator) and for the declaration of functions
8840 /// that have been instantiated via C++ template instantiation (called
8841 /// via InstantiateDecl).
8842 ///
8843 /// \param IsExplicitSpecialization whether this new function declaration is
8844 /// an explicit specialization of the previous declaration.
8845 ///
8846 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8847 ///
8848 /// \returns true if the function declaration is a redeclaration.
8849 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8850                                     LookupResult &Previous,
8851                                     bool IsExplicitSpecialization) {
8852   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8853          "Variably modified return types are not handled here");
8854
8855   // Determine whether the type of this function should be merged with
8856   // a previous visible declaration. This never happens for functions in C++,
8857   // and always happens in C if the previous declaration was visible.
8858   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8859                                !Previous.isShadowed();
8860
8861   bool Redeclaration = false;
8862   NamedDecl *OldDecl = nullptr;
8863
8864   // Merge or overload the declaration with an existing declaration of
8865   // the same name, if appropriate.
8866   if (!Previous.empty()) {
8867     // Determine whether NewFD is an overload of PrevDecl or
8868     // a declaration that requires merging. If it's an overload,
8869     // there's no more work to do here; we'll just add the new
8870     // function to the scope.
8871     if (!AllowOverloadingOfFunction(Previous, Context)) {
8872       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8873       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8874         Redeclaration = true;
8875         OldDecl = Candidate;
8876       }
8877     } else {
8878       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8879                             /*NewIsUsingDecl*/ false)) {
8880       case Ovl_Match:
8881         Redeclaration = true;
8882         break;
8883
8884       case Ovl_NonFunction:
8885         Redeclaration = true;
8886         break;
8887
8888       case Ovl_Overload:
8889         Redeclaration = false;
8890         break;
8891       }
8892
8893       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8894         // If a function name is overloadable in C, then every function
8895         // with that name must be marked "overloadable".
8896         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8897           << Redeclaration << NewFD;
8898         NamedDecl *OverloadedDecl = nullptr;
8899         if (Redeclaration)
8900           OverloadedDecl = OldDecl;
8901         else if (!Previous.empty())
8902           OverloadedDecl = Previous.getRepresentativeDecl();
8903         if (OverloadedDecl)
8904           Diag(OverloadedDecl->getLocation(),
8905                diag::note_attribute_overloadable_prev_overload);
8906         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8907       }
8908     }
8909   }
8910
8911   // Check for a previous extern "C" declaration with this name.
8912   if (!Redeclaration &&
8913       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8914     if (!Previous.empty()) {
8915       // This is an extern "C" declaration with the same name as a previous
8916       // declaration, and thus redeclares that entity...
8917       Redeclaration = true;
8918       OldDecl = Previous.getFoundDecl();
8919       MergeTypeWithPrevious = false;
8920
8921       // ... except in the presence of __attribute__((overloadable)).
8922       if (OldDecl->hasAttr<OverloadableAttr>()) {
8923         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8924           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8925             << Redeclaration << NewFD;
8926           Diag(Previous.getFoundDecl()->getLocation(),
8927                diag::note_attribute_overloadable_prev_overload);
8928           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8929         }
8930         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8931           Redeclaration = false;
8932           OldDecl = nullptr;
8933         }
8934       }
8935     }
8936   }
8937
8938   // C++11 [dcl.constexpr]p8:
8939   //   A constexpr specifier for a non-static member function that is not
8940   //   a constructor declares that member function to be const.
8941   //
8942   // This needs to be delayed until we know whether this is an out-of-line
8943   // definition of a static member function.
8944   //
8945   // This rule is not present in C++1y, so we produce a backwards
8946   // compatibility warning whenever it happens in C++11.
8947   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8948   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8949       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8950       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8951     CXXMethodDecl *OldMD = nullptr;
8952     if (OldDecl)
8953       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8954     if (!OldMD || !OldMD->isStatic()) {
8955       const FunctionProtoType *FPT =
8956         MD->getType()->castAs<FunctionProtoType>();
8957       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8958       EPI.TypeQuals |= Qualifiers::Const;
8959       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8960                                           FPT->getParamTypes(), EPI));
8961
8962       // Warn that we did this, if we're not performing template instantiation.
8963       // In that case, we'll have warned already when the template was defined.
8964       if (ActiveTemplateInstantiations.empty()) {
8965         SourceLocation AddConstLoc;
8966         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8967                 .IgnoreParens().getAs<FunctionTypeLoc>())
8968           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8969
8970         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8971           << FixItHint::CreateInsertion(AddConstLoc, " const");
8972       }
8973     }
8974   }
8975
8976   if (Redeclaration) {
8977     // NewFD and OldDecl represent declarations that need to be
8978     // merged.
8979     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8980       NewFD->setInvalidDecl();
8981       return Redeclaration;
8982     }
8983
8984     Previous.clear();
8985     Previous.addDecl(OldDecl);
8986
8987     if (FunctionTemplateDecl *OldTemplateDecl
8988                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8989       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8990       FunctionTemplateDecl *NewTemplateDecl
8991         = NewFD->getDescribedFunctionTemplate();
8992       assert(NewTemplateDecl && "Template/non-template mismatch");
8993       if (CXXMethodDecl *Method
8994             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8995         Method->setAccess(OldTemplateDecl->getAccess());
8996         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8997       }
8998
8999       // If this is an explicit specialization of a member that is a function
9000       // template, mark it as a member specialization.
9001       if (IsExplicitSpecialization &&
9002           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9003         NewTemplateDecl->setMemberSpecialization();
9004         assert(OldTemplateDecl->isMemberSpecialization());
9005         // Explicit specializations of a member template do not inherit deleted
9006         // status from the parent member template that they are specializing.
9007         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9008           FunctionDecl *const OldTemplatedDecl =
9009               OldTemplateDecl->getTemplatedDecl();
9010           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9011           OldTemplatedDecl->setDeletedAsWritten(false);
9012         }
9013       }
9014
9015     } else {
9016       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9017         // This needs to happen first so that 'inline' propagates.
9018         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9019         if (isa<CXXMethodDecl>(NewFD))
9020           NewFD->setAccess(OldDecl->getAccess());
9021       }
9022     }
9023   }
9024
9025   // Semantic checking for this function declaration (in isolation).
9026
9027   if (getLangOpts().CPlusPlus) {
9028     // C++-specific checks.
9029     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9030       CheckConstructor(Constructor);
9031     } else if (CXXDestructorDecl *Destructor =
9032                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9033       CXXRecordDecl *Record = Destructor->getParent();
9034       QualType ClassType = Context.getTypeDeclType(Record);
9035
9036       // FIXME: Shouldn't we be able to perform this check even when the class
9037       // type is dependent? Both gcc and edg can handle that.
9038       if (!ClassType->isDependentType()) {
9039         DeclarationName Name
9040           = Context.DeclarationNames.getCXXDestructorName(
9041                                         Context.getCanonicalType(ClassType));
9042         if (NewFD->getDeclName() != Name) {
9043           Diag(NewFD->getLocation(), diag::err_destructor_name);
9044           NewFD->setInvalidDecl();
9045           return Redeclaration;
9046         }
9047       }
9048     } else if (CXXConversionDecl *Conversion
9049                = dyn_cast<CXXConversionDecl>(NewFD)) {
9050       ActOnConversionDeclarator(Conversion);
9051     }
9052
9053     // Find any virtual functions that this function overrides.
9054     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9055       if (!Method->isFunctionTemplateSpecialization() &&
9056           !Method->getDescribedFunctionTemplate() &&
9057           Method->isCanonicalDecl()) {
9058         if (AddOverriddenMethods(Method->getParent(), Method)) {
9059           // If the function was marked as "static", we have a problem.
9060           if (NewFD->getStorageClass() == SC_Static) {
9061             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9062           }
9063         }
9064       }
9065
9066       if (Method->isStatic())
9067         checkThisInStaticMemberFunctionType(Method);
9068     }
9069
9070     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9071     if (NewFD->isOverloadedOperator() &&
9072         CheckOverloadedOperatorDeclaration(NewFD)) {
9073       NewFD->setInvalidDecl();
9074       return Redeclaration;
9075     }
9076
9077     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9078     if (NewFD->getLiteralIdentifier() &&
9079         CheckLiteralOperatorDeclaration(NewFD)) {
9080       NewFD->setInvalidDecl();
9081       return Redeclaration;
9082     }
9083
9084     // In C++, check default arguments now that we have merged decls. Unless
9085     // the lexical context is the class, because in this case this is done
9086     // during delayed parsing anyway.
9087     if (!CurContext->isRecord())
9088       CheckCXXDefaultArguments(NewFD);
9089
9090     // If this function declares a builtin function, check the type of this
9091     // declaration against the expected type for the builtin.
9092     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9093       ASTContext::GetBuiltinTypeError Error;
9094       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9095       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9096       // If the type of the builtin differs only in its exception
9097       // specification, that's OK.
9098       // FIXME: If the types do differ in this way, it would be better to
9099       // retain the 'noexcept' form of the type.
9100       if (!T.isNull() &&
9101           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9102                                                             NewFD->getType()))
9103         // The type of this function differs from the type of the builtin,
9104         // so forget about the builtin entirely.
9105         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9106     }
9107
9108     // If this function is declared as being extern "C", then check to see if
9109     // the function returns a UDT (class, struct, or union type) that is not C
9110     // compatible, and if it does, warn the user.
9111     // But, issue any diagnostic on the first declaration only.
9112     if (Previous.empty() && NewFD->isExternC()) {
9113       QualType R = NewFD->getReturnType();
9114       if (R->isIncompleteType() && !R->isVoidType())
9115         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9116             << NewFD << R;
9117       else if (!R.isPODType(Context) && !R->isVoidType() &&
9118                !R->isObjCObjectPointerType())
9119         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9120     }
9121
9122     // C++1z [dcl.fct]p6:
9123     //   [...] whether the function has a non-throwing exception-specification
9124     //   [is] part of the function type
9125     //
9126     // This results in an ABI break between C++14 and C++17 for functions whose
9127     // declared type includes an exception-specification in a parameter or
9128     // return type. (Exception specifications on the function itself are OK in
9129     // most cases, and exception specifications are not permitted in most other
9130     // contexts where they could make it into a mangling.)
9131     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9132       auto HasNoexcept = [&](QualType T) -> bool {
9133         // Strip off declarator chunks that could be between us and a function
9134         // type. We don't need to look far, exception specifications are very
9135         // restricted prior to C++17.
9136         if (auto *RT = T->getAs<ReferenceType>())
9137           T = RT->getPointeeType();
9138         else if (T->isAnyPointerType())
9139           T = T->getPointeeType();
9140         else if (auto *MPT = T->getAs<MemberPointerType>())
9141           T = MPT->getPointeeType();
9142         if (auto *FPT = T->getAs<FunctionProtoType>())
9143           if (FPT->isNothrow(Context))
9144             return true;
9145         return false;
9146       };
9147
9148       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9149       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9150       for (QualType T : FPT->param_types())
9151         AnyNoexcept |= HasNoexcept(T);
9152       if (AnyNoexcept)
9153         Diag(NewFD->getLocation(),
9154              diag::warn_cxx1z_compat_exception_spec_in_signature)
9155             << NewFD;
9156     }
9157
9158     if (!Redeclaration && LangOpts.CUDA)
9159       checkCUDATargetOverload(NewFD, Previous);
9160   }
9161   return Redeclaration;
9162 }
9163
9164 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9165   // C++11 [basic.start.main]p3:
9166   //   A program that [...] declares main to be inline, static or
9167   //   constexpr is ill-formed.
9168   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9169   //   appear in a declaration of main.
9170   // static main is not an error under C99, but we should warn about it.
9171   // We accept _Noreturn main as an extension.
9172   if (FD->getStorageClass() == SC_Static)
9173     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9174          ? diag::err_static_main : diag::warn_static_main)
9175       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9176   if (FD->isInlineSpecified())
9177     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9178       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9179   if (DS.isNoreturnSpecified()) {
9180     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9181     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9182     Diag(NoreturnLoc, diag::ext_noreturn_main);
9183     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9184       << FixItHint::CreateRemoval(NoreturnRange);
9185   }
9186   if (FD->isConstexpr()) {
9187     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9188       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9189     FD->setConstexpr(false);
9190   }
9191
9192   if (getLangOpts().OpenCL) {
9193     Diag(FD->getLocation(), diag::err_opencl_no_main)
9194         << FD->hasAttr<OpenCLKernelAttr>();
9195     FD->setInvalidDecl();
9196     return;
9197   }
9198
9199   QualType T = FD->getType();
9200   assert(T->isFunctionType() && "function decl is not of function type");
9201   const FunctionType* FT = T->castAs<FunctionType>();
9202
9203   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9204     // In C with GNU extensions we allow main() to have non-integer return
9205     // type, but we should warn about the extension, and we disable the
9206     // implicit-return-zero rule.
9207
9208     // GCC in C mode accepts qualified 'int'.
9209     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9210       FD->setHasImplicitReturnZero(true);
9211     else {
9212       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9213       SourceRange RTRange = FD->getReturnTypeSourceRange();
9214       if (RTRange.isValid())
9215         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9216             << FixItHint::CreateReplacement(RTRange, "int");
9217     }
9218   } else {
9219     // In C and C++, main magically returns 0 if you fall off the end;
9220     // set the flag which tells us that.
9221     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9222
9223     // All the standards say that main() should return 'int'.
9224     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9225       FD->setHasImplicitReturnZero(true);
9226     else {
9227       // Otherwise, this is just a flat-out error.
9228       SourceRange RTRange = FD->getReturnTypeSourceRange();
9229       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9230           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9231                                 : FixItHint());
9232       FD->setInvalidDecl(true);
9233     }
9234   }
9235
9236   // Treat protoless main() as nullary.
9237   if (isa<FunctionNoProtoType>(FT)) return;
9238
9239   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9240   unsigned nparams = FTP->getNumParams();
9241   assert(FD->getNumParams() == nparams);
9242
9243   bool HasExtraParameters = (nparams > 3);
9244
9245   if (FTP->isVariadic()) {
9246     Diag(FD->getLocation(), diag::ext_variadic_main);
9247     // FIXME: if we had information about the location of the ellipsis, we
9248     // could add a FixIt hint to remove it as a parameter.
9249   }
9250
9251   // Darwin passes an undocumented fourth argument of type char**.  If
9252   // other platforms start sprouting these, the logic below will start
9253   // getting shifty.
9254   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9255     HasExtraParameters = false;
9256
9257   if (HasExtraParameters) {
9258     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9259     FD->setInvalidDecl(true);
9260     nparams = 3;
9261   }
9262
9263   // FIXME: a lot of the following diagnostics would be improved
9264   // if we had some location information about types.
9265
9266   QualType CharPP =
9267     Context.getPointerType(Context.getPointerType(Context.CharTy));
9268   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9269
9270   for (unsigned i = 0; i < nparams; ++i) {
9271     QualType AT = FTP->getParamType(i);
9272
9273     bool mismatch = true;
9274
9275     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9276       mismatch = false;
9277     else if (Expected[i] == CharPP) {
9278       // As an extension, the following forms are okay:
9279       //   char const **
9280       //   char const * const *
9281       //   char * const *
9282
9283       QualifierCollector qs;
9284       const PointerType* PT;
9285       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9286           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9287           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9288                               Context.CharTy)) {
9289         qs.removeConst();
9290         mismatch = !qs.empty();
9291       }
9292     }
9293
9294     if (mismatch) {
9295       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9296       // TODO: suggest replacing given type with expected type
9297       FD->setInvalidDecl(true);
9298     }
9299   }
9300
9301   if (nparams == 1 && !FD->isInvalidDecl()) {
9302     Diag(FD->getLocation(), diag::warn_main_one_arg);
9303   }
9304
9305   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9306     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9307     FD->setInvalidDecl();
9308   }
9309 }
9310
9311 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9312   QualType T = FD->getType();
9313   assert(T->isFunctionType() && "function decl is not of function type");
9314   const FunctionType *FT = T->castAs<FunctionType>();
9315
9316   // Set an implicit return of 'zero' if the function can return some integral,
9317   // enumeration, pointer or nullptr type.
9318   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9319       FT->getReturnType()->isAnyPointerType() ||
9320       FT->getReturnType()->isNullPtrType())
9321     // DllMain is exempt because a return value of zero means it failed.
9322     if (FD->getName() != "DllMain")
9323       FD->setHasImplicitReturnZero(true);
9324
9325   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9326     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9327     FD->setInvalidDecl();
9328   }
9329 }
9330
9331 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9332   // FIXME: Need strict checking.  In C89, we need to check for
9333   // any assignment, increment, decrement, function-calls, or
9334   // commas outside of a sizeof.  In C99, it's the same list,
9335   // except that the aforementioned are allowed in unevaluated
9336   // expressions.  Everything else falls under the
9337   // "may accept other forms of constant expressions" exception.
9338   // (We never end up here for C++, so the constant expression
9339   // rules there don't matter.)
9340   const Expr *Culprit;
9341   if (Init->isConstantInitializer(Context, false, &Culprit))
9342     return false;
9343   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9344     << Culprit->getSourceRange();
9345   return true;
9346 }
9347
9348 namespace {
9349   // Visits an initialization expression to see if OrigDecl is evaluated in
9350   // its own initialization and throws a warning if it does.
9351   class SelfReferenceChecker
9352       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9353     Sema &S;
9354     Decl *OrigDecl;
9355     bool isRecordType;
9356     bool isPODType;
9357     bool isReferenceType;
9358
9359     bool isInitList;
9360     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9361
9362   public:
9363     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9364
9365     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9366                                                     S(S), OrigDecl(OrigDecl) {
9367       isPODType = false;
9368       isRecordType = false;
9369       isReferenceType = false;
9370       isInitList = false;
9371       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9372         isPODType = VD->getType().isPODType(S.Context);
9373         isRecordType = VD->getType()->isRecordType();
9374         isReferenceType = VD->getType()->isReferenceType();
9375       }
9376     }
9377
9378     // For most expressions, just call the visitor.  For initializer lists,
9379     // track the index of the field being initialized since fields are
9380     // initialized in order allowing use of previously initialized fields.
9381     void CheckExpr(Expr *E) {
9382       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9383       if (!InitList) {
9384         Visit(E);
9385         return;
9386       }
9387
9388       // Track and increment the index here.
9389       isInitList = true;
9390       InitFieldIndex.push_back(0);
9391       for (auto Child : InitList->children()) {
9392         CheckExpr(cast<Expr>(Child));
9393         ++InitFieldIndex.back();
9394       }
9395       InitFieldIndex.pop_back();
9396     }
9397
9398     // Returns true if MemberExpr is checked and no futher checking is needed.
9399     // Returns false if additional checking is required.
9400     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9401       llvm::SmallVector<FieldDecl*, 4> Fields;
9402       Expr *Base = E;
9403       bool ReferenceField = false;
9404
9405       // Get the field memebers used.
9406       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9407         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9408         if (!FD)
9409           return false;
9410         Fields.push_back(FD);
9411         if (FD->getType()->isReferenceType())
9412           ReferenceField = true;
9413         Base = ME->getBase()->IgnoreParenImpCasts();
9414       }
9415
9416       // Keep checking only if the base Decl is the same.
9417       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9418       if (!DRE || DRE->getDecl() != OrigDecl)
9419         return false;
9420
9421       // A reference field can be bound to an unininitialized field.
9422       if (CheckReference && !ReferenceField)
9423         return true;
9424
9425       // Convert FieldDecls to their index number.
9426       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9427       for (const FieldDecl *I : llvm::reverse(Fields))
9428         UsedFieldIndex.push_back(I->getFieldIndex());
9429
9430       // See if a warning is needed by checking the first difference in index
9431       // numbers.  If field being used has index less than the field being
9432       // initialized, then the use is safe.
9433       for (auto UsedIter = UsedFieldIndex.begin(),
9434                 UsedEnd = UsedFieldIndex.end(),
9435                 OrigIter = InitFieldIndex.begin(),
9436                 OrigEnd = InitFieldIndex.end();
9437            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9438         if (*UsedIter < *OrigIter)
9439           return true;
9440         if (*UsedIter > *OrigIter)
9441           break;
9442       }
9443
9444       // TODO: Add a different warning which will print the field names.
9445       HandleDeclRefExpr(DRE);
9446       return true;
9447     }
9448
9449     // For most expressions, the cast is directly above the DeclRefExpr.
9450     // For conditional operators, the cast can be outside the conditional
9451     // operator if both expressions are DeclRefExpr's.
9452     void HandleValue(Expr *E) {
9453       E = E->IgnoreParens();
9454       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9455         HandleDeclRefExpr(DRE);
9456         return;
9457       }
9458
9459       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9460         Visit(CO->getCond());
9461         HandleValue(CO->getTrueExpr());
9462         HandleValue(CO->getFalseExpr());
9463         return;
9464       }
9465
9466       if (BinaryConditionalOperator *BCO =
9467               dyn_cast<BinaryConditionalOperator>(E)) {
9468         Visit(BCO->getCond());
9469         HandleValue(BCO->getFalseExpr());
9470         return;
9471       }
9472
9473       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9474         HandleValue(OVE->getSourceExpr());
9475         return;
9476       }
9477
9478       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9479         if (BO->getOpcode() == BO_Comma) {
9480           Visit(BO->getLHS());
9481           HandleValue(BO->getRHS());
9482           return;
9483         }
9484       }
9485
9486       if (isa<MemberExpr>(E)) {
9487         if (isInitList) {
9488           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9489                                       false /*CheckReference*/))
9490             return;
9491         }
9492
9493         Expr *Base = E->IgnoreParenImpCasts();
9494         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9495           // Check for static member variables and don't warn on them.
9496           if (!isa<FieldDecl>(ME->getMemberDecl()))
9497             return;
9498           Base = ME->getBase()->IgnoreParenImpCasts();
9499         }
9500         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9501           HandleDeclRefExpr(DRE);
9502         return;
9503       }
9504
9505       Visit(E);
9506     }
9507
9508     // Reference types not handled in HandleValue are handled here since all
9509     // uses of references are bad, not just r-value uses.
9510     void VisitDeclRefExpr(DeclRefExpr *E) {
9511       if (isReferenceType)
9512         HandleDeclRefExpr(E);
9513     }
9514
9515     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9516       if (E->getCastKind() == CK_LValueToRValue) {
9517         HandleValue(E->getSubExpr());
9518         return;
9519       }
9520
9521       Inherited::VisitImplicitCastExpr(E);
9522     }
9523
9524     void VisitMemberExpr(MemberExpr *E) {
9525       if (isInitList) {
9526         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9527           return;
9528       }
9529
9530       // Don't warn on arrays since they can be treated as pointers.
9531       if (E->getType()->canDecayToPointerType()) return;
9532
9533       // Warn when a non-static method call is followed by non-static member
9534       // field accesses, which is followed by a DeclRefExpr.
9535       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9536       bool Warn = (MD && !MD->isStatic());
9537       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9538       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9539         if (!isa<FieldDecl>(ME->getMemberDecl()))
9540           Warn = false;
9541         Base = ME->getBase()->IgnoreParenImpCasts();
9542       }
9543
9544       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9545         if (Warn)
9546           HandleDeclRefExpr(DRE);
9547         return;
9548       }
9549
9550       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9551       // Visit that expression.
9552       Visit(Base);
9553     }
9554
9555     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9556       Expr *Callee = E->getCallee();
9557
9558       if (isa<UnresolvedLookupExpr>(Callee))
9559         return Inherited::VisitCXXOperatorCallExpr(E);
9560
9561       Visit(Callee);
9562       for (auto Arg: E->arguments())
9563         HandleValue(Arg->IgnoreParenImpCasts());
9564     }
9565
9566     void VisitUnaryOperator(UnaryOperator *E) {
9567       // For POD record types, addresses of its own members are well-defined.
9568       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9569           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9570         if (!isPODType)
9571           HandleValue(E->getSubExpr());
9572         return;
9573       }
9574
9575       if (E->isIncrementDecrementOp()) {
9576         HandleValue(E->getSubExpr());
9577         return;
9578       }
9579
9580       Inherited::VisitUnaryOperator(E);
9581     }
9582
9583     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9584
9585     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9586       if (E->getConstructor()->isCopyConstructor()) {
9587         Expr *ArgExpr = E->getArg(0);
9588         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9589           if (ILE->getNumInits() == 1)
9590             ArgExpr = ILE->getInit(0);
9591         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9592           if (ICE->getCastKind() == CK_NoOp)
9593             ArgExpr = ICE->getSubExpr();
9594         HandleValue(ArgExpr);
9595         return;
9596       }
9597       Inherited::VisitCXXConstructExpr(E);
9598     }
9599
9600     void VisitCallExpr(CallExpr *E) {
9601       // Treat std::move as a use.
9602       if (E->getNumArgs() == 1) {
9603         if (FunctionDecl *FD = E->getDirectCallee()) {
9604           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9605               FD->getIdentifier()->isStr("move")) {
9606             HandleValue(E->getArg(0));
9607             return;
9608           }
9609         }
9610       }
9611
9612       Inherited::VisitCallExpr(E);
9613     }
9614
9615     void VisitBinaryOperator(BinaryOperator *E) {
9616       if (E->isCompoundAssignmentOp()) {
9617         HandleValue(E->getLHS());
9618         Visit(E->getRHS());
9619         return;
9620       }
9621
9622       Inherited::VisitBinaryOperator(E);
9623     }
9624
9625     // A custom visitor for BinaryConditionalOperator is needed because the
9626     // regular visitor would check the condition and true expression separately
9627     // but both point to the same place giving duplicate diagnostics.
9628     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9629       Visit(E->getCond());
9630       Visit(E->getFalseExpr());
9631     }
9632
9633     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9634       Decl* ReferenceDecl = DRE->getDecl();
9635       if (OrigDecl != ReferenceDecl) return;
9636       unsigned diag;
9637       if (isReferenceType) {
9638         diag = diag::warn_uninit_self_reference_in_reference_init;
9639       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9640         diag = diag::warn_static_self_reference_in_init;
9641       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9642                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9643                  DRE->getDecl()->getType()->isRecordType()) {
9644         diag = diag::warn_uninit_self_reference_in_init;
9645       } else {
9646         // Local variables will be handled by the CFG analysis.
9647         return;
9648       }
9649
9650       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9651                             S.PDiag(diag)
9652                               << DRE->getNameInfo().getName()
9653                               << OrigDecl->getLocation()
9654                               << DRE->getSourceRange());
9655     }
9656   };
9657
9658   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9659   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9660                                  bool DirectInit) {
9661     // Parameters arguments are occassionially constructed with itself,
9662     // for instance, in recursive functions.  Skip them.
9663     if (isa<ParmVarDecl>(OrigDecl))
9664       return;
9665
9666     E = E->IgnoreParens();
9667
9668     // Skip checking T a = a where T is not a record or reference type.
9669     // Doing so is a way to silence uninitialized warnings.
9670     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9671       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9672         if (ICE->getCastKind() == CK_LValueToRValue)
9673           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9674             if (DRE->getDecl() == OrigDecl)
9675               return;
9676
9677     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9678   }
9679 } // end anonymous namespace
9680
9681 namespace {
9682   // Simple wrapper to add the name of a variable or (if no variable is
9683   // available) a DeclarationName into a diagnostic.
9684   struct VarDeclOrName {
9685     VarDecl *VDecl;
9686     DeclarationName Name;
9687
9688     friend const Sema::SemaDiagnosticBuilder &
9689     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9690       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9691     }
9692   };
9693 } // end anonymous namespace
9694
9695 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9696                                             DeclarationName Name, QualType Type,
9697                                             TypeSourceInfo *TSI,
9698                                             SourceRange Range, bool DirectInit,
9699                                             Expr *Init) {
9700   bool IsInitCapture = !VDecl;
9701   assert((!VDecl || !VDecl->isInitCapture()) &&
9702          "init captures are expected to be deduced prior to initialization");
9703
9704   VarDeclOrName VN{VDecl, Name};
9705
9706   ArrayRef<Expr *> DeduceInits = Init;
9707   if (DirectInit) {
9708     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9709       DeduceInits = PL->exprs();
9710     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9711       DeduceInits = IL->inits();
9712   }
9713
9714   // Deduction only works if we have exactly one source expression.
9715   if (DeduceInits.empty()) {
9716     // It isn't possible to write this directly, but it is possible to
9717     // end up in this situation with "auto x(some_pack...);"
9718     Diag(Init->getLocStart(), IsInitCapture
9719                                   ? diag::err_init_capture_no_expression
9720                                   : diag::err_auto_var_init_no_expression)
9721         << VN << Type << Range;
9722     return QualType();
9723   }
9724
9725   if (DeduceInits.size() > 1) {
9726     Diag(DeduceInits[1]->getLocStart(),
9727          IsInitCapture ? diag::err_init_capture_multiple_expressions
9728                        : diag::err_auto_var_init_multiple_expressions)
9729         << VN << Type << Range;
9730     return QualType();
9731   }
9732
9733   Expr *DeduceInit = DeduceInits[0];
9734   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9735     Diag(Init->getLocStart(), IsInitCapture
9736                                   ? diag::err_init_capture_paren_braces
9737                                   : diag::err_auto_var_init_paren_braces)
9738         << isa<InitListExpr>(Init) << VN << Type << Range;
9739     return QualType();
9740   }
9741
9742   // Expressions default to 'id' when we're in a debugger.
9743   bool DefaultedAnyToId = false;
9744   if (getLangOpts().DebuggerCastResultToId &&
9745       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9746     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9747     if (Result.isInvalid()) {
9748       return QualType();
9749     }
9750     Init = Result.get();
9751     DefaultedAnyToId = true;
9752   }
9753
9754   // C++ [dcl.decomp]p1:
9755   //   If the assignment-expression [...] has array type A and no ref-qualifier
9756   //   is present, e has type cv A
9757   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9758       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9759       DeduceInit->getType()->isConstantArrayType())
9760     return Context.getQualifiedType(DeduceInit->getType(),
9761                                     Type.getQualifiers());
9762
9763   QualType DeducedType;
9764   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9765     if (!IsInitCapture)
9766       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9767     else if (isa<InitListExpr>(Init))
9768       Diag(Range.getBegin(),
9769            diag::err_init_capture_deduction_failure_from_init_list)
9770           << VN
9771           << (DeduceInit->getType().isNull() ? TSI->getType()
9772                                              : DeduceInit->getType())
9773           << DeduceInit->getSourceRange();
9774     else
9775       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9776           << VN << TSI->getType()
9777           << (DeduceInit->getType().isNull() ? TSI->getType()
9778                                              : DeduceInit->getType())
9779           << DeduceInit->getSourceRange();
9780   }
9781
9782   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9783   // 'id' instead of a specific object type prevents most of our usual
9784   // checks.
9785   // We only want to warn outside of template instantiations, though:
9786   // inside a template, the 'id' could have come from a parameter.
9787   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9788       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9789     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9790     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9791   }
9792
9793   return DeducedType;
9794 }
9795
9796 /// AddInitializerToDecl - Adds the initializer Init to the
9797 /// declaration dcl. If DirectInit is true, this is C++ direct
9798 /// initialization rather than copy initialization.
9799 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
9800   // If there is no declaration, there was an error parsing it.  Just ignore
9801   // the initializer.
9802   if (!RealDecl || RealDecl->isInvalidDecl()) {
9803     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9804     return;
9805   }
9806
9807   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9808     // Pure-specifiers are handled in ActOnPureSpecifier.
9809     Diag(Method->getLocation(), diag::err_member_function_initialization)
9810       << Method->getDeclName() << Init->getSourceRange();
9811     Method->setInvalidDecl();
9812     return;
9813   }
9814
9815   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9816   if (!VDecl) {
9817     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9818     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9819     RealDecl->setInvalidDecl();
9820     return;
9821   }
9822
9823   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9824   if (VDecl->getType()->isUndeducedType()) {
9825     // Attempt typo correction early so that the type of the init expression can
9826     // be deduced based on the chosen correction if the original init contains a
9827     // TypoExpr.
9828     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9829     if (!Res.isUsable()) {
9830       RealDecl->setInvalidDecl();
9831       return;
9832     }
9833     Init = Res.get();
9834
9835     QualType DeducedType = deduceVarTypeFromInitializer(
9836         VDecl, VDecl->getDeclName(), VDecl->getType(),
9837         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9838     if (DeducedType.isNull()) {
9839       RealDecl->setInvalidDecl();
9840       return;
9841     }
9842
9843     VDecl->setType(DeducedType);
9844     assert(VDecl->isLinkageValid());
9845
9846     // In ARC, infer lifetime.
9847     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9848       VDecl->setInvalidDecl();
9849
9850     // If this is a redeclaration, check that the type we just deduced matches
9851     // the previously declared type.
9852     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9853       // We never need to merge the type, because we cannot form an incomplete
9854       // array of auto, nor deduce such a type.
9855       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9856     }
9857
9858     // Check the deduced type is valid for a variable declaration.
9859     CheckVariableDeclarationType(VDecl);
9860     if (VDecl->isInvalidDecl())
9861       return;
9862   }
9863
9864   // dllimport cannot be used on variable definitions.
9865   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9866     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9867     VDecl->setInvalidDecl();
9868     return;
9869   }
9870
9871   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9872     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9873     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9874     VDecl->setInvalidDecl();
9875     return;
9876   }
9877
9878   if (!VDecl->getType()->isDependentType()) {
9879     // A definition must end up with a complete type, which means it must be
9880     // complete with the restriction that an array type might be completed by
9881     // the initializer; note that later code assumes this restriction.
9882     QualType BaseDeclType = VDecl->getType();
9883     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9884       BaseDeclType = Array->getElementType();
9885     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9886                             diag::err_typecheck_decl_incomplete_type)) {
9887       RealDecl->setInvalidDecl();
9888       return;
9889     }
9890
9891     // The variable can not have an abstract class type.
9892     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9893                                diag::err_abstract_type_in_decl,
9894                                AbstractVariableType))
9895       VDecl->setInvalidDecl();
9896   }
9897
9898   // If adding the initializer will turn this declaration into a definition,
9899   // and we already have a definition for this variable, diagnose or otherwise
9900   // handle the situation.
9901   VarDecl *Def;
9902   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
9903       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
9904       !VDecl->isThisDeclarationADemotedDefinition() &&
9905       checkVarDeclRedefinition(Def, VDecl))
9906     return;
9907
9908   if (getLangOpts().CPlusPlus) {
9909     // C++ [class.static.data]p4
9910     //   If a static data member is of const integral or const
9911     //   enumeration type, its declaration in the class definition can
9912     //   specify a constant-initializer which shall be an integral
9913     //   constant expression (5.19). In that case, the member can appear
9914     //   in integral constant expressions. The member shall still be
9915     //   defined in a namespace scope if it is used in the program and the
9916     //   namespace scope definition shall not contain an initializer.
9917     //
9918     // We already performed a redefinition check above, but for static
9919     // data members we also need to check whether there was an in-class
9920     // declaration with an initializer.
9921     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9922       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9923           << VDecl->getDeclName();
9924       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9925            diag::note_previous_initializer)
9926           << 0;
9927       return;
9928     }
9929
9930     if (VDecl->hasLocalStorage())
9931       getCurFunction()->setHasBranchProtectedScope();
9932
9933     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9934       VDecl->setInvalidDecl();
9935       return;
9936     }
9937   }
9938
9939   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9940   // a kernel function cannot be initialized."
9941   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9942     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9943     VDecl->setInvalidDecl();
9944     return;
9945   }
9946
9947   // Get the decls type and save a reference for later, since
9948   // CheckInitializerTypes may change it.
9949   QualType DclT = VDecl->getType(), SavT = DclT;
9950
9951   // Expressions default to 'id' when we're in a debugger
9952   // and we are assigning it to a variable of Objective-C pointer type.
9953   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9954       Init->getType() == Context.UnknownAnyTy) {
9955     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9956     if (Result.isInvalid()) {
9957       VDecl->setInvalidDecl();
9958       return;
9959     }
9960     Init = Result.get();
9961   }
9962
9963   // Perform the initialization.
9964   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9965   if (!VDecl->isInvalidDecl()) {
9966     // Handle errors like: int a({0})
9967     if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 &&
9968         !canInitializeWithParenthesizedList(VDecl->getType()))
9969       if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) {
9970         Diag(VDecl->getLocation(), diag::err_list_init_in_parens)
9971             << VDecl->getType() << CXXDirectInit->getSourceRange()
9972             << FixItHint::CreateRemoval(CXXDirectInit->getLocStart())
9973             << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd());
9974         Init = IList;
9975         CXXDirectInit = nullptr;
9976       }
9977
9978     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9979     InitializationKind Kind =
9980         DirectInit
9981             ? CXXDirectInit
9982                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9983                                                      Init->getLocStart(),
9984                                                      Init->getLocEnd())
9985                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9986             : InitializationKind::CreateCopy(VDecl->getLocation(),
9987                                              Init->getLocStart());
9988
9989     MultiExprArg Args = Init;
9990     if (CXXDirectInit)
9991       Args = MultiExprArg(CXXDirectInit->getExprs(),
9992                           CXXDirectInit->getNumExprs());
9993
9994     // Try to correct any TypoExprs in the initialization arguments.
9995     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9996       ExprResult Res = CorrectDelayedTyposInExpr(
9997           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9998             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9999             return Init.Failed() ? ExprError() : E;
10000           });
10001       if (Res.isInvalid()) {
10002         VDecl->setInvalidDecl();
10003       } else if (Res.get() != Args[Idx]) {
10004         Args[Idx] = Res.get();
10005       }
10006     }
10007     if (VDecl->isInvalidDecl())
10008       return;
10009
10010     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10011                                    /*TopLevelOfInitList=*/false,
10012                                    /*TreatUnavailableAsInvalid=*/false);
10013     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10014     if (Result.isInvalid()) {
10015       VDecl->setInvalidDecl();
10016       return;
10017     }
10018
10019     Init = Result.getAs<Expr>();
10020   }
10021
10022   // Check for self-references within variable initializers.
10023   // Variables declared within a function/method body (except for references)
10024   // are handled by a dataflow analysis.
10025   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10026       VDecl->getType()->isReferenceType()) {
10027     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10028   }
10029
10030   // If the type changed, it means we had an incomplete type that was
10031   // completed by the initializer. For example:
10032   //   int ary[] = { 1, 3, 5 };
10033   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10034   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10035     VDecl->setType(DclT);
10036
10037   if (!VDecl->isInvalidDecl()) {
10038     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10039
10040     if (VDecl->hasAttr<BlocksAttr>())
10041       checkRetainCycles(VDecl, Init);
10042
10043     // It is safe to assign a weak reference into a strong variable.
10044     // Although this code can still have problems:
10045     //   id x = self.weakProp;
10046     //   id y = self.weakProp;
10047     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10048     // paths through the function. This should be revisited if
10049     // -Wrepeated-use-of-weak is made flow-sensitive.
10050     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
10051         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10052                          Init->getLocStart()))
10053       getCurFunction()->markSafeWeakUse(Init);
10054   }
10055
10056   // The initialization is usually a full-expression.
10057   //
10058   // FIXME: If this is a braced initialization of an aggregate, it is not
10059   // an expression, and each individual field initializer is a separate
10060   // full-expression. For instance, in:
10061   //
10062   //   struct Temp { ~Temp(); };
10063   //   struct S { S(Temp); };
10064   //   struct T { S a, b; } t = { Temp(), Temp() }
10065   //
10066   // we should destroy the first Temp before constructing the second.
10067   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10068                                           false,
10069                                           VDecl->isConstexpr());
10070   if (Result.isInvalid()) {
10071     VDecl->setInvalidDecl();
10072     return;
10073   }
10074   Init = Result.get();
10075
10076   // Attach the initializer to the decl.
10077   VDecl->setInit(Init);
10078
10079   if (VDecl->isLocalVarDecl()) {
10080     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10081     // static storage duration shall be constant expressions or string literals.
10082     // C++ does not have this restriction.
10083     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10084       const Expr *Culprit;
10085       if (VDecl->getStorageClass() == SC_Static)
10086         CheckForConstantInitializer(Init, DclT);
10087       // C89 is stricter than C99 for non-static aggregate types.
10088       // C89 6.5.7p3: All the expressions [...] in an initializer list
10089       // for an object that has aggregate or union type shall be
10090       // constant expressions.
10091       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10092                isa<InitListExpr>(Init) &&
10093                !Init->isConstantInitializer(Context, false, &Culprit))
10094         Diag(Culprit->getExprLoc(),
10095              diag::ext_aggregate_init_not_constant)
10096           << Culprit->getSourceRange();
10097     }
10098   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10099              VDecl->getLexicalDeclContext()->isRecord()) {
10100     // This is an in-class initialization for a static data member, e.g.,
10101     //
10102     // struct S {
10103     //   static const int value = 17;
10104     // };
10105
10106     // C++ [class.mem]p4:
10107     //   A member-declarator can contain a constant-initializer only
10108     //   if it declares a static member (9.4) of const integral or
10109     //   const enumeration type, see 9.4.2.
10110     //
10111     // C++11 [class.static.data]p3:
10112     //   If a non-volatile non-inline const static data member is of integral
10113     //   or enumeration type, its declaration in the class definition can
10114     //   specify a brace-or-equal-initializer in which every initalizer-clause
10115     //   that is an assignment-expression is a constant expression. A static
10116     //   data member of literal type can be declared in the class definition
10117     //   with the constexpr specifier; if so, its declaration shall specify a
10118     //   brace-or-equal-initializer in which every initializer-clause that is
10119     //   an assignment-expression is a constant expression.
10120
10121     // Do nothing on dependent types.
10122     if (DclT->isDependentType()) {
10123
10124     // Allow any 'static constexpr' members, whether or not they are of literal
10125     // type. We separately check that every constexpr variable is of literal
10126     // type.
10127     } else if (VDecl->isConstexpr()) {
10128
10129     // Require constness.
10130     } else if (!DclT.isConstQualified()) {
10131       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10132         << Init->getSourceRange();
10133       VDecl->setInvalidDecl();
10134
10135     // We allow integer constant expressions in all cases.
10136     } else if (DclT->isIntegralOrEnumerationType()) {
10137       // Check whether the expression is a constant expression.
10138       SourceLocation Loc;
10139       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10140         // In C++11, a non-constexpr const static data member with an
10141         // in-class initializer cannot be volatile.
10142         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10143       else if (Init->isValueDependent())
10144         ; // Nothing to check.
10145       else if (Init->isIntegerConstantExpr(Context, &Loc))
10146         ; // Ok, it's an ICE!
10147       else if (Init->isEvaluatable(Context)) {
10148         // If we can constant fold the initializer through heroics, accept it,
10149         // but report this as a use of an extension for -pedantic.
10150         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10151           << Init->getSourceRange();
10152       } else {
10153         // Otherwise, this is some crazy unknown case.  Report the issue at the
10154         // location provided by the isIntegerConstantExpr failed check.
10155         Diag(Loc, diag::err_in_class_initializer_non_constant)
10156           << Init->getSourceRange();
10157         VDecl->setInvalidDecl();
10158       }
10159
10160     // We allow foldable floating-point constants as an extension.
10161     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10162       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10163       // it anyway and provide a fixit to add the 'constexpr'.
10164       if (getLangOpts().CPlusPlus11) {
10165         Diag(VDecl->getLocation(),
10166              diag::ext_in_class_initializer_float_type_cxx11)
10167             << DclT << Init->getSourceRange();
10168         Diag(VDecl->getLocStart(),
10169              diag::note_in_class_initializer_float_type_cxx11)
10170             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10171       } else {
10172         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10173           << DclT << Init->getSourceRange();
10174
10175         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10176           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10177             << Init->getSourceRange();
10178           VDecl->setInvalidDecl();
10179         }
10180       }
10181
10182     // Suggest adding 'constexpr' in C++11 for literal types.
10183     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10184       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10185         << DclT << Init->getSourceRange()
10186         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10187       VDecl->setConstexpr(true);
10188
10189     } else {
10190       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10191         << DclT << Init->getSourceRange();
10192       VDecl->setInvalidDecl();
10193     }
10194   } else if (VDecl->isFileVarDecl()) {
10195     // In C, extern is typically used to avoid tentative definitions when
10196     // declaring variables in headers, but adding an intializer makes it a
10197     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10198     // In C++, extern is often used to give implictly static const variables
10199     // external linkage, so don't warn in that case. If selectany is present,
10200     // this might be header code intended for C and C++ inclusion, so apply the
10201     // C++ rules.
10202     if (VDecl->getStorageClass() == SC_Extern &&
10203         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10204          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10205         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10206         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10207       Diag(VDecl->getLocation(), diag::warn_extern_init);
10208
10209     // C99 6.7.8p4. All file scoped initializers need to be constant.
10210     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10211       CheckForConstantInitializer(Init, DclT);
10212   }
10213
10214   // We will represent direct-initialization similarly to copy-initialization:
10215   //    int x(1);  -as-> int x = 1;
10216   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10217   //
10218   // Clients that want to distinguish between the two forms, can check for
10219   // direct initializer using VarDecl::getInitStyle().
10220   // A major benefit is that clients that don't particularly care about which
10221   // exactly form was it (like the CodeGen) can handle both cases without
10222   // special case code.
10223
10224   // C++ 8.5p11:
10225   // The form of initialization (using parentheses or '=') is generally
10226   // insignificant, but does matter when the entity being initialized has a
10227   // class type.
10228   if (CXXDirectInit) {
10229     assert(DirectInit && "Call-style initializer must be direct init.");
10230     VDecl->setInitStyle(VarDecl::CallInit);
10231   } else if (DirectInit) {
10232     // This must be list-initialization. No other way is direct-initialization.
10233     VDecl->setInitStyle(VarDecl::ListInit);
10234   }
10235
10236   CheckCompleteVariableDeclaration(VDecl);
10237 }
10238
10239 /// ActOnInitializerError - Given that there was an error parsing an
10240 /// initializer for the given declaration, try to return to some form
10241 /// of sanity.
10242 void Sema::ActOnInitializerError(Decl *D) {
10243   // Our main concern here is re-establishing invariants like "a
10244   // variable's type is either dependent or complete".
10245   if (!D || D->isInvalidDecl()) return;
10246
10247   VarDecl *VD = dyn_cast<VarDecl>(D);
10248   if (!VD) return;
10249
10250   // Bindings are not usable if we can't make sense of the initializer.
10251   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10252     for (auto *BD : DD->bindings())
10253       BD->setInvalidDecl();
10254
10255   // Auto types are meaningless if we can't make sense of the initializer.
10256   if (ParsingInitForAutoVars.count(D)) {
10257     D->setInvalidDecl();
10258     return;
10259   }
10260
10261   QualType Ty = VD->getType();
10262   if (Ty->isDependentType()) return;
10263
10264   // Require a complete type.
10265   if (RequireCompleteType(VD->getLocation(),
10266                           Context.getBaseElementType(Ty),
10267                           diag::err_typecheck_decl_incomplete_type)) {
10268     VD->setInvalidDecl();
10269     return;
10270   }
10271
10272   // Require a non-abstract type.
10273   if (RequireNonAbstractType(VD->getLocation(), Ty,
10274                              diag::err_abstract_type_in_decl,
10275                              AbstractVariableType)) {
10276     VD->setInvalidDecl();
10277     return;
10278   }
10279
10280   // Don't bother complaining about constructors or destructors,
10281   // though.
10282 }
10283
10284 /// Checks if an object of the given type can be initialized with parenthesized
10285 /// init-list.
10286 ///
10287 /// \param TargetType Type of object being initialized.
10288 ///
10289 /// The function is used to detect wrong initializations, such as 'int({0})'.
10290 ///
10291 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) {
10292   return TargetType->isDependentType() || TargetType->isRecordType() ||
10293          TargetType->getContainedAutoType();
10294 }
10295
10296 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10297   // If there is no declaration, there was an error parsing it. Just ignore it.
10298   if (!RealDecl)
10299     return;
10300
10301   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10302     QualType Type = Var->getType();
10303
10304     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10305     if (isa<DecompositionDecl>(RealDecl)) {
10306       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10307       Var->setInvalidDecl();
10308       return;
10309     }
10310
10311     // C++11 [dcl.spec.auto]p3
10312     if (Type->isUndeducedType()) {
10313       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
10314         << Var->getDeclName() << Type;
10315       Var->setInvalidDecl();
10316       return;
10317     }
10318
10319     // C++11 [class.static.data]p3: A static data member can be declared with
10320     // the constexpr specifier; if so, its declaration shall specify
10321     // a brace-or-equal-initializer.
10322     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10323     // the definition of a variable [...] or the declaration of a static data
10324     // member.
10325     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10326         !Var->isThisDeclarationADemotedDefinition()) {
10327       if (Var->isStaticDataMember()) {
10328         // C++1z removes the relevant rule; the in-class declaration is always
10329         // a definition there.
10330         if (!getLangOpts().CPlusPlus1z) {
10331           Diag(Var->getLocation(),
10332                diag::err_constexpr_static_mem_var_requires_init)
10333             << Var->getDeclName();
10334           Var->setInvalidDecl();
10335           return;
10336         }
10337       } else {
10338         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10339         Var->setInvalidDecl();
10340         return;
10341       }
10342     }
10343
10344     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10345     // definition having the concept specifier is called a variable concept. A
10346     // concept definition refers to [...] a variable concept and its initializer.
10347     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10348       if (VTD->isConcept()) {
10349         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10350         Var->setInvalidDecl();
10351         return;
10352       }
10353     }
10354
10355     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10356     // be initialized.
10357     if (!Var->isInvalidDecl() &&
10358         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10359         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10360       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10361       Var->setInvalidDecl();
10362       return;
10363     }
10364
10365     switch (Var->isThisDeclarationADefinition()) {
10366     case VarDecl::Definition:
10367       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10368         break;
10369
10370       // We have an out-of-line definition of a static data member
10371       // that has an in-class initializer, so we type-check this like
10372       // a declaration.
10373       //
10374       // Fall through
10375
10376     case VarDecl::DeclarationOnly:
10377       // It's only a declaration.
10378
10379       // Block scope. C99 6.7p7: If an identifier for an object is
10380       // declared with no linkage (C99 6.2.2p6), the type for the
10381       // object shall be complete.
10382       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10383           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10384           RequireCompleteType(Var->getLocation(), Type,
10385                               diag::err_typecheck_decl_incomplete_type))
10386         Var->setInvalidDecl();
10387
10388       // Make sure that the type is not abstract.
10389       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10390           RequireNonAbstractType(Var->getLocation(), Type,
10391                                  diag::err_abstract_type_in_decl,
10392                                  AbstractVariableType))
10393         Var->setInvalidDecl();
10394       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10395           Var->getStorageClass() == SC_PrivateExtern) {
10396         Diag(Var->getLocation(), diag::warn_private_extern);
10397         Diag(Var->getLocation(), diag::note_private_extern);
10398       }
10399
10400       return;
10401
10402     case VarDecl::TentativeDefinition:
10403       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10404       // object that has file scope without an initializer, and without a
10405       // storage-class specifier or with the storage-class specifier "static",
10406       // constitutes a tentative definition. Note: A tentative definition with
10407       // external linkage is valid (C99 6.2.2p5).
10408       if (!Var->isInvalidDecl()) {
10409         if (const IncompleteArrayType *ArrayT
10410                                     = Context.getAsIncompleteArrayType(Type)) {
10411           if (RequireCompleteType(Var->getLocation(),
10412                                   ArrayT->getElementType(),
10413                                   diag::err_illegal_decl_array_incomplete_type))
10414             Var->setInvalidDecl();
10415         } else if (Var->getStorageClass() == SC_Static) {
10416           // C99 6.9.2p3: If the declaration of an identifier for an object is
10417           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10418           // declared type shall not be an incomplete type.
10419           // NOTE: code such as the following
10420           //     static struct s;
10421           //     struct s { int a; };
10422           // is accepted by gcc. Hence here we issue a warning instead of
10423           // an error and we do not invalidate the static declaration.
10424           // NOTE: to avoid multiple warnings, only check the first declaration.
10425           if (Var->isFirstDecl())
10426             RequireCompleteType(Var->getLocation(), Type,
10427                                 diag::ext_typecheck_decl_incomplete_type);
10428         }
10429       }
10430
10431       // Record the tentative definition; we're done.
10432       if (!Var->isInvalidDecl())
10433         TentativeDefinitions.push_back(Var);
10434       return;
10435     }
10436
10437     // Provide a specific diagnostic for uninitialized variable
10438     // definitions with incomplete array type.
10439     if (Type->isIncompleteArrayType()) {
10440       Diag(Var->getLocation(),
10441            diag::err_typecheck_incomplete_array_needs_initializer);
10442       Var->setInvalidDecl();
10443       return;
10444     }
10445
10446     // Provide a specific diagnostic for uninitialized variable
10447     // definitions with reference type.
10448     if (Type->isReferenceType()) {
10449       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10450         << Var->getDeclName()
10451         << SourceRange(Var->getLocation(), Var->getLocation());
10452       Var->setInvalidDecl();
10453       return;
10454     }
10455
10456     // Do not attempt to type-check the default initializer for a
10457     // variable with dependent type.
10458     if (Type->isDependentType())
10459       return;
10460
10461     if (Var->isInvalidDecl())
10462       return;
10463
10464     if (!Var->hasAttr<AliasAttr>()) {
10465       if (RequireCompleteType(Var->getLocation(),
10466                               Context.getBaseElementType(Type),
10467                               diag::err_typecheck_decl_incomplete_type)) {
10468         Var->setInvalidDecl();
10469         return;
10470       }
10471     } else {
10472       return;
10473     }
10474
10475     // The variable can not have an abstract class type.
10476     if (RequireNonAbstractType(Var->getLocation(), Type,
10477                                diag::err_abstract_type_in_decl,
10478                                AbstractVariableType)) {
10479       Var->setInvalidDecl();
10480       return;
10481     }
10482
10483     // Check for jumps past the implicit initializer.  C++0x
10484     // clarifies that this applies to a "variable with automatic
10485     // storage duration", not a "local variable".
10486     // C++11 [stmt.dcl]p3
10487     //   A program that jumps from a point where a variable with automatic
10488     //   storage duration is not in scope to a point where it is in scope is
10489     //   ill-formed unless the variable has scalar type, class type with a
10490     //   trivial default constructor and a trivial destructor, a cv-qualified
10491     //   version of one of these types, or an array of one of the preceding
10492     //   types and is declared without an initializer.
10493     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10494       if (const RecordType *Record
10495             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10496         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10497         // Mark the function for further checking even if the looser rules of
10498         // C++11 do not require such checks, so that we can diagnose
10499         // incompatibilities with C++98.
10500         if (!CXXRecord->isPOD())
10501           getCurFunction()->setHasBranchProtectedScope();
10502       }
10503     }
10504
10505     // C++03 [dcl.init]p9:
10506     //   If no initializer is specified for an object, and the
10507     //   object is of (possibly cv-qualified) non-POD class type (or
10508     //   array thereof), the object shall be default-initialized; if
10509     //   the object is of const-qualified type, the underlying class
10510     //   type shall have a user-declared default
10511     //   constructor. Otherwise, if no initializer is specified for
10512     //   a non- static object, the object and its subobjects, if
10513     //   any, have an indeterminate initial value); if the object
10514     //   or any of its subobjects are of const-qualified type, the
10515     //   program is ill-formed.
10516     // C++0x [dcl.init]p11:
10517     //   If no initializer is specified for an object, the object is
10518     //   default-initialized; [...].
10519     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10520     InitializationKind Kind
10521       = InitializationKind::CreateDefault(Var->getLocation());
10522
10523     InitializationSequence InitSeq(*this, Entity, Kind, None);
10524     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10525     if (Init.isInvalid())
10526       Var->setInvalidDecl();
10527     else if (Init.get()) {
10528       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10529       // This is important for template substitution.
10530       Var->setInitStyle(VarDecl::CallInit);
10531     }
10532
10533     CheckCompleteVariableDeclaration(Var);
10534   }
10535 }
10536
10537 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10538   // If there is no declaration, there was an error parsing it. Ignore it.
10539   if (!D)
10540     return;
10541
10542   VarDecl *VD = dyn_cast<VarDecl>(D);
10543   if (!VD) {
10544     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10545     D->setInvalidDecl();
10546     return;
10547   }
10548
10549   VD->setCXXForRangeDecl(true);
10550
10551   // for-range-declaration cannot be given a storage class specifier.
10552   int Error = -1;
10553   switch (VD->getStorageClass()) {
10554   case SC_None:
10555     break;
10556   case SC_Extern:
10557     Error = 0;
10558     break;
10559   case SC_Static:
10560     Error = 1;
10561     break;
10562   case SC_PrivateExtern:
10563     Error = 2;
10564     break;
10565   case SC_Auto:
10566     Error = 3;
10567     break;
10568   case SC_Register:
10569     Error = 4;
10570     break;
10571   }
10572   if (Error != -1) {
10573     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10574       << VD->getDeclName() << Error;
10575     D->setInvalidDecl();
10576   }
10577 }
10578
10579 StmtResult
10580 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10581                                  IdentifierInfo *Ident,
10582                                  ParsedAttributes &Attrs,
10583                                  SourceLocation AttrEnd) {
10584   // C++1y [stmt.iter]p1:
10585   //   A range-based for statement of the form
10586   //      for ( for-range-identifier : for-range-initializer ) statement
10587   //   is equivalent to
10588   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10589   DeclSpec DS(Attrs.getPool().getFactory());
10590
10591   const char *PrevSpec;
10592   unsigned DiagID;
10593   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10594                      getPrintingPolicy());
10595
10596   Declarator D(DS, Declarator::ForContext);
10597   D.SetIdentifier(Ident, IdentLoc);
10598   D.takeAttributes(Attrs, AttrEnd);
10599
10600   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10601   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10602                 EmptyAttrs, IdentLoc);
10603   Decl *Var = ActOnDeclarator(S, D);
10604   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10605   FinalizeDeclaration(Var);
10606   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10607                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10608 }
10609
10610 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10611   if (var->isInvalidDecl()) return;
10612
10613   if (getLangOpts().OpenCL) {
10614     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10615     // initialiser
10616     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10617         !var->hasInit()) {
10618       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10619           << 1 /*Init*/;
10620       var->setInvalidDecl();
10621       return;
10622     }
10623   }
10624
10625   // In Objective-C, don't allow jumps past the implicit initialization of a
10626   // local retaining variable.
10627   if (getLangOpts().ObjC1 &&
10628       var->hasLocalStorage()) {
10629     switch (var->getType().getObjCLifetime()) {
10630     case Qualifiers::OCL_None:
10631     case Qualifiers::OCL_ExplicitNone:
10632     case Qualifiers::OCL_Autoreleasing:
10633       break;
10634
10635     case Qualifiers::OCL_Weak:
10636     case Qualifiers::OCL_Strong:
10637       getCurFunction()->setHasBranchProtectedScope();
10638       break;
10639     }
10640   }
10641
10642   // Warn about externally-visible variables being defined without a
10643   // prior declaration.  We only want to do this for global
10644   // declarations, but we also specifically need to avoid doing it for
10645   // class members because the linkage of an anonymous class can
10646   // change if it's later given a typedef name.
10647   if (var->isThisDeclarationADefinition() &&
10648       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10649       var->isExternallyVisible() && var->hasLinkage() &&
10650       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10651                                   var->getLocation())) {
10652     // Find a previous declaration that's not a definition.
10653     VarDecl *prev = var->getPreviousDecl();
10654     while (prev && prev->isThisDeclarationADefinition())
10655       prev = prev->getPreviousDecl();
10656
10657     if (!prev)
10658       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10659   }
10660
10661   // Cache the result of checking for constant initialization.
10662   Optional<bool> CacheHasConstInit;
10663   const Expr *CacheCulprit;
10664   auto checkConstInit = [&]() mutable {
10665     if (!CacheHasConstInit)
10666       CacheHasConstInit = var->getInit()->isConstantInitializer(
10667             Context, var->getType()->isReferenceType(), &CacheCulprit);
10668     return *CacheHasConstInit;
10669   };
10670
10671   if (var->getTLSKind() == VarDecl::TLS_Static) {
10672     if (var->getType().isDestructedType()) {
10673       // GNU C++98 edits for __thread, [basic.start.term]p3:
10674       //   The type of an object with thread storage duration shall not
10675       //   have a non-trivial destructor.
10676       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10677       if (getLangOpts().CPlusPlus11)
10678         Diag(var->getLocation(), diag::note_use_thread_local);
10679     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10680       if (!checkConstInit()) {
10681         // GNU C++98 edits for __thread, [basic.start.init]p4:
10682         //   An object of thread storage duration shall not require dynamic
10683         //   initialization.
10684         // FIXME: Need strict checking here.
10685         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10686           << CacheCulprit->getSourceRange();
10687         if (getLangOpts().CPlusPlus11)
10688           Diag(var->getLocation(), diag::note_use_thread_local);
10689       }
10690     }
10691   }
10692
10693   // Apply section attributes and pragmas to global variables.
10694   bool GlobalStorage = var->hasGlobalStorage();
10695   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10696       ActiveTemplateInstantiations.empty()) {
10697     PragmaStack<StringLiteral *> *Stack = nullptr;
10698     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10699     if (var->getType().isConstQualified())
10700       Stack = &ConstSegStack;
10701     else if (!var->getInit()) {
10702       Stack = &BSSSegStack;
10703       SectionFlags |= ASTContext::PSF_Write;
10704     } else {
10705       Stack = &DataSegStack;
10706       SectionFlags |= ASTContext::PSF_Write;
10707     }
10708     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10709       var->addAttr(SectionAttr::CreateImplicit(
10710           Context, SectionAttr::Declspec_allocate,
10711           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10712     }
10713     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10714       if (UnifySection(SA->getName(), SectionFlags, var))
10715         var->dropAttr<SectionAttr>();
10716
10717     // Apply the init_seg attribute if this has an initializer.  If the
10718     // initializer turns out to not be dynamic, we'll end up ignoring this
10719     // attribute.
10720     if (CurInitSeg && var->getInit())
10721       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10722                                                CurInitSegLoc));
10723   }
10724
10725   // All the following checks are C++ only.
10726   if (!getLangOpts().CPlusPlus) {
10727       // If this variable must be emitted, add it as an initializer for the
10728       // current module.
10729      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10730        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10731      return;
10732   }
10733
10734   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10735     CheckCompleteDecompositionDeclaration(DD);
10736
10737   QualType type = var->getType();
10738   if (type->isDependentType()) return;
10739
10740   // __block variables might require us to capture a copy-initializer.
10741   if (var->hasAttr<BlocksAttr>()) {
10742     // It's currently invalid to ever have a __block variable with an
10743     // array type; should we diagnose that here?
10744
10745     // Regardless, we don't want to ignore array nesting when
10746     // constructing this copy.
10747     if (type->isStructureOrClassType()) {
10748       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10749       SourceLocation poi = var->getLocation();
10750       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10751       ExprResult result
10752         = PerformMoveOrCopyInitialization(
10753             InitializedEntity::InitializeBlock(poi, type, false),
10754             var, var->getType(), varRef, /*AllowNRVO=*/true);
10755       if (!result.isInvalid()) {
10756         result = MaybeCreateExprWithCleanups(result);
10757         Expr *init = result.getAs<Expr>();
10758         Context.setBlockVarCopyInits(var, init);
10759       }
10760     }
10761   }
10762
10763   Expr *Init = var->getInit();
10764   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10765   QualType baseType = Context.getBaseElementType(type);
10766
10767   if (!var->getDeclContext()->isDependentContext() &&
10768       Init && !Init->isValueDependent()) {
10769
10770     if (var->isConstexpr()) {
10771       SmallVector<PartialDiagnosticAt, 8> Notes;
10772       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10773         SourceLocation DiagLoc = var->getLocation();
10774         // If the note doesn't add any useful information other than a source
10775         // location, fold it into the primary diagnostic.
10776         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10777               diag::note_invalid_subexpr_in_const_expr) {
10778           DiagLoc = Notes[0].first;
10779           Notes.clear();
10780         }
10781         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10782           << var << Init->getSourceRange();
10783         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10784           Diag(Notes[I].first, Notes[I].second);
10785       }
10786     } else if (var->isUsableInConstantExpressions(Context)) {
10787       // Check whether the initializer of a const variable of integral or
10788       // enumeration type is an ICE now, since we can't tell whether it was
10789       // initialized by a constant expression if we check later.
10790       var->checkInitIsICE();
10791     }
10792
10793     // Don't emit further diagnostics about constexpr globals since they
10794     // were just diagnosed.
10795     if (!var->isConstexpr() && GlobalStorage &&
10796             var->hasAttr<RequireConstantInitAttr>()) {
10797       // FIXME: Need strict checking in C++03 here.
10798       bool DiagErr = getLangOpts().CPlusPlus11
10799           ? !var->checkInitIsICE() : !checkConstInit();
10800       if (DiagErr) {
10801         auto attr = var->getAttr<RequireConstantInitAttr>();
10802         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10803           << Init->getSourceRange();
10804         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10805           << attr->getRange();
10806       }
10807     }
10808     else if (!var->isConstexpr() && IsGlobal &&
10809              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10810                                     var->getLocation())) {
10811       // Warn about globals which don't have a constant initializer.  Don't
10812       // warn about globals with a non-trivial destructor because we already
10813       // warned about them.
10814       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10815       if (!(RD && !RD->hasTrivialDestructor())) {
10816         if (!checkConstInit())
10817           Diag(var->getLocation(), diag::warn_global_constructor)
10818             << Init->getSourceRange();
10819       }
10820     }
10821   }
10822
10823   // Require the destructor.
10824   if (const RecordType *recordType = baseType->getAs<RecordType>())
10825     FinalizeVarWithDestructor(var, recordType);
10826
10827   // If this variable must be emitted, add it as an initializer for the current
10828   // module.
10829   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10830     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10831 }
10832
10833 /// \brief Determines if a variable's alignment is dependent.
10834 static bool hasDependentAlignment(VarDecl *VD) {
10835   if (VD->getType()->isDependentType())
10836     return true;
10837   for (auto *I : VD->specific_attrs<AlignedAttr>())
10838     if (I->isAlignmentDependent())
10839       return true;
10840   return false;
10841 }
10842
10843 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10844 /// any semantic actions necessary after any initializer has been attached.
10845 void
10846 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10847   // Note that we are no longer parsing the initializer for this declaration.
10848   ParsingInitForAutoVars.erase(ThisDecl);
10849
10850   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10851   if (!VD)
10852     return;
10853
10854   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10855     for (auto *BD : DD->bindings()) {
10856       FinalizeDeclaration(BD);
10857     }
10858   }
10859
10860   checkAttributesAfterMerging(*this, *VD);
10861
10862   // Perform TLS alignment check here after attributes attached to the variable
10863   // which may affect the alignment have been processed. Only perform the check
10864   // if the target has a maximum TLS alignment (zero means no constraints).
10865   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10866     // Protect the check so that it's not performed on dependent types and
10867     // dependent alignments (we can't determine the alignment in that case).
10868     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10869       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10870       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10871         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10872           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10873           << (unsigned)MaxAlignChars.getQuantity();
10874       }
10875     }
10876   }
10877
10878   if (VD->isStaticLocal()) {
10879     if (FunctionDecl *FD =
10880             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10881       // Static locals inherit dll attributes from their function.
10882       if (Attr *A = getDLLAttr(FD)) {
10883         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10884         NewAttr->setInherited(true);
10885         VD->addAttr(NewAttr);
10886       }
10887       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10888       // function, only __shared__ variables may be declared with
10889       // static storage class.
10890       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
10891           CUDADiagIfDeviceCode(VD->getLocation(),
10892                                diag::err_device_static_local_var)
10893               << CurrentCUDATarget())
10894         VD->setInvalidDecl();
10895     }
10896   }
10897
10898   // Perform check for initializers of device-side global variables.
10899   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10900   // 7.5). We must also apply the same checks to all __shared__
10901   // variables whether they are local or not. CUDA also allows
10902   // constant initializers for __constant__ and __device__ variables.
10903   if (getLangOpts().CUDA) {
10904     const Expr *Init = VD->getInit();
10905     if (Init && VD->hasGlobalStorage()) {
10906       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10907           VD->hasAttr<CUDASharedAttr>()) {
10908         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
10909         bool AllowedInit = false;
10910         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10911           AllowedInit =
10912               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10913         // We'll allow constant initializers even if it's a non-empty
10914         // constructor according to CUDA rules. This deviates from NVCC,
10915         // but allows us to handle things like constexpr constructors.
10916         if (!AllowedInit &&
10917             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10918           AllowedInit = VD->getInit()->isConstantInitializer(
10919               Context, VD->getType()->isReferenceType());
10920
10921         // Also make sure that destructor, if there is one, is empty.
10922         if (AllowedInit)
10923           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10924             AllowedInit =
10925                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10926
10927         if (!AllowedInit) {
10928           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10929                                       ? diag::err_shared_var_init
10930                                       : diag::err_dynamic_var_init)
10931               << Init->getSourceRange();
10932           VD->setInvalidDecl();
10933         }
10934       } else {
10935         // This is a host-side global variable.  Check that the initializer is
10936         // callable from the host side.
10937         const FunctionDecl *InitFn = nullptr;
10938         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
10939           InitFn = CE->getConstructor();
10940         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
10941           InitFn = CE->getDirectCallee();
10942         }
10943         if (InitFn) {
10944           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
10945           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
10946             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
10947                 << InitFnTarget << InitFn;
10948             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
10949             VD->setInvalidDecl();
10950           }
10951         }
10952       }
10953     }
10954   }
10955
10956   // Grab the dllimport or dllexport attribute off of the VarDecl.
10957   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10958
10959   // Imported static data members cannot be defined out-of-line.
10960   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10961     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10962         VD->isThisDeclarationADefinition()) {
10963       // We allow definitions of dllimport class template static data members
10964       // with a warning.
10965       CXXRecordDecl *Context =
10966         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10967       bool IsClassTemplateMember =
10968           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10969           Context->getDescribedClassTemplate();
10970
10971       Diag(VD->getLocation(),
10972            IsClassTemplateMember
10973                ? diag::warn_attribute_dllimport_static_field_definition
10974                : diag::err_attribute_dllimport_static_field_definition);
10975       Diag(IA->getLocation(), diag::note_attribute);
10976       if (!IsClassTemplateMember)
10977         VD->setInvalidDecl();
10978     }
10979   }
10980
10981   // dllimport/dllexport variables cannot be thread local, their TLS index
10982   // isn't exported with the variable.
10983   if (DLLAttr && VD->getTLSKind()) {
10984     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10985     if (F && getDLLAttr(F)) {
10986       assert(VD->isStaticLocal());
10987       // But if this is a static local in a dlimport/dllexport function, the
10988       // function will never be inlined, which means the var would never be
10989       // imported, so having it marked import/export is safe.
10990     } else {
10991       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10992                                                                     << DLLAttr;
10993       VD->setInvalidDecl();
10994     }
10995   }
10996
10997   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10998     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10999       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11000       VD->dropAttr<UsedAttr>();
11001     }
11002   }
11003
11004   const DeclContext *DC = VD->getDeclContext();
11005   // If there's a #pragma GCC visibility in scope, and this isn't a class
11006   // member, set the visibility of this variable.
11007   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11008     AddPushedVisibilityAttribute(VD);
11009
11010   // FIXME: Warn on unused templates.
11011   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11012       !isa<VarTemplatePartialSpecializationDecl>(VD))
11013     MarkUnusedFileScopedDecl(VD);
11014
11015   // Now we have parsed the initializer and can update the table of magic
11016   // tag values.
11017   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11018       !VD->getType()->isIntegralOrEnumerationType())
11019     return;
11020
11021   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11022     const Expr *MagicValueExpr = VD->getInit();
11023     if (!MagicValueExpr) {
11024       continue;
11025     }
11026     llvm::APSInt MagicValueInt;
11027     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11028       Diag(I->getRange().getBegin(),
11029            diag::err_type_tag_for_datatype_not_ice)
11030         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11031       continue;
11032     }
11033     if (MagicValueInt.getActiveBits() > 64) {
11034       Diag(I->getRange().getBegin(),
11035            diag::err_type_tag_for_datatype_too_large)
11036         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11037       continue;
11038     }
11039     uint64_t MagicValue = MagicValueInt.getZExtValue();
11040     RegisterTypeTagForDatatype(I->getArgumentKind(),
11041                                MagicValue,
11042                                I->getMatchingCType(),
11043                                I->getLayoutCompatible(),
11044                                I->getMustBeNull());
11045   }
11046 }
11047
11048 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11049                                                    ArrayRef<Decl *> Group) {
11050   SmallVector<Decl*, 8> Decls;
11051
11052   if (DS.isTypeSpecOwned())
11053     Decls.push_back(DS.getRepAsDecl());
11054
11055   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11056   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11057   bool DiagnosedMultipleDecomps = false;
11058
11059   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11060     if (Decl *D = Group[i]) {
11061       auto *DD = dyn_cast<DeclaratorDecl>(D);
11062       if (DD && !FirstDeclaratorInGroup)
11063         FirstDeclaratorInGroup = DD;
11064
11065       auto *Decomp = dyn_cast<DecompositionDecl>(D);
11066       if (Decomp && !FirstDecompDeclaratorInGroup)
11067         FirstDecompDeclaratorInGroup = Decomp;
11068
11069       // A decomposition declaration cannot be combined with any other
11070       // declaration in the same group.
11071       auto *OtherDD = FirstDeclaratorInGroup;
11072       if (OtherDD == FirstDecompDeclaratorInGroup)
11073         OtherDD = DD;
11074       if (OtherDD && FirstDecompDeclaratorInGroup &&
11075           OtherDD != FirstDecompDeclaratorInGroup &&
11076           !DiagnosedMultipleDecomps) {
11077         Diag(FirstDecompDeclaratorInGroup->getLocation(),
11078              diag::err_decomp_decl_not_alone)
11079           << OtherDD->getSourceRange();
11080         DiagnosedMultipleDecomps = true;
11081       }
11082
11083       Decls.push_back(D);
11084     }
11085   }
11086
11087   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11088     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11089       handleTagNumbering(Tag, S);
11090       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11091           getLangOpts().CPlusPlus)
11092         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11093     }
11094   }
11095
11096   return BuildDeclaratorGroup(Decls);
11097 }
11098
11099 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11100 /// group, performing any necessary semantic checking.
11101 Sema::DeclGroupPtrTy
11102 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11103   // C++14 [dcl.spec.auto]p7: (DR1347)
11104   //   If the type that replaces the placeholder type is not the same in each
11105   //   deduction, the program is ill-formed.
11106   if (Group.size() > 1) {
11107     QualType Deduced;
11108     CanQualType DeducedCanon;
11109     VarDecl *DeducedDecl = nullptr;
11110     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11111       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
11112         AutoType *AT = D->getType()->getContainedAutoType();
11113         // FIXME: DR1265: if we have a function pointer declaration, we can have
11114         // an 'auto' from a trailing return type. In that case, the return type
11115         // must match the various other uses of 'auto'.
11116         if (!AT)
11117           continue;
11118         // Don't reissue diagnostics when instantiating a template.
11119         if (D->isInvalidDecl())
11120           break;
11121         QualType U = AT->getDeducedType();
11122         if (!U.isNull()) {
11123           CanQualType UCanon = Context.getCanonicalType(U);
11124           if (Deduced.isNull()) {
11125             Deduced = U;
11126             DeducedCanon = UCanon;
11127             DeducedDecl = D;
11128           } else if (DeducedCanon != UCanon) {
11129             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11130                  diag::err_auto_different_deductions)
11131               << (unsigned)AT->getKeyword()
11132               << Deduced << DeducedDecl->getDeclName()
11133               << U << D->getDeclName()
11134               << DeducedDecl->getInit()->getSourceRange()
11135               << D->getInit()->getSourceRange();
11136             D->setInvalidDecl();
11137             break;
11138           }
11139         }
11140       }
11141     }
11142   }
11143
11144   ActOnDocumentableDecls(Group);
11145
11146   return DeclGroupPtrTy::make(
11147       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11148 }
11149
11150 void Sema::ActOnDocumentableDecl(Decl *D) {
11151   ActOnDocumentableDecls(D);
11152 }
11153
11154 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11155   // Don't parse the comment if Doxygen diagnostics are ignored.
11156   if (Group.empty() || !Group[0])
11157     return;
11158
11159   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11160                       Group[0]->getLocation()) &&
11161       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11162                       Group[0]->getLocation()))
11163     return;
11164
11165   if (Group.size() >= 2) {
11166     // This is a decl group.  Normally it will contain only declarations
11167     // produced from declarator list.  But in case we have any definitions or
11168     // additional declaration references:
11169     //   'typedef struct S {} S;'
11170     //   'typedef struct S *S;'
11171     //   'struct S *pS;'
11172     // FinalizeDeclaratorGroup adds these as separate declarations.
11173     Decl *MaybeTagDecl = Group[0];
11174     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11175       Group = Group.slice(1);
11176     }
11177   }
11178
11179   // See if there are any new comments that are not attached to a decl.
11180   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11181   if (!Comments.empty() &&
11182       !Comments.back()->isAttached()) {
11183     // There is at least one comment that not attached to a decl.
11184     // Maybe it should be attached to one of these decls?
11185     //
11186     // Note that this way we pick up not only comments that precede the
11187     // declaration, but also comments that *follow* the declaration -- thanks to
11188     // the lookahead in the lexer: we've consumed the semicolon and looked
11189     // ahead through comments.
11190     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11191       Context.getCommentForDecl(Group[i], &PP);
11192   }
11193 }
11194
11195 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11196 /// to introduce parameters into function prototype scope.
11197 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11198   const DeclSpec &DS = D.getDeclSpec();
11199
11200   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11201
11202   // C++03 [dcl.stc]p2 also permits 'auto'.
11203   StorageClass SC = SC_None;
11204   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11205     SC = SC_Register;
11206   } else if (getLangOpts().CPlusPlus &&
11207              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11208     SC = SC_Auto;
11209   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11210     Diag(DS.getStorageClassSpecLoc(),
11211          diag::err_invalid_storage_class_in_func_decl);
11212     D.getMutableDeclSpec().ClearStorageClassSpecs();
11213   }
11214
11215   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11216     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11217       << DeclSpec::getSpecifierName(TSCS);
11218   if (DS.isInlineSpecified())
11219     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11220         << getLangOpts().CPlusPlus1z;
11221   if (DS.isConstexprSpecified())
11222     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11223       << 0;
11224   if (DS.isConceptSpecified())
11225     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11226
11227   DiagnoseFunctionSpecifiers(DS);
11228
11229   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11230   QualType parmDeclType = TInfo->getType();
11231
11232   if (getLangOpts().CPlusPlus) {
11233     // Check that there are no default arguments inside the type of this
11234     // parameter.
11235     CheckExtraCXXDefaultArguments(D);
11236
11237     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11238     if (D.getCXXScopeSpec().isSet()) {
11239       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11240         << D.getCXXScopeSpec().getRange();
11241       D.getCXXScopeSpec().clear();
11242     }
11243   }
11244
11245   // Ensure we have a valid name
11246   IdentifierInfo *II = nullptr;
11247   if (D.hasName()) {
11248     II = D.getIdentifier();
11249     if (!II) {
11250       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11251         << GetNameForDeclarator(D).getName();
11252       D.setInvalidType(true);
11253     }
11254   }
11255
11256   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11257   if (II) {
11258     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11259                    ForRedeclaration);
11260     LookupName(R, S);
11261     if (R.isSingleResult()) {
11262       NamedDecl *PrevDecl = R.getFoundDecl();
11263       if (PrevDecl->isTemplateParameter()) {
11264         // Maybe we will complain about the shadowed template parameter.
11265         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11266         // Just pretend that we didn't see the previous declaration.
11267         PrevDecl = nullptr;
11268       } else if (S->isDeclScope(PrevDecl)) {
11269         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11270         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11271
11272         // Recover by removing the name
11273         II = nullptr;
11274         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11275         D.setInvalidType(true);
11276       }
11277     }
11278   }
11279
11280   // Temporarily put parameter variables in the translation unit, not
11281   // the enclosing context.  This prevents them from accidentally
11282   // looking like class members in C++.
11283   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11284                                     D.getLocStart(),
11285                                     D.getIdentifierLoc(), II,
11286                                     parmDeclType, TInfo,
11287                                     SC);
11288
11289   if (D.isInvalidType())
11290     New->setInvalidDecl();
11291
11292   assert(S->isFunctionPrototypeScope());
11293   assert(S->getFunctionPrototypeDepth() >= 1);
11294   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11295                     S->getNextFunctionPrototypeIndex());
11296
11297   // Add the parameter declaration into this scope.
11298   S->AddDecl(New);
11299   if (II)
11300     IdResolver.AddDecl(New);
11301
11302   ProcessDeclAttributes(S, New, D);
11303
11304   if (D.getDeclSpec().isModulePrivateSpecified())
11305     Diag(New->getLocation(), diag::err_module_private_local)
11306       << 1 << New->getDeclName()
11307       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11308       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11309
11310   if (New->hasAttr<BlocksAttr>()) {
11311     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11312   }
11313   return New;
11314 }
11315
11316 /// \brief Synthesizes a variable for a parameter arising from a
11317 /// typedef.
11318 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11319                                               SourceLocation Loc,
11320                                               QualType T) {
11321   /* FIXME: setting StartLoc == Loc.
11322      Would it be worth to modify callers so as to provide proper source
11323      location for the unnamed parameters, embedding the parameter's type? */
11324   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11325                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11326                                            SC_None, nullptr);
11327   Param->setImplicit();
11328   return Param;
11329 }
11330
11331 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11332   // Don't diagnose unused-parameter errors in template instantiations; we
11333   // will already have done so in the template itself.
11334   if (!ActiveTemplateInstantiations.empty())
11335     return;
11336
11337   for (const ParmVarDecl *Parameter : Parameters) {
11338     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11339         !Parameter->hasAttr<UnusedAttr>()) {
11340       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11341         << Parameter->getDeclName();
11342     }
11343   }
11344 }
11345
11346 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11347     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11348   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11349     return;
11350
11351   // Warn if the return value is pass-by-value and larger than the specified
11352   // threshold.
11353   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11354     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11355     if (Size > LangOpts.NumLargeByValueCopy)
11356       Diag(D->getLocation(), diag::warn_return_value_size)
11357           << D->getDeclName() << Size;
11358   }
11359
11360   // Warn if any parameter is pass-by-value and larger than the specified
11361   // threshold.
11362   for (const ParmVarDecl *Parameter : Parameters) {
11363     QualType T = Parameter->getType();
11364     if (T->isDependentType() || !T.isPODType(Context))
11365       continue;
11366     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11367     if (Size > LangOpts.NumLargeByValueCopy)
11368       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11369           << Parameter->getDeclName() << Size;
11370   }
11371 }
11372
11373 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11374                                   SourceLocation NameLoc, IdentifierInfo *Name,
11375                                   QualType T, TypeSourceInfo *TSInfo,
11376                                   StorageClass SC) {
11377   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11378   if (getLangOpts().ObjCAutoRefCount &&
11379       T.getObjCLifetime() == Qualifiers::OCL_None &&
11380       T->isObjCLifetimeType()) {
11381
11382     Qualifiers::ObjCLifetime lifetime;
11383
11384     // Special cases for arrays:
11385     //   - if it's const, use __unsafe_unretained
11386     //   - otherwise, it's an error
11387     if (T->isArrayType()) {
11388       if (!T.isConstQualified()) {
11389         DelayedDiagnostics.add(
11390             sema::DelayedDiagnostic::makeForbiddenType(
11391             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11392       }
11393       lifetime = Qualifiers::OCL_ExplicitNone;
11394     } else {
11395       lifetime = T->getObjCARCImplicitLifetime();
11396     }
11397     T = Context.getLifetimeQualifiedType(T, lifetime);
11398   }
11399
11400   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11401                                          Context.getAdjustedParameterType(T),
11402                                          TSInfo, SC, nullptr);
11403
11404   // Parameters can not be abstract class types.
11405   // For record types, this is done by the AbstractClassUsageDiagnoser once
11406   // the class has been completely parsed.
11407   if (!CurContext->isRecord() &&
11408       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11409                              AbstractParamType))
11410     New->setInvalidDecl();
11411
11412   // Parameter declarators cannot be interface types. All ObjC objects are
11413   // passed by reference.
11414   if (T->isObjCObjectType()) {
11415     SourceLocation TypeEndLoc =
11416         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11417     Diag(NameLoc,
11418          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11419       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11420     T = Context.getObjCObjectPointerType(T);
11421     New->setType(T);
11422   }
11423
11424   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11425   // duration shall not be qualified by an address-space qualifier."
11426   // Since all parameters have automatic store duration, they can not have
11427   // an address space.
11428   if (T.getAddressSpace() != 0) {
11429     // OpenCL allows function arguments declared to be an array of a type
11430     // to be qualified with an address space.
11431     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11432       Diag(NameLoc, diag::err_arg_with_address_space);
11433       New->setInvalidDecl();
11434     }
11435   }
11436
11437   return New;
11438 }
11439
11440 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11441                                            SourceLocation LocAfterDecls) {
11442   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11443
11444   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11445   // for a K&R function.
11446   if (!FTI.hasPrototype) {
11447     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11448       --i;
11449       if (FTI.Params[i].Param == nullptr) {
11450         SmallString<256> Code;
11451         llvm::raw_svector_ostream(Code)
11452             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11453         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11454             << FTI.Params[i].Ident
11455             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11456
11457         // Implicitly declare the argument as type 'int' for lack of a better
11458         // type.
11459         AttributeFactory attrs;
11460         DeclSpec DS(attrs);
11461         const char* PrevSpec; // unused
11462         unsigned DiagID; // unused
11463         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11464                            DiagID, Context.getPrintingPolicy());
11465         // Use the identifier location for the type source range.
11466         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11467         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11468         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11469         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11470         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11471       }
11472     }
11473   }
11474 }
11475
11476 Decl *
11477 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11478                               MultiTemplateParamsArg TemplateParameterLists,
11479                               SkipBodyInfo *SkipBody) {
11480   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11481   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11482   Scope *ParentScope = FnBodyScope->getParent();
11483
11484   D.setFunctionDefinitionKind(FDK_Definition);
11485   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11486   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11487 }
11488
11489 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11490   Consumer.HandleInlineFunctionDefinition(D);
11491 }
11492
11493 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11494                              const FunctionDecl*& PossibleZeroParamPrototype) {
11495   // Don't warn about invalid declarations.
11496   if (FD->isInvalidDecl())
11497     return false;
11498
11499   // Or declarations that aren't global.
11500   if (!FD->isGlobal())
11501     return false;
11502
11503   // Don't warn about C++ member functions.
11504   if (isa<CXXMethodDecl>(FD))
11505     return false;
11506
11507   // Don't warn about 'main'.
11508   if (FD->isMain())
11509     return false;
11510
11511   // Don't warn about inline functions.
11512   if (FD->isInlined())
11513     return false;
11514
11515   // Don't warn about function templates.
11516   if (FD->getDescribedFunctionTemplate())
11517     return false;
11518
11519   // Don't warn about function template specializations.
11520   if (FD->isFunctionTemplateSpecialization())
11521     return false;
11522
11523   // Don't warn for OpenCL kernels.
11524   if (FD->hasAttr<OpenCLKernelAttr>())
11525     return false;
11526
11527   // Don't warn on explicitly deleted functions.
11528   if (FD->isDeleted())
11529     return false;
11530
11531   bool MissingPrototype = true;
11532   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11533        Prev; Prev = Prev->getPreviousDecl()) {
11534     // Ignore any declarations that occur in function or method
11535     // scope, because they aren't visible from the header.
11536     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11537       continue;
11538
11539     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11540     if (FD->getNumParams() == 0)
11541       PossibleZeroParamPrototype = Prev;
11542     break;
11543   }
11544
11545   return MissingPrototype;
11546 }
11547
11548 void
11549 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11550                                    const FunctionDecl *EffectiveDefinition,
11551                                    SkipBodyInfo *SkipBody) {
11552   // Don't complain if we're in GNU89 mode and the previous definition
11553   // was an extern inline function.
11554   const FunctionDecl *Definition = EffectiveDefinition;
11555   if (!Definition)
11556     if (!FD->isDefined(Definition))
11557       return;
11558
11559   if (canRedefineFunction(Definition, getLangOpts()))
11560     return;
11561
11562   // If we don't have a visible definition of the function, and it's inline or
11563   // a template, skip the new definition.
11564   if (SkipBody && !hasVisibleDefinition(Definition) &&
11565       (Definition->getFormalLinkage() == InternalLinkage ||
11566        Definition->isInlined() ||
11567        Definition->getDescribedFunctionTemplate() ||
11568        Definition->getNumTemplateParameterLists())) {
11569     SkipBody->ShouldSkip = true;
11570     if (auto *TD = Definition->getDescribedFunctionTemplate())
11571       makeMergedDefinitionVisible(TD, FD->getLocation());
11572     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11573                                 FD->getLocation());
11574     return;
11575   }
11576
11577   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11578       Definition->getStorageClass() == SC_Extern)
11579     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11580         << FD->getDeclName() << getLangOpts().CPlusPlus;
11581   else
11582     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11583
11584   Diag(Definition->getLocation(), diag::note_previous_definition);
11585   FD->setInvalidDecl();
11586 }
11587
11588 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11589                                    Sema &S) {
11590   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11591
11592   LambdaScopeInfo *LSI = S.PushLambdaScope();
11593   LSI->CallOperator = CallOperator;
11594   LSI->Lambda = LambdaClass;
11595   LSI->ReturnType = CallOperator->getReturnType();
11596   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11597
11598   if (LCD == LCD_None)
11599     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11600   else if (LCD == LCD_ByCopy)
11601     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11602   else if (LCD == LCD_ByRef)
11603     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11604   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11605
11606   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11607   LSI->Mutable = !CallOperator->isConst();
11608
11609   // Add the captures to the LSI so they can be noted as already
11610   // captured within tryCaptureVar.
11611   auto I = LambdaClass->field_begin();
11612   for (const auto &C : LambdaClass->captures()) {
11613     if (C.capturesVariable()) {
11614       VarDecl *VD = C.getCapturedVar();
11615       if (VD->isInitCapture())
11616         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11617       QualType CaptureType = VD->getType();
11618       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11619       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11620           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11621           /*EllipsisLoc*/C.isPackExpansion()
11622                          ? C.getEllipsisLoc() : SourceLocation(),
11623           CaptureType, /*Expr*/ nullptr);
11624
11625     } else if (C.capturesThis()) {
11626       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11627                               /*Expr*/ nullptr,
11628                               C.getCaptureKind() == LCK_StarThis);
11629     } else {
11630       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11631     }
11632     ++I;
11633   }
11634 }
11635
11636 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11637                                     SkipBodyInfo *SkipBody) {
11638   // Clear the last template instantiation error context.
11639   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11640
11641   if (!D)
11642     return D;
11643   FunctionDecl *FD = nullptr;
11644
11645   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11646     FD = FunTmpl->getTemplatedDecl();
11647   else
11648     FD = cast<FunctionDecl>(D);
11649
11650   // See if this is a redefinition.
11651   if (!FD->isLateTemplateParsed()) {
11652     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11653
11654     // If we're skipping the body, we're done. Don't enter the scope.
11655     if (SkipBody && SkipBody->ShouldSkip)
11656       return D;
11657   }
11658
11659   // Mark this function as "will have a body eventually".  This lets users to
11660   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11661   // this function.
11662   FD->setWillHaveBody();
11663
11664   // If we are instantiating a generic lambda call operator, push
11665   // a LambdaScopeInfo onto the function stack.  But use the information
11666   // that's already been calculated (ActOnLambdaExpr) to prime the current
11667   // LambdaScopeInfo.
11668   // When the template operator is being specialized, the LambdaScopeInfo,
11669   // has to be properly restored so that tryCaptureVariable doesn't try
11670   // and capture any new variables. In addition when calculating potential
11671   // captures during transformation of nested lambdas, it is necessary to
11672   // have the LSI properly restored.
11673   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11674     assert(ActiveTemplateInstantiations.size() &&
11675       "There should be an active template instantiation on the stack "
11676       "when instantiating a generic lambda!");
11677     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11678   }
11679   else
11680     // Enter a new function scope
11681     PushFunctionScope();
11682
11683   // Builtin functions cannot be defined.
11684   if (unsigned BuiltinID = FD->getBuiltinID()) {
11685     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11686         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11687       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11688       FD->setInvalidDecl();
11689     }
11690   }
11691
11692   // The return type of a function definition must be complete
11693   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11694   QualType ResultType = FD->getReturnType();
11695   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11696       !FD->isInvalidDecl() &&
11697       RequireCompleteType(FD->getLocation(), ResultType,
11698                           diag::err_func_def_incomplete_result))
11699     FD->setInvalidDecl();
11700
11701   if (FnBodyScope)
11702     PushDeclContext(FnBodyScope, FD);
11703
11704   // Check the validity of our function parameters
11705   CheckParmsForFunctionDef(FD->parameters(),
11706                            /*CheckParameterNames=*/true);
11707
11708   // Add non-parameter declarations already in the function to the current
11709   // scope.
11710   if (FnBodyScope) {
11711     for (Decl *NPD : FD->decls()) {
11712       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11713       if (!NonParmDecl)
11714         continue;
11715       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11716              "parameters should not be in newly created FD yet");
11717
11718       // If the decl has a name, make it accessible in the current scope.
11719       if (NonParmDecl->getDeclName())
11720         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11721
11722       // Similarly, dive into enums and fish their constants out, making them
11723       // accessible in this scope.
11724       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11725         for (auto *EI : ED->enumerators())
11726           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11727       }
11728     }
11729   }
11730
11731   // Introduce our parameters into the function scope
11732   for (auto Param : FD->parameters()) {
11733     Param->setOwningFunction(FD);
11734
11735     // If this has an identifier, add it to the scope stack.
11736     if (Param->getIdentifier() && FnBodyScope) {
11737       CheckShadow(FnBodyScope, Param);
11738
11739       PushOnScopeChains(Param, FnBodyScope);
11740     }
11741   }
11742
11743   // Ensure that the function's exception specification is instantiated.
11744   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11745     ResolveExceptionSpec(D->getLocation(), FPT);
11746
11747   // dllimport cannot be applied to non-inline function definitions.
11748   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11749       !FD->isTemplateInstantiation()) {
11750     assert(!FD->hasAttr<DLLExportAttr>());
11751     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11752     FD->setInvalidDecl();
11753     return D;
11754   }
11755   // We want to attach documentation to original Decl (which might be
11756   // a function template).
11757   ActOnDocumentableDecl(D);
11758   if (getCurLexicalContext()->isObjCContainer() &&
11759       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11760       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11761     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11762
11763   return D;
11764 }
11765
11766 /// \brief Given the set of return statements within a function body,
11767 /// compute the variables that are subject to the named return value
11768 /// optimization.
11769 ///
11770 /// Each of the variables that is subject to the named return value
11771 /// optimization will be marked as NRVO variables in the AST, and any
11772 /// return statement that has a marked NRVO variable as its NRVO candidate can
11773 /// use the named return value optimization.
11774 ///
11775 /// This function applies a very simplistic algorithm for NRVO: if every return
11776 /// statement in the scope of a variable has the same NRVO candidate, that
11777 /// candidate is an NRVO variable.
11778 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11779   ReturnStmt **Returns = Scope->Returns.data();
11780
11781   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11782     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11783       if (!NRVOCandidate->isNRVOVariable())
11784         Returns[I]->setNRVOCandidate(nullptr);
11785     }
11786   }
11787 }
11788
11789 bool Sema::canDelayFunctionBody(const Declarator &D) {
11790   // We can't delay parsing the body of a constexpr function template (yet).
11791   if (D.getDeclSpec().isConstexprSpecified())
11792     return false;
11793
11794   // We can't delay parsing the body of a function template with a deduced
11795   // return type (yet).
11796   if (D.getDeclSpec().containsPlaceholderType()) {
11797     // If the placeholder introduces a non-deduced trailing return type,
11798     // we can still delay parsing it.
11799     if (D.getNumTypeObjects()) {
11800       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11801       if (Outer.Kind == DeclaratorChunk::Function &&
11802           Outer.Fun.hasTrailingReturnType()) {
11803         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11804         return Ty.isNull() || !Ty->isUndeducedType();
11805       }
11806     }
11807     return false;
11808   }
11809
11810   return true;
11811 }
11812
11813 bool Sema::canSkipFunctionBody(Decl *D) {
11814   // We cannot skip the body of a function (or function template) which is
11815   // constexpr, since we may need to evaluate its body in order to parse the
11816   // rest of the file.
11817   // We cannot skip the body of a function with an undeduced return type,
11818   // because any callers of that function need to know the type.
11819   if (const FunctionDecl *FD = D->getAsFunction())
11820     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11821       return false;
11822   return Consumer.shouldSkipFunctionBody(D);
11823 }
11824
11825 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11826   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11827     FD->setHasSkippedBody();
11828   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11829     MD->setHasSkippedBody();
11830   return Decl;
11831 }
11832
11833 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11834   return ActOnFinishFunctionBody(D, BodyArg, false);
11835 }
11836
11837 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11838                                     bool IsInstantiation) {
11839   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11840
11841   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11842   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11843
11844   if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
11845     CheckCompletedCoroutineBody(FD, Body);
11846
11847   if (FD) {
11848     FD->setBody(Body);
11849
11850     if (getLangOpts().CPlusPlus14) {
11851       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11852           FD->getReturnType()->isUndeducedType()) {
11853         // If the function has a deduced result type but contains no 'return'
11854         // statements, the result type as written must be exactly 'auto', and
11855         // the deduced result type is 'void'.
11856         if (!FD->getReturnType()->getAs<AutoType>()) {
11857           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11858               << FD->getReturnType();
11859           FD->setInvalidDecl();
11860         } else {
11861           // Substitute 'void' for the 'auto' in the type.
11862           TypeLoc ResultType = getReturnTypeLoc(FD);
11863           Context.adjustDeducedFunctionResultType(
11864               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11865         }
11866       }
11867     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11868       // In C++11, we don't use 'auto' deduction rules for lambda call
11869       // operators because we don't support return type deduction.
11870       auto *LSI = getCurLambda();
11871       if (LSI->HasImplicitReturnType) {
11872         deduceClosureReturnType(*LSI);
11873
11874         // C++11 [expr.prim.lambda]p4:
11875         //   [...] if there are no return statements in the compound-statement
11876         //   [the deduced type is] the type void
11877         QualType RetType =
11878             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11879
11880         // Update the return type to the deduced type.
11881         const FunctionProtoType *Proto =
11882             FD->getType()->getAs<FunctionProtoType>();
11883         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11884                                             Proto->getExtProtoInfo()));
11885       }
11886     }
11887
11888     // The only way to be included in UndefinedButUsed is if there is an
11889     // ODR use before the definition. Avoid the expensive map lookup if this
11890     // is the first declaration.
11891     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11892       if (!FD->isExternallyVisible())
11893         UndefinedButUsed.erase(FD);
11894       else if (FD->isInlined() &&
11895                !LangOpts.GNUInline &&
11896                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11897         UndefinedButUsed.erase(FD);
11898     }
11899
11900     // If the function implicitly returns zero (like 'main') or is naked,
11901     // don't complain about missing return statements.
11902     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11903       WP.disableCheckFallThrough();
11904
11905     // MSVC permits the use of pure specifier (=0) on function definition,
11906     // defined at class scope, warn about this non-standard construct.
11907     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11908       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11909
11910     if (!FD->isInvalidDecl()) {
11911       // Don't diagnose unused parameters of defaulted or deleted functions.
11912       if (!FD->isDeleted() && !FD->isDefaulted())
11913         DiagnoseUnusedParameters(FD->parameters());
11914       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11915                                              FD->getReturnType(), FD);
11916
11917       // If this is a structor, we need a vtable.
11918       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11919         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11920       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11921         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11922
11923       // Try to apply the named return value optimization. We have to check
11924       // if we can do this here because lambdas keep return statements around
11925       // to deduce an implicit return type.
11926       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11927           !FD->isDependentContext())
11928         computeNRVO(Body, getCurFunction());
11929     }
11930
11931     // GNU warning -Wmissing-prototypes:
11932     //   Warn if a global function is defined without a previous
11933     //   prototype declaration. This warning is issued even if the
11934     //   definition itself provides a prototype. The aim is to detect
11935     //   global functions that fail to be declared in header files.
11936     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11937     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11938       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11939
11940       if (PossibleZeroParamPrototype) {
11941         // We found a declaration that is not a prototype,
11942         // but that could be a zero-parameter prototype
11943         if (TypeSourceInfo *TI =
11944                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11945           TypeLoc TL = TI->getTypeLoc();
11946           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11947             Diag(PossibleZeroParamPrototype->getLocation(),
11948                  diag::note_declaration_not_a_prototype)
11949                 << PossibleZeroParamPrototype
11950                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11951         }
11952       }
11953
11954       // GNU warning -Wstrict-prototypes
11955       //   Warn if K&R function is defined without a previous declaration.
11956       //   This warning is issued only if the definition itself does not provide
11957       //   a prototype. Only K&R definitions do not provide a prototype.
11958       //   An empty list in a function declarator that is part of a definition
11959       //   of that function specifies that the function has no parameters
11960       //   (C99 6.7.5.3p14)
11961       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
11962           !LangOpts.CPlusPlus) {
11963         TypeSourceInfo *TI = FD->getTypeSourceInfo();
11964         TypeLoc TL = TI->getTypeLoc();
11965         FunctionTypeLoc FTL = TL.castAs<FunctionTypeLoc>();
11966         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
11967       }
11968     }
11969
11970     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11971       const CXXMethodDecl *KeyFunction;
11972       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11973           MD->isVirtual() &&
11974           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11975           MD == KeyFunction->getCanonicalDecl()) {
11976         // Update the key-function state if necessary for this ABI.
11977         if (FD->isInlined() &&
11978             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11979           Context.setNonKeyFunction(MD);
11980
11981           // If the newly-chosen key function is already defined, then we
11982           // need to mark the vtable as used retroactively.
11983           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11984           const FunctionDecl *Definition;
11985           if (KeyFunction && KeyFunction->isDefined(Definition))
11986             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11987         } else {
11988           // We just defined they key function; mark the vtable as used.
11989           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11990         }
11991       }
11992     }
11993
11994     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11995            "Function parsing confused");
11996   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11997     assert(MD == getCurMethodDecl() && "Method parsing confused");
11998     MD->setBody(Body);
11999     if (!MD->isInvalidDecl()) {
12000       DiagnoseUnusedParameters(MD->parameters());
12001       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12002                                              MD->getReturnType(), MD);
12003
12004       if (Body)
12005         computeNRVO(Body, getCurFunction());
12006     }
12007     if (getCurFunction()->ObjCShouldCallSuper) {
12008       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12009         << MD->getSelector().getAsString();
12010       getCurFunction()->ObjCShouldCallSuper = false;
12011     }
12012     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12013       const ObjCMethodDecl *InitMethod = nullptr;
12014       bool isDesignated =
12015           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12016       assert(isDesignated && InitMethod);
12017       (void)isDesignated;
12018
12019       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12020         auto IFace = MD->getClassInterface();
12021         if (!IFace)
12022           return false;
12023         auto SuperD = IFace->getSuperClass();
12024         if (!SuperD)
12025           return false;
12026         return SuperD->getIdentifier() ==
12027             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12028       };
12029       // Don't issue this warning for unavailable inits or direct subclasses
12030       // of NSObject.
12031       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12032         Diag(MD->getLocation(),
12033              diag::warn_objc_designated_init_missing_super_call);
12034         Diag(InitMethod->getLocation(),
12035              diag::note_objc_designated_init_marked_here);
12036       }
12037       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12038     }
12039     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12040       // Don't issue this warning for unavaialable inits.
12041       if (!MD->isUnavailable())
12042         Diag(MD->getLocation(),
12043              diag::warn_objc_secondary_init_missing_init_call);
12044       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12045     }
12046   } else {
12047     return nullptr;
12048   }
12049
12050   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12051     DiagnoseUnguardedAvailabilityViolations(dcl);
12052
12053   assert(!getCurFunction()->ObjCShouldCallSuper &&
12054          "This should only be set for ObjC methods, which should have been "
12055          "handled in the block above.");
12056
12057   // Verify and clean out per-function state.
12058   if (Body && (!FD || !FD->isDefaulted())) {
12059     // C++ constructors that have function-try-blocks can't have return
12060     // statements in the handlers of that block. (C++ [except.handle]p14)
12061     // Verify this.
12062     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12063       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12064
12065     // Verify that gotos and switch cases don't jump into scopes illegally.
12066     if (getCurFunction()->NeedsScopeChecking() &&
12067         !PP.isCodeCompletionEnabled())
12068       DiagnoseInvalidJumps(Body);
12069
12070     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12071       if (!Destructor->getParent()->isDependentType())
12072         CheckDestructor(Destructor);
12073
12074       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12075                                              Destructor->getParent());
12076     }
12077
12078     // If any errors have occurred, clear out any temporaries that may have
12079     // been leftover. This ensures that these temporaries won't be picked up for
12080     // deletion in some later function.
12081     if (getDiagnostics().hasErrorOccurred() ||
12082         getDiagnostics().getSuppressAllDiagnostics()) {
12083       DiscardCleanupsInEvaluationContext();
12084     }
12085     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12086         !isa<FunctionTemplateDecl>(dcl)) {
12087       // Since the body is valid, issue any analysis-based warnings that are
12088       // enabled.
12089       ActivePolicy = &WP;
12090     }
12091
12092     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12093         (!CheckConstexprFunctionDecl(FD) ||
12094          !CheckConstexprFunctionBody(FD, Body)))
12095       FD->setInvalidDecl();
12096
12097     if (FD && FD->hasAttr<NakedAttr>()) {
12098       for (const Stmt *S : Body->children()) {
12099         // Allow local register variables without initializer as they don't
12100         // require prologue.
12101         bool RegisterVariables = false;
12102         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12103           for (const auto *Decl : DS->decls()) {
12104             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12105               RegisterVariables =
12106                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12107               if (!RegisterVariables)
12108                 break;
12109             }
12110           }
12111         }
12112         if (RegisterVariables)
12113           continue;
12114         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12115           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12116           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12117           FD->setInvalidDecl();
12118           break;
12119         }
12120       }
12121     }
12122
12123     assert(ExprCleanupObjects.size() ==
12124                ExprEvalContexts.back().NumCleanupObjects &&
12125            "Leftover temporaries in function");
12126     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12127     assert(MaybeODRUseExprs.empty() &&
12128            "Leftover expressions for odr-use checking");
12129   }
12130
12131   if (!IsInstantiation)
12132     PopDeclContext();
12133
12134   PopFunctionScopeInfo(ActivePolicy, dcl);
12135   // If any errors have occurred, clear out any temporaries that may have
12136   // been leftover. This ensures that these temporaries won't be picked up for
12137   // deletion in some later function.
12138   if (getDiagnostics().hasErrorOccurred()) {
12139     DiscardCleanupsInEvaluationContext();
12140   }
12141
12142   return dcl;
12143 }
12144
12145 /// When we finish delayed parsing of an attribute, we must attach it to the
12146 /// relevant Decl.
12147 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12148                                        ParsedAttributes &Attrs) {
12149   // Always attach attributes to the underlying decl.
12150   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12151     D = TD->getTemplatedDecl();
12152   ProcessDeclAttributeList(S, D, Attrs.getList());
12153
12154   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12155     if (Method->isStatic())
12156       checkThisInStaticMemberFunctionAttributes(Method);
12157 }
12158
12159 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12160 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12161 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12162                                           IdentifierInfo &II, Scope *S) {
12163   // Before we produce a declaration for an implicitly defined
12164   // function, see whether there was a locally-scoped declaration of
12165   // this name as a function or variable. If so, use that
12166   // (non-visible) declaration, and complain about it.
12167   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12168     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12169     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12170     return ExternCPrev;
12171   }
12172
12173   // Extension in C99.  Legal in C90, but warn about it.
12174   unsigned diag_id;
12175   if (II.getName().startswith("__builtin_"))
12176     diag_id = diag::warn_builtin_unknown;
12177   else if (getLangOpts().C99)
12178     diag_id = diag::ext_implicit_function_decl;
12179   else
12180     diag_id = diag::warn_implicit_function_decl;
12181   Diag(Loc, diag_id) << &II;
12182
12183   // Because typo correction is expensive, only do it if the implicit
12184   // function declaration is going to be treated as an error.
12185   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12186     TypoCorrection Corrected;
12187     if (S &&
12188         (Corrected = CorrectTypo(
12189              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12190              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12191       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12192                    /*ErrorRecovery*/false);
12193   }
12194
12195   // Set a Declarator for the implicit definition: int foo();
12196   const char *Dummy;
12197   AttributeFactory attrFactory;
12198   DeclSpec DS(attrFactory);
12199   unsigned DiagID;
12200   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12201                                   Context.getPrintingPolicy());
12202   (void)Error; // Silence warning.
12203   assert(!Error && "Error setting up implicit decl!");
12204   SourceLocation NoLoc;
12205   Declarator D(DS, Declarator::BlockContext);
12206   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12207                                              /*IsAmbiguous=*/false,
12208                                              /*LParenLoc=*/NoLoc,
12209                                              /*Params=*/nullptr,
12210                                              /*NumParams=*/0,
12211                                              /*EllipsisLoc=*/NoLoc,
12212                                              /*RParenLoc=*/NoLoc,
12213                                              /*TypeQuals=*/0,
12214                                              /*RefQualifierIsLvalueRef=*/true,
12215                                              /*RefQualifierLoc=*/NoLoc,
12216                                              /*ConstQualifierLoc=*/NoLoc,
12217                                              /*VolatileQualifierLoc=*/NoLoc,
12218                                              /*RestrictQualifierLoc=*/NoLoc,
12219                                              /*MutableLoc=*/NoLoc,
12220                                              EST_None,
12221                                              /*ESpecRange=*/SourceRange(),
12222                                              /*Exceptions=*/nullptr,
12223                                              /*ExceptionRanges=*/nullptr,
12224                                              /*NumExceptions=*/0,
12225                                              /*NoexceptExpr=*/nullptr,
12226                                              /*ExceptionSpecTokens=*/nullptr,
12227                                              /*DeclsInPrototype=*/None,
12228                                              Loc, Loc, D),
12229                 DS.getAttributes(),
12230                 SourceLocation());
12231   D.SetIdentifier(&II, Loc);
12232
12233   // Insert this function into translation-unit scope.
12234
12235   DeclContext *PrevDC = CurContext;
12236   CurContext = Context.getTranslationUnitDecl();
12237
12238   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12239   FD->setImplicit();
12240
12241   CurContext = PrevDC;
12242
12243   AddKnownFunctionAttributes(FD);
12244
12245   return FD;
12246 }
12247
12248 /// \brief Adds any function attributes that we know a priori based on
12249 /// the declaration of this function.
12250 ///
12251 /// These attributes can apply both to implicitly-declared builtins
12252 /// (like __builtin___printf_chk) or to library-declared functions
12253 /// like NSLog or printf.
12254 ///
12255 /// We need to check for duplicate attributes both here and where user-written
12256 /// attributes are applied to declarations.
12257 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12258   if (FD->isInvalidDecl())
12259     return;
12260
12261   // If this is a built-in function, map its builtin attributes to
12262   // actual attributes.
12263   if (unsigned BuiltinID = FD->getBuiltinID()) {
12264     // Handle printf-formatting attributes.
12265     unsigned FormatIdx;
12266     bool HasVAListArg;
12267     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12268       if (!FD->hasAttr<FormatAttr>()) {
12269         const char *fmt = "printf";
12270         unsigned int NumParams = FD->getNumParams();
12271         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12272             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12273           fmt = "NSString";
12274         FD->addAttr(FormatAttr::CreateImplicit(Context,
12275                                                &Context.Idents.get(fmt),
12276                                                FormatIdx+1,
12277                                                HasVAListArg ? 0 : FormatIdx+2,
12278                                                FD->getLocation()));
12279       }
12280     }
12281     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12282                                              HasVAListArg)) {
12283      if (!FD->hasAttr<FormatAttr>())
12284        FD->addAttr(FormatAttr::CreateImplicit(Context,
12285                                               &Context.Idents.get("scanf"),
12286                                               FormatIdx+1,
12287                                               HasVAListArg ? 0 : FormatIdx+2,
12288                                               FD->getLocation()));
12289     }
12290
12291     // Mark const if we don't care about errno and that is the only
12292     // thing preventing the function from being const. This allows
12293     // IRgen to use LLVM intrinsics for such functions.
12294     if (!getLangOpts().MathErrno &&
12295         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12296       if (!FD->hasAttr<ConstAttr>())
12297         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12298     }
12299
12300     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12301         !FD->hasAttr<ReturnsTwiceAttr>())
12302       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12303                                          FD->getLocation()));
12304     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12305       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12306     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12307       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12308     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12309       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12310     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12311         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12312       // Add the appropriate attribute, depending on the CUDA compilation mode
12313       // and which target the builtin belongs to. For example, during host
12314       // compilation, aux builtins are __device__, while the rest are __host__.
12315       if (getLangOpts().CUDAIsDevice !=
12316           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12317         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12318       else
12319         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12320     }
12321   }
12322
12323   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12324   // throw, add an implicit nothrow attribute to any extern "C" function we come
12325   // across.
12326   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12327       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12328     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12329     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12330       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12331   }
12332
12333   IdentifierInfo *Name = FD->getIdentifier();
12334   if (!Name)
12335     return;
12336   if ((!getLangOpts().CPlusPlus &&
12337        FD->getDeclContext()->isTranslationUnit()) ||
12338       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12339        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12340        LinkageSpecDecl::lang_c)) {
12341     // Okay: this could be a libc/libm/Objective-C function we know
12342     // about.
12343   } else
12344     return;
12345
12346   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12347     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12348     // target-specific builtins, perhaps?
12349     if (!FD->hasAttr<FormatAttr>())
12350       FD->addAttr(FormatAttr::CreateImplicit(Context,
12351                                              &Context.Idents.get("printf"), 2,
12352                                              Name->isStr("vasprintf") ? 0 : 3,
12353                                              FD->getLocation()));
12354   }
12355
12356   if (Name->isStr("__CFStringMakeConstantString")) {
12357     // We already have a __builtin___CFStringMakeConstantString,
12358     // but builds that use -fno-constant-cfstrings don't go through that.
12359     if (!FD->hasAttr<FormatArgAttr>())
12360       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12361                                                 FD->getLocation()));
12362   }
12363 }
12364
12365 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12366                                     TypeSourceInfo *TInfo) {
12367   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12368   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12369
12370   if (!TInfo) {
12371     assert(D.isInvalidType() && "no declarator info for valid type");
12372     TInfo = Context.getTrivialTypeSourceInfo(T);
12373   }
12374
12375   // Scope manipulation handled by caller.
12376   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12377                                            D.getLocStart(),
12378                                            D.getIdentifierLoc(),
12379                                            D.getIdentifier(),
12380                                            TInfo);
12381
12382   // Bail out immediately if we have an invalid declaration.
12383   if (D.isInvalidType()) {
12384     NewTD->setInvalidDecl();
12385     return NewTD;
12386   }
12387
12388   if (D.getDeclSpec().isModulePrivateSpecified()) {
12389     if (CurContext->isFunctionOrMethod())
12390       Diag(NewTD->getLocation(), diag::err_module_private_local)
12391         << 2 << NewTD->getDeclName()
12392         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12393         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12394     else
12395       NewTD->setModulePrivate();
12396   }
12397
12398   // C++ [dcl.typedef]p8:
12399   //   If the typedef declaration defines an unnamed class (or
12400   //   enum), the first typedef-name declared by the declaration
12401   //   to be that class type (or enum type) is used to denote the
12402   //   class type (or enum type) for linkage purposes only.
12403   // We need to check whether the type was declared in the declaration.
12404   switch (D.getDeclSpec().getTypeSpecType()) {
12405   case TST_enum:
12406   case TST_struct:
12407   case TST_interface:
12408   case TST_union:
12409   case TST_class: {
12410     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12411     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12412     break;
12413   }
12414
12415   default:
12416     break;
12417   }
12418
12419   return NewTD;
12420 }
12421
12422 /// \brief Check that this is a valid underlying type for an enum declaration.
12423 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12424   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12425   QualType T = TI->getType();
12426
12427   if (T->isDependentType())
12428     return false;
12429
12430   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12431     if (BT->isInteger())
12432       return false;
12433
12434   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12435   return true;
12436 }
12437
12438 /// Check whether this is a valid redeclaration of a previous enumeration.
12439 /// \return true if the redeclaration was invalid.
12440 bool Sema::CheckEnumRedeclaration(
12441     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12442     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12443   bool IsFixed = !EnumUnderlyingTy.isNull();
12444
12445   if (IsScoped != Prev->isScoped()) {
12446     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12447       << Prev->isScoped();
12448     Diag(Prev->getLocation(), diag::note_previous_declaration);
12449     return true;
12450   }
12451
12452   if (IsFixed && Prev->isFixed()) {
12453     if (!EnumUnderlyingTy->isDependentType() &&
12454         !Prev->getIntegerType()->isDependentType() &&
12455         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12456                                         Prev->getIntegerType())) {
12457       // TODO: Highlight the underlying type of the redeclaration.
12458       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12459         << EnumUnderlyingTy << Prev->getIntegerType();
12460       Diag(Prev->getLocation(), diag::note_previous_declaration)
12461           << Prev->getIntegerTypeRange();
12462       return true;
12463     }
12464   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12465     ;
12466   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12467     ;
12468   } else if (IsFixed != Prev->isFixed()) {
12469     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12470       << Prev->isFixed();
12471     Diag(Prev->getLocation(), diag::note_previous_declaration);
12472     return true;
12473   }
12474
12475   return false;
12476 }
12477
12478 /// \brief Get diagnostic %select index for tag kind for
12479 /// redeclaration diagnostic message.
12480 /// WARNING: Indexes apply to particular diagnostics only!
12481 ///
12482 /// \returns diagnostic %select index.
12483 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12484   switch (Tag) {
12485   case TTK_Struct: return 0;
12486   case TTK_Interface: return 1;
12487   case TTK_Class:  return 2;
12488   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12489   }
12490 }
12491
12492 /// \brief Determine if tag kind is a class-key compatible with
12493 /// class for redeclaration (class, struct, or __interface).
12494 ///
12495 /// \returns true iff the tag kind is compatible.
12496 static bool isClassCompatTagKind(TagTypeKind Tag)
12497 {
12498   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12499 }
12500
12501 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12502                                              TagTypeKind TTK) {
12503   if (isa<TypedefDecl>(PrevDecl))
12504     return NTK_Typedef;
12505   else if (isa<TypeAliasDecl>(PrevDecl))
12506     return NTK_TypeAlias;
12507   else if (isa<ClassTemplateDecl>(PrevDecl))
12508     return NTK_Template;
12509   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12510     return NTK_TypeAliasTemplate;
12511   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12512     return NTK_TemplateTemplateArgument;
12513   switch (TTK) {
12514   case TTK_Struct:
12515   case TTK_Interface:
12516   case TTK_Class:
12517     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12518   case TTK_Union:
12519     return NTK_NonUnion;
12520   case TTK_Enum:
12521     return NTK_NonEnum;
12522   }
12523   llvm_unreachable("invalid TTK");
12524 }
12525
12526 /// \brief Determine whether a tag with a given kind is acceptable
12527 /// as a redeclaration of the given tag declaration.
12528 ///
12529 /// \returns true if the new tag kind is acceptable, false otherwise.
12530 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12531                                         TagTypeKind NewTag, bool isDefinition,
12532                                         SourceLocation NewTagLoc,
12533                                         const IdentifierInfo *Name) {
12534   // C++ [dcl.type.elab]p3:
12535   //   The class-key or enum keyword present in the
12536   //   elaborated-type-specifier shall agree in kind with the
12537   //   declaration to which the name in the elaborated-type-specifier
12538   //   refers. This rule also applies to the form of
12539   //   elaborated-type-specifier that declares a class-name or
12540   //   friend class since it can be construed as referring to the
12541   //   definition of the class. Thus, in any
12542   //   elaborated-type-specifier, the enum keyword shall be used to
12543   //   refer to an enumeration (7.2), the union class-key shall be
12544   //   used to refer to a union (clause 9), and either the class or
12545   //   struct class-key shall be used to refer to a class (clause 9)
12546   //   declared using the class or struct class-key.
12547   TagTypeKind OldTag = Previous->getTagKind();
12548   if (!isDefinition || !isClassCompatTagKind(NewTag))
12549     if (OldTag == NewTag)
12550       return true;
12551
12552   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12553     // Warn about the struct/class tag mismatch.
12554     bool isTemplate = false;
12555     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12556       isTemplate = Record->getDescribedClassTemplate();
12557
12558     if (!ActiveTemplateInstantiations.empty()) {
12559       // In a template instantiation, do not offer fix-its for tag mismatches
12560       // since they usually mess up the template instead of fixing the problem.
12561       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12562         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12563         << getRedeclDiagFromTagKind(OldTag);
12564       return true;
12565     }
12566
12567     if (isDefinition) {
12568       // On definitions, check previous tags and issue a fix-it for each
12569       // one that doesn't match the current tag.
12570       if (Previous->getDefinition()) {
12571         // Don't suggest fix-its for redefinitions.
12572         return true;
12573       }
12574
12575       bool previousMismatch = false;
12576       for (auto I : Previous->redecls()) {
12577         if (I->getTagKind() != NewTag) {
12578           if (!previousMismatch) {
12579             previousMismatch = true;
12580             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12581               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12582               << getRedeclDiagFromTagKind(I->getTagKind());
12583           }
12584           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12585             << getRedeclDiagFromTagKind(NewTag)
12586             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12587                  TypeWithKeyword::getTagTypeKindName(NewTag));
12588         }
12589       }
12590       return true;
12591     }
12592
12593     // Check for a previous definition.  If current tag and definition
12594     // are same type, do nothing.  If no definition, but disagree with
12595     // with previous tag type, give a warning, but no fix-it.
12596     const TagDecl *Redecl = Previous->getDefinition() ?
12597                             Previous->getDefinition() : Previous;
12598     if (Redecl->getTagKind() == NewTag) {
12599       return true;
12600     }
12601
12602     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12603       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12604       << getRedeclDiagFromTagKind(OldTag);
12605     Diag(Redecl->getLocation(), diag::note_previous_use);
12606
12607     // If there is a previous definition, suggest a fix-it.
12608     if (Previous->getDefinition()) {
12609         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12610           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12611           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12612                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12613     }
12614
12615     return true;
12616   }
12617   return false;
12618 }
12619
12620 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12621 /// from an outer enclosing namespace or file scope inside a friend declaration.
12622 /// This should provide the commented out code in the following snippet:
12623 ///   namespace N {
12624 ///     struct X;
12625 ///     namespace M {
12626 ///       struct Y { friend struct /*N::*/ X; };
12627 ///     }
12628 ///   }
12629 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12630                                          SourceLocation NameLoc) {
12631   // While the decl is in a namespace, do repeated lookup of that name and see
12632   // if we get the same namespace back.  If we do not, continue until
12633   // translation unit scope, at which point we have a fully qualified NNS.
12634   SmallVector<IdentifierInfo *, 4> Namespaces;
12635   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12636   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12637     // This tag should be declared in a namespace, which can only be enclosed by
12638     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12639     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12640     if (!Namespace || Namespace->isAnonymousNamespace())
12641       return FixItHint();
12642     IdentifierInfo *II = Namespace->getIdentifier();
12643     Namespaces.push_back(II);
12644     NamedDecl *Lookup = SemaRef.LookupSingleName(
12645         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12646     if (Lookup == Namespace)
12647       break;
12648   }
12649
12650   // Once we have all the namespaces, reverse them to go outermost first, and
12651   // build an NNS.
12652   SmallString<64> Insertion;
12653   llvm::raw_svector_ostream OS(Insertion);
12654   if (DC->isTranslationUnit())
12655     OS << "::";
12656   std::reverse(Namespaces.begin(), Namespaces.end());
12657   for (auto *II : Namespaces)
12658     OS << II->getName() << "::";
12659   return FixItHint::CreateInsertion(NameLoc, Insertion);
12660 }
12661
12662 /// \brief Determine whether a tag originally declared in context \p OldDC can
12663 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12664 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12665 /// using-declaration).
12666 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12667                                          DeclContext *NewDC) {
12668   OldDC = OldDC->getRedeclContext();
12669   NewDC = NewDC->getRedeclContext();
12670
12671   if (OldDC->Equals(NewDC))
12672     return true;
12673
12674   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12675   // encloses the other).
12676   if (S.getLangOpts().MSVCCompat &&
12677       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12678     return true;
12679
12680   return false;
12681 }
12682
12683 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12684 /// former case, Name will be non-null.  In the later case, Name will be null.
12685 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12686 /// reference/declaration/definition of a tag.
12687 ///
12688 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12689 /// trailing-type-specifier) other than one in an alias-declaration.
12690 ///
12691 /// \param SkipBody If non-null, will be set to indicate if the caller should
12692 /// skip the definition of this tag and treat it as if it were a declaration.
12693 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12694                      SourceLocation KWLoc, CXXScopeSpec &SS,
12695                      IdentifierInfo *Name, SourceLocation NameLoc,
12696                      AttributeList *Attr, AccessSpecifier AS,
12697                      SourceLocation ModulePrivateLoc,
12698                      MultiTemplateParamsArg TemplateParameterLists,
12699                      bool &OwnedDecl, bool &IsDependent,
12700                      SourceLocation ScopedEnumKWLoc,
12701                      bool ScopedEnumUsesClassTag,
12702                      TypeResult UnderlyingType,
12703                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12704   // If this is not a definition, it must have a name.
12705   IdentifierInfo *OrigName = Name;
12706   assert((Name != nullptr || TUK == TUK_Definition) &&
12707          "Nameless record must be a definition!");
12708   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12709
12710   OwnedDecl = false;
12711   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12712   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12713
12714   // FIXME: Check explicit specializations more carefully.
12715   bool isExplicitSpecialization = false;
12716   bool Invalid = false;
12717
12718   // We only need to do this matching if we have template parameters
12719   // or a scope specifier, which also conveniently avoids this work
12720   // for non-C++ cases.
12721   if (TemplateParameterLists.size() > 0 ||
12722       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12723     if (TemplateParameterList *TemplateParams =
12724             MatchTemplateParametersToScopeSpecifier(
12725                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12726                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12727       if (Kind == TTK_Enum) {
12728         Diag(KWLoc, diag::err_enum_template);
12729         return nullptr;
12730       }
12731
12732       if (TemplateParams->size() > 0) {
12733         // This is a declaration or definition of a class template (which may
12734         // be a member of another template).
12735
12736         if (Invalid)
12737           return nullptr;
12738
12739         OwnedDecl = false;
12740         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12741                                                SS, Name, NameLoc, Attr,
12742                                                TemplateParams, AS,
12743                                                ModulePrivateLoc,
12744                                                /*FriendLoc*/SourceLocation(),
12745                                                TemplateParameterLists.size()-1,
12746                                                TemplateParameterLists.data(),
12747                                                SkipBody);
12748         return Result.get();
12749       } else {
12750         // The "template<>" header is extraneous.
12751         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12752           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12753         isExplicitSpecialization = true;
12754       }
12755     }
12756   }
12757
12758   // Figure out the underlying type if this a enum declaration. We need to do
12759   // this early, because it's needed to detect if this is an incompatible
12760   // redeclaration.
12761   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12762   bool EnumUnderlyingIsImplicit = false;
12763
12764   if (Kind == TTK_Enum) {
12765     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12766       // No underlying type explicitly specified, or we failed to parse the
12767       // type, default to int.
12768       EnumUnderlying = Context.IntTy.getTypePtr();
12769     else if (UnderlyingType.get()) {
12770       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12771       // integral type; any cv-qualification is ignored.
12772       TypeSourceInfo *TI = nullptr;
12773       GetTypeFromParser(UnderlyingType.get(), &TI);
12774       EnumUnderlying = TI;
12775
12776       if (CheckEnumUnderlyingType(TI))
12777         // Recover by falling back to int.
12778         EnumUnderlying = Context.IntTy.getTypePtr();
12779
12780       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12781                                           UPPC_FixedUnderlyingType))
12782         EnumUnderlying = Context.IntTy.getTypePtr();
12783
12784     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12785       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12786         // Microsoft enums are always of int type.
12787         EnumUnderlying = Context.IntTy.getTypePtr();
12788         EnumUnderlyingIsImplicit = true;
12789       }
12790     }
12791   }
12792
12793   DeclContext *SearchDC = CurContext;
12794   DeclContext *DC = CurContext;
12795   bool isStdBadAlloc = false;
12796   bool isStdAlignValT = false;
12797
12798   RedeclarationKind Redecl = ForRedeclaration;
12799   if (TUK == TUK_Friend || TUK == TUK_Reference)
12800     Redecl = NotForRedeclaration;
12801
12802   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12803   if (Name && SS.isNotEmpty()) {
12804     // We have a nested-name tag ('struct foo::bar').
12805
12806     // Check for invalid 'foo::'.
12807     if (SS.isInvalid()) {
12808       Name = nullptr;
12809       goto CreateNewDecl;
12810     }
12811
12812     // If this is a friend or a reference to a class in a dependent
12813     // context, don't try to make a decl for it.
12814     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12815       DC = computeDeclContext(SS, false);
12816       if (!DC) {
12817         IsDependent = true;
12818         return nullptr;
12819       }
12820     } else {
12821       DC = computeDeclContext(SS, true);
12822       if (!DC) {
12823         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12824           << SS.getRange();
12825         return nullptr;
12826       }
12827     }
12828
12829     if (RequireCompleteDeclContext(SS, DC))
12830       return nullptr;
12831
12832     SearchDC = DC;
12833     // Look-up name inside 'foo::'.
12834     LookupQualifiedName(Previous, DC);
12835
12836     if (Previous.isAmbiguous())
12837       return nullptr;
12838
12839     if (Previous.empty()) {
12840       // Name lookup did not find anything. However, if the
12841       // nested-name-specifier refers to the current instantiation,
12842       // and that current instantiation has any dependent base
12843       // classes, we might find something at instantiation time: treat
12844       // this as a dependent elaborated-type-specifier.
12845       // But this only makes any sense for reference-like lookups.
12846       if (Previous.wasNotFoundInCurrentInstantiation() &&
12847           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12848         IsDependent = true;
12849         return nullptr;
12850       }
12851
12852       // A tag 'foo::bar' must already exist.
12853       Diag(NameLoc, diag::err_not_tag_in_scope)
12854         << Kind << Name << DC << SS.getRange();
12855       Name = nullptr;
12856       Invalid = true;
12857       goto CreateNewDecl;
12858     }
12859   } else if (Name) {
12860     // C++14 [class.mem]p14:
12861     //   If T is the name of a class, then each of the following shall have a
12862     //   name different from T:
12863     //    -- every member of class T that is itself a type
12864     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12865         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12866       return nullptr;
12867
12868     // If this is a named struct, check to see if there was a previous forward
12869     // declaration or definition.
12870     // FIXME: We're looking into outer scopes here, even when we
12871     // shouldn't be. Doing so can result in ambiguities that we
12872     // shouldn't be diagnosing.
12873     LookupName(Previous, S);
12874
12875     // When declaring or defining a tag, ignore ambiguities introduced
12876     // by types using'ed into this scope.
12877     if (Previous.isAmbiguous() &&
12878         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12879       LookupResult::Filter F = Previous.makeFilter();
12880       while (F.hasNext()) {
12881         NamedDecl *ND = F.next();
12882         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12883                 SearchDC->getRedeclContext()))
12884           F.erase();
12885       }
12886       F.done();
12887     }
12888
12889     // C++11 [namespace.memdef]p3:
12890     //   If the name in a friend declaration is neither qualified nor
12891     //   a template-id and the declaration is a function or an
12892     //   elaborated-type-specifier, the lookup to determine whether
12893     //   the entity has been previously declared shall not consider
12894     //   any scopes outside the innermost enclosing namespace.
12895     //
12896     // MSVC doesn't implement the above rule for types, so a friend tag
12897     // declaration may be a redeclaration of a type declared in an enclosing
12898     // scope.  They do implement this rule for friend functions.
12899     //
12900     // Does it matter that this should be by scope instead of by
12901     // semantic context?
12902     if (!Previous.empty() && TUK == TUK_Friend) {
12903       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12904       LookupResult::Filter F = Previous.makeFilter();
12905       bool FriendSawTagOutsideEnclosingNamespace = false;
12906       while (F.hasNext()) {
12907         NamedDecl *ND = F.next();
12908         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12909         if (DC->isFileContext() &&
12910             !EnclosingNS->Encloses(ND->getDeclContext())) {
12911           if (getLangOpts().MSVCCompat)
12912             FriendSawTagOutsideEnclosingNamespace = true;
12913           else
12914             F.erase();
12915         }
12916       }
12917       F.done();
12918
12919       // Diagnose this MSVC extension in the easy case where lookup would have
12920       // unambiguously found something outside the enclosing namespace.
12921       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12922         NamedDecl *ND = Previous.getFoundDecl();
12923         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12924             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12925       }
12926     }
12927
12928     // Note:  there used to be some attempt at recovery here.
12929     if (Previous.isAmbiguous())
12930       return nullptr;
12931
12932     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12933       // FIXME: This makes sure that we ignore the contexts associated
12934       // with C structs, unions, and enums when looking for a matching
12935       // tag declaration or definition. See the similar lookup tweak
12936       // in Sema::LookupName; is there a better way to deal with this?
12937       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12938         SearchDC = SearchDC->getParent();
12939     }
12940   }
12941
12942   if (Previous.isSingleResult() &&
12943       Previous.getFoundDecl()->isTemplateParameter()) {
12944     // Maybe we will complain about the shadowed template parameter.
12945     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12946     // Just pretend that we didn't see the previous declaration.
12947     Previous.clear();
12948   }
12949
12950   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12951       DC->Equals(getStdNamespace())) {
12952     if (Name->isStr("bad_alloc")) {
12953       // This is a declaration of or a reference to "std::bad_alloc".
12954       isStdBadAlloc = true;
12955
12956       // If std::bad_alloc has been implicitly declared (but made invisible to
12957       // name lookup), fill in this implicit declaration as the previous
12958       // declaration, so that the declarations get chained appropriately.
12959       if (Previous.empty() && StdBadAlloc)
12960         Previous.addDecl(getStdBadAlloc());
12961     } else if (Name->isStr("align_val_t")) {
12962       isStdAlignValT = true;
12963       if (Previous.empty() && StdAlignValT)
12964         Previous.addDecl(getStdAlignValT());
12965     }
12966   }
12967
12968   // If we didn't find a previous declaration, and this is a reference
12969   // (or friend reference), move to the correct scope.  In C++, we
12970   // also need to do a redeclaration lookup there, just in case
12971   // there's a shadow friend decl.
12972   if (Name && Previous.empty() &&
12973       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12974     if (Invalid) goto CreateNewDecl;
12975     assert(SS.isEmpty());
12976
12977     if (TUK == TUK_Reference) {
12978       // C++ [basic.scope.pdecl]p5:
12979       //   -- for an elaborated-type-specifier of the form
12980       //
12981       //          class-key identifier
12982       //
12983       //      if the elaborated-type-specifier is used in the
12984       //      decl-specifier-seq or parameter-declaration-clause of a
12985       //      function defined in namespace scope, the identifier is
12986       //      declared as a class-name in the namespace that contains
12987       //      the declaration; otherwise, except as a friend
12988       //      declaration, the identifier is declared in the smallest
12989       //      non-class, non-function-prototype scope that contains the
12990       //      declaration.
12991       //
12992       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12993       // C structs and unions.
12994       //
12995       // It is an error in C++ to declare (rather than define) an enum
12996       // type, including via an elaborated type specifier.  We'll
12997       // diagnose that later; for now, declare the enum in the same
12998       // scope as we would have picked for any other tag type.
12999       //
13000       // GNU C also supports this behavior as part of its incomplete
13001       // enum types extension, while GNU C++ does not.
13002       //
13003       // Find the context where we'll be declaring the tag.
13004       // FIXME: We would like to maintain the current DeclContext as the
13005       // lexical context,
13006       SearchDC = getTagInjectionContext(SearchDC);
13007
13008       // Find the scope where we'll be declaring the tag.
13009       S = getTagInjectionScope(S, getLangOpts());
13010     } else {
13011       assert(TUK == TUK_Friend);
13012       // C++ [namespace.memdef]p3:
13013       //   If a friend declaration in a non-local class first declares a
13014       //   class or function, the friend class or function is a member of
13015       //   the innermost enclosing namespace.
13016       SearchDC = SearchDC->getEnclosingNamespaceContext();
13017     }
13018
13019     // In C++, we need to do a redeclaration lookup to properly
13020     // diagnose some problems.
13021     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13022     // hidden declaration so that we don't get ambiguity errors when using a
13023     // type declared by an elaborated-type-specifier.  In C that is not correct
13024     // and we should instead merge compatible types found by lookup.
13025     if (getLangOpts().CPlusPlus) {
13026       Previous.setRedeclarationKind(ForRedeclaration);
13027       LookupQualifiedName(Previous, SearchDC);
13028     } else {
13029       Previous.setRedeclarationKind(ForRedeclaration);
13030       LookupName(Previous, S);
13031     }
13032   }
13033
13034   // If we have a known previous declaration to use, then use it.
13035   if (Previous.empty() && SkipBody && SkipBody->Previous)
13036     Previous.addDecl(SkipBody->Previous);
13037
13038   if (!Previous.empty()) {
13039     NamedDecl *PrevDecl = Previous.getFoundDecl();
13040     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13041
13042     // It's okay to have a tag decl in the same scope as a typedef
13043     // which hides a tag decl in the same scope.  Finding this
13044     // insanity with a redeclaration lookup can only actually happen
13045     // in C++.
13046     //
13047     // This is also okay for elaborated-type-specifiers, which is
13048     // technically forbidden by the current standard but which is
13049     // okay according to the likely resolution of an open issue;
13050     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13051     if (getLangOpts().CPlusPlus) {
13052       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13053         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13054           TagDecl *Tag = TT->getDecl();
13055           if (Tag->getDeclName() == Name &&
13056               Tag->getDeclContext()->getRedeclContext()
13057                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13058             PrevDecl = Tag;
13059             Previous.clear();
13060             Previous.addDecl(Tag);
13061             Previous.resolveKind();
13062           }
13063         }
13064       }
13065     }
13066
13067     // If this is a redeclaration of a using shadow declaration, it must
13068     // declare a tag in the same context. In MSVC mode, we allow a
13069     // redefinition if either context is within the other.
13070     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13071       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13072       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13073           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
13074           !(OldTag && isAcceptableTagRedeclContext(
13075                           *this, OldTag->getDeclContext(), SearchDC))) {
13076         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13077         Diag(Shadow->getTargetDecl()->getLocation(),
13078              diag::note_using_decl_target);
13079         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13080             << 0;
13081         // Recover by ignoring the old declaration.
13082         Previous.clear();
13083         goto CreateNewDecl;
13084       }
13085     }
13086
13087     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13088       // If this is a use of a previous tag, or if the tag is already declared
13089       // in the same scope (so that the definition/declaration completes or
13090       // rementions the tag), reuse the decl.
13091       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13092           isDeclInScope(DirectPrevDecl, SearchDC, S,
13093                         SS.isNotEmpty() || isExplicitSpecialization)) {
13094         // Make sure that this wasn't declared as an enum and now used as a
13095         // struct or something similar.
13096         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13097                                           TUK == TUK_Definition, KWLoc,
13098                                           Name)) {
13099           bool SafeToContinue
13100             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13101                Kind != TTK_Enum);
13102           if (SafeToContinue)
13103             Diag(KWLoc, diag::err_use_with_wrong_tag)
13104               << Name
13105               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13106                                               PrevTagDecl->getKindName());
13107           else
13108             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13109           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13110
13111           if (SafeToContinue)
13112             Kind = PrevTagDecl->getTagKind();
13113           else {
13114             // Recover by making this an anonymous redefinition.
13115             Name = nullptr;
13116             Previous.clear();
13117             Invalid = true;
13118           }
13119         }
13120
13121         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13122           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13123
13124           // If this is an elaborated-type-specifier for a scoped enumeration,
13125           // the 'class' keyword is not necessary and not permitted.
13126           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13127             if (ScopedEnum)
13128               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13129                 << PrevEnum->isScoped()
13130                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13131             return PrevTagDecl;
13132           }
13133
13134           QualType EnumUnderlyingTy;
13135           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13136             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13137           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13138             EnumUnderlyingTy = QualType(T, 0);
13139
13140           // All conflicts with previous declarations are recovered by
13141           // returning the previous declaration, unless this is a definition,
13142           // in which case we want the caller to bail out.
13143           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13144                                      ScopedEnum, EnumUnderlyingTy,
13145                                      EnumUnderlyingIsImplicit, PrevEnum))
13146             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13147         }
13148
13149         // C++11 [class.mem]p1:
13150         //   A member shall not be declared twice in the member-specification,
13151         //   except that a nested class or member class template can be declared
13152         //   and then later defined.
13153         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13154             S->isDeclScope(PrevDecl)) {
13155           Diag(NameLoc, diag::ext_member_redeclared);
13156           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13157         }
13158
13159         if (!Invalid) {
13160           // If this is a use, just return the declaration we found, unless
13161           // we have attributes.
13162           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13163             if (Attr) {
13164               // FIXME: Diagnose these attributes. For now, we create a new
13165               // declaration to hold them.
13166             } else if (TUK == TUK_Reference &&
13167                        (PrevTagDecl->getFriendObjectKind() ==
13168                             Decl::FOK_Undeclared ||
13169                         PP.getModuleContainingLocation(
13170                             PrevDecl->getLocation()) !=
13171                             PP.getModuleContainingLocation(KWLoc)) &&
13172                        SS.isEmpty()) {
13173               // This declaration is a reference to an existing entity, but
13174               // has different visibility from that entity: it either makes
13175               // a friend visible or it makes a type visible in a new module.
13176               // In either case, create a new declaration. We only do this if
13177               // the declaration would have meant the same thing if no prior
13178               // declaration were found, that is, if it was found in the same
13179               // scope where we would have injected a declaration.
13180               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13181                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13182                 return PrevTagDecl;
13183               // This is in the injected scope, create a new declaration in
13184               // that scope.
13185               S = getTagInjectionScope(S, getLangOpts());
13186             } else {
13187               return PrevTagDecl;
13188             }
13189           }
13190
13191           // Diagnose attempts to redefine a tag.
13192           if (TUK == TUK_Definition) {
13193             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13194               // If we're defining a specialization and the previous definition
13195               // is from an implicit instantiation, don't emit an error
13196               // here; we'll catch this in the general case below.
13197               bool IsExplicitSpecializationAfterInstantiation = false;
13198               if (isExplicitSpecialization) {
13199                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13200                   IsExplicitSpecializationAfterInstantiation =
13201                     RD->getTemplateSpecializationKind() !=
13202                     TSK_ExplicitSpecialization;
13203                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13204                   IsExplicitSpecializationAfterInstantiation =
13205                     ED->getTemplateSpecializationKind() !=
13206                     TSK_ExplicitSpecialization;
13207               }
13208
13209               NamedDecl *Hidden = nullptr;
13210               if (SkipBody && getLangOpts().CPlusPlus &&
13211                   !hasVisibleDefinition(Def, &Hidden)) {
13212                 // There is a definition of this tag, but it is not visible. We
13213                 // explicitly make use of C++'s one definition rule here, and
13214                 // assume that this definition is identical to the hidden one
13215                 // we already have. Make the existing definition visible and
13216                 // use it in place of this one.
13217                 SkipBody->ShouldSkip = true;
13218                 makeMergedDefinitionVisible(Hidden, KWLoc);
13219                 return Def;
13220               } else if (!IsExplicitSpecializationAfterInstantiation) {
13221                 // A redeclaration in function prototype scope in C isn't
13222                 // visible elsewhere, so merely issue a warning.
13223                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13224                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13225                 else
13226                   Diag(NameLoc, diag::err_redefinition) << Name;
13227                 Diag(Def->getLocation(), diag::note_previous_definition);
13228                 // If this is a redefinition, recover by making this
13229                 // struct be anonymous, which will make any later
13230                 // references get the previous definition.
13231                 Name = nullptr;
13232                 Previous.clear();
13233                 Invalid = true;
13234               }
13235             } else {
13236               // If the type is currently being defined, complain
13237               // about a nested redefinition.
13238               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13239               if (TD->isBeingDefined()) {
13240                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13241                 Diag(PrevTagDecl->getLocation(),
13242                      diag::note_previous_definition);
13243                 Name = nullptr;
13244                 Previous.clear();
13245                 Invalid = true;
13246               }
13247             }
13248
13249             // Okay, this is definition of a previously declared or referenced
13250             // tag. We're going to create a new Decl for it.
13251           }
13252
13253           // Okay, we're going to make a redeclaration.  If this is some kind
13254           // of reference, make sure we build the redeclaration in the same DC
13255           // as the original, and ignore the current access specifier.
13256           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13257             SearchDC = PrevTagDecl->getDeclContext();
13258             AS = AS_none;
13259           }
13260         }
13261         // If we get here we have (another) forward declaration or we
13262         // have a definition.  Just create a new decl.
13263
13264       } else {
13265         // If we get here, this is a definition of a new tag type in a nested
13266         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13267         // new decl/type.  We set PrevDecl to NULL so that the entities
13268         // have distinct types.
13269         Previous.clear();
13270       }
13271       // If we get here, we're going to create a new Decl. If PrevDecl
13272       // is non-NULL, it's a definition of the tag declared by
13273       // PrevDecl. If it's NULL, we have a new definition.
13274
13275     // Otherwise, PrevDecl is not a tag, but was found with tag
13276     // lookup.  This is only actually possible in C++, where a few
13277     // things like templates still live in the tag namespace.
13278     } else {
13279       // Use a better diagnostic if an elaborated-type-specifier
13280       // found the wrong kind of type on the first
13281       // (non-redeclaration) lookup.
13282       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13283           !Previous.isForRedeclaration()) {
13284         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13285         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13286                                                        << Kind;
13287         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13288         Invalid = true;
13289
13290       // Otherwise, only diagnose if the declaration is in scope.
13291       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13292                                 SS.isNotEmpty() || isExplicitSpecialization)) {
13293         // do nothing
13294
13295       // Diagnose implicit declarations introduced by elaborated types.
13296       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13297         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13298         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13299         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13300         Invalid = true;
13301
13302       // Otherwise it's a declaration.  Call out a particularly common
13303       // case here.
13304       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13305         unsigned Kind = 0;
13306         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13307         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13308           << Name << Kind << TND->getUnderlyingType();
13309         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13310         Invalid = true;
13311
13312       // Otherwise, diagnose.
13313       } else {
13314         // The tag name clashes with something else in the target scope,
13315         // issue an error and recover by making this tag be anonymous.
13316         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13317         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13318         Name = nullptr;
13319         Invalid = true;
13320       }
13321
13322       // The existing declaration isn't relevant to us; we're in a
13323       // new scope, so clear out the previous declaration.
13324       Previous.clear();
13325     }
13326   }
13327
13328 CreateNewDecl:
13329
13330   TagDecl *PrevDecl = nullptr;
13331   if (Previous.isSingleResult())
13332     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13333
13334   // If there is an identifier, use the location of the identifier as the
13335   // location of the decl, otherwise use the location of the struct/union
13336   // keyword.
13337   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13338
13339   // Otherwise, create a new declaration. If there is a previous
13340   // declaration of the same entity, the two will be linked via
13341   // PrevDecl.
13342   TagDecl *New;
13343
13344   bool IsForwardReference = false;
13345   if (Kind == TTK_Enum) {
13346     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13347     // enum X { A, B, C } D;    D should chain to X.
13348     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13349                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13350                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13351
13352     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13353       StdAlignValT = cast<EnumDecl>(New);
13354
13355     // If this is an undefined enum, warn.
13356     if (TUK != TUK_Definition && !Invalid) {
13357       TagDecl *Def;
13358       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13359           cast<EnumDecl>(New)->isFixed()) {
13360         // C++0x: 7.2p2: opaque-enum-declaration.
13361         // Conflicts are diagnosed above. Do nothing.
13362       }
13363       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13364         Diag(Loc, diag::ext_forward_ref_enum_def)
13365           << New;
13366         Diag(Def->getLocation(), diag::note_previous_definition);
13367       } else {
13368         unsigned DiagID = diag::ext_forward_ref_enum;
13369         if (getLangOpts().MSVCCompat)
13370           DiagID = diag::ext_ms_forward_ref_enum;
13371         else if (getLangOpts().CPlusPlus)
13372           DiagID = diag::err_forward_ref_enum;
13373         Diag(Loc, DiagID);
13374
13375         // If this is a forward-declared reference to an enumeration, make a
13376         // note of it; we won't actually be introducing the declaration into
13377         // the declaration context.
13378         if (TUK == TUK_Reference)
13379           IsForwardReference = true;
13380       }
13381     }
13382
13383     if (EnumUnderlying) {
13384       EnumDecl *ED = cast<EnumDecl>(New);
13385       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13386         ED->setIntegerTypeSourceInfo(TI);
13387       else
13388         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13389       ED->setPromotionType(ED->getIntegerType());
13390     }
13391   } else {
13392     // struct/union/class
13393
13394     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13395     // struct X { int A; } D;    D should chain to X.
13396     if (getLangOpts().CPlusPlus) {
13397       // FIXME: Look for a way to use RecordDecl for simple structs.
13398       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13399                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13400
13401       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13402         StdBadAlloc = cast<CXXRecordDecl>(New);
13403     } else
13404       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13405                                cast_or_null<RecordDecl>(PrevDecl));
13406   }
13407
13408   // C++11 [dcl.type]p3:
13409   //   A type-specifier-seq shall not define a class or enumeration [...].
13410   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13411     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13412       << Context.getTagDeclType(New);
13413     Invalid = true;
13414   }
13415
13416   // Maybe add qualifier info.
13417   if (SS.isNotEmpty()) {
13418     if (SS.isSet()) {
13419       // If this is either a declaration or a definition, check the
13420       // nested-name-specifier against the current context. We don't do this
13421       // for explicit specializations, because they have similar checking
13422       // (with more specific diagnostics) in the call to
13423       // CheckMemberSpecialization, below.
13424       if (!isExplicitSpecialization &&
13425           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13426           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13427         Invalid = true;
13428
13429       New->setQualifierInfo(SS.getWithLocInContext(Context));
13430       if (TemplateParameterLists.size() > 0) {
13431         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13432       }
13433     }
13434     else
13435       Invalid = true;
13436   }
13437
13438   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13439     // Add alignment attributes if necessary; these attributes are checked when
13440     // the ASTContext lays out the structure.
13441     //
13442     // It is important for implementing the correct semantics that this
13443     // happen here (in act on tag decl). The #pragma pack stack is
13444     // maintained as a result of parser callbacks which can occur at
13445     // many points during the parsing of a struct declaration (because
13446     // the #pragma tokens are effectively skipped over during the
13447     // parsing of the struct).
13448     if (TUK == TUK_Definition) {
13449       AddAlignmentAttributesForRecord(RD);
13450       AddMsStructLayoutForRecord(RD);
13451     }
13452   }
13453
13454   if (ModulePrivateLoc.isValid()) {
13455     if (isExplicitSpecialization)
13456       Diag(New->getLocation(), diag::err_module_private_specialization)
13457         << 2
13458         << FixItHint::CreateRemoval(ModulePrivateLoc);
13459     // __module_private__ does not apply to local classes. However, we only
13460     // diagnose this as an error when the declaration specifiers are
13461     // freestanding. Here, we just ignore the __module_private__.
13462     else if (!SearchDC->isFunctionOrMethod())
13463       New->setModulePrivate();
13464   }
13465
13466   // If this is a specialization of a member class (of a class template),
13467   // check the specialization.
13468   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13469     Invalid = true;
13470
13471   // If we're declaring or defining a tag in function prototype scope in C,
13472   // note that this type can only be used within the function and add it to
13473   // the list of decls to inject into the function definition scope.
13474   if ((Name || Kind == TTK_Enum) &&
13475       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13476     if (getLangOpts().CPlusPlus) {
13477       // C++ [dcl.fct]p6:
13478       //   Types shall not be defined in return or parameter types.
13479       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13480         Diag(Loc, diag::err_type_defined_in_param_type)
13481             << Name;
13482         Invalid = true;
13483       }
13484     } else if (!PrevDecl) {
13485       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13486     }
13487   }
13488
13489   if (Invalid)
13490     New->setInvalidDecl();
13491
13492   if (Attr)
13493     ProcessDeclAttributeList(S, New, Attr);
13494
13495   // Set the lexical context. If the tag has a C++ scope specifier, the
13496   // lexical context will be different from the semantic context.
13497   New->setLexicalDeclContext(CurContext);
13498
13499   // Mark this as a friend decl if applicable.
13500   // In Microsoft mode, a friend declaration also acts as a forward
13501   // declaration so we always pass true to setObjectOfFriendDecl to make
13502   // the tag name visible.
13503   if (TUK == TUK_Friend)
13504     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13505
13506   // Set the access specifier.
13507   if (!Invalid && SearchDC->isRecord())
13508     SetMemberAccessSpecifier(New, PrevDecl, AS);
13509
13510   if (TUK == TUK_Definition)
13511     New->startDefinition();
13512
13513   // If this has an identifier, add it to the scope stack.
13514   if (TUK == TUK_Friend) {
13515     // We might be replacing an existing declaration in the lookup tables;
13516     // if so, borrow its access specifier.
13517     if (PrevDecl)
13518       New->setAccess(PrevDecl->getAccess());
13519
13520     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13521     DC->makeDeclVisibleInContext(New);
13522     if (Name) // can be null along some error paths
13523       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13524         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13525   } else if (Name) {
13526     S = getNonFieldDeclScope(S);
13527     PushOnScopeChains(New, S, !IsForwardReference);
13528     if (IsForwardReference)
13529       SearchDC->makeDeclVisibleInContext(New);
13530   } else {
13531     CurContext->addDecl(New);
13532   }
13533
13534   // If this is the C FILE type, notify the AST context.
13535   if (IdentifierInfo *II = New->getIdentifier())
13536     if (!New->isInvalidDecl() &&
13537         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13538         II->isStr("FILE"))
13539       Context.setFILEDecl(New);
13540
13541   if (PrevDecl)
13542     mergeDeclAttributes(New, PrevDecl);
13543
13544   // If there's a #pragma GCC visibility in scope, set the visibility of this
13545   // record.
13546   AddPushedVisibilityAttribute(New);
13547
13548   OwnedDecl = true;
13549   // In C++, don't return an invalid declaration. We can't recover well from
13550   // the cases where we make the type anonymous.
13551   if (Invalid && getLangOpts().CPlusPlus) {
13552     if (New->isBeingDefined())
13553       if (auto RD = dyn_cast<RecordDecl>(New))
13554         RD->completeDefinition();
13555     return nullptr;
13556   } else {
13557     return New;
13558   }
13559 }
13560
13561 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13562   AdjustDeclIfTemplate(TagD);
13563   TagDecl *Tag = cast<TagDecl>(TagD);
13564
13565   // Enter the tag context.
13566   PushDeclContext(S, Tag);
13567
13568   ActOnDocumentableDecl(TagD);
13569
13570   // If there's a #pragma GCC visibility in scope, set the visibility of this
13571   // record.
13572   AddPushedVisibilityAttribute(Tag);
13573 }
13574
13575 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13576   assert(isa<ObjCContainerDecl>(IDecl) &&
13577          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13578   DeclContext *OCD = cast<DeclContext>(IDecl);
13579   assert(getContainingDC(OCD) == CurContext &&
13580       "The next DeclContext should be lexically contained in the current one.");
13581   CurContext = OCD;
13582   return IDecl;
13583 }
13584
13585 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13586                                            SourceLocation FinalLoc,
13587                                            bool IsFinalSpelledSealed,
13588                                            SourceLocation LBraceLoc) {
13589   AdjustDeclIfTemplate(TagD);
13590   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13591
13592   FieldCollector->StartClass();
13593
13594   if (!Record->getIdentifier())
13595     return;
13596
13597   if (FinalLoc.isValid())
13598     Record->addAttr(new (Context)
13599                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13600
13601   // C++ [class]p2:
13602   //   [...] The class-name is also inserted into the scope of the
13603   //   class itself; this is known as the injected-class-name. For
13604   //   purposes of access checking, the injected-class-name is treated
13605   //   as if it were a public member name.
13606   CXXRecordDecl *InjectedClassName
13607     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13608                             Record->getLocStart(), Record->getLocation(),
13609                             Record->getIdentifier(),
13610                             /*PrevDecl=*/nullptr,
13611                             /*DelayTypeCreation=*/true);
13612   Context.getTypeDeclType(InjectedClassName, Record);
13613   InjectedClassName->setImplicit();
13614   InjectedClassName->setAccess(AS_public);
13615   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13616       InjectedClassName->setDescribedClassTemplate(Template);
13617   PushOnScopeChains(InjectedClassName, S);
13618   assert(InjectedClassName->isInjectedClassName() &&
13619          "Broken injected-class-name");
13620 }
13621
13622 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13623                                     SourceRange BraceRange) {
13624   AdjustDeclIfTemplate(TagD);
13625   TagDecl *Tag = cast<TagDecl>(TagD);
13626   Tag->setBraceRange(BraceRange);
13627
13628   // Make sure we "complete" the definition even it is invalid.
13629   if (Tag->isBeingDefined()) {
13630     assert(Tag->isInvalidDecl() && "We should already have completed it");
13631     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13632       RD->completeDefinition();
13633   }
13634
13635   if (isa<CXXRecordDecl>(Tag))
13636     FieldCollector->FinishClass();
13637
13638   // Exit this scope of this tag's definition.
13639   PopDeclContext();
13640
13641   if (getCurLexicalContext()->isObjCContainer() &&
13642       Tag->getDeclContext()->isFileContext())
13643     Tag->setTopLevelDeclInObjCContainer();
13644
13645   // Notify the consumer that we've defined a tag.
13646   if (!Tag->isInvalidDecl())
13647     Consumer.HandleTagDeclDefinition(Tag);
13648 }
13649
13650 void Sema::ActOnObjCContainerFinishDefinition() {
13651   // Exit this scope of this interface definition.
13652   PopDeclContext();
13653 }
13654
13655 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13656   assert(DC == CurContext && "Mismatch of container contexts");
13657   OriginalLexicalContext = DC;
13658   ActOnObjCContainerFinishDefinition();
13659 }
13660
13661 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13662   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13663   OriginalLexicalContext = nullptr;
13664 }
13665
13666 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13667   AdjustDeclIfTemplate(TagD);
13668   TagDecl *Tag = cast<TagDecl>(TagD);
13669   Tag->setInvalidDecl();
13670
13671   // Make sure we "complete" the definition even it is invalid.
13672   if (Tag->isBeingDefined()) {
13673     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13674       RD->completeDefinition();
13675   }
13676
13677   // We're undoing ActOnTagStartDefinition here, not
13678   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13679   // the FieldCollector.
13680
13681   PopDeclContext();
13682 }
13683
13684 // Note that FieldName may be null for anonymous bitfields.
13685 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13686                                 IdentifierInfo *FieldName,
13687                                 QualType FieldTy, bool IsMsStruct,
13688                                 Expr *BitWidth, bool *ZeroWidth) {
13689   // Default to true; that shouldn't confuse checks for emptiness
13690   if (ZeroWidth)
13691     *ZeroWidth = true;
13692
13693   // C99 6.7.2.1p4 - verify the field type.
13694   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13695   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13696     // Handle incomplete types with specific error.
13697     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13698       return ExprError();
13699     if (FieldName)
13700       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13701         << FieldName << FieldTy << BitWidth->getSourceRange();
13702     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13703       << FieldTy << BitWidth->getSourceRange();
13704   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13705                                              UPPC_BitFieldWidth))
13706     return ExprError();
13707
13708   // If the bit-width is type- or value-dependent, don't try to check
13709   // it now.
13710   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13711     return BitWidth;
13712
13713   llvm::APSInt Value;
13714   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13715   if (ICE.isInvalid())
13716     return ICE;
13717   BitWidth = ICE.get();
13718
13719   if (Value != 0 && ZeroWidth)
13720     *ZeroWidth = false;
13721
13722   // Zero-width bitfield is ok for anonymous field.
13723   if (Value == 0 && FieldName)
13724     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13725
13726   if (Value.isSigned() && Value.isNegative()) {
13727     if (FieldName)
13728       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13729                << FieldName << Value.toString(10);
13730     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13731       << Value.toString(10);
13732   }
13733
13734   if (!FieldTy->isDependentType()) {
13735     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13736     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13737     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13738
13739     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13740     // ABI.
13741     bool CStdConstraintViolation =
13742         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13743     bool MSBitfieldViolation =
13744         Value.ugt(TypeStorageSize) &&
13745         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13746     if (CStdConstraintViolation || MSBitfieldViolation) {
13747       unsigned DiagWidth =
13748           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13749       if (FieldName)
13750         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13751                << FieldName << (unsigned)Value.getZExtValue()
13752                << !CStdConstraintViolation << DiagWidth;
13753
13754       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13755              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13756              << DiagWidth;
13757     }
13758
13759     // Warn on types where the user might conceivably expect to get all
13760     // specified bits as value bits: that's all integral types other than
13761     // 'bool'.
13762     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13763       if (FieldName)
13764         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13765             << FieldName << (unsigned)Value.getZExtValue()
13766             << (unsigned)TypeWidth;
13767       else
13768         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13769             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13770     }
13771   }
13772
13773   return BitWidth;
13774 }
13775
13776 /// ActOnField - Each field of a C struct/union is passed into this in order
13777 /// to create a FieldDecl object for it.
13778 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13779                        Declarator &D, Expr *BitfieldWidth) {
13780   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13781                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13782                                /*InitStyle=*/ICIS_NoInit, AS_public);
13783   return Res;
13784 }
13785
13786 /// HandleField - Analyze a field of a C struct or a C++ data member.
13787 ///
13788 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13789                              SourceLocation DeclStart,
13790                              Declarator &D, Expr *BitWidth,
13791                              InClassInitStyle InitStyle,
13792                              AccessSpecifier AS) {
13793   if (D.isDecompositionDeclarator()) {
13794     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13795     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13796       << Decomp.getSourceRange();
13797     return nullptr;
13798   }
13799
13800   IdentifierInfo *II = D.getIdentifier();
13801   SourceLocation Loc = DeclStart;
13802   if (II) Loc = D.getIdentifierLoc();
13803
13804   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13805   QualType T = TInfo->getType();
13806   if (getLangOpts().CPlusPlus) {
13807     CheckExtraCXXDefaultArguments(D);
13808
13809     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13810                                         UPPC_DataMemberType)) {
13811       D.setInvalidType();
13812       T = Context.IntTy;
13813       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13814     }
13815   }
13816
13817   // TR 18037 does not allow fields to be declared with address spaces.
13818   if (T.getQualifiers().hasAddressSpace()) {
13819     Diag(Loc, diag::err_field_with_address_space);
13820     D.setInvalidType();
13821   }
13822
13823   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13824   // used as structure or union field: image, sampler, event or block types.
13825   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13826                           T->isSamplerT() || T->isBlockPointerType())) {
13827     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13828     D.setInvalidType();
13829   }
13830
13831   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13832
13833   if (D.getDeclSpec().isInlineSpecified())
13834     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13835         << getLangOpts().CPlusPlus1z;
13836   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13837     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13838          diag::err_invalid_thread)
13839       << DeclSpec::getSpecifierName(TSCS);
13840
13841   // Check to see if this name was declared as a member previously
13842   NamedDecl *PrevDecl = nullptr;
13843   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13844   LookupName(Previous, S);
13845   switch (Previous.getResultKind()) {
13846     case LookupResult::Found:
13847     case LookupResult::FoundUnresolvedValue:
13848       PrevDecl = Previous.getAsSingle<NamedDecl>();
13849       break;
13850
13851     case LookupResult::FoundOverloaded:
13852       PrevDecl = Previous.getRepresentativeDecl();
13853       break;
13854
13855     case LookupResult::NotFound:
13856     case LookupResult::NotFoundInCurrentInstantiation:
13857     case LookupResult::Ambiguous:
13858       break;
13859   }
13860   Previous.suppressDiagnostics();
13861
13862   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13863     // Maybe we will complain about the shadowed template parameter.
13864     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13865     // Just pretend that we didn't see the previous declaration.
13866     PrevDecl = nullptr;
13867   }
13868
13869   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13870     PrevDecl = nullptr;
13871
13872   bool Mutable
13873     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13874   SourceLocation TSSL = D.getLocStart();
13875   FieldDecl *NewFD
13876     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13877                      TSSL, AS, PrevDecl, &D);
13878
13879   if (NewFD->isInvalidDecl())
13880     Record->setInvalidDecl();
13881
13882   if (D.getDeclSpec().isModulePrivateSpecified())
13883     NewFD->setModulePrivate();
13884
13885   if (NewFD->isInvalidDecl() && PrevDecl) {
13886     // Don't introduce NewFD into scope; there's already something
13887     // with the same name in the same scope.
13888   } else if (II) {
13889     PushOnScopeChains(NewFD, S);
13890   } else
13891     Record->addDecl(NewFD);
13892
13893   return NewFD;
13894 }
13895
13896 /// \brief Build a new FieldDecl and check its well-formedness.
13897 ///
13898 /// This routine builds a new FieldDecl given the fields name, type,
13899 /// record, etc. \p PrevDecl should refer to any previous declaration
13900 /// with the same name and in the same scope as the field to be
13901 /// created.
13902 ///
13903 /// \returns a new FieldDecl.
13904 ///
13905 /// \todo The Declarator argument is a hack. It will be removed once
13906 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13907                                 TypeSourceInfo *TInfo,
13908                                 RecordDecl *Record, SourceLocation Loc,
13909                                 bool Mutable, Expr *BitWidth,
13910                                 InClassInitStyle InitStyle,
13911                                 SourceLocation TSSL,
13912                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13913                                 Declarator *D) {
13914   IdentifierInfo *II = Name.getAsIdentifierInfo();
13915   bool InvalidDecl = false;
13916   if (D) InvalidDecl = D->isInvalidType();
13917
13918   // If we receive a broken type, recover by assuming 'int' and
13919   // marking this declaration as invalid.
13920   if (T.isNull()) {
13921     InvalidDecl = true;
13922     T = Context.IntTy;
13923   }
13924
13925   QualType EltTy = Context.getBaseElementType(T);
13926   if (!EltTy->isDependentType()) {
13927     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13928       // Fields of incomplete type force their record to be invalid.
13929       Record->setInvalidDecl();
13930       InvalidDecl = true;
13931     } else {
13932       NamedDecl *Def;
13933       EltTy->isIncompleteType(&Def);
13934       if (Def && Def->isInvalidDecl()) {
13935         Record->setInvalidDecl();
13936         InvalidDecl = true;
13937       }
13938     }
13939   }
13940
13941   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13942   if (BitWidth && getLangOpts().OpenCL) {
13943     Diag(Loc, diag::err_opencl_bitfields);
13944     InvalidDecl = true;
13945   }
13946
13947   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13948   // than a variably modified type.
13949   if (!InvalidDecl && T->isVariablyModifiedType()) {
13950     bool SizeIsNegative;
13951     llvm::APSInt Oversized;
13952
13953     TypeSourceInfo *FixedTInfo =
13954       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13955                                                     SizeIsNegative,
13956                                                     Oversized);
13957     if (FixedTInfo) {
13958       Diag(Loc, diag::warn_illegal_constant_array_size);
13959       TInfo = FixedTInfo;
13960       T = FixedTInfo->getType();
13961     } else {
13962       if (SizeIsNegative)
13963         Diag(Loc, diag::err_typecheck_negative_array_size);
13964       else if (Oversized.getBoolValue())
13965         Diag(Loc, diag::err_array_too_large)
13966           << Oversized.toString(10);
13967       else
13968         Diag(Loc, diag::err_typecheck_field_variable_size);
13969       InvalidDecl = true;
13970     }
13971   }
13972
13973   // Fields can not have abstract class types
13974   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13975                                              diag::err_abstract_type_in_decl,
13976                                              AbstractFieldType))
13977     InvalidDecl = true;
13978
13979   bool ZeroWidth = false;
13980   if (InvalidDecl)
13981     BitWidth = nullptr;
13982   // If this is declared as a bit-field, check the bit-field.
13983   if (BitWidth) {
13984     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13985                               &ZeroWidth).get();
13986     if (!BitWidth) {
13987       InvalidDecl = true;
13988       BitWidth = nullptr;
13989       ZeroWidth = false;
13990     }
13991   }
13992
13993   // Check that 'mutable' is consistent with the type of the declaration.
13994   if (!InvalidDecl && Mutable) {
13995     unsigned DiagID = 0;
13996     if (T->isReferenceType())
13997       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13998                                         : diag::err_mutable_reference;
13999     else if (T.isConstQualified())
14000       DiagID = diag::err_mutable_const;
14001
14002     if (DiagID) {
14003       SourceLocation ErrLoc = Loc;
14004       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14005         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14006       Diag(ErrLoc, DiagID);
14007       if (DiagID != diag::ext_mutable_reference) {
14008         Mutable = false;
14009         InvalidDecl = true;
14010       }
14011     }
14012   }
14013
14014   // C++11 [class.union]p8 (DR1460):
14015   //   At most one variant member of a union may have a
14016   //   brace-or-equal-initializer.
14017   if (InitStyle != ICIS_NoInit)
14018     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14019
14020   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14021                                        BitWidth, Mutable, InitStyle);
14022   if (InvalidDecl)
14023     NewFD->setInvalidDecl();
14024
14025   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14026     Diag(Loc, diag::err_duplicate_member) << II;
14027     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14028     NewFD->setInvalidDecl();
14029   }
14030
14031   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14032     if (Record->isUnion()) {
14033       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14034         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14035         if (RDecl->getDefinition()) {
14036           // C++ [class.union]p1: An object of a class with a non-trivial
14037           // constructor, a non-trivial copy constructor, a non-trivial
14038           // destructor, or a non-trivial copy assignment operator
14039           // cannot be a member of a union, nor can an array of such
14040           // objects.
14041           if (CheckNontrivialField(NewFD))
14042             NewFD->setInvalidDecl();
14043         }
14044       }
14045
14046       // C++ [class.union]p1: If a union contains a member of reference type,
14047       // the program is ill-formed, except when compiling with MSVC extensions
14048       // enabled.
14049       if (EltTy->isReferenceType()) {
14050         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14051                                     diag::ext_union_member_of_reference_type :
14052                                     diag::err_union_member_of_reference_type)
14053           << NewFD->getDeclName() << EltTy;
14054         if (!getLangOpts().MicrosoftExt)
14055           NewFD->setInvalidDecl();
14056       }
14057     }
14058   }
14059
14060   // FIXME: We need to pass in the attributes given an AST
14061   // representation, not a parser representation.
14062   if (D) {
14063     // FIXME: The current scope is almost... but not entirely... correct here.
14064     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14065
14066     if (NewFD->hasAttrs())
14067       CheckAlignasUnderalignment(NewFD);
14068   }
14069
14070   // In auto-retain/release, infer strong retension for fields of
14071   // retainable type.
14072   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14073     NewFD->setInvalidDecl();
14074
14075   if (T.isObjCGCWeak())
14076     Diag(Loc, diag::warn_attribute_weak_on_field);
14077
14078   NewFD->setAccess(AS);
14079   return NewFD;
14080 }
14081
14082 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14083   assert(FD);
14084   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14085
14086   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14087     return false;
14088
14089   QualType EltTy = Context.getBaseElementType(FD->getType());
14090   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14091     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14092     if (RDecl->getDefinition()) {
14093       // We check for copy constructors before constructors
14094       // because otherwise we'll never get complaints about
14095       // copy constructors.
14096
14097       CXXSpecialMember member = CXXInvalid;
14098       // We're required to check for any non-trivial constructors. Since the
14099       // implicit default constructor is suppressed if there are any
14100       // user-declared constructors, we just need to check that there is a
14101       // trivial default constructor and a trivial copy constructor. (We don't
14102       // worry about move constructors here, since this is a C++98 check.)
14103       if (RDecl->hasNonTrivialCopyConstructor())
14104         member = CXXCopyConstructor;
14105       else if (!RDecl->hasTrivialDefaultConstructor())
14106         member = CXXDefaultConstructor;
14107       else if (RDecl->hasNonTrivialCopyAssignment())
14108         member = CXXCopyAssignment;
14109       else if (RDecl->hasNonTrivialDestructor())
14110         member = CXXDestructor;
14111
14112       if (member != CXXInvalid) {
14113         if (!getLangOpts().CPlusPlus11 &&
14114             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14115           // Objective-C++ ARC: it is an error to have a non-trivial field of
14116           // a union. However, system headers in Objective-C programs
14117           // occasionally have Objective-C lifetime objects within unions,
14118           // and rather than cause the program to fail, we make those
14119           // members unavailable.
14120           SourceLocation Loc = FD->getLocation();
14121           if (getSourceManager().isInSystemHeader(Loc)) {
14122             if (!FD->hasAttr<UnavailableAttr>())
14123               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14124                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14125             return false;
14126           }
14127         }
14128
14129         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14130                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14131                diag::err_illegal_union_or_anon_struct_member)
14132           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14133         DiagnoseNontrivial(RDecl, member);
14134         return !getLangOpts().CPlusPlus11;
14135       }
14136     }
14137   }
14138
14139   return false;
14140 }
14141
14142 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14143 ///  AST enum value.
14144 static ObjCIvarDecl::AccessControl
14145 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14146   switch (ivarVisibility) {
14147   default: llvm_unreachable("Unknown visitibility kind");
14148   case tok::objc_private: return ObjCIvarDecl::Private;
14149   case tok::objc_public: return ObjCIvarDecl::Public;
14150   case tok::objc_protected: return ObjCIvarDecl::Protected;
14151   case tok::objc_package: return ObjCIvarDecl::Package;
14152   }
14153 }
14154
14155 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14156 /// in order to create an IvarDecl object for it.
14157 Decl *Sema::ActOnIvar(Scope *S,
14158                                 SourceLocation DeclStart,
14159                                 Declarator &D, Expr *BitfieldWidth,
14160                                 tok::ObjCKeywordKind Visibility) {
14161
14162   IdentifierInfo *II = D.getIdentifier();
14163   Expr *BitWidth = (Expr*)BitfieldWidth;
14164   SourceLocation Loc = DeclStart;
14165   if (II) Loc = D.getIdentifierLoc();
14166
14167   // FIXME: Unnamed fields can be handled in various different ways, for
14168   // example, unnamed unions inject all members into the struct namespace!
14169
14170   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14171   QualType T = TInfo->getType();
14172
14173   if (BitWidth) {
14174     // 6.7.2.1p3, 6.7.2.1p4
14175     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14176     if (!BitWidth)
14177       D.setInvalidType();
14178   } else {
14179     // Not a bitfield.
14180
14181     // validate II.
14182
14183   }
14184   if (T->isReferenceType()) {
14185     Diag(Loc, diag::err_ivar_reference_type);
14186     D.setInvalidType();
14187   }
14188   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14189   // than a variably modified type.
14190   else if (T->isVariablyModifiedType()) {
14191     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14192     D.setInvalidType();
14193   }
14194
14195   // Get the visibility (access control) for this ivar.
14196   ObjCIvarDecl::AccessControl ac =
14197     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14198                                         : ObjCIvarDecl::None;
14199   // Must set ivar's DeclContext to its enclosing interface.
14200   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14201   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14202     return nullptr;
14203   ObjCContainerDecl *EnclosingContext;
14204   if (ObjCImplementationDecl *IMPDecl =
14205       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14206     if (LangOpts.ObjCRuntime.isFragile()) {
14207     // Case of ivar declared in an implementation. Context is that of its class.
14208       EnclosingContext = IMPDecl->getClassInterface();
14209       assert(EnclosingContext && "Implementation has no class interface!");
14210     }
14211     else
14212       EnclosingContext = EnclosingDecl;
14213   } else {
14214     if (ObjCCategoryDecl *CDecl =
14215         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14216       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14217         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14218         return nullptr;
14219       }
14220     }
14221     EnclosingContext = EnclosingDecl;
14222   }
14223
14224   // Construct the decl.
14225   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14226                                              DeclStart, Loc, II, T,
14227                                              TInfo, ac, (Expr *)BitfieldWidth);
14228
14229   if (II) {
14230     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14231                                            ForRedeclaration);
14232     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14233         && !isa<TagDecl>(PrevDecl)) {
14234       Diag(Loc, diag::err_duplicate_member) << II;
14235       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14236       NewID->setInvalidDecl();
14237     }
14238   }
14239
14240   // Process attributes attached to the ivar.
14241   ProcessDeclAttributes(S, NewID, D);
14242
14243   if (D.isInvalidType())
14244     NewID->setInvalidDecl();
14245
14246   // In ARC, infer 'retaining' for ivars of retainable type.
14247   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14248     NewID->setInvalidDecl();
14249
14250   if (D.getDeclSpec().isModulePrivateSpecified())
14251     NewID->setModulePrivate();
14252
14253   if (II) {
14254     // FIXME: When interfaces are DeclContexts, we'll need to add
14255     // these to the interface.
14256     S->AddDecl(NewID);
14257     IdResolver.AddDecl(NewID);
14258   }
14259
14260   if (LangOpts.ObjCRuntime.isNonFragile() &&
14261       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14262     Diag(Loc, diag::warn_ivars_in_interface);
14263
14264   return NewID;
14265 }
14266
14267 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14268 /// class and class extensions. For every class \@interface and class
14269 /// extension \@interface, if the last ivar is a bitfield of any type,
14270 /// then add an implicit `char :0` ivar to the end of that interface.
14271 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14272                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14273   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14274     return;
14275
14276   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14277   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14278
14279   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14280     return;
14281   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14282   if (!ID) {
14283     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14284       if (!CD->IsClassExtension())
14285         return;
14286     }
14287     // No need to add this to end of @implementation.
14288     else
14289       return;
14290   }
14291   // All conditions are met. Add a new bitfield to the tail end of ivars.
14292   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14293   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14294
14295   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14296                               DeclLoc, DeclLoc, nullptr,
14297                               Context.CharTy,
14298                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14299                                                                DeclLoc),
14300                               ObjCIvarDecl::Private, BW,
14301                               true);
14302   AllIvarDecls.push_back(Ivar);
14303 }
14304
14305 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14306                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14307                        SourceLocation RBrac, AttributeList *Attr) {
14308   assert(EnclosingDecl && "missing record or interface decl");
14309
14310   // If this is an Objective-C @implementation or category and we have
14311   // new fields here we should reset the layout of the interface since
14312   // it will now change.
14313   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14314     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14315     switch (DC->getKind()) {
14316     default: break;
14317     case Decl::ObjCCategory:
14318       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14319       break;
14320     case Decl::ObjCImplementation:
14321       Context.
14322         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14323       break;
14324     }
14325   }
14326
14327   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14328
14329   // Start counting up the number of named members; make sure to include
14330   // members of anonymous structs and unions in the total.
14331   unsigned NumNamedMembers = 0;
14332   if (Record) {
14333     for (const auto *I : Record->decls()) {
14334       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14335         if (IFD->getDeclName())
14336           ++NumNamedMembers;
14337     }
14338   }
14339
14340   // Verify that all the fields are okay.
14341   SmallVector<FieldDecl*, 32> RecFields;
14342
14343   bool ARCErrReported = false;
14344   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14345        i != end; ++i) {
14346     FieldDecl *FD = cast<FieldDecl>(*i);
14347
14348     // Get the type for the field.
14349     const Type *FDTy = FD->getType().getTypePtr();
14350
14351     if (!FD->isAnonymousStructOrUnion()) {
14352       // Remember all fields written by the user.
14353       RecFields.push_back(FD);
14354     }
14355
14356     // If the field is already invalid for some reason, don't emit more
14357     // diagnostics about it.
14358     if (FD->isInvalidDecl()) {
14359       EnclosingDecl->setInvalidDecl();
14360       continue;
14361     }
14362
14363     // C99 6.7.2.1p2:
14364     //   A structure or union shall not contain a member with
14365     //   incomplete or function type (hence, a structure shall not
14366     //   contain an instance of itself, but may contain a pointer to
14367     //   an instance of itself), except that the last member of a
14368     //   structure with more than one named member may have incomplete
14369     //   array type; such a structure (and any union containing,
14370     //   possibly recursively, a member that is such a structure)
14371     //   shall not be a member of a structure or an element of an
14372     //   array.
14373     if (FDTy->isFunctionType()) {
14374       // Field declared as a function.
14375       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14376         << FD->getDeclName();
14377       FD->setInvalidDecl();
14378       EnclosingDecl->setInvalidDecl();
14379       continue;
14380     } else if (FDTy->isIncompleteArrayType() && Record &&
14381                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14382                 ((getLangOpts().MicrosoftExt ||
14383                   getLangOpts().CPlusPlus) &&
14384                  (i + 1 == Fields.end() || Record->isUnion())))) {
14385       // Flexible array member.
14386       // Microsoft and g++ is more permissive regarding flexible array.
14387       // It will accept flexible array in union and also
14388       // as the sole element of a struct/class.
14389       unsigned DiagID = 0;
14390       if (Record->isUnion())
14391         DiagID = getLangOpts().MicrosoftExt
14392                      ? diag::ext_flexible_array_union_ms
14393                      : getLangOpts().CPlusPlus
14394                            ? diag::ext_flexible_array_union_gnu
14395                            : diag::err_flexible_array_union;
14396       else if (NumNamedMembers < 1)
14397         DiagID = getLangOpts().MicrosoftExt
14398                      ? diag::ext_flexible_array_empty_aggregate_ms
14399                      : getLangOpts().CPlusPlus
14400                            ? diag::ext_flexible_array_empty_aggregate_gnu
14401                            : diag::err_flexible_array_empty_aggregate;
14402
14403       if (DiagID)
14404         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14405                                         << Record->getTagKind();
14406       // While the layout of types that contain virtual bases is not specified
14407       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14408       // virtual bases after the derived members.  This would make a flexible
14409       // array member declared at the end of an object not adjacent to the end
14410       // of the type.
14411       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14412         if (RD->getNumVBases() != 0)
14413           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14414             << FD->getDeclName() << Record->getTagKind();
14415       if (!getLangOpts().C99)
14416         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14417           << FD->getDeclName() << Record->getTagKind();
14418
14419       // If the element type has a non-trivial destructor, we would not
14420       // implicitly destroy the elements, so disallow it for now.
14421       //
14422       // FIXME: GCC allows this. We should probably either implicitly delete
14423       // the destructor of the containing class, or just allow this.
14424       QualType BaseElem = Context.getBaseElementType(FD->getType());
14425       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14426         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14427           << FD->getDeclName() << FD->getType();
14428         FD->setInvalidDecl();
14429         EnclosingDecl->setInvalidDecl();
14430         continue;
14431       }
14432       // Okay, we have a legal flexible array member at the end of the struct.
14433       Record->setHasFlexibleArrayMember(true);
14434     } else if (!FDTy->isDependentType() &&
14435                RequireCompleteType(FD->getLocation(), FD->getType(),
14436                                    diag::err_field_incomplete)) {
14437       // Incomplete type
14438       FD->setInvalidDecl();
14439       EnclosingDecl->setInvalidDecl();
14440       continue;
14441     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14442       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14443         // A type which contains a flexible array member is considered to be a
14444         // flexible array member.
14445         Record->setHasFlexibleArrayMember(true);
14446         if (!Record->isUnion()) {
14447           // If this is a struct/class and this is not the last element, reject
14448           // it.  Note that GCC supports variable sized arrays in the middle of
14449           // structures.
14450           if (i + 1 != Fields.end())
14451             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14452               << FD->getDeclName() << FD->getType();
14453           else {
14454             // We support flexible arrays at the end of structs in
14455             // other structs as an extension.
14456             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14457               << FD->getDeclName();
14458           }
14459         }
14460       }
14461       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14462           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14463                                  diag::err_abstract_type_in_decl,
14464                                  AbstractIvarType)) {
14465         // Ivars can not have abstract class types
14466         FD->setInvalidDecl();
14467       }
14468       if (Record && FDTTy->getDecl()->hasObjectMember())
14469         Record->setHasObjectMember(true);
14470       if (Record && FDTTy->getDecl()->hasVolatileMember())
14471         Record->setHasVolatileMember(true);
14472     } else if (FDTy->isObjCObjectType()) {
14473       /// A field cannot be an Objective-c object
14474       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14475         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14476       QualType T = Context.getObjCObjectPointerType(FD->getType());
14477       FD->setType(T);
14478     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14479                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14480       // It's an error in ARC if a field has lifetime.
14481       // We don't want to report this in a system header, though,
14482       // so we just make the field unavailable.
14483       // FIXME: that's really not sufficient; we need to make the type
14484       // itself invalid to, say, initialize or copy.
14485       QualType T = FD->getType();
14486       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14487       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14488         SourceLocation loc = FD->getLocation();
14489         if (getSourceManager().isInSystemHeader(loc)) {
14490           if (!FD->hasAttr<UnavailableAttr>()) {
14491             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14492                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14493           }
14494         } else {
14495           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14496             << T->isBlockPointerType() << Record->getTagKind();
14497         }
14498         ARCErrReported = true;
14499       }
14500     } else if (getLangOpts().ObjC1 &&
14501                getLangOpts().getGC() != LangOptions::NonGC &&
14502                Record && !Record->hasObjectMember()) {
14503       if (FD->getType()->isObjCObjectPointerType() ||
14504           FD->getType().isObjCGCStrong())
14505         Record->setHasObjectMember(true);
14506       else if (Context.getAsArrayType(FD->getType())) {
14507         QualType BaseType = Context.getBaseElementType(FD->getType());
14508         if (BaseType->isRecordType() &&
14509             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14510           Record->setHasObjectMember(true);
14511         else if (BaseType->isObjCObjectPointerType() ||
14512                  BaseType.isObjCGCStrong())
14513                Record->setHasObjectMember(true);
14514       }
14515     }
14516     if (Record && FD->getType().isVolatileQualified())
14517       Record->setHasVolatileMember(true);
14518     // Keep track of the number of named members.
14519     if (FD->getIdentifier())
14520       ++NumNamedMembers;
14521   }
14522
14523   // Okay, we successfully defined 'Record'.
14524   if (Record) {
14525     bool Completed = false;
14526     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14527       if (!CXXRecord->isInvalidDecl()) {
14528         // Set access bits correctly on the directly-declared conversions.
14529         for (CXXRecordDecl::conversion_iterator
14530                I = CXXRecord->conversion_begin(),
14531                E = CXXRecord->conversion_end(); I != E; ++I)
14532           I.setAccess((*I)->getAccess());
14533       }
14534
14535       if (!CXXRecord->isDependentType()) {
14536         if (CXXRecord->hasUserDeclaredDestructor()) {
14537           // Adjust user-defined destructor exception spec.
14538           if (getLangOpts().CPlusPlus11)
14539             AdjustDestructorExceptionSpec(CXXRecord,
14540                                           CXXRecord->getDestructor());
14541         }
14542
14543         if (!CXXRecord->isInvalidDecl()) {
14544           // Add any implicitly-declared members to this class.
14545           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14546
14547           // If we have virtual base classes, we may end up finding multiple
14548           // final overriders for a given virtual function. Check for this
14549           // problem now.
14550           if (CXXRecord->getNumVBases()) {
14551             CXXFinalOverriderMap FinalOverriders;
14552             CXXRecord->getFinalOverriders(FinalOverriders);
14553
14554             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14555                                              MEnd = FinalOverriders.end();
14556                  M != MEnd; ++M) {
14557               for (OverridingMethods::iterator SO = M->second.begin(),
14558                                             SOEnd = M->second.end();
14559                    SO != SOEnd; ++SO) {
14560                 assert(SO->second.size() > 0 &&
14561                        "Virtual function without overridding functions?");
14562                 if (SO->second.size() == 1)
14563                   continue;
14564
14565                 // C++ [class.virtual]p2:
14566                 //   In a derived class, if a virtual member function of a base
14567                 //   class subobject has more than one final overrider the
14568                 //   program is ill-formed.
14569                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14570                   << (const NamedDecl *)M->first << Record;
14571                 Diag(M->first->getLocation(),
14572                      diag::note_overridden_virtual_function);
14573                 for (OverridingMethods::overriding_iterator
14574                           OM = SO->second.begin(),
14575                        OMEnd = SO->second.end();
14576                      OM != OMEnd; ++OM)
14577                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14578                     << (const NamedDecl *)M->first << OM->Method->getParent();
14579
14580                 Record->setInvalidDecl();
14581               }
14582             }
14583             CXXRecord->completeDefinition(&FinalOverriders);
14584             Completed = true;
14585           }
14586         }
14587       }
14588     }
14589
14590     if (!Completed)
14591       Record->completeDefinition();
14592
14593     // We may have deferred checking for a deleted destructor. Check now.
14594     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14595       auto *Dtor = CXXRecord->getDestructor();
14596       if (Dtor && Dtor->isImplicit() &&
14597           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14598         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14599     }
14600
14601     if (Record->hasAttrs()) {
14602       CheckAlignasUnderalignment(Record);
14603
14604       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14605         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14606                                            IA->getRange(), IA->getBestCase(),
14607                                            IA->getSemanticSpelling());
14608     }
14609
14610     // Check if the structure/union declaration is a type that can have zero
14611     // size in C. For C this is a language extension, for C++ it may cause
14612     // compatibility problems.
14613     bool CheckForZeroSize;
14614     if (!getLangOpts().CPlusPlus) {
14615       CheckForZeroSize = true;
14616     } else {
14617       // For C++ filter out types that cannot be referenced in C code.
14618       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14619       CheckForZeroSize =
14620           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14621           !CXXRecord->isDependentType() &&
14622           CXXRecord->isCLike();
14623     }
14624     if (CheckForZeroSize) {
14625       bool ZeroSize = true;
14626       bool IsEmpty = true;
14627       unsigned NonBitFields = 0;
14628       for (RecordDecl::field_iterator I = Record->field_begin(),
14629                                       E = Record->field_end();
14630            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14631         IsEmpty = false;
14632         if (I->isUnnamedBitfield()) {
14633           if (I->getBitWidthValue(Context) > 0)
14634             ZeroSize = false;
14635         } else {
14636           ++NonBitFields;
14637           QualType FieldType = I->getType();
14638           if (FieldType->isIncompleteType() ||
14639               !Context.getTypeSizeInChars(FieldType).isZero())
14640             ZeroSize = false;
14641         }
14642       }
14643
14644       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14645       // allowed in C++, but warn if its declaration is inside
14646       // extern "C" block.
14647       if (ZeroSize) {
14648         Diag(RecLoc, getLangOpts().CPlusPlus ?
14649                          diag::warn_zero_size_struct_union_in_extern_c :
14650                          diag::warn_zero_size_struct_union_compat)
14651           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14652       }
14653
14654       // Structs without named members are extension in C (C99 6.7.2.1p7),
14655       // but are accepted by GCC.
14656       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14657         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14658                                diag::ext_no_named_members_in_struct_union)
14659           << Record->isUnion();
14660       }
14661     }
14662   } else {
14663     ObjCIvarDecl **ClsFields =
14664       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14665     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14666       ID->setEndOfDefinitionLoc(RBrac);
14667       // Add ivar's to class's DeclContext.
14668       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14669         ClsFields[i]->setLexicalDeclContext(ID);
14670         ID->addDecl(ClsFields[i]);
14671       }
14672       // Must enforce the rule that ivars in the base classes may not be
14673       // duplicates.
14674       if (ID->getSuperClass())
14675         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14676     } else if (ObjCImplementationDecl *IMPDecl =
14677                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14678       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14679       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14680         // Ivar declared in @implementation never belongs to the implementation.
14681         // Only it is in implementation's lexical context.
14682         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14683       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14684       IMPDecl->setIvarLBraceLoc(LBrac);
14685       IMPDecl->setIvarRBraceLoc(RBrac);
14686     } else if (ObjCCategoryDecl *CDecl =
14687                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14688       // case of ivars in class extension; all other cases have been
14689       // reported as errors elsewhere.
14690       // FIXME. Class extension does not have a LocEnd field.
14691       // CDecl->setLocEnd(RBrac);
14692       // Add ivar's to class extension's DeclContext.
14693       // Diagnose redeclaration of private ivars.
14694       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14695       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14696         if (IDecl) {
14697           if (const ObjCIvarDecl *ClsIvar =
14698               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14699             Diag(ClsFields[i]->getLocation(),
14700                  diag::err_duplicate_ivar_declaration);
14701             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14702             continue;
14703           }
14704           for (const auto *Ext : IDecl->known_extensions()) {
14705             if (const ObjCIvarDecl *ClsExtIvar
14706                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14707               Diag(ClsFields[i]->getLocation(),
14708                    diag::err_duplicate_ivar_declaration);
14709               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14710               continue;
14711             }
14712           }
14713         }
14714         ClsFields[i]->setLexicalDeclContext(CDecl);
14715         CDecl->addDecl(ClsFields[i]);
14716       }
14717       CDecl->setIvarLBraceLoc(LBrac);
14718       CDecl->setIvarRBraceLoc(RBrac);
14719     }
14720   }
14721
14722   if (Attr)
14723     ProcessDeclAttributeList(S, Record, Attr);
14724 }
14725
14726 /// \brief Determine whether the given integral value is representable within
14727 /// the given type T.
14728 static bool isRepresentableIntegerValue(ASTContext &Context,
14729                                         llvm::APSInt &Value,
14730                                         QualType T) {
14731   assert(T->isIntegralType(Context) && "Integral type required!");
14732   unsigned BitWidth = Context.getIntWidth(T);
14733
14734   if (Value.isUnsigned() || Value.isNonNegative()) {
14735     if (T->isSignedIntegerOrEnumerationType())
14736       --BitWidth;
14737     return Value.getActiveBits() <= BitWidth;
14738   }
14739   return Value.getMinSignedBits() <= BitWidth;
14740 }
14741
14742 // \brief Given an integral type, return the next larger integral type
14743 // (or a NULL type of no such type exists).
14744 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14745   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14746   // enum checking below.
14747   assert(T->isIntegralType(Context) && "Integral type required!");
14748   const unsigned NumTypes = 4;
14749   QualType SignedIntegralTypes[NumTypes] = {
14750     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14751   };
14752   QualType UnsignedIntegralTypes[NumTypes] = {
14753     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14754     Context.UnsignedLongLongTy
14755   };
14756
14757   unsigned BitWidth = Context.getTypeSize(T);
14758   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14759                                                         : UnsignedIntegralTypes;
14760   for (unsigned I = 0; I != NumTypes; ++I)
14761     if (Context.getTypeSize(Types[I]) > BitWidth)
14762       return Types[I];
14763
14764   return QualType();
14765 }
14766
14767 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14768                                           EnumConstantDecl *LastEnumConst,
14769                                           SourceLocation IdLoc,
14770                                           IdentifierInfo *Id,
14771                                           Expr *Val) {
14772   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14773   llvm::APSInt EnumVal(IntWidth);
14774   QualType EltTy;
14775
14776   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14777     Val = nullptr;
14778
14779   if (Val)
14780     Val = DefaultLvalueConversion(Val).get();
14781
14782   if (Val) {
14783     if (Enum->isDependentType() || Val->isTypeDependent())
14784       EltTy = Context.DependentTy;
14785     else {
14786       SourceLocation ExpLoc;
14787       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14788           !getLangOpts().MSVCCompat) {
14789         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14790         // constant-expression in the enumerator-definition shall be a converted
14791         // constant expression of the underlying type.
14792         EltTy = Enum->getIntegerType();
14793         ExprResult Converted =
14794           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14795                                            CCEK_Enumerator);
14796         if (Converted.isInvalid())
14797           Val = nullptr;
14798         else
14799           Val = Converted.get();
14800       } else if (!Val->isValueDependent() &&
14801                  !(Val = VerifyIntegerConstantExpression(Val,
14802                                                          &EnumVal).get())) {
14803         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14804       } else {
14805         if (Enum->isFixed()) {
14806           EltTy = Enum->getIntegerType();
14807
14808           // In Obj-C and Microsoft mode, require the enumeration value to be
14809           // representable in the underlying type of the enumeration. In C++11,
14810           // we perform a non-narrowing conversion as part of converted constant
14811           // expression checking.
14812           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14813             if (getLangOpts().MSVCCompat) {
14814               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14815               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14816             } else
14817               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14818           } else
14819             Val = ImpCastExprToType(Val, EltTy,
14820                                     EltTy->isBooleanType() ?
14821                                     CK_IntegralToBoolean : CK_IntegralCast)
14822                     .get();
14823         } else if (getLangOpts().CPlusPlus) {
14824           // C++11 [dcl.enum]p5:
14825           //   If the underlying type is not fixed, the type of each enumerator
14826           //   is the type of its initializing value:
14827           //     - If an initializer is specified for an enumerator, the
14828           //       initializing value has the same type as the expression.
14829           EltTy = Val->getType();
14830         } else {
14831           // C99 6.7.2.2p2:
14832           //   The expression that defines the value of an enumeration constant
14833           //   shall be an integer constant expression that has a value
14834           //   representable as an int.
14835
14836           // Complain if the value is not representable in an int.
14837           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14838             Diag(IdLoc, diag::ext_enum_value_not_int)
14839               << EnumVal.toString(10) << Val->getSourceRange()
14840               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14841           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14842             // Force the type of the expression to 'int'.
14843             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14844           }
14845           EltTy = Val->getType();
14846         }
14847       }
14848     }
14849   }
14850
14851   if (!Val) {
14852     if (Enum->isDependentType())
14853       EltTy = Context.DependentTy;
14854     else if (!LastEnumConst) {
14855       // C++0x [dcl.enum]p5:
14856       //   If the underlying type is not fixed, the type of each enumerator
14857       //   is the type of its initializing value:
14858       //     - If no initializer is specified for the first enumerator, the
14859       //       initializing value has an unspecified integral type.
14860       //
14861       // GCC uses 'int' for its unspecified integral type, as does
14862       // C99 6.7.2.2p3.
14863       if (Enum->isFixed()) {
14864         EltTy = Enum->getIntegerType();
14865       }
14866       else {
14867         EltTy = Context.IntTy;
14868       }
14869     } else {
14870       // Assign the last value + 1.
14871       EnumVal = LastEnumConst->getInitVal();
14872       ++EnumVal;
14873       EltTy = LastEnumConst->getType();
14874
14875       // Check for overflow on increment.
14876       if (EnumVal < LastEnumConst->getInitVal()) {
14877         // C++0x [dcl.enum]p5:
14878         //   If the underlying type is not fixed, the type of each enumerator
14879         //   is the type of its initializing value:
14880         //
14881         //     - Otherwise the type of the initializing value is the same as
14882         //       the type of the initializing value of the preceding enumerator
14883         //       unless the incremented value is not representable in that type,
14884         //       in which case the type is an unspecified integral type
14885         //       sufficient to contain the incremented value. If no such type
14886         //       exists, the program is ill-formed.
14887         QualType T = getNextLargerIntegralType(Context, EltTy);
14888         if (T.isNull() || Enum->isFixed()) {
14889           // There is no integral type larger enough to represent this
14890           // value. Complain, then allow the value to wrap around.
14891           EnumVal = LastEnumConst->getInitVal();
14892           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14893           ++EnumVal;
14894           if (Enum->isFixed())
14895             // When the underlying type is fixed, this is ill-formed.
14896             Diag(IdLoc, diag::err_enumerator_wrapped)
14897               << EnumVal.toString(10)
14898               << EltTy;
14899           else
14900             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14901               << EnumVal.toString(10);
14902         } else {
14903           EltTy = T;
14904         }
14905
14906         // Retrieve the last enumerator's value, extent that type to the
14907         // type that is supposed to be large enough to represent the incremented
14908         // value, then increment.
14909         EnumVal = LastEnumConst->getInitVal();
14910         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14911         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14912         ++EnumVal;
14913
14914         // If we're not in C++, diagnose the overflow of enumerator values,
14915         // which in C99 means that the enumerator value is not representable in
14916         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14917         // permits enumerator values that are representable in some larger
14918         // integral type.
14919         if (!getLangOpts().CPlusPlus && !T.isNull())
14920           Diag(IdLoc, diag::warn_enum_value_overflow);
14921       } else if (!getLangOpts().CPlusPlus &&
14922                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14923         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14924         Diag(IdLoc, diag::ext_enum_value_not_int)
14925           << EnumVal.toString(10) << 1;
14926       }
14927     }
14928   }
14929
14930   if (!EltTy->isDependentType()) {
14931     // Make the enumerator value match the signedness and size of the
14932     // enumerator's type.
14933     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14934     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14935   }
14936
14937   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14938                                   Val, EnumVal);
14939 }
14940
14941 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14942                                                 SourceLocation IILoc) {
14943   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14944       !getLangOpts().CPlusPlus)
14945     return SkipBodyInfo();
14946
14947   // We have an anonymous enum definition. Look up the first enumerator to
14948   // determine if we should merge the definition with an existing one and
14949   // skip the body.
14950   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14951                                          ForRedeclaration);
14952   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14953   if (!PrevECD)
14954     return SkipBodyInfo();
14955
14956   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14957   NamedDecl *Hidden;
14958   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14959     SkipBodyInfo Skip;
14960     Skip.Previous = Hidden;
14961     return Skip;
14962   }
14963
14964   return SkipBodyInfo();
14965 }
14966
14967 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14968                               SourceLocation IdLoc, IdentifierInfo *Id,
14969                               AttributeList *Attr,
14970                               SourceLocation EqualLoc, Expr *Val) {
14971   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14972   EnumConstantDecl *LastEnumConst =
14973     cast_or_null<EnumConstantDecl>(lastEnumConst);
14974
14975   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14976   // we find one that is.
14977   S = getNonFieldDeclScope(S);
14978
14979   // Verify that there isn't already something declared with this name in this
14980   // scope.
14981   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14982                                          ForRedeclaration);
14983   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14984     // Maybe we will complain about the shadowed template parameter.
14985     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14986     // Just pretend that we didn't see the previous declaration.
14987     PrevDecl = nullptr;
14988   }
14989
14990   // C++ [class.mem]p15:
14991   // If T is the name of a class, then each of the following shall have a name
14992   // different from T:
14993   // - every enumerator of every member of class T that is an unscoped
14994   // enumerated type
14995   if (!TheEnumDecl->isScoped())
14996     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14997                             DeclarationNameInfo(Id, IdLoc));
14998
14999   EnumConstantDecl *New =
15000     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15001   if (!New)
15002     return nullptr;
15003
15004   if (PrevDecl) {
15005     // When in C++, we may get a TagDecl with the same name; in this case the
15006     // enum constant will 'hide' the tag.
15007     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15008            "Received TagDecl when not in C++!");
15009     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15010         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15011       if (isa<EnumConstantDecl>(PrevDecl))
15012         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15013       else
15014         Diag(IdLoc, diag::err_redefinition) << Id;
15015       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15016       return nullptr;
15017     }
15018   }
15019
15020   // Process attributes.
15021   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15022
15023   // Register this decl in the current scope stack.
15024   New->setAccess(TheEnumDecl->getAccess());
15025   PushOnScopeChains(New, S);
15026
15027   ActOnDocumentableDecl(New);
15028
15029   return New;
15030 }
15031
15032 // Returns true when the enum initial expression does not trigger the
15033 // duplicate enum warning.  A few common cases are exempted as follows:
15034 // Element2 = Element1
15035 // Element2 = Element1 + 1
15036 // Element2 = Element1 - 1
15037 // Where Element2 and Element1 are from the same enum.
15038 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15039   Expr *InitExpr = ECD->getInitExpr();
15040   if (!InitExpr)
15041     return true;
15042   InitExpr = InitExpr->IgnoreImpCasts();
15043
15044   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15045     if (!BO->isAdditiveOp())
15046       return true;
15047     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15048     if (!IL)
15049       return true;
15050     if (IL->getValue() != 1)
15051       return true;
15052
15053     InitExpr = BO->getLHS();
15054   }
15055
15056   // This checks if the elements are from the same enum.
15057   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15058   if (!DRE)
15059     return true;
15060
15061   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15062   if (!EnumConstant)
15063     return true;
15064
15065   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15066       Enum)
15067     return true;
15068
15069   return false;
15070 }
15071
15072 namespace {
15073 struct DupKey {
15074   int64_t val;
15075   bool isTombstoneOrEmptyKey;
15076   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15077     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15078 };
15079
15080 static DupKey GetDupKey(const llvm::APSInt& Val) {
15081   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15082                 false);
15083 }
15084
15085 struct DenseMapInfoDupKey {
15086   static DupKey getEmptyKey() { return DupKey(0, true); }
15087   static DupKey getTombstoneKey() { return DupKey(1, true); }
15088   static unsigned getHashValue(const DupKey Key) {
15089     return (unsigned)(Key.val * 37);
15090   }
15091   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15092     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15093            LHS.val == RHS.val;
15094   }
15095 };
15096 } // end anonymous namespace
15097
15098 // Emits a warning when an element is implicitly set a value that
15099 // a previous element has already been set to.
15100 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15101                                         EnumDecl *Enum,
15102                                         QualType EnumType) {
15103   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15104     return;
15105   // Avoid anonymous enums
15106   if (!Enum->getIdentifier())
15107     return;
15108
15109   // Only check for small enums.
15110   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15111     return;
15112
15113   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15114   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15115
15116   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15117   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15118           ValueToVectorMap;
15119
15120   DuplicatesVector DupVector;
15121   ValueToVectorMap EnumMap;
15122
15123   // Populate the EnumMap with all values represented by enum constants without
15124   // an initialier.
15125   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15126     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15127
15128     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15129     // this constant.  Skip this enum since it may be ill-formed.
15130     if (!ECD) {
15131       return;
15132     }
15133
15134     if (ECD->getInitExpr())
15135       continue;
15136
15137     DupKey Key = GetDupKey(ECD->getInitVal());
15138     DeclOrVector &Entry = EnumMap[Key];
15139
15140     // First time encountering this value.
15141     if (Entry.isNull())
15142       Entry = ECD;
15143   }
15144
15145   // Create vectors for any values that has duplicates.
15146   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15147     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15148     if (!ValidDuplicateEnum(ECD, Enum))
15149       continue;
15150
15151     DupKey Key = GetDupKey(ECD->getInitVal());
15152
15153     DeclOrVector& Entry = EnumMap[Key];
15154     if (Entry.isNull())
15155       continue;
15156
15157     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15158       // Ensure constants are different.
15159       if (D == ECD)
15160         continue;
15161
15162       // Create new vector and push values onto it.
15163       ECDVector *Vec = new ECDVector();
15164       Vec->push_back(D);
15165       Vec->push_back(ECD);
15166
15167       // Update entry to point to the duplicates vector.
15168       Entry = Vec;
15169
15170       // Store the vector somewhere we can consult later for quick emission of
15171       // diagnostics.
15172       DupVector.push_back(Vec);
15173       continue;
15174     }
15175
15176     ECDVector *Vec = Entry.get<ECDVector*>();
15177     // Make sure constants are not added more than once.
15178     if (*Vec->begin() == ECD)
15179       continue;
15180
15181     Vec->push_back(ECD);
15182   }
15183
15184   // Emit diagnostics.
15185   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15186                                   DupVectorEnd = DupVector.end();
15187        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15188     ECDVector *Vec = *DupVectorIter;
15189     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15190
15191     // Emit warning for one enum constant.
15192     ECDVector::iterator I = Vec->begin();
15193     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15194       << (*I)->getName() << (*I)->getInitVal().toString(10)
15195       << (*I)->getSourceRange();
15196     ++I;
15197
15198     // Emit one note for each of the remaining enum constants with
15199     // the same value.
15200     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15201       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15202         << (*I)->getName() << (*I)->getInitVal().toString(10)
15203         << (*I)->getSourceRange();
15204     delete Vec;
15205   }
15206 }
15207
15208 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15209                              bool AllowMask) const {
15210   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
15211   assert(ED->isCompleteDefinition() && "expected enum definition");
15212
15213   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15214   llvm::APInt &FlagBits = R.first->second;
15215
15216   if (R.second) {
15217     for (auto *E : ED->enumerators()) {
15218       const auto &EVal = E->getInitVal();
15219       // Only single-bit enumerators introduce new flag values.
15220       if (EVal.isPowerOf2())
15221         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15222     }
15223   }
15224
15225   // A value is in a flag enum if either its bits are a subset of the enum's
15226   // flag bits (the first condition) or we are allowing masks and the same is
15227   // true of its complement (the second condition). When masks are allowed, we
15228   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15229   //
15230   // While it's true that any value could be used as a mask, the assumption is
15231   // that a mask will have all of the insignificant bits set. Anything else is
15232   // likely a logic error.
15233   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15234   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15235 }
15236
15237 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15238                          Decl *EnumDeclX,
15239                          ArrayRef<Decl *> Elements,
15240                          Scope *S, AttributeList *Attr) {
15241   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15242   QualType EnumType = Context.getTypeDeclType(Enum);
15243
15244   if (Attr)
15245     ProcessDeclAttributeList(S, Enum, Attr);
15246
15247   if (Enum->isDependentType()) {
15248     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15249       EnumConstantDecl *ECD =
15250         cast_or_null<EnumConstantDecl>(Elements[i]);
15251       if (!ECD) continue;
15252
15253       ECD->setType(EnumType);
15254     }
15255
15256     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15257     return;
15258   }
15259
15260   // TODO: If the result value doesn't fit in an int, it must be a long or long
15261   // long value.  ISO C does not support this, but GCC does as an extension,
15262   // emit a warning.
15263   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15264   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15265   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15266
15267   // Verify that all the values are okay, compute the size of the values, and
15268   // reverse the list.
15269   unsigned NumNegativeBits = 0;
15270   unsigned NumPositiveBits = 0;
15271
15272   // Keep track of whether all elements have type int.
15273   bool AllElementsInt = true;
15274
15275   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15276     EnumConstantDecl *ECD =
15277       cast_or_null<EnumConstantDecl>(Elements[i]);
15278     if (!ECD) continue;  // Already issued a diagnostic.
15279
15280     const llvm::APSInt &InitVal = ECD->getInitVal();
15281
15282     // Keep track of the size of positive and negative values.
15283     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15284       NumPositiveBits = std::max(NumPositiveBits,
15285                                  (unsigned)InitVal.getActiveBits());
15286     else
15287       NumNegativeBits = std::max(NumNegativeBits,
15288                                  (unsigned)InitVal.getMinSignedBits());
15289
15290     // Keep track of whether every enum element has type int (very commmon).
15291     if (AllElementsInt)
15292       AllElementsInt = ECD->getType() == Context.IntTy;
15293   }
15294
15295   // Figure out the type that should be used for this enum.
15296   QualType BestType;
15297   unsigned BestWidth;
15298
15299   // C++0x N3000 [conv.prom]p3:
15300   //   An rvalue of an unscoped enumeration type whose underlying
15301   //   type is not fixed can be converted to an rvalue of the first
15302   //   of the following types that can represent all the values of
15303   //   the enumeration: int, unsigned int, long int, unsigned long
15304   //   int, long long int, or unsigned long long int.
15305   // C99 6.4.4.3p2:
15306   //   An identifier declared as an enumeration constant has type int.
15307   // The C99 rule is modified by a gcc extension
15308   QualType BestPromotionType;
15309
15310   bool Packed = Enum->hasAttr<PackedAttr>();
15311   // -fshort-enums is the equivalent to specifying the packed attribute on all
15312   // enum definitions.
15313   if (LangOpts.ShortEnums)
15314     Packed = true;
15315
15316   if (Enum->isFixed()) {
15317     BestType = Enum->getIntegerType();
15318     if (BestType->isPromotableIntegerType())
15319       BestPromotionType = Context.getPromotedIntegerType(BestType);
15320     else
15321       BestPromotionType = BestType;
15322
15323     BestWidth = Context.getIntWidth(BestType);
15324   }
15325   else if (NumNegativeBits) {
15326     // If there is a negative value, figure out the smallest integer type (of
15327     // int/long/longlong) that fits.
15328     // If it's packed, check also if it fits a char or a short.
15329     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15330       BestType = Context.SignedCharTy;
15331       BestWidth = CharWidth;
15332     } else if (Packed && NumNegativeBits <= ShortWidth &&
15333                NumPositiveBits < ShortWidth) {
15334       BestType = Context.ShortTy;
15335       BestWidth = ShortWidth;
15336     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15337       BestType = Context.IntTy;
15338       BestWidth = IntWidth;
15339     } else {
15340       BestWidth = Context.getTargetInfo().getLongWidth();
15341
15342       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15343         BestType = Context.LongTy;
15344       } else {
15345         BestWidth = Context.getTargetInfo().getLongLongWidth();
15346
15347         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15348           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15349         BestType = Context.LongLongTy;
15350       }
15351     }
15352     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15353   } else {
15354     // If there is no negative value, figure out the smallest type that fits
15355     // all of the enumerator values.
15356     // If it's packed, check also if it fits a char or a short.
15357     if (Packed && NumPositiveBits <= CharWidth) {
15358       BestType = Context.UnsignedCharTy;
15359       BestPromotionType = Context.IntTy;
15360       BestWidth = CharWidth;
15361     } else if (Packed && NumPositiveBits <= ShortWidth) {
15362       BestType = Context.UnsignedShortTy;
15363       BestPromotionType = Context.IntTy;
15364       BestWidth = ShortWidth;
15365     } else if (NumPositiveBits <= IntWidth) {
15366       BestType = Context.UnsignedIntTy;
15367       BestWidth = IntWidth;
15368       BestPromotionType
15369         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15370                            ? Context.UnsignedIntTy : Context.IntTy;
15371     } else if (NumPositiveBits <=
15372                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15373       BestType = Context.UnsignedLongTy;
15374       BestPromotionType
15375         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15376                            ? Context.UnsignedLongTy : Context.LongTy;
15377     } else {
15378       BestWidth = Context.getTargetInfo().getLongLongWidth();
15379       assert(NumPositiveBits <= BestWidth &&
15380              "How could an initializer get larger than ULL?");
15381       BestType = Context.UnsignedLongLongTy;
15382       BestPromotionType
15383         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15384                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15385     }
15386   }
15387
15388   // Loop over all of the enumerator constants, changing their types to match
15389   // the type of the enum if needed.
15390   for (auto *D : Elements) {
15391     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15392     if (!ECD) continue;  // Already issued a diagnostic.
15393
15394     // Standard C says the enumerators have int type, but we allow, as an
15395     // extension, the enumerators to be larger than int size.  If each
15396     // enumerator value fits in an int, type it as an int, otherwise type it the
15397     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15398     // that X has type 'int', not 'unsigned'.
15399
15400     // Determine whether the value fits into an int.
15401     llvm::APSInt InitVal = ECD->getInitVal();
15402
15403     // If it fits into an integer type, force it.  Otherwise force it to match
15404     // the enum decl type.
15405     QualType NewTy;
15406     unsigned NewWidth;
15407     bool NewSign;
15408     if (!getLangOpts().CPlusPlus &&
15409         !Enum->isFixed() &&
15410         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15411       NewTy = Context.IntTy;
15412       NewWidth = IntWidth;
15413       NewSign = true;
15414     } else if (ECD->getType() == BestType) {
15415       // Already the right type!
15416       if (getLangOpts().CPlusPlus)
15417         // C++ [dcl.enum]p4: Following the closing brace of an
15418         // enum-specifier, each enumerator has the type of its
15419         // enumeration.
15420         ECD->setType(EnumType);
15421       continue;
15422     } else {
15423       NewTy = BestType;
15424       NewWidth = BestWidth;
15425       NewSign = BestType->isSignedIntegerOrEnumerationType();
15426     }
15427
15428     // Adjust the APSInt value.
15429     InitVal = InitVal.extOrTrunc(NewWidth);
15430     InitVal.setIsSigned(NewSign);
15431     ECD->setInitVal(InitVal);
15432
15433     // Adjust the Expr initializer and type.
15434     if (ECD->getInitExpr() &&
15435         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15436       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15437                                                 CK_IntegralCast,
15438                                                 ECD->getInitExpr(),
15439                                                 /*base paths*/ nullptr,
15440                                                 VK_RValue));
15441     if (getLangOpts().CPlusPlus)
15442       // C++ [dcl.enum]p4: Following the closing brace of an
15443       // enum-specifier, each enumerator has the type of its
15444       // enumeration.
15445       ECD->setType(EnumType);
15446     else
15447       ECD->setType(NewTy);
15448   }
15449
15450   Enum->completeDefinition(BestType, BestPromotionType,
15451                            NumPositiveBits, NumNegativeBits);
15452
15453   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15454
15455   if (Enum->hasAttr<FlagEnumAttr>()) {
15456     for (Decl *D : Elements) {
15457       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15458       if (!ECD) continue;  // Already issued a diagnostic.
15459
15460       llvm::APSInt InitVal = ECD->getInitVal();
15461       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15462           !IsValueInFlagEnum(Enum, InitVal, true))
15463         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15464           << ECD << Enum;
15465     }
15466   }
15467
15468   // Now that the enum type is defined, ensure it's not been underaligned.
15469   if (Enum->hasAttrs())
15470     CheckAlignasUnderalignment(Enum);
15471 }
15472
15473 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15474                                   SourceLocation StartLoc,
15475                                   SourceLocation EndLoc) {
15476   StringLiteral *AsmString = cast<StringLiteral>(expr);
15477
15478   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15479                                                    AsmString, StartLoc,
15480                                                    EndLoc);
15481   CurContext->addDecl(New);
15482   return New;
15483 }
15484
15485 static void checkModuleImportContext(Sema &S, Module *M,
15486                                      SourceLocation ImportLoc, DeclContext *DC,
15487                                      bool FromInclude = false) {
15488   SourceLocation ExternCLoc;
15489
15490   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15491     switch (LSD->getLanguage()) {
15492     case LinkageSpecDecl::lang_c:
15493       if (ExternCLoc.isInvalid())
15494         ExternCLoc = LSD->getLocStart();
15495       break;
15496     case LinkageSpecDecl::lang_cxx:
15497       break;
15498     }
15499     DC = LSD->getParent();
15500   }
15501
15502   while (isa<LinkageSpecDecl>(DC))
15503     DC = DC->getParent();
15504
15505   if (!isa<TranslationUnitDecl>(DC)) {
15506     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15507                           ? diag::ext_module_import_not_at_top_level_noop
15508                           : diag::err_module_import_not_at_top_level_fatal)
15509         << M->getFullModuleName() << DC;
15510     S.Diag(cast<Decl>(DC)->getLocStart(),
15511            diag::note_module_import_not_at_top_level) << DC;
15512   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15513     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15514       << M->getFullModuleName();
15515     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15516   }
15517 }
15518
15519 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15520                                            ModuleDeclKind MDK,
15521                                            ModuleIdPath Path) {
15522   // 'module implementation' requires that we are not compiling a module of any
15523   // kind. 'module' and 'module partition' require that we are compiling a
15524   // module inteface (not a module map).
15525   auto CMK = getLangOpts().getCompilingModule();
15526   if (MDK == ModuleDeclKind::Implementation
15527           ? CMK != LangOptions::CMK_None
15528           : CMK != LangOptions::CMK_ModuleInterface) {
15529     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15530       << (unsigned)MDK;
15531     return nullptr;
15532   }
15533
15534   // FIXME: Create a ModuleDecl and return it.
15535
15536   // FIXME: Most of this work should be done by the preprocessor rather than
15537   // here, in case we look ahead across something where the current
15538   // module matters (eg a #include).
15539
15540   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15541   // hierarchical module map modules, the dots here are just another character
15542   // that can appear in a module name. Flatten down to the actual module name.
15543   std::string ModuleName;
15544   for (auto &Piece : Path) {
15545     if (!ModuleName.empty())
15546       ModuleName += ".";
15547     ModuleName += Piece.first->getName();
15548   }
15549
15550   // If a module name was explicitly specified on the command line, it must be
15551   // correct.
15552   if (!getLangOpts().CurrentModule.empty() &&
15553       getLangOpts().CurrentModule != ModuleName) {
15554     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15555         << SourceRange(Path.front().second, Path.back().second)
15556         << getLangOpts().CurrentModule;
15557     return nullptr;
15558   }
15559   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15560
15561   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15562
15563   switch (MDK) {
15564   case ModuleDeclKind::Module: {
15565     // FIXME: Check we're not in a submodule.
15566
15567     // We can't have imported a definition of this module or parsed a module
15568     // map defining it already.
15569     if (auto *M = Map.findModule(ModuleName)) {
15570       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15571       if (M->DefinitionLoc.isValid())
15572         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15573       else if (const auto *FE = M->getASTFile())
15574         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15575             << FE->getName();
15576       return nullptr;
15577     }
15578
15579     // Create a Module for the module that we're defining.
15580     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15581     assert(Mod && "module creation should not fail");
15582
15583     // Enter the semantic scope of the module.
15584     ActOnModuleBegin(ModuleLoc, Mod);
15585     return nullptr;
15586   }
15587
15588   case ModuleDeclKind::Partition:
15589     // FIXME: Check we are in a submodule of the named module.
15590     return nullptr;
15591
15592   case ModuleDeclKind::Implementation:
15593     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15594         PP.getIdentifierInfo(ModuleName), Path[0].second);
15595
15596     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15597     if (Import.isInvalid())
15598       return nullptr;
15599     return ConvertDeclToDeclGroup(Import.get());
15600   }
15601
15602   llvm_unreachable("unexpected module decl kind");
15603 }
15604
15605 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15606                                    SourceLocation ImportLoc,
15607                                    ModuleIdPath Path) {
15608   Module *Mod =
15609       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15610                                    /*IsIncludeDirective=*/false);
15611   if (!Mod)
15612     return true;
15613
15614   VisibleModules.setVisible(Mod, ImportLoc);
15615
15616   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15617
15618   // FIXME: we should support importing a submodule within a different submodule
15619   // of the same top-level module. Until we do, make it an error rather than
15620   // silently ignoring the import.
15621   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15622   // warn on a redundant import of the current module?
15623   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15624       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15625     Diag(ImportLoc, getLangOpts().isCompilingModule()
15626                         ? diag::err_module_self_import
15627                         : diag::err_module_import_in_implementation)
15628         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15629
15630   SmallVector<SourceLocation, 2> IdentifierLocs;
15631   Module *ModCheck = Mod;
15632   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15633     // If we've run out of module parents, just drop the remaining identifiers.
15634     // We need the length to be consistent.
15635     if (!ModCheck)
15636       break;
15637     ModCheck = ModCheck->Parent;
15638
15639     IdentifierLocs.push_back(Path[I].second);
15640   }
15641
15642   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15643   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15644                                           Mod, IdentifierLocs);
15645   if (!ModuleScopes.empty())
15646     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15647   TU->addDecl(Import);
15648   return Import;
15649 }
15650
15651 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15652   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15653   BuildModuleInclude(DirectiveLoc, Mod);
15654 }
15655
15656 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15657   // Determine whether we're in the #include buffer for a module. The #includes
15658   // in that buffer do not qualify as module imports; they're just an
15659   // implementation detail of us building the module.
15660   //
15661   // FIXME: Should we even get ActOnModuleInclude calls for those?
15662   bool IsInModuleIncludes =
15663       TUKind == TU_Module &&
15664       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15665
15666   bool ShouldAddImport = !IsInModuleIncludes;
15667
15668   // If this module import was due to an inclusion directive, create an
15669   // implicit import declaration to capture it in the AST.
15670   if (ShouldAddImport) {
15671     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15672     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15673                                                      DirectiveLoc, Mod,
15674                                                      DirectiveLoc);
15675     if (!ModuleScopes.empty())
15676       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15677     TU->addDecl(ImportD);
15678     Consumer.HandleImplicitImportDecl(ImportD);
15679   }
15680
15681   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15682   VisibleModules.setVisible(Mod, DirectiveLoc);
15683 }
15684
15685 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15686   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15687
15688   ModuleScopes.push_back({});
15689   ModuleScopes.back().Module = Mod;
15690   if (getLangOpts().ModulesLocalVisibility)
15691     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15692
15693   VisibleModules.setVisible(Mod, DirectiveLoc);
15694 }
15695
15696 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15697   if (getLangOpts().ModulesLocalVisibility) {
15698     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15699     // Leaving a module hides namespace names, so our visible namespace cache
15700     // is now out of date.
15701     VisibleNamespaceCache.clear();
15702   }
15703
15704   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15705          "left the wrong module scope");
15706   ModuleScopes.pop_back();
15707
15708   // We got to the end of processing a #include of a local module. Create an
15709   // ImportDecl as we would for an imported module.
15710   FileID File = getSourceManager().getFileID(EofLoc);
15711   assert(File != getSourceManager().getMainFileID() &&
15712          "end of submodule in main source file");
15713   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15714   BuildModuleInclude(DirectiveLoc, Mod);
15715 }
15716
15717 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15718                                                       Module *Mod) {
15719   // Bail if we're not allowed to implicitly import a module here.
15720   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15721     return;
15722
15723   // Create the implicit import declaration.
15724   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15725   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15726                                                    Loc, Mod, Loc);
15727   TU->addDecl(ImportD);
15728   Consumer.HandleImplicitImportDecl(ImportD);
15729
15730   // Make the module visible.
15731   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15732   VisibleModules.setVisible(Mod, Loc);
15733 }
15734
15735 /// We have parsed the start of an export declaration, including the '{'
15736 /// (if present).
15737 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15738                                  SourceLocation LBraceLoc) {
15739   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15740
15741   // C++ Modules TS draft:
15742   //   An export-declaration [...] shall not contain more than one
15743   //   export keyword.
15744   //
15745   // The intent here is that an export-declaration cannot appear within another
15746   // export-declaration.
15747   if (D->isExported())
15748     Diag(ExportLoc, diag::err_export_within_export);
15749
15750   CurContext->addDecl(D);
15751   PushDeclContext(S, D);
15752   return D;
15753 }
15754
15755 /// Complete the definition of an export declaration.
15756 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15757   auto *ED = cast<ExportDecl>(D);
15758   if (RBraceLoc.isValid())
15759     ED->setRBraceLoc(RBraceLoc);
15760
15761   // FIXME: Diagnose export of internal-linkage declaration (including
15762   // anonymous namespace).
15763
15764   PopDeclContext();
15765   return D;
15766 }
15767
15768 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15769                                       IdentifierInfo* AliasName,
15770                                       SourceLocation PragmaLoc,
15771                                       SourceLocation NameLoc,
15772                                       SourceLocation AliasNameLoc) {
15773   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15774                                          LookupOrdinaryName);
15775   AsmLabelAttr *Attr =
15776       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15777
15778   // If a declaration that:
15779   // 1) declares a function or a variable
15780   // 2) has external linkage
15781   // already exists, add a label attribute to it.
15782   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15783     if (isDeclExternC(PrevDecl))
15784       PrevDecl->addAttr(Attr);
15785     else
15786       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15787           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15788   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15789   } else
15790     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15791 }
15792
15793 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15794                              SourceLocation PragmaLoc,
15795                              SourceLocation NameLoc) {
15796   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15797
15798   if (PrevDecl) {
15799     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15800   } else {
15801     (void)WeakUndeclaredIdentifiers.insert(
15802       std::pair<IdentifierInfo*,WeakInfo>
15803         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15804   }
15805 }
15806
15807 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15808                                 IdentifierInfo* AliasName,
15809                                 SourceLocation PragmaLoc,
15810                                 SourceLocation NameLoc,
15811                                 SourceLocation AliasNameLoc) {
15812   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15813                                     LookupOrdinaryName);
15814   WeakInfo W = WeakInfo(Name, NameLoc);
15815
15816   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15817     if (!PrevDecl->hasAttr<AliasAttr>())
15818       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15819         DeclApplyPragmaWeak(TUScope, ND, W);
15820   } else {
15821     (void)WeakUndeclaredIdentifiers.insert(
15822       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15823   }
15824 }
15825
15826 Decl *Sema::getObjCDeclContext() const {
15827   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15828 }