]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp
Merge llvm, clang, lld and lldb trunk r291012, and resolve conflicts.
[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     return NameClassification::TypeTemplate(
1049         TemplateName(cast<TemplateDecl>(FirstDecl)));
1050
1051   // Check for a tag type hidden by a non-type decl in a few cases where it
1052   // seems likely a type is wanted instead of the non-type that was found.
1053   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1054   if ((NextToken.is(tok::identifier) ||
1055        (NextIsOp &&
1056         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1057       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1058     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1059     DiagnoseUseOfDecl(Type, NameLoc);
1060     QualType T = Context.getTypeDeclType(Type);
1061     if (SS.isNotEmpty())
1062       return buildNestedType(*this, SS, T, NameLoc);
1063     return ParsedType::make(T);
1064   }
1065
1066   if (FirstDecl->isCXXClassMember())
1067     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1068                                            nullptr, S);
1069
1070   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1071   return BuildDeclarationNameExpr(SS, Result, ADL);
1072 }
1073
1074 // Determines the context to return to after temporarily entering a
1075 // context.  This depends in an unnecessarily complicated way on the
1076 // exact ordering of callbacks from the parser.
1077 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1078
1079   // Functions defined inline within classes aren't parsed until we've
1080   // finished parsing the top-level class, so the top-level class is
1081   // the context we'll need to return to.
1082   // A Lambda call operator whose parent is a class must not be treated
1083   // as an inline member function.  A Lambda can be used legally
1084   // either as an in-class member initializer or a default argument.  These
1085   // are parsed once the class has been marked complete and so the containing
1086   // context would be the nested class (when the lambda is defined in one);
1087   // If the class is not complete, then the lambda is being used in an
1088   // ill-formed fashion (such as to specify the width of a bit-field, or
1089   // in an array-bound) - in which case we still want to return the
1090   // lexically containing DC (which could be a nested class).
1091   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1092     DC = DC->getLexicalParent();
1093
1094     // A function not defined within a class will always return to its
1095     // lexical context.
1096     if (!isa<CXXRecordDecl>(DC))
1097       return DC;
1098
1099     // A C++ inline method/friend is parsed *after* the topmost class
1100     // it was declared in is fully parsed ("complete");  the topmost
1101     // class is the context we need to return to.
1102     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1103       DC = RD;
1104
1105     // Return the declaration context of the topmost class the inline method is
1106     // declared in.
1107     return DC;
1108   }
1109
1110   return DC->getLexicalParent();
1111 }
1112
1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1114   assert(getContainingDC(DC) == CurContext &&
1115       "The next DeclContext should be lexically contained in the current one.");
1116   CurContext = DC;
1117   S->setEntity(DC);
1118 }
1119
1120 void Sema::PopDeclContext() {
1121   assert(CurContext && "DeclContext imbalance!");
1122
1123   CurContext = getContainingDC(CurContext);
1124   assert(CurContext && "Popped translation unit!");
1125 }
1126
1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1128                                                                     Decl *D) {
1129   // Unlike PushDeclContext, the context to which we return is not necessarily
1130   // the containing DC of TD, because the new context will be some pre-existing
1131   // TagDecl definition instead of a fresh one.
1132   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1133   CurContext = cast<TagDecl>(D)->getDefinition();
1134   assert(CurContext && "skipping definition of undefined tag");
1135   // Start lookups from the parent of the current context; we don't want to look
1136   // into the pre-existing complete definition.
1137   S->setEntity(CurContext->getLookupParent());
1138   return Result;
1139 }
1140
1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1142   CurContext = static_cast<decltype(CurContext)>(Context);
1143 }
1144
1145 /// EnterDeclaratorContext - Used when we must lookup names in the context
1146 /// of a declarator's nested name specifier.
1147 ///
1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1149   // C++0x [basic.lookup.unqual]p13:
1150   //   A name used in the definition of a static data member of class
1151   //   X (after the qualified-id of the static member) is looked up as
1152   //   if the name was used in a member function of X.
1153   // C++0x [basic.lookup.unqual]p14:
1154   //   If a variable member of a namespace is defined outside of the
1155   //   scope of its namespace then any name used in the definition of
1156   //   the variable member (after the declarator-id) is looked up as
1157   //   if the definition of the variable member occurred in its
1158   //   namespace.
1159   // Both of these imply that we should push a scope whose context
1160   // is the semantic context of the declaration.  We can't use
1161   // PushDeclContext here because that context is not necessarily
1162   // lexically contained in the current context.  Fortunately,
1163   // the containing scope should have the appropriate information.
1164
1165   assert(!S->getEntity() && "scope already has entity");
1166
1167 #ifndef NDEBUG
1168   Scope *Ancestor = S->getParent();
1169   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1170   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1171 #endif
1172
1173   CurContext = DC;
1174   S->setEntity(DC);
1175 }
1176
1177 void Sema::ExitDeclaratorContext(Scope *S) {
1178   assert(S->getEntity() == CurContext && "Context imbalance!");
1179
1180   // Switch back to the lexical context.  The safety of this is
1181   // enforced by an assert in EnterDeclaratorContext.
1182   Scope *Ancestor = S->getParent();
1183   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1184   CurContext = Ancestor->getEntity();
1185
1186   // We don't need to do anything with the scope, which is going to
1187   // disappear.
1188 }
1189
1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1191   // We assume that the caller has already called
1192   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1193   FunctionDecl *FD = D->getAsFunction();
1194   if (!FD)
1195     return;
1196
1197   // Same implementation as PushDeclContext, but enters the context
1198   // from the lexical parent, rather than the top-level class.
1199   assert(CurContext == FD->getLexicalParent() &&
1200     "The next DeclContext should be lexically contained in the current one.");
1201   CurContext = FD;
1202   S->setEntity(CurContext);
1203
1204   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1205     ParmVarDecl *Param = FD->getParamDecl(P);
1206     // If the parameter has an identifier, then add it to the scope
1207     if (Param->getIdentifier()) {
1208       S->AddDecl(Param);
1209       IdResolver.AddDecl(Param);
1210     }
1211   }
1212 }
1213
1214 void Sema::ActOnExitFunctionContext() {
1215   // Same implementation as PopDeclContext, but returns to the lexical parent,
1216   // rather than the top-level class.
1217   assert(CurContext && "DeclContext imbalance!");
1218   CurContext = CurContext->getLexicalParent();
1219   assert(CurContext && "Popped translation unit!");
1220 }
1221
1222 /// \brief Determine whether we allow overloading of the function
1223 /// PrevDecl with another declaration.
1224 ///
1225 /// This routine determines whether overloading is possible, not
1226 /// whether some new function is actually an overload. It will return
1227 /// true in C++ (where we can always provide overloads) or, as an
1228 /// extension, in C when the previous function is already an
1229 /// overloaded function declaration or has the "overloadable"
1230 /// attribute.
1231 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1232                                        ASTContext &Context) {
1233   if (Context.getLangOpts().CPlusPlus)
1234     return true;
1235
1236   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1237     return true;
1238
1239   return (Previous.getResultKind() == LookupResult::Found
1240           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1241 }
1242
1243 /// Add this decl to the scope shadowed decl chains.
1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1245   // Move up the scope chain until we find the nearest enclosing
1246   // non-transparent context. The declaration will be introduced into this
1247   // scope.
1248   while (S->getEntity() && S->getEntity()->isTransparentContext())
1249     S = S->getParent();
1250
1251   // Add scoped declarations into their context, so that they can be
1252   // found later. Declarations without a context won't be inserted
1253   // into any context.
1254   if (AddToContext)
1255     CurContext->addDecl(D);
1256
1257   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1258   // are function-local declarations.
1259   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1260       !D->getDeclContext()->getRedeclContext()->Equals(
1261         D->getLexicalDeclContext()->getRedeclContext()) &&
1262       !D->getLexicalDeclContext()->isFunctionOrMethod())
1263     return;
1264
1265   // Template instantiations should also not be pushed into scope.
1266   if (isa<FunctionDecl>(D) &&
1267       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1268     return;
1269
1270   // If this replaces anything in the current scope,
1271   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1272                                IEnd = IdResolver.end();
1273   for (; I != IEnd; ++I) {
1274     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1275       S->RemoveDecl(*I);
1276       IdResolver.RemoveDecl(*I);
1277
1278       // Should only need to replace one decl.
1279       break;
1280     }
1281   }
1282
1283   S->AddDecl(D);
1284
1285   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1286     // Implicitly-generated labels may end up getting generated in an order that
1287     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1288     // the label at the appropriate place in the identifier chain.
1289     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1290       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1291       if (IDC == CurContext) {
1292         if (!S->isDeclScope(*I))
1293           continue;
1294       } else if (IDC->Encloses(CurContext))
1295         break;
1296     }
1297
1298     IdResolver.InsertDeclAfter(I, D);
1299   } else {
1300     IdResolver.AddDecl(D);
1301   }
1302 }
1303
1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1305   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1306     TUScope->AddDecl(D);
1307 }
1308
1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1310                          bool AllowInlineNamespace) {
1311   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1312 }
1313
1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1315   DeclContext *TargetDC = DC->getPrimaryContext();
1316   do {
1317     if (DeclContext *ScopeDC = S->getEntity())
1318       if (ScopeDC->getPrimaryContext() == TargetDC)
1319         return S;
1320   } while ((S = S->getParent()));
1321
1322   return nullptr;
1323 }
1324
1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1326                                             DeclContext*,
1327                                             ASTContext&);
1328
1329 /// Filters out lookup results that don't fall within the given scope
1330 /// as determined by isDeclInScope.
1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1332                                 bool ConsiderLinkage,
1333                                 bool AllowInlineNamespace) {
1334   LookupResult::Filter F = R.makeFilter();
1335   while (F.hasNext()) {
1336     NamedDecl *D = F.next();
1337
1338     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1339       continue;
1340
1341     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1342       continue;
1343
1344     F.erase();
1345   }
1346
1347   F.done();
1348 }
1349
1350 static bool isUsingDecl(NamedDecl *D) {
1351   return isa<UsingShadowDecl>(D) ||
1352          isa<UnresolvedUsingTypenameDecl>(D) ||
1353          isa<UnresolvedUsingValueDecl>(D);
1354 }
1355
1356 /// Removes using shadow declarations from the lookup results.
1357 static void RemoveUsingDecls(LookupResult &R) {
1358   LookupResult::Filter F = R.makeFilter();
1359   while (F.hasNext())
1360     if (isUsingDecl(F.next()))
1361       F.erase();
1362
1363   F.done();
1364 }
1365
1366 /// \brief Check for this common pattern:
1367 /// @code
1368 /// class S {
1369 ///   S(const S&); // DO NOT IMPLEMENT
1370 ///   void operator=(const S&); // DO NOT IMPLEMENT
1371 /// };
1372 /// @endcode
1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1374   // FIXME: Should check for private access too but access is set after we get
1375   // the decl here.
1376   if (D->doesThisDeclarationHaveABody())
1377     return false;
1378
1379   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1380     return CD->isCopyConstructor();
1381   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1382     return Method->isCopyAssignmentOperator();
1383   return false;
1384 }
1385
1386 // We need this to handle
1387 //
1388 // typedef struct {
1389 //   void *foo() { return 0; }
1390 // } A;
1391 //
1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1393 // for example. If 'A', foo will have external linkage. If we have '*A',
1394 // foo will have no linkage. Since we can't know until we get to the end
1395 // of the typedef, this function finds out if D might have non-external linkage.
1396 // Callers should verify at the end of the TU if it D has external linkage or
1397 // not.
1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1399   const DeclContext *DC = D->getDeclContext();
1400   while (!DC->isTranslationUnit()) {
1401     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1402       if (!RD->hasNameForLinkage())
1403         return true;
1404     }
1405     DC = DC->getParent();
1406   }
1407
1408   return !D->isExternallyVisible();
1409 }
1410
1411 // FIXME: This needs to be refactored; some other isInMainFile users want
1412 // these semantics.
1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1414   if (S.TUKind != TU_Complete)
1415     return false;
1416   return S.SourceMgr.isInMainFile(Loc);
1417 }
1418
1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1420   assert(D);
1421
1422   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1423     return false;
1424
1425   // Ignore all entities declared within templates, and out-of-line definitions
1426   // of members of class templates.
1427   if (D->getDeclContext()->isDependentContext() ||
1428       D->getLexicalDeclContext()->isDependentContext())
1429     return false;
1430
1431   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1433       return false;
1434
1435     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1436       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1437         return false;
1438     } else {
1439       // 'static inline' functions are defined in headers; don't warn.
1440       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1441         return false;
1442     }
1443
1444     if (FD->doesThisDeclarationHaveABody() &&
1445         Context.DeclMustBeEmitted(FD))
1446       return false;
1447   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1448     // Constants and utility variables are defined in headers with internal
1449     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1450     // like "inline".)
1451     if (!isMainFileLoc(*this, VD->getLocation()))
1452       return false;
1453
1454     if (Context.DeclMustBeEmitted(VD))
1455       return false;
1456
1457     if (VD->isStaticDataMember() &&
1458         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1459       return false;
1460
1461     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1462       return false;
1463   } else {
1464     return false;
1465   }
1466
1467   // Only warn for unused decls internal to the translation unit.
1468   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1469   // for inline functions defined in the main source file, for instance.
1470   return mightHaveNonExternalLinkage(D);
1471 }
1472
1473 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1474   if (!D)
1475     return;
1476
1477   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1478     const FunctionDecl *First = FD->getFirstDecl();
1479     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1480       return; // First should already be in the vector.
1481   }
1482
1483   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1484     const VarDecl *First = VD->getFirstDecl();
1485     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1486       return; // First should already be in the vector.
1487   }
1488
1489   if (ShouldWarnIfUnusedFileScopedDecl(D))
1490     UnusedFileScopedDecls.push_back(D);
1491 }
1492
1493 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1494   if (D->isInvalidDecl())
1495     return false;
1496
1497   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1498       D->hasAttr<ObjCPreciseLifetimeAttr>())
1499     return false;
1500
1501   if (isa<LabelDecl>(D))
1502     return true;
1503
1504   // Except for labels, we only care about unused decls that are local to
1505   // functions.
1506   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1507   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1508     // For dependent types, the diagnostic is deferred.
1509     WithinFunction =
1510         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1511   if (!WithinFunction)
1512     return false;
1513
1514   if (isa<TypedefNameDecl>(D))
1515     return true;
1516
1517   // White-list anything that isn't a local variable.
1518   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1519     return false;
1520
1521   // Types of valid local variables should be complete, so this should succeed.
1522   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1523
1524     // White-list anything with an __attribute__((unused)) type.
1525     const auto *Ty = VD->getType().getTypePtr();
1526
1527     // Only look at the outermost level of typedef.
1528     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1529       if (TT->getDecl()->hasAttr<UnusedAttr>())
1530         return false;
1531     }
1532
1533     // If we failed to complete the type for some reason, or if the type is
1534     // dependent, don't diagnose the variable.
1535     if (Ty->isIncompleteType() || Ty->isDependentType())
1536       return false;
1537
1538     // Look at the element type to ensure that the warning behaviour is
1539     // consistent for both scalars and arrays.
1540     Ty = Ty->getBaseElementTypeUnsafe();
1541
1542     if (const TagType *TT = Ty->getAs<TagType>()) {
1543       const TagDecl *Tag = TT->getDecl();
1544       if (Tag->hasAttr<UnusedAttr>())
1545         return false;
1546
1547       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1548         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1549           return false;
1550
1551         if (const Expr *Init = VD->getInit()) {
1552           if (const ExprWithCleanups *Cleanups =
1553                   dyn_cast<ExprWithCleanups>(Init))
1554             Init = Cleanups->getSubExpr();
1555           const CXXConstructExpr *Construct =
1556             dyn_cast<CXXConstructExpr>(Init);
1557           if (Construct && !Construct->isElidable()) {
1558             CXXConstructorDecl *CD = Construct->getConstructor();
1559             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1560               return false;
1561           }
1562         }
1563       }
1564     }
1565
1566     // TODO: __attribute__((unused)) templates?
1567   }
1568
1569   return true;
1570 }
1571
1572 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1573                                      FixItHint &Hint) {
1574   if (isa<LabelDecl>(D)) {
1575     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1576                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1577     if (AfterColon.isInvalid())
1578       return;
1579     Hint = FixItHint::CreateRemoval(CharSourceRange::
1580                                     getCharRange(D->getLocStart(), AfterColon));
1581   }
1582 }
1583
1584 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1585   if (D->getTypeForDecl()->isDependentType())
1586     return;
1587
1588   for (auto *TmpD : D->decls()) {
1589     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1590       DiagnoseUnusedDecl(T);
1591     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1592       DiagnoseUnusedNestedTypedefs(R);
1593   }
1594 }
1595
1596 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1597 /// unless they are marked attr(unused).
1598 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1599   if (!ShouldDiagnoseUnusedDecl(D))
1600     return;
1601
1602   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1603     // typedefs can be referenced later on, so the diagnostics are emitted
1604     // at end-of-translation-unit.
1605     UnusedLocalTypedefNameCandidates.insert(TD);
1606     return;
1607   }
1608
1609   FixItHint Hint;
1610   GenerateFixForUnusedDecl(D, Context, Hint);
1611
1612   unsigned DiagID;
1613   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1614     DiagID = diag::warn_unused_exception_param;
1615   else if (isa<LabelDecl>(D))
1616     DiagID = diag::warn_unused_label;
1617   else
1618     DiagID = diag::warn_unused_variable;
1619
1620   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1621 }
1622
1623 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1624   // Verify that we have no forward references left.  If so, there was a goto
1625   // or address of a label taken, but no definition of it.  Label fwd
1626   // definitions are indicated with a null substmt which is also not a resolved
1627   // MS inline assembly label name.
1628   bool Diagnose = false;
1629   if (L->isMSAsmLabel())
1630     Diagnose = !L->isResolvedMSAsmLabel();
1631   else
1632     Diagnose = L->getStmt() == nullptr;
1633   if (Diagnose)
1634     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1635 }
1636
1637 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1638   S->mergeNRVOIntoParent();
1639
1640   if (S->decl_empty()) return;
1641   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1642          "Scope shouldn't contain decls!");
1643
1644   for (auto *TmpD : S->decls()) {
1645     assert(TmpD && "This decl didn't get pushed??");
1646
1647     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1648     NamedDecl *D = cast<NamedDecl>(TmpD);
1649
1650     if (!D->getDeclName()) continue;
1651
1652     // Diagnose unused variables in this scope.
1653     if (!S->hasUnrecoverableErrorOccurred()) {
1654       DiagnoseUnusedDecl(D);
1655       if (const auto *RD = dyn_cast<RecordDecl>(D))
1656         DiagnoseUnusedNestedTypedefs(RD);
1657     }
1658
1659     // If this was a forward reference to a label, verify it was defined.
1660     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1661       CheckPoppedLabel(LD, *this);
1662
1663     // Remove this name from our lexical scope, and warn on it if we haven't
1664     // already.
1665     IdResolver.RemoveDecl(D);
1666     auto ShadowI = ShadowingDecls.find(D);
1667     if (ShadowI != ShadowingDecls.end()) {
1668       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1669         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1670             << D << FD << FD->getParent();
1671         Diag(FD->getLocation(), diag::note_previous_declaration);
1672       }
1673       ShadowingDecls.erase(ShadowI);
1674     }
1675   }
1676 }
1677
1678 /// \brief Look for an Objective-C class in the translation unit.
1679 ///
1680 /// \param Id The name of the Objective-C class we're looking for. If
1681 /// typo-correction fixes this name, the Id will be updated
1682 /// to the fixed name.
1683 ///
1684 /// \param IdLoc The location of the name in the translation unit.
1685 ///
1686 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1687 /// if there is no class with the given name.
1688 ///
1689 /// \returns The declaration of the named Objective-C class, or NULL if the
1690 /// class could not be found.
1691 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1692                                               SourceLocation IdLoc,
1693                                               bool DoTypoCorrection) {
1694   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1695   // creation from this context.
1696   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1697
1698   if (!IDecl && DoTypoCorrection) {
1699     // Perform typo correction at the given location, but only if we
1700     // find an Objective-C class name.
1701     if (TypoCorrection C = CorrectTypo(
1702             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1703             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1704             CTK_ErrorRecovery)) {
1705       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1706       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1707       Id = IDecl->getIdentifier();
1708     }
1709   }
1710   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1711   // This routine must always return a class definition, if any.
1712   if (Def && Def->getDefinition())
1713       Def = Def->getDefinition();
1714   return Def;
1715 }
1716
1717 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1718 /// from S, where a non-field would be declared. This routine copes
1719 /// with the difference between C and C++ scoping rules in structs and
1720 /// unions. For example, the following code is well-formed in C but
1721 /// ill-formed in C++:
1722 /// @code
1723 /// struct S6 {
1724 ///   enum { BAR } e;
1725 /// };
1726 ///
1727 /// void test_S6() {
1728 ///   struct S6 a;
1729 ///   a.e = BAR;
1730 /// }
1731 /// @endcode
1732 /// For the declaration of BAR, this routine will return a different
1733 /// scope. The scope S will be the scope of the unnamed enumeration
1734 /// within S6. In C++, this routine will return the scope associated
1735 /// with S6, because the enumeration's scope is a transparent
1736 /// context but structures can contain non-field names. In C, this
1737 /// routine will return the translation unit scope, since the
1738 /// enumeration's scope is a transparent context and structures cannot
1739 /// contain non-field names.
1740 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1741   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1742          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1743          (S->isClassScope() && !getLangOpts().CPlusPlus))
1744     S = S->getParent();
1745   return S;
1746 }
1747
1748 /// \brief Looks up the declaration of "struct objc_super" and
1749 /// saves it for later use in building builtin declaration of
1750 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1751 /// pre-existing declaration exists no action takes place.
1752 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1753                                         IdentifierInfo *II) {
1754   if (!II->isStr("objc_msgSendSuper"))
1755     return;
1756   ASTContext &Context = ThisSema.Context;
1757
1758   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1759                       SourceLocation(), Sema::LookupTagName);
1760   ThisSema.LookupName(Result, S);
1761   if (Result.getResultKind() == LookupResult::Found)
1762     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1763       Context.setObjCSuperType(Context.getTagDeclType(TD));
1764 }
1765
1766 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1767   switch (Error) {
1768   case ASTContext::GE_None:
1769     return "";
1770   case ASTContext::GE_Missing_stdio:
1771     return "stdio.h";
1772   case ASTContext::GE_Missing_setjmp:
1773     return "setjmp.h";
1774   case ASTContext::GE_Missing_ucontext:
1775     return "ucontext.h";
1776   }
1777   llvm_unreachable("unhandled error kind");
1778 }
1779
1780 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1781 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1782 /// if we're creating this built-in in anticipation of redeclaring the
1783 /// built-in.
1784 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1785                                      Scope *S, bool ForRedeclaration,
1786                                      SourceLocation Loc) {
1787   LookupPredefedObjCSuperType(*this, S, II);
1788
1789   ASTContext::GetBuiltinTypeError Error;
1790   QualType R = Context.GetBuiltinType(ID, Error);
1791   if (Error) {
1792     if (ForRedeclaration)
1793       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1794           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1795     return nullptr;
1796   }
1797
1798   if (!ForRedeclaration &&
1799       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1800        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1801     Diag(Loc, diag::ext_implicit_lib_function_decl)
1802         << Context.BuiltinInfo.getName(ID) << R;
1803     if (Context.BuiltinInfo.getHeaderName(ID) &&
1804         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1805       Diag(Loc, diag::note_include_header_or_declare)
1806           << Context.BuiltinInfo.getHeaderName(ID)
1807           << Context.BuiltinInfo.getName(ID);
1808   }
1809
1810   if (R.isNull())
1811     return nullptr;
1812
1813   DeclContext *Parent = Context.getTranslationUnitDecl();
1814   if (getLangOpts().CPlusPlus) {
1815     LinkageSpecDecl *CLinkageDecl =
1816         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1817                                 LinkageSpecDecl::lang_c, false);
1818     CLinkageDecl->setImplicit();
1819     Parent->addDecl(CLinkageDecl);
1820     Parent = CLinkageDecl;
1821   }
1822
1823   FunctionDecl *New = FunctionDecl::Create(Context,
1824                                            Parent,
1825                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1826                                            SC_Extern,
1827                                            false,
1828                                            R->isFunctionProtoType());
1829   New->setImplicit();
1830
1831   // Create Decl objects for each parameter, adding them to the
1832   // FunctionDecl.
1833   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1834     SmallVector<ParmVarDecl*, 16> Params;
1835     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1836       ParmVarDecl *parm =
1837           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1838                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1839                               SC_None, nullptr);
1840       parm->setScopeInfo(0, i);
1841       Params.push_back(parm);
1842     }
1843     New->setParams(Params);
1844   }
1845
1846   AddKnownFunctionAttributes(New);
1847   RegisterLocallyScopedExternCDecl(New, S);
1848
1849   // TUScope is the translation-unit scope to insert this function into.
1850   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1851   // relate Scopes to DeclContexts, and probably eliminate CurContext
1852   // entirely, but we're not there yet.
1853   DeclContext *SavedContext = CurContext;
1854   CurContext = Parent;
1855   PushOnScopeChains(New, TUScope);
1856   CurContext = SavedContext;
1857   return New;
1858 }
1859
1860 /// Typedef declarations don't have linkage, but they still denote the same
1861 /// entity if their types are the same.
1862 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1863 /// isSameEntity.
1864 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1865                                                      TypedefNameDecl *Decl,
1866                                                      LookupResult &Previous) {
1867   // This is only interesting when modules are enabled.
1868   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1869     return;
1870
1871   // Empty sets are uninteresting.
1872   if (Previous.empty())
1873     return;
1874
1875   LookupResult::Filter Filter = Previous.makeFilter();
1876   while (Filter.hasNext()) {
1877     NamedDecl *Old = Filter.next();
1878
1879     // Non-hidden declarations are never ignored.
1880     if (S.isVisible(Old))
1881       continue;
1882
1883     // Declarations of the same entity are not ignored, even if they have
1884     // different linkages.
1885     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1886       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1887                                 Decl->getUnderlyingType()))
1888         continue;
1889
1890       // If both declarations give a tag declaration a typedef name for linkage
1891       // purposes, then they declare the same entity.
1892       if (S.getLangOpts().CPlusPlus &&
1893           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1894           Decl->getAnonDeclWithTypedefName())
1895         continue;
1896     }
1897
1898     Filter.erase();
1899   }
1900
1901   Filter.done();
1902 }
1903
1904 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1905   QualType OldType;
1906   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1907     OldType = OldTypedef->getUnderlyingType();
1908   else
1909     OldType = Context.getTypeDeclType(Old);
1910   QualType NewType = New->getUnderlyingType();
1911
1912   if (NewType->isVariablyModifiedType()) {
1913     // Must not redefine a typedef with a variably-modified type.
1914     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1915     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1916       << Kind << NewType;
1917     if (Old->getLocation().isValid())
1918       Diag(Old->getLocation(), diag::note_previous_definition);
1919     New->setInvalidDecl();
1920     return true;
1921   }
1922
1923   if (OldType != NewType &&
1924       !OldType->isDependentType() &&
1925       !NewType->isDependentType() &&
1926       !Context.hasSameType(OldType, NewType)) {
1927     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1928     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1929       << Kind << NewType << OldType;
1930     if (Old->getLocation().isValid())
1931       Diag(Old->getLocation(), diag::note_previous_definition);
1932     New->setInvalidDecl();
1933     return true;
1934   }
1935   return false;
1936 }
1937
1938 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1939 /// same name and scope as a previous declaration 'Old'.  Figure out
1940 /// how to resolve this situation, merging decls or emitting
1941 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1942 ///
1943 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1944                                 LookupResult &OldDecls) {
1945   // If the new decl is known invalid already, don't bother doing any
1946   // merging checks.
1947   if (New->isInvalidDecl()) return;
1948
1949   // Allow multiple definitions for ObjC built-in typedefs.
1950   // FIXME: Verify the underlying types are equivalent!
1951   if (getLangOpts().ObjC1) {
1952     const IdentifierInfo *TypeID = New->getIdentifier();
1953     switch (TypeID->getLength()) {
1954     default: break;
1955     case 2:
1956       {
1957         if (!TypeID->isStr("id"))
1958           break;
1959         QualType T = New->getUnderlyingType();
1960         if (!T->isPointerType())
1961           break;
1962         if (!T->isVoidPointerType()) {
1963           QualType PT = T->getAs<PointerType>()->getPointeeType();
1964           if (!PT->isStructureType())
1965             break;
1966         }
1967         Context.setObjCIdRedefinitionType(T);
1968         // Install the built-in type for 'id', ignoring the current definition.
1969         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1970         return;
1971       }
1972     case 5:
1973       if (!TypeID->isStr("Class"))
1974         break;
1975       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1976       // Install the built-in type for 'Class', ignoring the current definition.
1977       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1978       return;
1979     case 3:
1980       if (!TypeID->isStr("SEL"))
1981         break;
1982       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1983       // Install the built-in type for 'SEL', ignoring the current definition.
1984       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1985       return;
1986     }
1987     // Fall through - the typedef name was not a builtin type.
1988   }
1989
1990   // Verify the old decl was also a type.
1991   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1992   if (!Old) {
1993     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1994       << New->getDeclName();
1995
1996     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1997     if (OldD->getLocation().isValid())
1998       Diag(OldD->getLocation(), diag::note_previous_definition);
1999
2000     return New->setInvalidDecl();
2001   }
2002
2003   // If the old declaration is invalid, just give up here.
2004   if (Old->isInvalidDecl())
2005     return New->setInvalidDecl();
2006
2007   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2008     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2009     auto *NewTag = New->getAnonDeclWithTypedefName();
2010     NamedDecl *Hidden = nullptr;
2011     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2012         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2013         !hasVisibleDefinition(OldTag, &Hidden)) {
2014       // There is a definition of this tag, but it is not visible. Use it
2015       // instead of our tag.
2016       New->setTypeForDecl(OldTD->getTypeForDecl());
2017       if (OldTD->isModed())
2018         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2019                                     OldTD->getUnderlyingType());
2020       else
2021         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2022
2023       // Make the old tag definition visible.
2024       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2025
2026       // If this was an unscoped enumeration, yank all of its enumerators
2027       // out of the scope.
2028       if (isa<EnumDecl>(NewTag)) {
2029         Scope *EnumScope = getNonFieldDeclScope(S);
2030         for (auto *D : NewTag->decls()) {
2031           auto *ED = cast<EnumConstantDecl>(D);
2032           assert(EnumScope->isDeclScope(ED));
2033           EnumScope->RemoveDecl(ED);
2034           IdResolver.RemoveDecl(ED);
2035           ED->getLexicalDeclContext()->removeDecl(ED);
2036         }
2037       }
2038     }
2039   }
2040
2041   // If the typedef types are not identical, reject them in all languages and
2042   // with any extensions enabled.
2043   if (isIncompatibleTypedef(Old, New))
2044     return;
2045
2046   // The types match.  Link up the redeclaration chain and merge attributes if
2047   // the old declaration was a typedef.
2048   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2049     New->setPreviousDecl(Typedef);
2050     mergeDeclAttributes(New, Old);
2051   }
2052
2053   if (getLangOpts().MicrosoftExt)
2054     return;
2055
2056   if (getLangOpts().CPlusPlus) {
2057     // C++ [dcl.typedef]p2:
2058     //   In a given non-class scope, a typedef specifier can be used to
2059     //   redefine the name of any type declared in that scope to refer
2060     //   to the type to which it already refers.
2061     if (!isa<CXXRecordDecl>(CurContext))
2062       return;
2063
2064     // C++0x [dcl.typedef]p4:
2065     //   In a given class scope, a typedef specifier can be used to redefine
2066     //   any class-name declared in that scope that is not also a typedef-name
2067     //   to refer to the type to which it already refers.
2068     //
2069     // This wording came in via DR424, which was a correction to the
2070     // wording in DR56, which accidentally banned code like:
2071     //
2072     //   struct S {
2073     //     typedef struct A { } A;
2074     //   };
2075     //
2076     // in the C++03 standard. We implement the C++0x semantics, which
2077     // allow the above but disallow
2078     //
2079     //   struct S {
2080     //     typedef int I;
2081     //     typedef int I;
2082     //   };
2083     //
2084     // since that was the intent of DR56.
2085     if (!isa<TypedefNameDecl>(Old))
2086       return;
2087
2088     Diag(New->getLocation(), diag::err_redefinition)
2089       << New->getDeclName();
2090     Diag(Old->getLocation(), diag::note_previous_definition);
2091     return New->setInvalidDecl();
2092   }
2093
2094   // Modules always permit redefinition of typedefs, as does C11.
2095   if (getLangOpts().Modules || getLangOpts().C11)
2096     return;
2097
2098   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2099   // is normally mapped to an error, but can be controlled with
2100   // -Wtypedef-redefinition.  If either the original or the redefinition is
2101   // in a system header, don't emit this for compatibility with GCC.
2102   if (getDiagnostics().getSuppressSystemWarnings() &&
2103       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2104        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2105     return;
2106
2107   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2108     << New->getDeclName();
2109   Diag(Old->getLocation(), diag::note_previous_definition);
2110 }
2111
2112 /// DeclhasAttr - returns true if decl Declaration already has the target
2113 /// attribute.
2114 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2115   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2116   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2117   for (const auto *i : D->attrs())
2118     if (i->getKind() == A->getKind()) {
2119       if (Ann) {
2120         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2121           return true;
2122         continue;
2123       }
2124       // FIXME: Don't hardcode this check
2125       if (OA && isa<OwnershipAttr>(i))
2126         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2127       return true;
2128     }
2129
2130   return false;
2131 }
2132
2133 static bool isAttributeTargetADefinition(Decl *D) {
2134   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2135     return VD->isThisDeclarationADefinition();
2136   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2137     return TD->isCompleteDefinition() || TD->isBeingDefined();
2138   return true;
2139 }
2140
2141 /// Merge alignment attributes from \p Old to \p New, taking into account the
2142 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2143 ///
2144 /// \return \c true if any attributes were added to \p New.
2145 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2146   // Look for alignas attributes on Old, and pick out whichever attribute
2147   // specifies the strictest alignment requirement.
2148   AlignedAttr *OldAlignasAttr = nullptr;
2149   AlignedAttr *OldStrictestAlignAttr = nullptr;
2150   unsigned OldAlign = 0;
2151   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2152     // FIXME: We have no way of representing inherited dependent alignments
2153     // in a case like:
2154     //   template<int A, int B> struct alignas(A) X;
2155     //   template<int A, int B> struct alignas(B) X {};
2156     // For now, we just ignore any alignas attributes which are not on the
2157     // definition in such a case.
2158     if (I->isAlignmentDependent())
2159       return false;
2160
2161     if (I->isAlignas())
2162       OldAlignasAttr = I;
2163
2164     unsigned Align = I->getAlignment(S.Context);
2165     if (Align > OldAlign) {
2166       OldAlign = Align;
2167       OldStrictestAlignAttr = I;
2168     }
2169   }
2170
2171   // Look for alignas attributes on New.
2172   AlignedAttr *NewAlignasAttr = nullptr;
2173   unsigned NewAlign = 0;
2174   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2175     if (I->isAlignmentDependent())
2176       return false;
2177
2178     if (I->isAlignas())
2179       NewAlignasAttr = I;
2180
2181     unsigned Align = I->getAlignment(S.Context);
2182     if (Align > NewAlign)
2183       NewAlign = Align;
2184   }
2185
2186   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2187     // Both declarations have 'alignas' attributes. We require them to match.
2188     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2189     // fall short. (If two declarations both have alignas, they must both match
2190     // every definition, and so must match each other if there is a definition.)
2191
2192     // If either declaration only contains 'alignas(0)' specifiers, then it
2193     // specifies the natural alignment for the type.
2194     if (OldAlign == 0 || NewAlign == 0) {
2195       QualType Ty;
2196       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2197         Ty = VD->getType();
2198       else
2199         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2200
2201       if (OldAlign == 0)
2202         OldAlign = S.Context.getTypeAlign(Ty);
2203       if (NewAlign == 0)
2204         NewAlign = S.Context.getTypeAlign(Ty);
2205     }
2206
2207     if (OldAlign != NewAlign) {
2208       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2209         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2210         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2211       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2212     }
2213   }
2214
2215   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2216     // C++11 [dcl.align]p6:
2217     //   if any declaration of an entity has an alignment-specifier,
2218     //   every defining declaration of that entity shall specify an
2219     //   equivalent alignment.
2220     // C11 6.7.5/7:
2221     //   If the definition of an object does not have an alignment
2222     //   specifier, any other declaration of that object shall also
2223     //   have no alignment specifier.
2224     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2225       << OldAlignasAttr;
2226     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2227       << OldAlignasAttr;
2228   }
2229
2230   bool AnyAdded = false;
2231
2232   // Ensure we have an attribute representing the strictest alignment.
2233   if (OldAlign > NewAlign) {
2234     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2235     Clone->setInherited(true);
2236     New->addAttr(Clone);
2237     AnyAdded = true;
2238   }
2239
2240   // Ensure we have an alignas attribute if the old declaration had one.
2241   if (OldAlignasAttr && !NewAlignasAttr &&
2242       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2243     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2244     Clone->setInherited(true);
2245     New->addAttr(Clone);
2246     AnyAdded = true;
2247   }
2248
2249   return AnyAdded;
2250 }
2251
2252 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2253                                const InheritableAttr *Attr,
2254                                Sema::AvailabilityMergeKind AMK) {
2255   // This function copies an attribute Attr from a previous declaration to the
2256   // new declaration D if the new declaration doesn't itself have that attribute
2257   // yet or if that attribute allows duplicates.
2258   // If you're adding a new attribute that requires logic different from
2259   // "use explicit attribute on decl if present, else use attribute from
2260   // previous decl", for example if the attribute needs to be consistent
2261   // between redeclarations, you need to call a custom merge function here.
2262   InheritableAttr *NewAttr = nullptr;
2263   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2264   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2265     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2266                                       AA->isImplicit(), AA->getIntroduced(),
2267                                       AA->getDeprecated(),
2268                                       AA->getObsoleted(), AA->getUnavailable(),
2269                                       AA->getMessage(), AA->getStrict(),
2270                                       AA->getReplacement(), AMK,
2271                                       AttrSpellingListIndex);
2272   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2273     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2274                                     AttrSpellingListIndex);
2275   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2276     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2277                                         AttrSpellingListIndex);
2278   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2279     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2280                                    AttrSpellingListIndex);
2281   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2282     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2283                                    AttrSpellingListIndex);
2284   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2285     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2286                                 FA->getFormatIdx(), FA->getFirstArg(),
2287                                 AttrSpellingListIndex);
2288   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2289     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2290                                  AttrSpellingListIndex);
2291   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2292     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2293                                        AttrSpellingListIndex,
2294                                        IA->getSemanticSpelling());
2295   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2296     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2297                                       &S.Context.Idents.get(AA->getSpelling()),
2298                                       AttrSpellingListIndex);
2299   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2300            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2301             isa<CUDAGlobalAttr>(Attr))) {
2302     // CUDA target attributes are part of function signature for
2303     // overloading purposes and must not be merged.
2304     return false;
2305   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2306     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2307   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2308     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2309   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2310     NewAttr = S.mergeInternalLinkageAttr(
2311         D, InternalLinkageA->getRange(),
2312         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2313         AttrSpellingListIndex);
2314   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2315     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2316                                 &S.Context.Idents.get(CommonA->getSpelling()),
2317                                 AttrSpellingListIndex);
2318   else if (isa<AlignedAttr>(Attr))
2319     // AlignedAttrs are handled separately, because we need to handle all
2320     // such attributes on a declaration at the same time.
2321     NewAttr = nullptr;
2322   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2323            (AMK == Sema::AMK_Override ||
2324             AMK == Sema::AMK_ProtocolImplementation))
2325     NewAttr = nullptr;
2326   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2327     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2328                               UA->getGuid());
2329   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2330     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2331
2332   if (NewAttr) {
2333     NewAttr->setInherited(true);
2334     D->addAttr(NewAttr);
2335     if (isa<MSInheritanceAttr>(NewAttr))
2336       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2337     return true;
2338   }
2339
2340   return false;
2341 }
2342
2343 static const Decl *getDefinition(const Decl *D) {
2344   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2345     return TD->getDefinition();
2346   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2347     const VarDecl *Def = VD->getDefinition();
2348     if (Def)
2349       return Def;
2350     return VD->getActingDefinition();
2351   }
2352   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2353     return FD->getDefinition();
2354   return nullptr;
2355 }
2356
2357 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2358   for (const auto *Attribute : D->attrs())
2359     if (Attribute->getKind() == Kind)
2360       return true;
2361   return false;
2362 }
2363
2364 /// checkNewAttributesAfterDef - If we already have a definition, check that
2365 /// there are no new attributes in this declaration.
2366 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2367   if (!New->hasAttrs())
2368     return;
2369
2370   const Decl *Def = getDefinition(Old);
2371   if (!Def || Def == New)
2372     return;
2373
2374   AttrVec &NewAttributes = New->getAttrs();
2375   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2376     const Attr *NewAttribute = NewAttributes[I];
2377
2378     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2379       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2380         Sema::SkipBodyInfo SkipBody;
2381         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2382
2383         // If we're skipping this definition, drop the "alias" attribute.
2384         if (SkipBody.ShouldSkip) {
2385           NewAttributes.erase(NewAttributes.begin() + I);
2386           --E;
2387           continue;
2388         }
2389       } else {
2390         VarDecl *VD = cast<VarDecl>(New);
2391         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2392                                 VarDecl::TentativeDefinition
2393                             ? diag::err_alias_after_tentative
2394                             : diag::err_redefinition;
2395         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2396         S.Diag(Def->getLocation(), diag::note_previous_definition);
2397         VD->setInvalidDecl();
2398       }
2399       ++I;
2400       continue;
2401     }
2402
2403     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2404       // Tentative definitions are only interesting for the alias check above.
2405       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2406         ++I;
2407         continue;
2408       }
2409     }
2410
2411     if (hasAttribute(Def, NewAttribute->getKind())) {
2412       ++I;
2413       continue; // regular attr merging will take care of validating this.
2414     }
2415
2416     if (isa<C11NoReturnAttr>(NewAttribute)) {
2417       // C's _Noreturn is allowed to be added to a function after it is defined.
2418       ++I;
2419       continue;
2420     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2421       if (AA->isAlignas()) {
2422         // C++11 [dcl.align]p6:
2423         //   if any declaration of an entity has an alignment-specifier,
2424         //   every defining declaration of that entity shall specify an
2425         //   equivalent alignment.
2426         // C11 6.7.5/7:
2427         //   If the definition of an object does not have an alignment
2428         //   specifier, any other declaration of that object shall also
2429         //   have no alignment specifier.
2430         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2431           << AA;
2432         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2433           << AA;
2434         NewAttributes.erase(NewAttributes.begin() + I);
2435         --E;
2436         continue;
2437       }
2438     }
2439
2440     S.Diag(NewAttribute->getLocation(),
2441            diag::warn_attribute_precede_definition);
2442     S.Diag(Def->getLocation(), diag::note_previous_definition);
2443     NewAttributes.erase(NewAttributes.begin() + I);
2444     --E;
2445   }
2446 }
2447
2448 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2449 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2450                                AvailabilityMergeKind AMK) {
2451   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2452     UsedAttr *NewAttr = OldAttr->clone(Context);
2453     NewAttr->setInherited(true);
2454     New->addAttr(NewAttr);
2455   }
2456
2457   if (!Old->hasAttrs() && !New->hasAttrs())
2458     return;
2459
2460   // Attributes declared post-definition are currently ignored.
2461   checkNewAttributesAfterDef(*this, New, Old);
2462
2463   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2464     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2465       if (OldA->getLabel() != NewA->getLabel()) {
2466         // This redeclaration changes __asm__ label.
2467         Diag(New->getLocation(), diag::err_different_asm_label);
2468         Diag(OldA->getLocation(), diag::note_previous_declaration);
2469       }
2470     } else if (Old->isUsed()) {
2471       // This redeclaration adds an __asm__ label to a declaration that has
2472       // already been ODR-used.
2473       Diag(New->getLocation(), diag::err_late_asm_label_name)
2474         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2475     }
2476   }
2477
2478   // Re-declaration cannot add abi_tag's.
2479   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2480     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2481       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2482         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2483                       NewTag) == OldAbiTagAttr->tags_end()) {
2484           Diag(NewAbiTagAttr->getLocation(),
2485                diag::err_new_abi_tag_on_redeclaration)
2486               << NewTag;
2487           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2488         }
2489       }
2490     } else {
2491       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2492       Diag(Old->getLocation(), diag::note_previous_declaration);
2493     }
2494   }
2495
2496   if (!Old->hasAttrs())
2497     return;
2498
2499   bool foundAny = New->hasAttrs();
2500
2501   // Ensure that any moving of objects within the allocated map is done before
2502   // we process them.
2503   if (!foundAny) New->setAttrs(AttrVec());
2504
2505   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2506     // Ignore deprecated/unavailable/availability attributes if requested.
2507     AvailabilityMergeKind LocalAMK = AMK_None;
2508     if (isa<DeprecatedAttr>(I) ||
2509         isa<UnavailableAttr>(I) ||
2510         isa<AvailabilityAttr>(I)) {
2511       switch (AMK) {
2512       case AMK_None:
2513         continue;
2514
2515       case AMK_Redeclaration:
2516       case AMK_Override:
2517       case AMK_ProtocolImplementation:
2518         LocalAMK = AMK;
2519         break;
2520       }
2521     }
2522
2523     // Already handled.
2524     if (isa<UsedAttr>(I))
2525       continue;
2526
2527     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2528       foundAny = true;
2529   }
2530
2531   if (mergeAlignedAttrs(*this, New, Old))
2532     foundAny = true;
2533
2534   if (!foundAny) New->dropAttrs();
2535 }
2536
2537 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2538 /// to the new one.
2539 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2540                                      const ParmVarDecl *oldDecl,
2541                                      Sema &S) {
2542   // C++11 [dcl.attr.depend]p2:
2543   //   The first declaration of a function shall specify the
2544   //   carries_dependency attribute for its declarator-id if any declaration
2545   //   of the function specifies the carries_dependency attribute.
2546   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2547   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2548     S.Diag(CDA->getLocation(),
2549            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2550     // Find the first declaration of the parameter.
2551     // FIXME: Should we build redeclaration chains for function parameters?
2552     const FunctionDecl *FirstFD =
2553       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2554     const ParmVarDecl *FirstVD =
2555       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2556     S.Diag(FirstVD->getLocation(),
2557            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2558   }
2559
2560   if (!oldDecl->hasAttrs())
2561     return;
2562
2563   bool foundAny = newDecl->hasAttrs();
2564
2565   // Ensure that any moving of objects within the allocated map is
2566   // done before we process them.
2567   if (!foundAny) newDecl->setAttrs(AttrVec());
2568
2569   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2570     if (!DeclHasAttr(newDecl, I)) {
2571       InheritableAttr *newAttr =
2572         cast<InheritableParamAttr>(I->clone(S.Context));
2573       newAttr->setInherited(true);
2574       newDecl->addAttr(newAttr);
2575       foundAny = true;
2576     }
2577   }
2578
2579   if (!foundAny) newDecl->dropAttrs();
2580 }
2581
2582 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2583                                 const ParmVarDecl *OldParam,
2584                                 Sema &S) {
2585   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2586     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2587       if (*Oldnullability != *Newnullability) {
2588         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2589           << DiagNullabilityKind(
2590                *Newnullability,
2591                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2592                 != 0))
2593           << DiagNullabilityKind(
2594                *Oldnullability,
2595                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2596                 != 0));
2597         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2598       }
2599     } else {
2600       QualType NewT = NewParam->getType();
2601       NewT = S.Context.getAttributedType(
2602                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2603                          NewT, NewT);
2604       NewParam->setType(NewT);
2605     }
2606   }
2607 }
2608
2609 namespace {
2610
2611 /// Used in MergeFunctionDecl to keep track of function parameters in
2612 /// C.
2613 struct GNUCompatibleParamWarning {
2614   ParmVarDecl *OldParm;
2615   ParmVarDecl *NewParm;
2616   QualType PromotedType;
2617 };
2618
2619 } // end anonymous namespace
2620
2621 /// getSpecialMember - get the special member enum for a method.
2622 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2623   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2624     if (Ctor->isDefaultConstructor())
2625       return Sema::CXXDefaultConstructor;
2626
2627     if (Ctor->isCopyConstructor())
2628       return Sema::CXXCopyConstructor;
2629
2630     if (Ctor->isMoveConstructor())
2631       return Sema::CXXMoveConstructor;
2632   } else if (isa<CXXDestructorDecl>(MD)) {
2633     return Sema::CXXDestructor;
2634   } else if (MD->isCopyAssignmentOperator()) {
2635     return Sema::CXXCopyAssignment;
2636   } else if (MD->isMoveAssignmentOperator()) {
2637     return Sema::CXXMoveAssignment;
2638   }
2639
2640   return Sema::CXXInvalid;
2641 }
2642
2643 // Determine whether the previous declaration was a definition, implicit
2644 // declaration, or a declaration.
2645 template <typename T>
2646 static std::pair<diag::kind, SourceLocation>
2647 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2648   diag::kind PrevDiag;
2649   SourceLocation OldLocation = Old->getLocation();
2650   if (Old->isThisDeclarationADefinition())
2651     PrevDiag = diag::note_previous_definition;
2652   else if (Old->isImplicit()) {
2653     PrevDiag = diag::note_previous_implicit_declaration;
2654     if (OldLocation.isInvalid())
2655       OldLocation = New->getLocation();
2656   } else
2657     PrevDiag = diag::note_previous_declaration;
2658   return std::make_pair(PrevDiag, OldLocation);
2659 }
2660
2661 /// canRedefineFunction - checks if a function can be redefined. Currently,
2662 /// only extern inline functions can be redefined, and even then only in
2663 /// GNU89 mode.
2664 static bool canRedefineFunction(const FunctionDecl *FD,
2665                                 const LangOptions& LangOpts) {
2666   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2667           !LangOpts.CPlusPlus &&
2668           FD->isInlineSpecified() &&
2669           FD->getStorageClass() == SC_Extern);
2670 }
2671
2672 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2673   const AttributedType *AT = T->getAs<AttributedType>();
2674   while (AT && !AT->isCallingConv())
2675     AT = AT->getModifiedType()->getAs<AttributedType>();
2676   return AT;
2677 }
2678
2679 template <typename T>
2680 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2681   const DeclContext *DC = Old->getDeclContext();
2682   if (DC->isRecord())
2683     return false;
2684
2685   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2686   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2687     return true;
2688   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2689     return true;
2690   return false;
2691 }
2692
2693 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2694 static bool isExternC(VarTemplateDecl *) { return false; }
2695
2696 /// \brief Check whether a redeclaration of an entity introduced by a
2697 /// using-declaration is valid, given that we know it's not an overload
2698 /// (nor a hidden tag declaration).
2699 template<typename ExpectedDecl>
2700 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2701                                    ExpectedDecl *New) {
2702   // C++11 [basic.scope.declarative]p4:
2703   //   Given a set of declarations in a single declarative region, each of
2704   //   which specifies the same unqualified name,
2705   //   -- they shall all refer to the same entity, or all refer to functions
2706   //      and function templates; or
2707   //   -- exactly one declaration shall declare a class name or enumeration
2708   //      name that is not a typedef name and the other declarations shall all
2709   //      refer to the same variable or enumerator, or all refer to functions
2710   //      and function templates; in this case the class name or enumeration
2711   //      name is hidden (3.3.10).
2712
2713   // C++11 [namespace.udecl]p14:
2714   //   If a function declaration in namespace scope or block scope has the
2715   //   same name and the same parameter-type-list as a function introduced
2716   //   by a using-declaration, and the declarations do not declare the same
2717   //   function, the program is ill-formed.
2718
2719   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2720   if (Old &&
2721       !Old->getDeclContext()->getRedeclContext()->Equals(
2722           New->getDeclContext()->getRedeclContext()) &&
2723       !(isExternC(Old) && isExternC(New)))
2724     Old = nullptr;
2725
2726   if (!Old) {
2727     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2728     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2729     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2730     return true;
2731   }
2732   return false;
2733 }
2734
2735 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2736                                             const FunctionDecl *B) {
2737   assert(A->getNumParams() == B->getNumParams());
2738
2739   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2740     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2741     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2742     if (AttrA == AttrB)
2743       return true;
2744     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2745   };
2746
2747   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2748 }
2749
2750 /// MergeFunctionDecl - We just parsed a function 'New' from
2751 /// declarator D which has the same name and scope as a previous
2752 /// declaration 'Old'.  Figure out how to resolve this situation,
2753 /// merging decls or emitting diagnostics as appropriate.
2754 ///
2755 /// In C++, New and Old must be declarations that are not
2756 /// overloaded. Use IsOverload to determine whether New and Old are
2757 /// overloaded, and to select the Old declaration that New should be
2758 /// merged with.
2759 ///
2760 /// Returns true if there was an error, false otherwise.
2761 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2762                              Scope *S, bool MergeTypeWithOld) {
2763   // Verify the old decl was also a function.
2764   FunctionDecl *Old = OldD->getAsFunction();
2765   if (!Old) {
2766     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2767       if (New->getFriendObjectKind()) {
2768         Diag(New->getLocation(), diag::err_using_decl_friend);
2769         Diag(Shadow->getTargetDecl()->getLocation(),
2770              diag::note_using_decl_target);
2771         Diag(Shadow->getUsingDecl()->getLocation(),
2772              diag::note_using_decl) << 0;
2773         return true;
2774       }
2775
2776       // Check whether the two declarations might declare the same function.
2777       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2778         return true;
2779       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2780     } else {
2781       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2782         << New->getDeclName();
2783       Diag(OldD->getLocation(), diag::note_previous_definition);
2784       return true;
2785     }
2786   }
2787
2788   // If the old declaration is invalid, just give up here.
2789   if (Old->isInvalidDecl())
2790     return true;
2791
2792   diag::kind PrevDiag;
2793   SourceLocation OldLocation;
2794   std::tie(PrevDiag, OldLocation) =
2795       getNoteDiagForInvalidRedeclaration(Old, New);
2796
2797   // Don't complain about this if we're in GNU89 mode and the old function
2798   // is an extern inline function.
2799   // Don't complain about specializations. They are not supposed to have
2800   // storage classes.
2801   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2802       New->getStorageClass() == SC_Static &&
2803       Old->hasExternalFormalLinkage() &&
2804       !New->getTemplateSpecializationInfo() &&
2805       !canRedefineFunction(Old, getLangOpts())) {
2806     if (getLangOpts().MicrosoftExt) {
2807       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2808       Diag(OldLocation, PrevDiag);
2809     } else {
2810       Diag(New->getLocation(), diag::err_static_non_static) << New;
2811       Diag(OldLocation, PrevDiag);
2812       return true;
2813     }
2814   }
2815
2816   if (New->hasAttr<InternalLinkageAttr>() &&
2817       !Old->hasAttr<InternalLinkageAttr>()) {
2818     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2819         << New->getDeclName();
2820     Diag(Old->getLocation(), diag::note_previous_definition);
2821     New->dropAttr<InternalLinkageAttr>();
2822   }
2823
2824   // If a function is first declared with a calling convention, but is later
2825   // declared or defined without one, all following decls assume the calling
2826   // convention of the first.
2827   //
2828   // It's OK if a function is first declared without a calling convention,
2829   // but is later declared or defined with the default calling convention.
2830   //
2831   // To test if either decl has an explicit calling convention, we look for
2832   // AttributedType sugar nodes on the type as written.  If they are missing or
2833   // were canonicalized away, we assume the calling convention was implicit.
2834   //
2835   // Note also that we DO NOT return at this point, because we still have
2836   // other tests to run.
2837   QualType OldQType = Context.getCanonicalType(Old->getType());
2838   QualType NewQType = Context.getCanonicalType(New->getType());
2839   const FunctionType *OldType = cast<FunctionType>(OldQType);
2840   const FunctionType *NewType = cast<FunctionType>(NewQType);
2841   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2842   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2843   bool RequiresAdjustment = false;
2844
2845   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2846     FunctionDecl *First = Old->getFirstDecl();
2847     const FunctionType *FT =
2848         First->getType().getCanonicalType()->castAs<FunctionType>();
2849     FunctionType::ExtInfo FI = FT->getExtInfo();
2850     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2851     if (!NewCCExplicit) {
2852       // Inherit the CC from the previous declaration if it was specified
2853       // there but not here.
2854       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2855       RequiresAdjustment = true;
2856     } else {
2857       // Calling conventions aren't compatible, so complain.
2858       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2859       Diag(New->getLocation(), diag::err_cconv_change)
2860         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2861         << !FirstCCExplicit
2862         << (!FirstCCExplicit ? "" :
2863             FunctionType::getNameForCallConv(FI.getCC()));
2864
2865       // Put the note on the first decl, since it is the one that matters.
2866       Diag(First->getLocation(), diag::note_previous_declaration);
2867       return true;
2868     }
2869   }
2870
2871   // FIXME: diagnose the other way around?
2872   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2873     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2874     RequiresAdjustment = true;
2875   }
2876
2877   // Merge regparm attribute.
2878   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2879       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2880     if (NewTypeInfo.getHasRegParm()) {
2881       Diag(New->getLocation(), diag::err_regparm_mismatch)
2882         << NewType->getRegParmType()
2883         << OldType->getRegParmType();
2884       Diag(OldLocation, diag::note_previous_declaration);
2885       return true;
2886     }
2887
2888     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2889     RequiresAdjustment = true;
2890   }
2891
2892   // Merge ns_returns_retained attribute.
2893   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2894     if (NewTypeInfo.getProducesResult()) {
2895       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2896       Diag(OldLocation, diag::note_previous_declaration);
2897       return true;
2898     }
2899
2900     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2901     RequiresAdjustment = true;
2902   }
2903
2904   if (RequiresAdjustment) {
2905     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2906     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2907     New->setType(QualType(AdjustedType, 0));
2908     NewQType = Context.getCanonicalType(New->getType());
2909     NewType = cast<FunctionType>(NewQType);
2910   }
2911
2912   // If this redeclaration makes the function inline, we may need to add it to
2913   // UndefinedButUsed.
2914   if (!Old->isInlined() && New->isInlined() &&
2915       !New->hasAttr<GNUInlineAttr>() &&
2916       !getLangOpts().GNUInline &&
2917       Old->isUsed(false) &&
2918       !Old->isDefined() && !New->isThisDeclarationADefinition())
2919     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2920                                            SourceLocation()));
2921
2922   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2923   // about it.
2924   if (New->hasAttr<GNUInlineAttr>() &&
2925       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2926     UndefinedButUsed.erase(Old->getCanonicalDecl());
2927   }
2928
2929   // If pass_object_size params don't match up perfectly, this isn't a valid
2930   // redeclaration.
2931   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2932       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2933     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2934         << New->getDeclName();
2935     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2936     return true;
2937   }
2938
2939   if (getLangOpts().CPlusPlus) {
2940     // C++1z [over.load]p2
2941     //   Certain function declarations cannot be overloaded:
2942     //     -- Function declarations that differ only in the return type,
2943     //        the exception specification, or both cannot be overloaded.
2944
2945     // Check the exception specifications match. This may recompute the type of
2946     // both Old and New if it resolved exception specifications, so grab the
2947     // types again after this. Because this updates the type, we do this before
2948     // any of the other checks below, which may update the "de facto" NewQType
2949     // but do not necessarily update the type of New.
2950     if (CheckEquivalentExceptionSpec(Old, New))
2951       return true;
2952     OldQType = Context.getCanonicalType(Old->getType());
2953     NewQType = Context.getCanonicalType(New->getType());
2954
2955     // Go back to the type source info to compare the declared return types,
2956     // per C++1y [dcl.type.auto]p13:
2957     //   Redeclarations or specializations of a function or function template
2958     //   with a declared return type that uses a placeholder type shall also
2959     //   use that placeholder, not a deduced type.
2960     QualType OldDeclaredReturnType =
2961         (Old->getTypeSourceInfo()
2962              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2963              : OldType)->getReturnType();
2964     QualType NewDeclaredReturnType =
2965         (New->getTypeSourceInfo()
2966              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2967              : NewType)->getReturnType();
2968     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2969         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2970           New->isLocalExternDecl())) {
2971       QualType ResQT;
2972       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2973           OldDeclaredReturnType->isObjCObjectPointerType())
2974         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2975       if (ResQT.isNull()) {
2976         if (New->isCXXClassMember() && New->isOutOfLine())
2977           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2978               << New << New->getReturnTypeSourceRange();
2979         else
2980           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2981               << New->getReturnTypeSourceRange();
2982         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2983                                     << Old->getReturnTypeSourceRange();
2984         return true;
2985       }
2986       else
2987         NewQType = ResQT;
2988     }
2989
2990     QualType OldReturnType = OldType->getReturnType();
2991     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2992     if (OldReturnType != NewReturnType) {
2993       // If this function has a deduced return type and has already been
2994       // defined, copy the deduced value from the old declaration.
2995       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2996       if (OldAT && OldAT->isDeduced()) {
2997         New->setType(
2998             SubstAutoType(New->getType(),
2999                           OldAT->isDependentType() ? Context.DependentTy
3000                                                    : OldAT->getDeducedType()));
3001         NewQType = Context.getCanonicalType(
3002             SubstAutoType(NewQType,
3003                           OldAT->isDependentType() ? Context.DependentTy
3004                                                    : OldAT->getDeducedType()));
3005       }
3006     }
3007
3008     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3009     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3010     if (OldMethod && NewMethod) {
3011       // Preserve triviality.
3012       NewMethod->setTrivial(OldMethod->isTrivial());
3013
3014       // MSVC allows explicit template specialization at class scope:
3015       // 2 CXXMethodDecls referring to the same function will be injected.
3016       // We don't want a redeclaration error.
3017       bool IsClassScopeExplicitSpecialization =
3018                               OldMethod->isFunctionTemplateSpecialization() &&
3019                               NewMethod->isFunctionTemplateSpecialization();
3020       bool isFriend = NewMethod->getFriendObjectKind();
3021
3022       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3023           !IsClassScopeExplicitSpecialization) {
3024         //    -- Member function declarations with the same name and the
3025         //       same parameter types cannot be overloaded if any of them
3026         //       is a static member function declaration.
3027         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3028           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3029           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3030           return true;
3031         }
3032
3033         // C++ [class.mem]p1:
3034         //   [...] A member shall not be declared twice in the
3035         //   member-specification, except that a nested class or member
3036         //   class template can be declared and then later defined.
3037         if (ActiveTemplateInstantiations.empty()) {
3038           unsigned NewDiag;
3039           if (isa<CXXConstructorDecl>(OldMethod))
3040             NewDiag = diag::err_constructor_redeclared;
3041           else if (isa<CXXDestructorDecl>(NewMethod))
3042             NewDiag = diag::err_destructor_redeclared;
3043           else if (isa<CXXConversionDecl>(NewMethod))
3044             NewDiag = diag::err_conv_function_redeclared;
3045           else
3046             NewDiag = diag::err_member_redeclared;
3047
3048           Diag(New->getLocation(), NewDiag);
3049         } else {
3050           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3051             << New << New->getType();
3052         }
3053         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3054         return true;
3055
3056       // Complain if this is an explicit declaration of a special
3057       // member that was initially declared implicitly.
3058       //
3059       // As an exception, it's okay to befriend such methods in order
3060       // to permit the implicit constructor/destructor/operator calls.
3061       } else if (OldMethod->isImplicit()) {
3062         if (isFriend) {
3063           NewMethod->setImplicit();
3064         } else {
3065           Diag(NewMethod->getLocation(),
3066                diag::err_definition_of_implicitly_declared_member)
3067             << New << getSpecialMember(OldMethod);
3068           return true;
3069         }
3070       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3071         Diag(NewMethod->getLocation(),
3072              diag::err_definition_of_explicitly_defaulted_member)
3073           << getSpecialMember(OldMethod);
3074         return true;
3075       }
3076     }
3077
3078     // C++11 [dcl.attr.noreturn]p1:
3079     //   The first declaration of a function shall specify the noreturn
3080     //   attribute if any declaration of that function specifies the noreturn
3081     //   attribute.
3082     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3083     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3084       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3085       Diag(Old->getFirstDecl()->getLocation(),
3086            diag::note_noreturn_missing_first_decl);
3087     }
3088
3089     // C++11 [dcl.attr.depend]p2:
3090     //   The first declaration of a function shall specify the
3091     //   carries_dependency attribute for its declarator-id if any declaration
3092     //   of the function specifies the carries_dependency attribute.
3093     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3094     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3095       Diag(CDA->getLocation(),
3096            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3097       Diag(Old->getFirstDecl()->getLocation(),
3098            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3099     }
3100
3101     // (C++98 8.3.5p3):
3102     //   All declarations for a function shall agree exactly in both the
3103     //   return type and the parameter-type-list.
3104     // We also want to respect all the extended bits except noreturn.
3105
3106     // noreturn should now match unless the old type info didn't have it.
3107     QualType OldQTypeForComparison = OldQType;
3108     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3109       auto *OldType = OldQType->castAs<FunctionProtoType>();
3110       const FunctionType *OldTypeForComparison
3111         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3112       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3113       assert(OldQTypeForComparison.isCanonical());
3114     }
3115
3116     if (haveIncompatibleLanguageLinkages(Old, New)) {
3117       // As a special case, retain the language linkage from previous
3118       // declarations of a friend function as an extension.
3119       //
3120       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3121       // and is useful because there's otherwise no way to specify language
3122       // linkage within class scope.
3123       //
3124       // Check cautiously as the friend object kind isn't yet complete.
3125       if (New->getFriendObjectKind() != Decl::FOK_None) {
3126         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3127         Diag(OldLocation, PrevDiag);
3128       } else {
3129         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3130         Diag(OldLocation, PrevDiag);
3131         return true;
3132       }
3133     }
3134
3135     if (OldQTypeForComparison == NewQType)
3136       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3137
3138     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3139         New->isLocalExternDecl()) {
3140       // It's OK if we couldn't merge types for a local function declaraton
3141       // if either the old or new type is dependent. We'll merge the types
3142       // when we instantiate the function.
3143       return false;
3144     }
3145
3146     // Fall through for conflicting redeclarations and redefinitions.
3147   }
3148
3149   // C: Function types need to be compatible, not identical. This handles
3150   // duplicate function decls like "void f(int); void f(enum X);" properly.
3151   if (!getLangOpts().CPlusPlus &&
3152       Context.typesAreCompatible(OldQType, NewQType)) {
3153     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3154     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3155     const FunctionProtoType *OldProto = nullptr;
3156     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3157         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3158       // The old declaration provided a function prototype, but the
3159       // new declaration does not. Merge in the prototype.
3160       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3161       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3162       NewQType =
3163           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3164                                   OldProto->getExtProtoInfo());
3165       New->setType(NewQType);
3166       New->setHasInheritedPrototype();
3167
3168       // Synthesize parameters with the same types.
3169       SmallVector<ParmVarDecl*, 16> Params;
3170       for (const auto &ParamType : OldProto->param_types()) {
3171         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3172                                                  SourceLocation(), nullptr,
3173                                                  ParamType, /*TInfo=*/nullptr,
3174                                                  SC_None, nullptr);
3175         Param->setScopeInfo(0, Params.size());
3176         Param->setImplicit();
3177         Params.push_back(Param);
3178       }
3179
3180       New->setParams(Params);
3181     }
3182
3183     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3184   }
3185
3186   // GNU C permits a K&R definition to follow a prototype declaration
3187   // if the declared types of the parameters in the K&R definition
3188   // match the types in the prototype declaration, even when the
3189   // promoted types of the parameters from the K&R definition differ
3190   // from the types in the prototype. GCC then keeps the types from
3191   // the prototype.
3192   //
3193   // If a variadic prototype is followed by a non-variadic K&R definition,
3194   // the K&R definition becomes variadic.  This is sort of an edge case, but
3195   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3196   // C99 6.9.1p8.
3197   if (!getLangOpts().CPlusPlus &&
3198       Old->hasPrototype() && !New->hasPrototype() &&
3199       New->getType()->getAs<FunctionProtoType>() &&
3200       Old->getNumParams() == New->getNumParams()) {
3201     SmallVector<QualType, 16> ArgTypes;
3202     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3203     const FunctionProtoType *OldProto
3204       = Old->getType()->getAs<FunctionProtoType>();
3205     const FunctionProtoType *NewProto
3206       = New->getType()->getAs<FunctionProtoType>();
3207
3208     // Determine whether this is the GNU C extension.
3209     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3210                                                NewProto->getReturnType());
3211     bool LooseCompatible = !MergedReturn.isNull();
3212     for (unsigned Idx = 0, End = Old->getNumParams();
3213          LooseCompatible && Idx != End; ++Idx) {
3214       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3215       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3216       if (Context.typesAreCompatible(OldParm->getType(),
3217                                      NewProto->getParamType(Idx))) {
3218         ArgTypes.push_back(NewParm->getType());
3219       } else if (Context.typesAreCompatible(OldParm->getType(),
3220                                             NewParm->getType(),
3221                                             /*CompareUnqualified=*/true)) {
3222         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3223                                            NewProto->getParamType(Idx) };
3224         Warnings.push_back(Warn);
3225         ArgTypes.push_back(NewParm->getType());
3226       } else
3227         LooseCompatible = false;
3228     }
3229
3230     if (LooseCompatible) {
3231       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3232         Diag(Warnings[Warn].NewParm->getLocation(),
3233              diag::ext_param_promoted_not_compatible_with_prototype)
3234           << Warnings[Warn].PromotedType
3235           << Warnings[Warn].OldParm->getType();
3236         if (Warnings[Warn].OldParm->getLocation().isValid())
3237           Diag(Warnings[Warn].OldParm->getLocation(),
3238                diag::note_previous_declaration);
3239       }
3240
3241       if (MergeTypeWithOld)
3242         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3243                                              OldProto->getExtProtoInfo()));
3244       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3245     }
3246
3247     // Fall through to diagnose conflicting types.
3248   }
3249
3250   // A function that has already been declared has been redeclared or
3251   // defined with a different type; show an appropriate diagnostic.
3252
3253   // If the previous declaration was an implicitly-generated builtin
3254   // declaration, then at the very least we should use a specialized note.
3255   unsigned BuiltinID;
3256   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3257     // If it's actually a library-defined builtin function like 'malloc'
3258     // or 'printf', just warn about the incompatible redeclaration.
3259     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3260       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3261       Diag(OldLocation, diag::note_previous_builtin_declaration)
3262         << Old << Old->getType();
3263
3264       // If this is a global redeclaration, just forget hereafter
3265       // about the "builtin-ness" of the function.
3266       //
3267       // Doing this for local extern declarations is problematic.  If
3268       // the builtin declaration remains visible, a second invalid
3269       // local declaration will produce a hard error; if it doesn't
3270       // remain visible, a single bogus local redeclaration (which is
3271       // actually only a warning) could break all the downstream code.
3272       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3273         New->getIdentifier()->revertBuiltin();
3274
3275       return false;
3276     }
3277
3278     PrevDiag = diag::note_previous_builtin_declaration;
3279   }
3280
3281   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3282   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3283   return true;
3284 }
3285
3286 /// \brief Completes the merge of two function declarations that are
3287 /// known to be compatible.
3288 ///
3289 /// This routine handles the merging of attributes and other
3290 /// properties of function declarations from the old declaration to
3291 /// the new declaration, once we know that New is in fact a
3292 /// redeclaration of Old.
3293 ///
3294 /// \returns false
3295 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3296                                         Scope *S, bool MergeTypeWithOld) {
3297   // Merge the attributes
3298   mergeDeclAttributes(New, Old);
3299
3300   // Merge "pure" flag.
3301   if (Old->isPure())
3302     New->setPure();
3303
3304   // Merge "used" flag.
3305   if (Old->getMostRecentDecl()->isUsed(false))
3306     New->setIsUsed();
3307
3308   // Merge attributes from the parameters.  These can mismatch with K&R
3309   // declarations.
3310   if (New->getNumParams() == Old->getNumParams())
3311       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3312         ParmVarDecl *NewParam = New->getParamDecl(i);
3313         ParmVarDecl *OldParam = Old->getParamDecl(i);
3314         mergeParamDeclAttributes(NewParam, OldParam, *this);
3315         mergeParamDeclTypes(NewParam, OldParam, *this);
3316       }
3317
3318   if (getLangOpts().CPlusPlus)
3319     return MergeCXXFunctionDecl(New, Old, S);
3320
3321   // Merge the function types so the we get the composite types for the return
3322   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3323   // was visible.
3324   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3325   if (!Merged.isNull() && MergeTypeWithOld)
3326     New->setType(Merged);
3327
3328   return false;
3329 }
3330
3331 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3332                                 ObjCMethodDecl *oldMethod) {
3333   // Merge the attributes, including deprecated/unavailable
3334   AvailabilityMergeKind MergeKind =
3335     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3336       ? AMK_ProtocolImplementation
3337       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3338                                                        : AMK_Override;
3339
3340   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3341
3342   // Merge attributes from the parameters.
3343   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3344                                        oe = oldMethod->param_end();
3345   for (ObjCMethodDecl::param_iterator
3346          ni = newMethod->param_begin(), ne = newMethod->param_end();
3347        ni != ne && oi != oe; ++ni, ++oi)
3348     mergeParamDeclAttributes(*ni, *oi, *this);
3349
3350   CheckObjCMethodOverride(newMethod, oldMethod);
3351 }
3352
3353 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3354   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3355
3356   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3357          ? diag::err_redefinition_different_type
3358          : diag::err_redeclaration_different_type)
3359     << New->getDeclName() << New->getType() << Old->getType();
3360
3361   diag::kind PrevDiag;
3362   SourceLocation OldLocation;
3363   std::tie(PrevDiag, OldLocation)
3364     = getNoteDiagForInvalidRedeclaration(Old, New);
3365   S.Diag(OldLocation, PrevDiag);
3366   New->setInvalidDecl();
3367 }
3368
3369 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3370 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3371 /// emitting diagnostics as appropriate.
3372 ///
3373 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3374 /// to here in AddInitializerToDecl. We can't check them before the initializer
3375 /// is attached.
3376 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3377                              bool MergeTypeWithOld) {
3378   if (New->isInvalidDecl() || Old->isInvalidDecl())
3379     return;
3380
3381   QualType MergedT;
3382   if (getLangOpts().CPlusPlus) {
3383     if (New->getType()->isUndeducedType()) {
3384       // We don't know what the new type is until the initializer is attached.
3385       return;
3386     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3387       // These could still be something that needs exception specs checked.
3388       return MergeVarDeclExceptionSpecs(New, Old);
3389     }
3390     // C++ [basic.link]p10:
3391     //   [...] the types specified by all declarations referring to a given
3392     //   object or function shall be identical, except that declarations for an
3393     //   array object can specify array types that differ by the presence or
3394     //   absence of a major array bound (8.3.4).
3395     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3396       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3397       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3398
3399       // We are merging a variable declaration New into Old. If it has an array
3400       // bound, and that bound differs from Old's bound, we should diagnose the
3401       // mismatch.
3402       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3403         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3404              PrevVD = PrevVD->getPreviousDecl()) {
3405           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3406           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3407             continue;
3408
3409           if (!Context.hasSameType(NewArray, PrevVDTy))
3410             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3411         }
3412       }
3413
3414       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3415         if (Context.hasSameType(OldArray->getElementType(),
3416                                 NewArray->getElementType()))
3417           MergedT = New->getType();
3418       }
3419       // FIXME: Check visibility. New is hidden but has a complete type. If New
3420       // has no array bound, it should not inherit one from Old, if Old is not
3421       // visible.
3422       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3423         if (Context.hasSameType(OldArray->getElementType(),
3424                                 NewArray->getElementType()))
3425           MergedT = Old->getType();
3426       }
3427     }
3428     else if (New->getType()->isObjCObjectPointerType() &&
3429                Old->getType()->isObjCObjectPointerType()) {
3430       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3431                                               Old->getType());
3432     }
3433   } else {
3434     // C 6.2.7p2:
3435     //   All declarations that refer to the same object or function shall have
3436     //   compatible type.
3437     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3438   }
3439   if (MergedT.isNull()) {
3440     // It's OK if we couldn't merge types if either type is dependent, for a
3441     // block-scope variable. In other cases (static data members of class
3442     // templates, variable templates, ...), we require the types to be
3443     // equivalent.
3444     // FIXME: The C++ standard doesn't say anything about this.
3445     if ((New->getType()->isDependentType() ||
3446          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3447       // If the old type was dependent, we can't merge with it, so the new type
3448       // becomes dependent for now. We'll reproduce the original type when we
3449       // instantiate the TypeSourceInfo for the variable.
3450       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3451         New->setType(Context.DependentTy);
3452       return;
3453     }
3454     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3455   }
3456
3457   // Don't actually update the type on the new declaration if the old
3458   // declaration was an extern declaration in a different scope.
3459   if (MergeTypeWithOld)
3460     New->setType(MergedT);
3461 }
3462
3463 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3464                                   LookupResult &Previous) {
3465   // C11 6.2.7p4:
3466   //   For an identifier with internal or external linkage declared
3467   //   in a scope in which a prior declaration of that identifier is
3468   //   visible, if the prior declaration specifies internal or
3469   //   external linkage, the type of the identifier at the later
3470   //   declaration becomes the composite type.
3471   //
3472   // If the variable isn't visible, we do not merge with its type.
3473   if (Previous.isShadowed())
3474     return false;
3475
3476   if (S.getLangOpts().CPlusPlus) {
3477     // C++11 [dcl.array]p3:
3478     //   If there is a preceding declaration of the entity in the same
3479     //   scope in which the bound was specified, an omitted array bound
3480     //   is taken to be the same as in that earlier declaration.
3481     return NewVD->isPreviousDeclInSameBlockScope() ||
3482            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3483             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3484   } else {
3485     // If the old declaration was function-local, don't merge with its
3486     // type unless we're in the same function.
3487     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3488            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3489   }
3490 }
3491
3492 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3493 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3494 /// situation, merging decls or emitting diagnostics as appropriate.
3495 ///
3496 /// Tentative definition rules (C99 6.9.2p2) are checked by
3497 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3498 /// definitions here, since the initializer hasn't been attached.
3499 ///
3500 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3501   // If the new decl is already invalid, don't do any other checking.
3502   if (New->isInvalidDecl())
3503     return;
3504
3505   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3506     return;
3507
3508   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3509
3510   // Verify the old decl was also a variable or variable template.
3511   VarDecl *Old = nullptr;
3512   VarTemplateDecl *OldTemplate = nullptr;
3513   if (Previous.isSingleResult()) {
3514     if (NewTemplate) {
3515       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3516       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3517
3518       if (auto *Shadow =
3519               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3520         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3521           return New->setInvalidDecl();
3522     } else {
3523       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3524
3525       if (auto *Shadow =
3526               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3527         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3528           return New->setInvalidDecl();
3529     }
3530   }
3531   if (!Old) {
3532     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3533       << New->getDeclName();
3534     Diag(Previous.getRepresentativeDecl()->getLocation(),
3535          diag::note_previous_definition);
3536     return New->setInvalidDecl();
3537   }
3538
3539   // Ensure the template parameters are compatible.
3540   if (NewTemplate &&
3541       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3542                                       OldTemplate->getTemplateParameters(),
3543                                       /*Complain=*/true, TPL_TemplateMatch))
3544     return New->setInvalidDecl();
3545
3546   // C++ [class.mem]p1:
3547   //   A member shall not be declared twice in the member-specification [...]
3548   //
3549   // Here, we need only consider static data members.
3550   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3551     Diag(New->getLocation(), diag::err_duplicate_member)
3552       << New->getIdentifier();
3553     Diag(Old->getLocation(), diag::note_previous_declaration);
3554     New->setInvalidDecl();
3555   }
3556
3557   mergeDeclAttributes(New, Old);
3558   // Warn if an already-declared variable is made a weak_import in a subsequent
3559   // declaration
3560   if (New->hasAttr<WeakImportAttr>() &&
3561       Old->getStorageClass() == SC_None &&
3562       !Old->hasAttr<WeakImportAttr>()) {
3563     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3564     Diag(Old->getLocation(), diag::note_previous_definition);
3565     // Remove weak_import attribute on new declaration.
3566     New->dropAttr<WeakImportAttr>();
3567   }
3568
3569   if (New->hasAttr<InternalLinkageAttr>() &&
3570       !Old->hasAttr<InternalLinkageAttr>()) {
3571     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3572         << New->getDeclName();
3573     Diag(Old->getLocation(), diag::note_previous_definition);
3574     New->dropAttr<InternalLinkageAttr>();
3575   }
3576
3577   // Merge the types.
3578   VarDecl *MostRecent = Old->getMostRecentDecl();
3579   if (MostRecent != Old) {
3580     MergeVarDeclTypes(New, MostRecent,
3581                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3582     if (New->isInvalidDecl())
3583       return;
3584   }
3585
3586   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3587   if (New->isInvalidDecl())
3588     return;
3589
3590   diag::kind PrevDiag;
3591   SourceLocation OldLocation;
3592   std::tie(PrevDiag, OldLocation) =
3593       getNoteDiagForInvalidRedeclaration(Old, New);
3594
3595   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3596   if (New->getStorageClass() == SC_Static &&
3597       !New->isStaticDataMember() &&
3598       Old->hasExternalFormalLinkage()) {
3599     if (getLangOpts().MicrosoftExt) {
3600       Diag(New->getLocation(), diag::ext_static_non_static)
3601           << New->getDeclName();
3602       Diag(OldLocation, PrevDiag);
3603     } else {
3604       Diag(New->getLocation(), diag::err_static_non_static)
3605           << New->getDeclName();
3606       Diag(OldLocation, PrevDiag);
3607       return New->setInvalidDecl();
3608     }
3609   }
3610   // C99 6.2.2p4:
3611   //   For an identifier declared with the storage-class specifier
3612   //   extern in a scope in which a prior declaration of that
3613   //   identifier is visible,23) if the prior declaration specifies
3614   //   internal or external linkage, the linkage of the identifier at
3615   //   the later declaration is the same as the linkage specified at
3616   //   the prior declaration. If no prior declaration is visible, or
3617   //   if the prior declaration specifies no linkage, then the
3618   //   identifier has external linkage.
3619   if (New->hasExternalStorage() && Old->hasLinkage())
3620     /* Okay */;
3621   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3622            !New->isStaticDataMember() &&
3623            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3624     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3625     Diag(OldLocation, PrevDiag);
3626     return New->setInvalidDecl();
3627   }
3628
3629   // Check if extern is followed by non-extern and vice-versa.
3630   if (New->hasExternalStorage() &&
3631       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3632     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3633     Diag(OldLocation, PrevDiag);
3634     return New->setInvalidDecl();
3635   }
3636   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3637       !New->hasExternalStorage()) {
3638     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3639     Diag(OldLocation, PrevDiag);
3640     return New->setInvalidDecl();
3641   }
3642
3643   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3644
3645   // FIXME: The test for external storage here seems wrong? We still
3646   // need to check for mismatches.
3647   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3648       // Don't complain about out-of-line definitions of static members.
3649       !(Old->getLexicalDeclContext()->isRecord() &&
3650         !New->getLexicalDeclContext()->isRecord())) {
3651     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3652     Diag(OldLocation, PrevDiag);
3653     return New->setInvalidDecl();
3654   }
3655
3656   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3657     if (VarDecl *Def = Old->getDefinition()) {
3658       // C++1z [dcl.fcn.spec]p4:
3659       //   If the definition of a variable appears in a translation unit before
3660       //   its first declaration as inline, the program is ill-formed.
3661       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3662       Diag(Def->getLocation(), diag::note_previous_definition);
3663     }
3664   }
3665
3666   // If this redeclaration makes the function inline, we may need to add it to
3667   // UndefinedButUsed.
3668   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3669       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3670     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3671                                            SourceLocation()));
3672
3673   if (New->getTLSKind() != Old->getTLSKind()) {
3674     if (!Old->getTLSKind()) {
3675       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3676       Diag(OldLocation, PrevDiag);
3677     } else if (!New->getTLSKind()) {
3678       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3679       Diag(OldLocation, PrevDiag);
3680     } else {
3681       // Do not allow redeclaration to change the variable between requiring
3682       // static and dynamic initialization.
3683       // FIXME: GCC allows this, but uses the TLS keyword on the first
3684       // declaration to determine the kind. Do we need to be compatible here?
3685       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3686         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3687       Diag(OldLocation, PrevDiag);
3688     }
3689   }
3690
3691   // C++ doesn't have tentative definitions, so go right ahead and check here.
3692   if (getLangOpts().CPlusPlus &&
3693       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3694     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3695         Old->getCanonicalDecl()->isConstexpr()) {
3696       // This definition won't be a definition any more once it's been merged.
3697       Diag(New->getLocation(),
3698            diag::warn_deprecated_redundant_constexpr_static_def);
3699     } else if (VarDecl *Def = Old->getDefinition()) {
3700       if (checkVarDeclRedefinition(Def, New))
3701         return;
3702     }
3703   }
3704
3705   if (haveIncompatibleLanguageLinkages(Old, New)) {
3706     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3707     Diag(OldLocation, PrevDiag);
3708     New->setInvalidDecl();
3709     return;
3710   }
3711
3712   // Merge "used" flag.
3713   if (Old->getMostRecentDecl()->isUsed(false))
3714     New->setIsUsed();
3715
3716   // Keep a chain of previous declarations.
3717   New->setPreviousDecl(Old);
3718   if (NewTemplate)
3719     NewTemplate->setPreviousDecl(OldTemplate);
3720
3721   // Inherit access appropriately.
3722   New->setAccess(Old->getAccess());
3723   if (NewTemplate)
3724     NewTemplate->setAccess(New->getAccess());
3725
3726   if (Old->isInline())
3727     New->setImplicitlyInline();
3728 }
3729
3730 /// We've just determined that \p Old and \p New both appear to be definitions
3731 /// of the same variable. Either diagnose or fix the problem.
3732 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3733   if (!hasVisibleDefinition(Old) &&
3734       (New->getFormalLinkage() == InternalLinkage ||
3735        New->isInline() ||
3736        New->getDescribedVarTemplate() ||
3737        New->getNumTemplateParameterLists() ||
3738        New->getDeclContext()->isDependentContext())) {
3739     // The previous definition is hidden, and multiple definitions are
3740     // permitted (in separate TUs). Demote this to a declaration.
3741     New->demoteThisDefinitionToDeclaration();
3742
3743     // Make the canonical definition visible.
3744     if (auto *OldTD = Old->getDescribedVarTemplate())
3745       makeMergedDefinitionVisible(OldTD, New->getLocation());
3746     makeMergedDefinitionVisible(Old, New->getLocation());
3747     return false;
3748   } else {
3749     Diag(New->getLocation(), diag::err_redefinition) << New;
3750     Diag(Old->getLocation(), diag::note_previous_definition);
3751     New->setInvalidDecl();
3752     return true;
3753   }
3754 }
3755
3756 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3757 /// no declarator (e.g. "struct foo;") is parsed.
3758 Decl *
3759 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3760                                  RecordDecl *&AnonRecord) {
3761   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3762                                     AnonRecord);
3763 }
3764
3765 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3766 // disambiguate entities defined in different scopes.
3767 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3768 // compatibility.
3769 // We will pick our mangling number depending on which version of MSVC is being
3770 // targeted.
3771 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3772   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3773              ? S->getMSCurManglingNumber()
3774              : S->getMSLastManglingNumber();
3775 }
3776
3777 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3778   if (!Context.getLangOpts().CPlusPlus)
3779     return;
3780
3781   if (isa<CXXRecordDecl>(Tag->getParent())) {
3782     // If this tag is the direct child of a class, number it if
3783     // it is anonymous.
3784     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3785       return;
3786     MangleNumberingContext &MCtx =
3787         Context.getManglingNumberContext(Tag->getParent());
3788     Context.setManglingNumber(
3789         Tag, MCtx.getManglingNumber(
3790                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3791     return;
3792   }
3793
3794   // If this tag isn't a direct child of a class, number it if it is local.
3795   Decl *ManglingContextDecl;
3796   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3797           Tag->getDeclContext(), ManglingContextDecl)) {
3798     Context.setManglingNumber(
3799         Tag, MCtx->getManglingNumber(
3800                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3801   }
3802 }
3803
3804 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3805                                         TypedefNameDecl *NewTD) {
3806   if (TagFromDeclSpec->isInvalidDecl())
3807     return;
3808
3809   // Do nothing if the tag already has a name for linkage purposes.
3810   if (TagFromDeclSpec->hasNameForLinkage())
3811     return;
3812
3813   // A well-formed anonymous tag must always be a TUK_Definition.
3814   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3815
3816   // The type must match the tag exactly;  no qualifiers allowed.
3817   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3818                            Context.getTagDeclType(TagFromDeclSpec))) {
3819     if (getLangOpts().CPlusPlus)
3820       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3821     return;
3822   }
3823
3824   // If we've already computed linkage for the anonymous tag, then
3825   // adding a typedef name for the anonymous decl can change that
3826   // linkage, which might be a serious problem.  Diagnose this as
3827   // unsupported and ignore the typedef name.  TODO: we should
3828   // pursue this as a language defect and establish a formal rule
3829   // for how to handle it.
3830   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3831     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3832
3833     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3834     tagLoc = getLocForEndOfToken(tagLoc);
3835
3836     llvm::SmallString<40> textToInsert;
3837     textToInsert += ' ';
3838     textToInsert += NewTD->getIdentifier()->getName();
3839     Diag(tagLoc, diag::note_typedef_changes_linkage)
3840         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3841     return;
3842   }
3843
3844   // Otherwise, set this is the anon-decl typedef for the tag.
3845   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3846 }
3847
3848 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3849   switch (T) {
3850   case DeclSpec::TST_class:
3851     return 0;
3852   case DeclSpec::TST_struct:
3853     return 1;
3854   case DeclSpec::TST_interface:
3855     return 2;
3856   case DeclSpec::TST_union:
3857     return 3;
3858   case DeclSpec::TST_enum:
3859     return 4;
3860   default:
3861     llvm_unreachable("unexpected type specifier");
3862   }
3863 }
3864
3865 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3866 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3867 /// parameters to cope with template friend declarations.
3868 Decl *
3869 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3870                                  MultiTemplateParamsArg TemplateParams,
3871                                  bool IsExplicitInstantiation,
3872                                  RecordDecl *&AnonRecord) {
3873   Decl *TagD = nullptr;
3874   TagDecl *Tag = nullptr;
3875   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3876       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3877       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3878       DS.getTypeSpecType() == DeclSpec::TST_union ||
3879       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3880     TagD = DS.getRepAsDecl();
3881
3882     if (!TagD) // We probably had an error
3883       return nullptr;
3884
3885     // Note that the above type specs guarantee that the
3886     // type rep is a Decl, whereas in many of the others
3887     // it's a Type.
3888     if (isa<TagDecl>(TagD))
3889       Tag = cast<TagDecl>(TagD);
3890     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3891       Tag = CTD->getTemplatedDecl();
3892   }
3893
3894   if (Tag) {
3895     handleTagNumbering(Tag, S);
3896     Tag->setFreeStanding();
3897     if (Tag->isInvalidDecl())
3898       return Tag;
3899   }
3900
3901   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3902     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3903     // or incomplete types shall not be restrict-qualified."
3904     if (TypeQuals & DeclSpec::TQ_restrict)
3905       Diag(DS.getRestrictSpecLoc(),
3906            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3907            << DS.getSourceRange();
3908   }
3909
3910   if (DS.isInlineSpecified())
3911     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3912         << getLangOpts().CPlusPlus1z;
3913
3914   if (DS.isConstexprSpecified()) {
3915     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3916     // and definitions of functions and variables.
3917     if (Tag)
3918       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3919           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3920     else
3921       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3922     // Don't emit warnings after this error.
3923     return TagD;
3924   }
3925
3926   if (DS.isConceptSpecified()) {
3927     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3928     // either a function concept and its definition or a variable concept and
3929     // its initializer.
3930     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3931     return TagD;
3932   }
3933
3934   DiagnoseFunctionSpecifiers(DS);
3935
3936   if (DS.isFriendSpecified()) {
3937     // If we're dealing with a decl but not a TagDecl, assume that
3938     // whatever routines created it handled the friendship aspect.
3939     if (TagD && !Tag)
3940       return nullptr;
3941     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3942   }
3943
3944   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3945   bool IsExplicitSpecialization =
3946     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3947   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3948       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3949       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3950     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3951     // nested-name-specifier unless it is an explicit instantiation
3952     // or an explicit specialization.
3953     //
3954     // FIXME: We allow class template partial specializations here too, per the
3955     // obvious intent of DR1819.
3956     //
3957     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3958     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3959         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3960     return nullptr;
3961   }
3962
3963   // Track whether this decl-specifier declares anything.
3964   bool DeclaresAnything = true;
3965
3966   // Handle anonymous struct definitions.
3967   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3968     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3969         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3970       if (getLangOpts().CPlusPlus ||
3971           Record->getDeclContext()->isRecord()) {
3972         // If CurContext is a DeclContext that can contain statements,
3973         // RecursiveASTVisitor won't visit the decls that
3974         // BuildAnonymousStructOrUnion() will put into CurContext.
3975         // Also store them here so that they can be part of the
3976         // DeclStmt that gets created in this case.
3977         // FIXME: Also return the IndirectFieldDecls created by
3978         // BuildAnonymousStructOr union, for the same reason?
3979         if (CurContext->isFunctionOrMethod())
3980           AnonRecord = Record;
3981         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3982                                            Context.getPrintingPolicy());
3983       }
3984
3985       DeclaresAnything = false;
3986     }
3987   }
3988
3989   // C11 6.7.2.1p2:
3990   //   A struct-declaration that does not declare an anonymous structure or
3991   //   anonymous union shall contain a struct-declarator-list.
3992   //
3993   // This rule also existed in C89 and C99; the grammar for struct-declaration
3994   // did not permit a struct-declaration without a struct-declarator-list.
3995   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3996       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3997     // Check for Microsoft C extension: anonymous struct/union member.
3998     // Handle 2 kinds of anonymous struct/union:
3999     //   struct STRUCT;
4000     //   union UNION;
4001     // and
4002     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4003     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4004     if ((Tag && Tag->getDeclName()) ||
4005         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4006       RecordDecl *Record = nullptr;
4007       if (Tag)
4008         Record = dyn_cast<RecordDecl>(Tag);
4009       else if (const RecordType *RT =
4010                    DS.getRepAsType().get()->getAsStructureType())
4011         Record = RT->getDecl();
4012       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4013         Record = UT->getDecl();
4014
4015       if (Record && getLangOpts().MicrosoftExt) {
4016         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4017           << Record->isUnion() << DS.getSourceRange();
4018         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4019       }
4020
4021       DeclaresAnything = false;
4022     }
4023   }
4024
4025   // Skip all the checks below if we have a type error.
4026   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4027       (TagD && TagD->isInvalidDecl()))
4028     return TagD;
4029
4030   if (getLangOpts().CPlusPlus &&
4031       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4032     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4033       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4034           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4035         DeclaresAnything = false;
4036
4037   if (!DS.isMissingDeclaratorOk()) {
4038     // Customize diagnostic for a typedef missing a name.
4039     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4040       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4041         << DS.getSourceRange();
4042     else
4043       DeclaresAnything = false;
4044   }
4045
4046   if (DS.isModulePrivateSpecified() &&
4047       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4048     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4049       << Tag->getTagKind()
4050       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4051
4052   ActOnDocumentableDecl(TagD);
4053
4054   // C 6.7/2:
4055   //   A declaration [...] shall declare at least a declarator [...], a tag,
4056   //   or the members of an enumeration.
4057   // C++ [dcl.dcl]p3:
4058   //   [If there are no declarators], and except for the declaration of an
4059   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4060   //   names into the program, or shall redeclare a name introduced by a
4061   //   previous declaration.
4062   if (!DeclaresAnything) {
4063     // In C, we allow this as a (popular) extension / bug. Don't bother
4064     // producing further diagnostics for redundant qualifiers after this.
4065     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4066     return TagD;
4067   }
4068
4069   // C++ [dcl.stc]p1:
4070   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4071   //   init-declarator-list of the declaration shall not be empty.
4072   // C++ [dcl.fct.spec]p1:
4073   //   If a cv-qualifier appears in a decl-specifier-seq, the
4074   //   init-declarator-list of the declaration shall not be empty.
4075   //
4076   // Spurious qualifiers here appear to be valid in C.
4077   unsigned DiagID = diag::warn_standalone_specifier;
4078   if (getLangOpts().CPlusPlus)
4079     DiagID = diag::ext_standalone_specifier;
4080
4081   // Note that a linkage-specification sets a storage class, but
4082   // 'extern "C" struct foo;' is actually valid and not theoretically
4083   // useless.
4084   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4085     if (SCS == DeclSpec::SCS_mutable)
4086       // Since mutable is not a viable storage class specifier in C, there is
4087       // no reason to treat it as an extension. Instead, diagnose as an error.
4088       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4089     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4090       Diag(DS.getStorageClassSpecLoc(), DiagID)
4091         << DeclSpec::getSpecifierName(SCS);
4092   }
4093
4094   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4095     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4096       << DeclSpec::getSpecifierName(TSCS);
4097   if (DS.getTypeQualifiers()) {
4098     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4099       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4100     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4101       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4102     // Restrict is covered above.
4103     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4104       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4105     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4106       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4107   }
4108
4109   // Warn about ignored type attributes, for example:
4110   // __attribute__((aligned)) struct A;
4111   // Attributes should be placed after tag to apply to type declaration.
4112   if (!DS.getAttributes().empty()) {
4113     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4114     if (TypeSpecType == DeclSpec::TST_class ||
4115         TypeSpecType == DeclSpec::TST_struct ||
4116         TypeSpecType == DeclSpec::TST_interface ||
4117         TypeSpecType == DeclSpec::TST_union ||
4118         TypeSpecType == DeclSpec::TST_enum) {
4119       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4120            attrs = attrs->getNext())
4121         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4122             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4123     }
4124   }
4125
4126   return TagD;
4127 }
4128
4129 /// We are trying to inject an anonymous member into the given scope;
4130 /// check if there's an existing declaration that can't be overloaded.
4131 ///
4132 /// \return true if this is a forbidden redeclaration
4133 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4134                                          Scope *S,
4135                                          DeclContext *Owner,
4136                                          DeclarationName Name,
4137                                          SourceLocation NameLoc,
4138                                          bool IsUnion) {
4139   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4140                  Sema::ForRedeclaration);
4141   if (!SemaRef.LookupName(R, S)) return false;
4142
4143   // Pick a representative declaration.
4144   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4145   assert(PrevDecl && "Expected a non-null Decl");
4146
4147   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4148     return false;
4149
4150   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4151     << IsUnion << Name;
4152   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4153
4154   return true;
4155 }
4156
4157 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4158 /// anonymous struct or union AnonRecord into the owning context Owner
4159 /// and scope S. This routine will be invoked just after we realize
4160 /// that an unnamed union or struct is actually an anonymous union or
4161 /// struct, e.g.,
4162 ///
4163 /// @code
4164 /// union {
4165 ///   int i;
4166 ///   float f;
4167 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4168 ///    // f into the surrounding scope.x
4169 /// @endcode
4170 ///
4171 /// This routine is recursive, injecting the names of nested anonymous
4172 /// structs/unions into the owning context and scope as well.
4173 static bool
4174 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4175                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4176                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4177   bool Invalid = false;
4178
4179   // Look every FieldDecl and IndirectFieldDecl with a name.
4180   for (auto *D : AnonRecord->decls()) {
4181     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4182         cast<NamedDecl>(D)->getDeclName()) {
4183       ValueDecl *VD = cast<ValueDecl>(D);
4184       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4185                                        VD->getLocation(),
4186                                        AnonRecord->isUnion())) {
4187         // C++ [class.union]p2:
4188         //   The names of the members of an anonymous union shall be
4189         //   distinct from the names of any other entity in the
4190         //   scope in which the anonymous union is declared.
4191         Invalid = true;
4192       } else {
4193         // C++ [class.union]p2:
4194         //   For the purpose of name lookup, after the anonymous union
4195         //   definition, the members of the anonymous union are
4196         //   considered to have been defined in the scope in which the
4197         //   anonymous union is declared.
4198         unsigned OldChainingSize = Chaining.size();
4199         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4200           Chaining.append(IF->chain_begin(), IF->chain_end());
4201         else
4202           Chaining.push_back(VD);
4203
4204         assert(Chaining.size() >= 2);
4205         NamedDecl **NamedChain =
4206           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4207         for (unsigned i = 0; i < Chaining.size(); i++)
4208           NamedChain[i] = Chaining[i];
4209
4210         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4211             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4212             VD->getType(), {NamedChain, Chaining.size()});
4213
4214         for (const auto *Attr : VD->attrs())
4215           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4216
4217         IndirectField->setAccess(AS);
4218         IndirectField->setImplicit();
4219         SemaRef.PushOnScopeChains(IndirectField, S);
4220
4221         // That includes picking up the appropriate access specifier.
4222         if (AS != AS_none) IndirectField->setAccess(AS);
4223
4224         Chaining.resize(OldChainingSize);
4225       }
4226     }
4227   }
4228
4229   return Invalid;
4230 }
4231
4232 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4233 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4234 /// illegal input values are mapped to SC_None.
4235 static StorageClass
4236 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4237   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4238   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4239          "Parser allowed 'typedef' as storage class VarDecl.");
4240   switch (StorageClassSpec) {
4241   case DeclSpec::SCS_unspecified:    return SC_None;
4242   case DeclSpec::SCS_extern:
4243     if (DS.isExternInLinkageSpec())
4244       return SC_None;
4245     return SC_Extern;
4246   case DeclSpec::SCS_static:         return SC_Static;
4247   case DeclSpec::SCS_auto:           return SC_Auto;
4248   case DeclSpec::SCS_register:       return SC_Register;
4249   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4250     // Illegal SCSs map to None: error reporting is up to the caller.
4251   case DeclSpec::SCS_mutable:        // Fall through.
4252   case DeclSpec::SCS_typedef:        return SC_None;
4253   }
4254   llvm_unreachable("unknown storage class specifier");
4255 }
4256
4257 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4258   assert(Record->hasInClassInitializer());
4259
4260   for (const auto *I : Record->decls()) {
4261     const auto *FD = dyn_cast<FieldDecl>(I);
4262     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4263       FD = IFD->getAnonField();
4264     if (FD && FD->hasInClassInitializer())
4265       return FD->getLocation();
4266   }
4267
4268   llvm_unreachable("couldn't find in-class initializer");
4269 }
4270
4271 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4272                                       SourceLocation DefaultInitLoc) {
4273   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4274     return;
4275
4276   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4277   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4278 }
4279
4280 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4281                                       CXXRecordDecl *AnonUnion) {
4282   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4283     return;
4284
4285   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4286 }
4287
4288 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4289 /// anonymous structure or union. Anonymous unions are a C++ feature
4290 /// (C++ [class.union]) and a C11 feature; anonymous structures
4291 /// are a C11 feature and GNU C++ extension.
4292 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4293                                         AccessSpecifier AS,
4294                                         RecordDecl *Record,
4295                                         const PrintingPolicy &Policy) {
4296   DeclContext *Owner = Record->getDeclContext();
4297
4298   // Diagnose whether this anonymous struct/union is an extension.
4299   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4300     Diag(Record->getLocation(), diag::ext_anonymous_union);
4301   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4302     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4303   else if (!Record->isUnion() && !getLangOpts().C11)
4304     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4305
4306   // C and C++ require different kinds of checks for anonymous
4307   // structs/unions.
4308   bool Invalid = false;
4309   if (getLangOpts().CPlusPlus) {
4310     const char *PrevSpec = nullptr;
4311     unsigned DiagID;
4312     if (Record->isUnion()) {
4313       // C++ [class.union]p6:
4314       //   Anonymous unions declared in a named namespace or in the
4315       //   global namespace shall be declared static.
4316       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4317           (isa<TranslationUnitDecl>(Owner) ||
4318            (isa<NamespaceDecl>(Owner) &&
4319             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4320         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4321           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4322
4323         // Recover by adding 'static'.
4324         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4325                                PrevSpec, DiagID, Policy);
4326       }
4327       // C++ [class.union]p6:
4328       //   A storage class is not allowed in a declaration of an
4329       //   anonymous union in a class scope.
4330       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4331                isa<RecordDecl>(Owner)) {
4332         Diag(DS.getStorageClassSpecLoc(),
4333              diag::err_anonymous_union_with_storage_spec)
4334           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4335
4336         // Recover by removing the storage specifier.
4337         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4338                                SourceLocation(),
4339                                PrevSpec, DiagID, Context.getPrintingPolicy());
4340       }
4341     }
4342
4343     // Ignore const/volatile/restrict qualifiers.
4344     if (DS.getTypeQualifiers()) {
4345       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4346         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4347           << Record->isUnion() << "const"
4348           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4349       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4350         Diag(DS.getVolatileSpecLoc(),
4351              diag::ext_anonymous_struct_union_qualified)
4352           << Record->isUnion() << "volatile"
4353           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4354       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4355         Diag(DS.getRestrictSpecLoc(),
4356              diag::ext_anonymous_struct_union_qualified)
4357           << Record->isUnion() << "restrict"
4358           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4359       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4360         Diag(DS.getAtomicSpecLoc(),
4361              diag::ext_anonymous_struct_union_qualified)
4362           << Record->isUnion() << "_Atomic"
4363           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4364       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4365         Diag(DS.getUnalignedSpecLoc(),
4366              diag::ext_anonymous_struct_union_qualified)
4367           << Record->isUnion() << "__unaligned"
4368           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4369
4370       DS.ClearTypeQualifiers();
4371     }
4372
4373     // C++ [class.union]p2:
4374     //   The member-specification of an anonymous union shall only
4375     //   define non-static data members. [Note: nested types and
4376     //   functions cannot be declared within an anonymous union. ]
4377     for (auto *Mem : Record->decls()) {
4378       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4379         // C++ [class.union]p3:
4380         //   An anonymous union shall not have private or protected
4381         //   members (clause 11).
4382         assert(FD->getAccess() != AS_none);
4383         if (FD->getAccess() != AS_public) {
4384           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4385             << Record->isUnion() << (FD->getAccess() == AS_protected);
4386           Invalid = true;
4387         }
4388
4389         // C++ [class.union]p1
4390         //   An object of a class with a non-trivial constructor, a non-trivial
4391         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4392         //   assignment operator cannot be a member of a union, nor can an
4393         //   array of such objects.
4394         if (CheckNontrivialField(FD))
4395           Invalid = true;
4396       } else if (Mem->isImplicit()) {
4397         // Any implicit members are fine.
4398       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4399         // This is a type that showed up in an
4400         // elaborated-type-specifier inside the anonymous struct or
4401         // union, but which actually declares a type outside of the
4402         // anonymous struct or union. It's okay.
4403       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4404         if (!MemRecord->isAnonymousStructOrUnion() &&
4405             MemRecord->getDeclName()) {
4406           // Visual C++ allows type definition in anonymous struct or union.
4407           if (getLangOpts().MicrosoftExt)
4408             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4409               << Record->isUnion();
4410           else {
4411             // This is a nested type declaration.
4412             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4413               << Record->isUnion();
4414             Invalid = true;
4415           }
4416         } else {
4417           // This is an anonymous type definition within another anonymous type.
4418           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4419           // not part of standard C++.
4420           Diag(MemRecord->getLocation(),
4421                diag::ext_anonymous_record_with_anonymous_type)
4422             << Record->isUnion();
4423         }
4424       } else if (isa<AccessSpecDecl>(Mem)) {
4425         // Any access specifier is fine.
4426       } else if (isa<StaticAssertDecl>(Mem)) {
4427         // In C++1z, static_assert declarations are also fine.
4428       } else {
4429         // We have something that isn't a non-static data
4430         // member. Complain about it.
4431         unsigned DK = diag::err_anonymous_record_bad_member;
4432         if (isa<TypeDecl>(Mem))
4433           DK = diag::err_anonymous_record_with_type;
4434         else if (isa<FunctionDecl>(Mem))
4435           DK = diag::err_anonymous_record_with_function;
4436         else if (isa<VarDecl>(Mem))
4437           DK = diag::err_anonymous_record_with_static;
4438
4439         // Visual C++ allows type definition in anonymous struct or union.
4440         if (getLangOpts().MicrosoftExt &&
4441             DK == diag::err_anonymous_record_with_type)
4442           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4443             << Record->isUnion();
4444         else {
4445           Diag(Mem->getLocation(), DK) << Record->isUnion();
4446           Invalid = true;
4447         }
4448       }
4449     }
4450
4451     // C++11 [class.union]p8 (DR1460):
4452     //   At most one variant member of a union may have a
4453     //   brace-or-equal-initializer.
4454     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4455         Owner->isRecord())
4456       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4457                                 cast<CXXRecordDecl>(Record));
4458   }
4459
4460   if (!Record->isUnion() && !Owner->isRecord()) {
4461     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4462       << getLangOpts().CPlusPlus;
4463     Invalid = true;
4464   }
4465
4466   // Mock up a declarator.
4467   Declarator Dc(DS, Declarator::MemberContext);
4468   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4469   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4470
4471   // Create a declaration for this anonymous struct/union.
4472   NamedDecl *Anon = nullptr;
4473   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4474     Anon = FieldDecl::Create(Context, OwningClass,
4475                              DS.getLocStart(),
4476                              Record->getLocation(),
4477                              /*IdentifierInfo=*/nullptr,
4478                              Context.getTypeDeclType(Record),
4479                              TInfo,
4480                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4481                              /*InitStyle=*/ICIS_NoInit);
4482     Anon->setAccess(AS);
4483     if (getLangOpts().CPlusPlus)
4484       FieldCollector->Add(cast<FieldDecl>(Anon));
4485   } else {
4486     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4487     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4488     if (SCSpec == DeclSpec::SCS_mutable) {
4489       // mutable can only appear on non-static class members, so it's always
4490       // an error here
4491       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4492       Invalid = true;
4493       SC = SC_None;
4494     }
4495
4496     Anon = VarDecl::Create(Context, Owner,
4497                            DS.getLocStart(),
4498                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4499                            Context.getTypeDeclType(Record),
4500                            TInfo, SC);
4501
4502     // Default-initialize the implicit variable. This initialization will be
4503     // trivial in almost all cases, except if a union member has an in-class
4504     // initializer:
4505     //   union { int n = 0; };
4506     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4507   }
4508   Anon->setImplicit();
4509
4510   // Mark this as an anonymous struct/union type.
4511   Record->setAnonymousStructOrUnion(true);
4512
4513   // Add the anonymous struct/union object to the current
4514   // context. We'll be referencing this object when we refer to one of
4515   // its members.
4516   Owner->addDecl(Anon);
4517
4518   // Inject the members of the anonymous struct/union into the owning
4519   // context and into the identifier resolver chain for name lookup
4520   // purposes.
4521   SmallVector<NamedDecl*, 2> Chain;
4522   Chain.push_back(Anon);
4523
4524   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4525     Invalid = true;
4526
4527   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4528     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4529       Decl *ManglingContextDecl;
4530       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4531               NewVD->getDeclContext(), ManglingContextDecl)) {
4532         Context.setManglingNumber(
4533             NewVD, MCtx->getManglingNumber(
4534                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4535         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4536       }
4537     }
4538   }
4539
4540   if (Invalid)
4541     Anon->setInvalidDecl();
4542
4543   return Anon;
4544 }
4545
4546 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4547 /// Microsoft C anonymous structure.
4548 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4549 /// Example:
4550 ///
4551 /// struct A { int a; };
4552 /// struct B { struct A; int b; };
4553 ///
4554 /// void foo() {
4555 ///   B var;
4556 ///   var.a = 3;
4557 /// }
4558 ///
4559 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4560                                            RecordDecl *Record) {
4561   assert(Record && "expected a record!");
4562
4563   // Mock up a declarator.
4564   Declarator Dc(DS, Declarator::TypeNameContext);
4565   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4566   assert(TInfo && "couldn't build declarator info for anonymous struct");
4567
4568   auto *ParentDecl = cast<RecordDecl>(CurContext);
4569   QualType RecTy = Context.getTypeDeclType(Record);
4570
4571   // Create a declaration for this anonymous struct.
4572   NamedDecl *Anon = FieldDecl::Create(Context,
4573                              ParentDecl,
4574                              DS.getLocStart(),
4575                              DS.getLocStart(),
4576                              /*IdentifierInfo=*/nullptr,
4577                              RecTy,
4578                              TInfo,
4579                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4580                              /*InitStyle=*/ICIS_NoInit);
4581   Anon->setImplicit();
4582
4583   // Add the anonymous struct object to the current context.
4584   CurContext->addDecl(Anon);
4585
4586   // Inject the members of the anonymous struct into the current
4587   // context and into the identifier resolver chain for name lookup
4588   // purposes.
4589   SmallVector<NamedDecl*, 2> Chain;
4590   Chain.push_back(Anon);
4591
4592   RecordDecl *RecordDef = Record->getDefinition();
4593   if (RequireCompleteType(Anon->getLocation(), RecTy,
4594                           diag::err_field_incomplete) ||
4595       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4596                                           AS_none, Chain)) {
4597     Anon->setInvalidDecl();
4598     ParentDecl->setInvalidDecl();
4599   }
4600
4601   return Anon;
4602 }
4603
4604 /// GetNameForDeclarator - Determine the full declaration name for the
4605 /// given Declarator.
4606 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4607   return GetNameFromUnqualifiedId(D.getName());
4608 }
4609
4610 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4611 DeclarationNameInfo
4612 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4613   DeclarationNameInfo NameInfo;
4614   NameInfo.setLoc(Name.StartLocation);
4615
4616   switch (Name.getKind()) {
4617
4618   case UnqualifiedId::IK_ImplicitSelfParam:
4619   case UnqualifiedId::IK_Identifier:
4620     NameInfo.setName(Name.Identifier);
4621     NameInfo.setLoc(Name.StartLocation);
4622     return NameInfo;
4623
4624   case UnqualifiedId::IK_OperatorFunctionId:
4625     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4626                                            Name.OperatorFunctionId.Operator));
4627     NameInfo.setLoc(Name.StartLocation);
4628     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4629       = Name.OperatorFunctionId.SymbolLocations[0];
4630     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4631       = Name.EndLocation.getRawEncoding();
4632     return NameInfo;
4633
4634   case UnqualifiedId::IK_LiteralOperatorId:
4635     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4636                                                            Name.Identifier));
4637     NameInfo.setLoc(Name.StartLocation);
4638     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4639     return NameInfo;
4640
4641   case UnqualifiedId::IK_ConversionFunctionId: {
4642     TypeSourceInfo *TInfo;
4643     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4644     if (Ty.isNull())
4645       return DeclarationNameInfo();
4646     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4647                                                Context.getCanonicalType(Ty)));
4648     NameInfo.setLoc(Name.StartLocation);
4649     NameInfo.setNamedTypeInfo(TInfo);
4650     return NameInfo;
4651   }
4652
4653   case UnqualifiedId::IK_ConstructorName: {
4654     TypeSourceInfo *TInfo;
4655     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4656     if (Ty.isNull())
4657       return DeclarationNameInfo();
4658     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4659                                               Context.getCanonicalType(Ty)));
4660     NameInfo.setLoc(Name.StartLocation);
4661     NameInfo.setNamedTypeInfo(TInfo);
4662     return NameInfo;
4663   }
4664
4665   case UnqualifiedId::IK_ConstructorTemplateId: {
4666     // In well-formed code, we can only have a constructor
4667     // template-id that refers to the current context, so go there
4668     // to find the actual type being constructed.
4669     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4670     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4671       return DeclarationNameInfo();
4672
4673     // Determine the type of the class being constructed.
4674     QualType CurClassType = Context.getTypeDeclType(CurClass);
4675
4676     // FIXME: Check two things: that the template-id names the same type as
4677     // CurClassType, and that the template-id does not occur when the name
4678     // was qualified.
4679
4680     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4681                                     Context.getCanonicalType(CurClassType)));
4682     NameInfo.setLoc(Name.StartLocation);
4683     // FIXME: should we retrieve TypeSourceInfo?
4684     NameInfo.setNamedTypeInfo(nullptr);
4685     return NameInfo;
4686   }
4687
4688   case UnqualifiedId::IK_DestructorName: {
4689     TypeSourceInfo *TInfo;
4690     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4691     if (Ty.isNull())
4692       return DeclarationNameInfo();
4693     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4694                                               Context.getCanonicalType(Ty)));
4695     NameInfo.setLoc(Name.StartLocation);
4696     NameInfo.setNamedTypeInfo(TInfo);
4697     return NameInfo;
4698   }
4699
4700   case UnqualifiedId::IK_TemplateId: {
4701     TemplateName TName = Name.TemplateId->Template.get();
4702     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4703     return Context.getNameForTemplate(TName, TNameLoc);
4704   }
4705
4706   } // switch (Name.getKind())
4707
4708   llvm_unreachable("Unknown name kind");
4709 }
4710
4711 static QualType getCoreType(QualType Ty) {
4712   do {
4713     if (Ty->isPointerType() || Ty->isReferenceType())
4714       Ty = Ty->getPointeeType();
4715     else if (Ty->isArrayType())
4716       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4717     else
4718       return Ty.withoutLocalFastQualifiers();
4719   } while (true);
4720 }
4721
4722 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4723 /// and Definition have "nearly" matching parameters. This heuristic is
4724 /// used to improve diagnostics in the case where an out-of-line function
4725 /// definition doesn't match any declaration within the class or namespace.
4726 /// Also sets Params to the list of indices to the parameters that differ
4727 /// between the declaration and the definition. If hasSimilarParameters
4728 /// returns true and Params is empty, then all of the parameters match.
4729 static bool hasSimilarParameters(ASTContext &Context,
4730                                      FunctionDecl *Declaration,
4731                                      FunctionDecl *Definition,
4732                                      SmallVectorImpl<unsigned> &Params) {
4733   Params.clear();
4734   if (Declaration->param_size() != Definition->param_size())
4735     return false;
4736   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4737     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4738     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4739
4740     // The parameter types are identical
4741     if (Context.hasSameType(DefParamTy, DeclParamTy))
4742       continue;
4743
4744     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4745     QualType DefParamBaseTy = getCoreType(DefParamTy);
4746     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4747     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4748
4749     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4750         (DeclTyName && DeclTyName == DefTyName))
4751       Params.push_back(Idx);
4752     else  // The two parameters aren't even close
4753       return false;
4754   }
4755
4756   return true;
4757 }
4758
4759 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4760 /// declarator needs to be rebuilt in the current instantiation.
4761 /// Any bits of declarator which appear before the name are valid for
4762 /// consideration here.  That's specifically the type in the decl spec
4763 /// and the base type in any member-pointer chunks.
4764 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4765                                                     DeclarationName Name) {
4766   // The types we specifically need to rebuild are:
4767   //   - typenames, typeofs, and decltypes
4768   //   - types which will become injected class names
4769   // Of course, we also need to rebuild any type referencing such a
4770   // type.  It's safest to just say "dependent", but we call out a
4771   // few cases here.
4772
4773   DeclSpec &DS = D.getMutableDeclSpec();
4774   switch (DS.getTypeSpecType()) {
4775   case DeclSpec::TST_typename:
4776   case DeclSpec::TST_typeofType:
4777   case DeclSpec::TST_underlyingType:
4778   case DeclSpec::TST_atomic: {
4779     // Grab the type from the parser.
4780     TypeSourceInfo *TSI = nullptr;
4781     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4782     if (T.isNull() || !T->isDependentType()) break;
4783
4784     // Make sure there's a type source info.  This isn't really much
4785     // of a waste; most dependent types should have type source info
4786     // attached already.
4787     if (!TSI)
4788       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4789
4790     // Rebuild the type in the current instantiation.
4791     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4792     if (!TSI) return true;
4793
4794     // Store the new type back in the decl spec.
4795     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4796     DS.UpdateTypeRep(LocType);
4797     break;
4798   }
4799
4800   case DeclSpec::TST_decltype:
4801   case DeclSpec::TST_typeofExpr: {
4802     Expr *E = DS.getRepAsExpr();
4803     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4804     if (Result.isInvalid()) return true;
4805     DS.UpdateExprRep(Result.get());
4806     break;
4807   }
4808
4809   default:
4810     // Nothing to do for these decl specs.
4811     break;
4812   }
4813
4814   // It doesn't matter what order we do this in.
4815   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4816     DeclaratorChunk &Chunk = D.getTypeObject(I);
4817
4818     // The only type information in the declarator which can come
4819     // before the declaration name is the base type of a member
4820     // pointer.
4821     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4822       continue;
4823
4824     // Rebuild the scope specifier in-place.
4825     CXXScopeSpec &SS = Chunk.Mem.Scope();
4826     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4827       return true;
4828   }
4829
4830   return false;
4831 }
4832
4833 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4834   D.setFunctionDefinitionKind(FDK_Declaration);
4835   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4836
4837   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4838       Dcl && Dcl->getDeclContext()->isFileContext())
4839     Dcl->setTopLevelDeclInObjCContainer();
4840
4841   if (getLangOpts().OpenCL)
4842     setCurrentOpenCLExtensionForDecl(Dcl);
4843
4844   return Dcl;
4845 }
4846
4847 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4848 ///   If T is the name of a class, then each of the following shall have a
4849 ///   name different from T:
4850 ///     - every static data member of class T;
4851 ///     - every member function of class T
4852 ///     - every member of class T that is itself a type;
4853 /// \returns true if the declaration name violates these rules.
4854 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4855                                    DeclarationNameInfo NameInfo) {
4856   DeclarationName Name = NameInfo.getName();
4857
4858   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4859   while (Record && Record->isAnonymousStructOrUnion())
4860     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4861   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4862     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4863     return true;
4864   }
4865
4866   return false;
4867 }
4868
4869 /// \brief Diagnose a declaration whose declarator-id has the given
4870 /// nested-name-specifier.
4871 ///
4872 /// \param SS The nested-name-specifier of the declarator-id.
4873 ///
4874 /// \param DC The declaration context to which the nested-name-specifier
4875 /// resolves.
4876 ///
4877 /// \param Name The name of the entity being declared.
4878 ///
4879 /// \param Loc The location of the name of the entity being declared.
4880 ///
4881 /// \returns true if we cannot safely recover from this error, false otherwise.
4882 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4883                                         DeclarationName Name,
4884                                         SourceLocation Loc) {
4885   DeclContext *Cur = CurContext;
4886   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4887     Cur = Cur->getParent();
4888
4889   // If the user provided a superfluous scope specifier that refers back to the
4890   // class in which the entity is already declared, diagnose and ignore it.
4891   //
4892   // class X {
4893   //   void X::f();
4894   // };
4895   //
4896   // Note, it was once ill-formed to give redundant qualification in all
4897   // contexts, but that rule was removed by DR482.
4898   if (Cur->Equals(DC)) {
4899     if (Cur->isRecord()) {
4900       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4901                                       : diag::err_member_extra_qualification)
4902         << Name << FixItHint::CreateRemoval(SS.getRange());
4903       SS.clear();
4904     } else {
4905       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4906     }
4907     return false;
4908   }
4909
4910   // Check whether the qualifying scope encloses the scope of the original
4911   // declaration.
4912   if (!Cur->Encloses(DC)) {
4913     if (Cur->isRecord())
4914       Diag(Loc, diag::err_member_qualification)
4915         << Name << SS.getRange();
4916     else if (isa<TranslationUnitDecl>(DC))
4917       Diag(Loc, diag::err_invalid_declarator_global_scope)
4918         << Name << SS.getRange();
4919     else if (isa<FunctionDecl>(Cur))
4920       Diag(Loc, diag::err_invalid_declarator_in_function)
4921         << Name << SS.getRange();
4922     else if (isa<BlockDecl>(Cur))
4923       Diag(Loc, diag::err_invalid_declarator_in_block)
4924         << Name << SS.getRange();
4925     else
4926       Diag(Loc, diag::err_invalid_declarator_scope)
4927       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4928
4929     return true;
4930   }
4931
4932   if (Cur->isRecord()) {
4933     // Cannot qualify members within a class.
4934     Diag(Loc, diag::err_member_qualification)
4935       << Name << SS.getRange();
4936     SS.clear();
4937
4938     // C++ constructors and destructors with incorrect scopes can break
4939     // our AST invariants by having the wrong underlying types. If
4940     // that's the case, then drop this declaration entirely.
4941     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4942          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4943         !Context.hasSameType(Name.getCXXNameType(),
4944                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4945       return true;
4946
4947     return false;
4948   }
4949
4950   // C++11 [dcl.meaning]p1:
4951   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4952   //   not begin with a decltype-specifer"
4953   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4954   while (SpecLoc.getPrefix())
4955     SpecLoc = SpecLoc.getPrefix();
4956   if (dyn_cast_or_null<DecltypeType>(
4957         SpecLoc.getNestedNameSpecifier()->getAsType()))
4958     Diag(Loc, diag::err_decltype_in_declarator)
4959       << SpecLoc.getTypeLoc().getSourceRange();
4960
4961   return false;
4962 }
4963
4964 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4965                                   MultiTemplateParamsArg TemplateParamLists) {
4966   // TODO: consider using NameInfo for diagnostic.
4967   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4968   DeclarationName Name = NameInfo.getName();
4969
4970   // All of these full declarators require an identifier.  If it doesn't have
4971   // one, the ParsedFreeStandingDeclSpec action should be used.
4972   if (D.isDecompositionDeclarator()) {
4973     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
4974   } else if (!Name) {
4975     if (!D.isInvalidType())  // Reject this if we think it is valid.
4976       Diag(D.getDeclSpec().getLocStart(),
4977            diag::err_declarator_need_ident)
4978         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4979     return nullptr;
4980   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4981     return nullptr;
4982
4983   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4984   // we find one that is.
4985   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4986          (S->getFlags() & Scope::TemplateParamScope) != 0)
4987     S = S->getParent();
4988
4989   DeclContext *DC = CurContext;
4990   if (D.getCXXScopeSpec().isInvalid())
4991     D.setInvalidType();
4992   else if (D.getCXXScopeSpec().isSet()) {
4993     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4994                                         UPPC_DeclarationQualifier))
4995       return nullptr;
4996
4997     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4998     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4999     if (!DC || isa<EnumDecl>(DC)) {
5000       // If we could not compute the declaration context, it's because the
5001       // declaration context is dependent but does not refer to a class,
5002       // class template, or class template partial specialization. Complain
5003       // and return early, to avoid the coming semantic disaster.
5004       Diag(D.getIdentifierLoc(),
5005            diag::err_template_qualified_declarator_no_match)
5006         << D.getCXXScopeSpec().getScopeRep()
5007         << D.getCXXScopeSpec().getRange();
5008       return nullptr;
5009     }
5010     bool IsDependentContext = DC->isDependentContext();
5011
5012     if (!IsDependentContext &&
5013         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5014       return nullptr;
5015
5016     // If a class is incomplete, do not parse entities inside it.
5017     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5018       Diag(D.getIdentifierLoc(),
5019            diag::err_member_def_undefined_record)
5020         << Name << DC << D.getCXXScopeSpec().getRange();
5021       return nullptr;
5022     }
5023     if (!D.getDeclSpec().isFriendSpecified()) {
5024       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5025                                       Name, D.getIdentifierLoc())) {
5026         if (DC->isRecord())
5027           return nullptr;
5028
5029         D.setInvalidType();
5030       }
5031     }
5032
5033     // Check whether we need to rebuild the type of the given
5034     // declaration in the current instantiation.
5035     if (EnteringContext && IsDependentContext &&
5036         TemplateParamLists.size() != 0) {
5037       ContextRAII SavedContext(*this, DC);
5038       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5039         D.setInvalidType();
5040     }
5041   }
5042
5043   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5044   QualType R = TInfo->getType();
5045
5046   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5047     // If this is a typedef, we'll end up spewing multiple diagnostics.
5048     // Just return early; it's safer. If this is a function, let the
5049     // "constructor cannot have a return type" diagnostic handle it.
5050     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5051       return nullptr;
5052
5053   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5054                                       UPPC_DeclarationType))
5055     D.setInvalidType();
5056
5057   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5058                         ForRedeclaration);
5059
5060   // See if this is a redefinition of a variable in the same scope.
5061   if (!D.getCXXScopeSpec().isSet()) {
5062     bool IsLinkageLookup = false;
5063     bool CreateBuiltins = false;
5064
5065     // If the declaration we're planning to build will be a function
5066     // or object with linkage, then look for another declaration with
5067     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5068     //
5069     // If the declaration we're planning to build will be declared with
5070     // external linkage in the translation unit, create any builtin with
5071     // the same name.
5072     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5073       /* Do nothing*/;
5074     else if (CurContext->isFunctionOrMethod() &&
5075              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5076               R->isFunctionType())) {
5077       IsLinkageLookup = true;
5078       CreateBuiltins =
5079           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5080     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5081                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5082       CreateBuiltins = true;
5083
5084     if (IsLinkageLookup)
5085       Previous.clear(LookupRedeclarationWithLinkage);
5086
5087     LookupName(Previous, S, CreateBuiltins);
5088   } else { // Something like "int foo::x;"
5089     LookupQualifiedName(Previous, DC);
5090
5091     // C++ [dcl.meaning]p1:
5092     //   When the declarator-id is qualified, the declaration shall refer to a
5093     //  previously declared member of the class or namespace to which the
5094     //  qualifier refers (or, in the case of a namespace, of an element of the
5095     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5096     //  thereof; [...]
5097     //
5098     // Note that we already checked the context above, and that we do not have
5099     // enough information to make sure that Previous contains the declaration
5100     // we want to match. For example, given:
5101     //
5102     //   class X {
5103     //     void f();
5104     //     void f(float);
5105     //   };
5106     //
5107     //   void X::f(int) { } // ill-formed
5108     //
5109     // In this case, Previous will point to the overload set
5110     // containing the two f's declared in X, but neither of them
5111     // matches.
5112
5113     // C++ [dcl.meaning]p1:
5114     //   [...] the member shall not merely have been introduced by a
5115     //   using-declaration in the scope of the class or namespace nominated by
5116     //   the nested-name-specifier of the declarator-id.
5117     RemoveUsingDecls(Previous);
5118   }
5119
5120   if (Previous.isSingleResult() &&
5121       Previous.getFoundDecl()->isTemplateParameter()) {
5122     // Maybe we will complain about the shadowed template parameter.
5123     if (!D.isInvalidType())
5124       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5125                                       Previous.getFoundDecl());
5126
5127     // Just pretend that we didn't see the previous declaration.
5128     Previous.clear();
5129   }
5130
5131   // In C++, the previous declaration we find might be a tag type
5132   // (class or enum). In this case, the new declaration will hide the
5133   // tag type. Note that this does does not apply if we're declaring a
5134   // typedef (C++ [dcl.typedef]p4).
5135   if (Previous.isSingleTagDecl() &&
5136       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5137     Previous.clear();
5138
5139   // Check that there are no default arguments other than in the parameters
5140   // of a function declaration (C++ only).
5141   if (getLangOpts().CPlusPlus)
5142     CheckExtraCXXDefaultArguments(D);
5143
5144   if (D.getDeclSpec().isConceptSpecified()) {
5145     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5146     // applied only to the definition of a function template or variable
5147     // template, declared in namespace scope
5148     if (!TemplateParamLists.size()) {
5149       Diag(D.getDeclSpec().getConceptSpecLoc(),
5150            diag:: err_concept_wrong_decl_kind);
5151       return nullptr;
5152     }
5153
5154     if (!DC->getRedeclContext()->isFileContext()) {
5155       Diag(D.getIdentifierLoc(),
5156            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5157       return nullptr;
5158     }
5159   }
5160
5161   NamedDecl *New;
5162
5163   bool AddToScope = true;
5164   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5165     if (TemplateParamLists.size()) {
5166       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5167       return nullptr;
5168     }
5169
5170     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5171   } else if (R->isFunctionType()) {
5172     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5173                                   TemplateParamLists,
5174                                   AddToScope);
5175   } else {
5176     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5177                                   AddToScope);
5178   }
5179
5180   if (!New)
5181     return nullptr;
5182
5183   // If this has an identifier and is not a function template specialization,
5184   // add it to the scope stack.
5185   if (New->getDeclName() && AddToScope) {
5186     // Only make a locally-scoped extern declaration visible if it is the first
5187     // declaration of this entity. Qualified lookup for such an entity should
5188     // only find this declaration if there is no visible declaration of it.
5189     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5190     PushOnScopeChains(New, S, AddToContext);
5191     if (!AddToContext)
5192       CurContext->addHiddenDecl(New);
5193   }
5194
5195   if (isInOpenMPDeclareTargetContext())
5196     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5197
5198   return New;
5199 }
5200
5201 /// Helper method to turn variable array types into constant array
5202 /// types in certain situations which would otherwise be errors (for
5203 /// GCC compatibility).
5204 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5205                                                     ASTContext &Context,
5206                                                     bool &SizeIsNegative,
5207                                                     llvm::APSInt &Oversized) {
5208   // This method tries to turn a variable array into a constant
5209   // array even when the size isn't an ICE.  This is necessary
5210   // for compatibility with code that depends on gcc's buggy
5211   // constant expression folding, like struct {char x[(int)(char*)2];}
5212   SizeIsNegative = false;
5213   Oversized = 0;
5214
5215   if (T->isDependentType())
5216     return QualType();
5217
5218   QualifierCollector Qs;
5219   const Type *Ty = Qs.strip(T);
5220
5221   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5222     QualType Pointee = PTy->getPointeeType();
5223     QualType FixedType =
5224         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5225                                             Oversized);
5226     if (FixedType.isNull()) return FixedType;
5227     FixedType = Context.getPointerType(FixedType);
5228     return Qs.apply(Context, FixedType);
5229   }
5230   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5231     QualType Inner = PTy->getInnerType();
5232     QualType FixedType =
5233         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5234                                             Oversized);
5235     if (FixedType.isNull()) return FixedType;
5236     FixedType = Context.getParenType(FixedType);
5237     return Qs.apply(Context, FixedType);
5238   }
5239
5240   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5241   if (!VLATy)
5242     return QualType();
5243   // FIXME: We should probably handle this case
5244   if (VLATy->getElementType()->isVariablyModifiedType())
5245     return QualType();
5246
5247   llvm::APSInt Res;
5248   if (!VLATy->getSizeExpr() ||
5249       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5250     return QualType();
5251
5252   // Check whether the array size is negative.
5253   if (Res.isSigned() && Res.isNegative()) {
5254     SizeIsNegative = true;
5255     return QualType();
5256   }
5257
5258   // Check whether the array is too large to be addressed.
5259   unsigned ActiveSizeBits
5260     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5261                                               Res);
5262   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5263     Oversized = Res;
5264     return QualType();
5265   }
5266
5267   return Context.getConstantArrayType(VLATy->getElementType(),
5268                                       Res, ArrayType::Normal, 0);
5269 }
5270
5271 static void
5272 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5273   SrcTL = SrcTL.getUnqualifiedLoc();
5274   DstTL = DstTL.getUnqualifiedLoc();
5275   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5276     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5277     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5278                                       DstPTL.getPointeeLoc());
5279     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5280     return;
5281   }
5282   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5283     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5284     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5285                                       DstPTL.getInnerLoc());
5286     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5287     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5288     return;
5289   }
5290   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5291   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5292   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5293   TypeLoc DstElemTL = DstATL.getElementLoc();
5294   DstElemTL.initializeFullCopy(SrcElemTL);
5295   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5296   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5297   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5298 }
5299
5300 /// Helper method to turn variable array types into constant array
5301 /// types in certain situations which would otherwise be errors (for
5302 /// GCC compatibility).
5303 static TypeSourceInfo*
5304 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5305                                               ASTContext &Context,
5306                                               bool &SizeIsNegative,
5307                                               llvm::APSInt &Oversized) {
5308   QualType FixedTy
5309     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5310                                           SizeIsNegative, Oversized);
5311   if (FixedTy.isNull())
5312     return nullptr;
5313   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5314   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5315                                     FixedTInfo->getTypeLoc());
5316   return FixedTInfo;
5317 }
5318
5319 /// \brief Register the given locally-scoped extern "C" declaration so
5320 /// that it can be found later for redeclarations. We include any extern "C"
5321 /// declaration that is not visible in the translation unit here, not just
5322 /// function-scope declarations.
5323 void
5324 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5325   if (!getLangOpts().CPlusPlus &&
5326       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5327     // Don't need to track declarations in the TU in C.
5328     return;
5329
5330   // Note that we have a locally-scoped external with this name.
5331   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5332 }
5333
5334 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5335   // FIXME: We can have multiple results via __attribute__((overloadable)).
5336   auto Result = Context.getExternCContextDecl()->lookup(Name);
5337   return Result.empty() ? nullptr : *Result.begin();
5338 }
5339
5340 /// \brief Diagnose function specifiers on a declaration of an identifier that
5341 /// does not identify a function.
5342 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5343   // FIXME: We should probably indicate the identifier in question to avoid
5344   // confusion for constructs like "virtual int a(), b;"
5345   if (DS.isVirtualSpecified())
5346     Diag(DS.getVirtualSpecLoc(),
5347          diag::err_virtual_non_function);
5348
5349   if (DS.isExplicitSpecified())
5350     Diag(DS.getExplicitSpecLoc(),
5351          diag::err_explicit_non_function);
5352
5353   if (DS.isNoreturnSpecified())
5354     Diag(DS.getNoreturnSpecLoc(),
5355          diag::err_noreturn_non_function);
5356 }
5357
5358 NamedDecl*
5359 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5360                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5361   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5362   if (D.getCXXScopeSpec().isSet()) {
5363     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5364       << D.getCXXScopeSpec().getRange();
5365     D.setInvalidType();
5366     // Pretend we didn't see the scope specifier.
5367     DC = CurContext;
5368     Previous.clear();
5369   }
5370
5371   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5372
5373   if (D.getDeclSpec().isInlineSpecified())
5374     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5375         << getLangOpts().CPlusPlus1z;
5376   if (D.getDeclSpec().isConstexprSpecified())
5377     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5378       << 1;
5379   if (D.getDeclSpec().isConceptSpecified())
5380     Diag(D.getDeclSpec().getConceptSpecLoc(),
5381          diag::err_concept_wrong_decl_kind);
5382
5383   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5384     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5385       << D.getName().getSourceRange();
5386     return nullptr;
5387   }
5388
5389   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5390   if (!NewTD) return nullptr;
5391
5392   // Handle attributes prior to checking for duplicates in MergeVarDecl
5393   ProcessDeclAttributes(S, NewTD, D);
5394
5395   CheckTypedefForVariablyModifiedType(S, NewTD);
5396
5397   bool Redeclaration = D.isRedeclaration();
5398   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5399   D.setRedeclaration(Redeclaration);
5400   return ND;
5401 }
5402
5403 void
5404 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5405   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5406   // then it shall have block scope.
5407   // Note that variably modified types must be fixed before merging the decl so
5408   // that redeclarations will match.
5409   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5410   QualType T = TInfo->getType();
5411   if (T->isVariablyModifiedType()) {
5412     getCurFunction()->setHasBranchProtectedScope();
5413
5414     if (S->getFnParent() == nullptr) {
5415       bool SizeIsNegative;
5416       llvm::APSInt Oversized;
5417       TypeSourceInfo *FixedTInfo =
5418         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5419                                                       SizeIsNegative,
5420                                                       Oversized);
5421       if (FixedTInfo) {
5422         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5423         NewTD->setTypeSourceInfo(FixedTInfo);
5424       } else {
5425         if (SizeIsNegative)
5426           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5427         else if (T->isVariableArrayType())
5428           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5429         else if (Oversized.getBoolValue())
5430           Diag(NewTD->getLocation(), diag::err_array_too_large)
5431             << Oversized.toString(10);
5432         else
5433           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5434         NewTD->setInvalidDecl();
5435       }
5436     }
5437   }
5438 }
5439
5440 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5441 /// declares a typedef-name, either using the 'typedef' type specifier or via
5442 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5443 NamedDecl*
5444 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5445                            LookupResult &Previous, bool &Redeclaration) {
5446   // Merge the decl with the existing one if appropriate. If the decl is
5447   // in an outer scope, it isn't the same thing.
5448   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5449                        /*AllowInlineNamespace*/false);
5450   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5451   if (!Previous.empty()) {
5452     Redeclaration = true;
5453     MergeTypedefNameDecl(S, NewTD, Previous);
5454   }
5455
5456   // If this is the C FILE type, notify the AST context.
5457   if (IdentifierInfo *II = NewTD->getIdentifier())
5458     if (!NewTD->isInvalidDecl() &&
5459         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5460       if (II->isStr("FILE"))
5461         Context.setFILEDecl(NewTD);
5462       else if (II->isStr("jmp_buf"))
5463         Context.setjmp_bufDecl(NewTD);
5464       else if (II->isStr("sigjmp_buf"))
5465         Context.setsigjmp_bufDecl(NewTD);
5466       else if (II->isStr("ucontext_t"))
5467         Context.setucontext_tDecl(NewTD);
5468     }
5469
5470   return NewTD;
5471 }
5472
5473 /// \brief Determines whether the given declaration is an out-of-scope
5474 /// previous declaration.
5475 ///
5476 /// This routine should be invoked when name lookup has found a
5477 /// previous declaration (PrevDecl) that is not in the scope where a
5478 /// new declaration by the same name is being introduced. If the new
5479 /// declaration occurs in a local scope, previous declarations with
5480 /// linkage may still be considered previous declarations (C99
5481 /// 6.2.2p4-5, C++ [basic.link]p6).
5482 ///
5483 /// \param PrevDecl the previous declaration found by name
5484 /// lookup
5485 ///
5486 /// \param DC the context in which the new declaration is being
5487 /// declared.
5488 ///
5489 /// \returns true if PrevDecl is an out-of-scope previous declaration
5490 /// for a new delcaration with the same name.
5491 static bool
5492 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5493                                 ASTContext &Context) {
5494   if (!PrevDecl)
5495     return false;
5496
5497   if (!PrevDecl->hasLinkage())
5498     return false;
5499
5500   if (Context.getLangOpts().CPlusPlus) {
5501     // C++ [basic.link]p6:
5502     //   If there is a visible declaration of an entity with linkage
5503     //   having the same name and type, ignoring entities declared
5504     //   outside the innermost enclosing namespace scope, the block
5505     //   scope declaration declares that same entity and receives the
5506     //   linkage of the previous declaration.
5507     DeclContext *OuterContext = DC->getRedeclContext();
5508     if (!OuterContext->isFunctionOrMethod())
5509       // This rule only applies to block-scope declarations.
5510       return false;
5511
5512     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5513     if (PrevOuterContext->isRecord())
5514       // We found a member function: ignore it.
5515       return false;
5516
5517     // Find the innermost enclosing namespace for the new and
5518     // previous declarations.
5519     OuterContext = OuterContext->getEnclosingNamespaceContext();
5520     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5521
5522     // The previous declaration is in a different namespace, so it
5523     // isn't the same function.
5524     if (!OuterContext->Equals(PrevOuterContext))
5525       return false;
5526   }
5527
5528   return true;
5529 }
5530
5531 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5532   CXXScopeSpec &SS = D.getCXXScopeSpec();
5533   if (!SS.isSet()) return;
5534   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5535 }
5536
5537 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5538   QualType type = decl->getType();
5539   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5540   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5541     // Various kinds of declaration aren't allowed to be __autoreleasing.
5542     unsigned kind = -1U;
5543     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5544       if (var->hasAttr<BlocksAttr>())
5545         kind = 0; // __block
5546       else if (!var->hasLocalStorage())
5547         kind = 1; // global
5548     } else if (isa<ObjCIvarDecl>(decl)) {
5549       kind = 3; // ivar
5550     } else if (isa<FieldDecl>(decl)) {
5551       kind = 2; // field
5552     }
5553
5554     if (kind != -1U) {
5555       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5556         << kind;
5557     }
5558   } else if (lifetime == Qualifiers::OCL_None) {
5559     // Try to infer lifetime.
5560     if (!type->isObjCLifetimeType())
5561       return false;
5562
5563     lifetime = type->getObjCARCImplicitLifetime();
5564     type = Context.getLifetimeQualifiedType(type, lifetime);
5565     decl->setType(type);
5566   }
5567
5568   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5569     // Thread-local variables cannot have lifetime.
5570     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5571         var->getTLSKind()) {
5572       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5573         << var->getType();
5574       return true;
5575     }
5576   }
5577
5578   return false;
5579 }
5580
5581 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5582   // Ensure that an auto decl is deduced otherwise the checks below might cache
5583   // the wrong linkage.
5584   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5585
5586   // 'weak' only applies to declarations with external linkage.
5587   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5588     if (!ND.isExternallyVisible()) {
5589       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5590       ND.dropAttr<WeakAttr>();
5591     }
5592   }
5593   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5594     if (ND.isExternallyVisible()) {
5595       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5596       ND.dropAttr<WeakRefAttr>();
5597       ND.dropAttr<AliasAttr>();
5598     }
5599   }
5600
5601   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5602     if (VD->hasInit()) {
5603       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5604         assert(VD->isThisDeclarationADefinition() &&
5605                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5606         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5607         VD->dropAttr<AliasAttr>();
5608       }
5609     }
5610   }
5611
5612   // 'selectany' only applies to externally visible variable declarations.
5613   // It does not apply to functions.
5614   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5615     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5616       S.Diag(Attr->getLocation(),
5617              diag::err_attribute_selectany_non_extern_data);
5618       ND.dropAttr<SelectAnyAttr>();
5619     }
5620   }
5621
5622   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5623     // dll attributes require external linkage. Static locals may have external
5624     // linkage but still cannot be explicitly imported or exported.
5625     auto *VD = dyn_cast<VarDecl>(&ND);
5626     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5627       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5628         << &ND << Attr;
5629       ND.setInvalidDecl();
5630     }
5631   }
5632
5633   // Virtual functions cannot be marked as 'notail'.
5634   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5635     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5636       if (MD->isVirtual()) {
5637         S.Diag(ND.getLocation(),
5638                diag::err_invalid_attribute_on_virtual_function)
5639             << Attr;
5640         ND.dropAttr<NotTailCalledAttr>();
5641       }
5642 }
5643
5644 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5645                                            NamedDecl *NewDecl,
5646                                            bool IsSpecialization,
5647                                            bool IsDefinition) {
5648   if (OldDecl->isInvalidDecl())
5649     return;
5650
5651   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5652     OldDecl = OldTD->getTemplatedDecl();
5653     if (!IsSpecialization)
5654       IsDefinition = false;
5655   }
5656   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5657     NewDecl = NewTD->getTemplatedDecl();
5658
5659   if (!OldDecl || !NewDecl)
5660     return;
5661
5662   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5663   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5664   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5665   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5666
5667   // dllimport and dllexport are inheritable attributes so we have to exclude
5668   // inherited attribute instances.
5669   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5670                     (NewExportAttr && !NewExportAttr->isInherited());
5671
5672   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5673   // the only exception being explicit specializations.
5674   // Implicitly generated declarations are also excluded for now because there
5675   // is no other way to switch these to use dllimport or dllexport.
5676   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5677
5678   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5679     // Allow with a warning for free functions and global variables.
5680     bool JustWarn = false;
5681     if (!OldDecl->isCXXClassMember()) {
5682       auto *VD = dyn_cast<VarDecl>(OldDecl);
5683       if (VD && !VD->getDescribedVarTemplate())
5684         JustWarn = true;
5685       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5686       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5687         JustWarn = true;
5688     }
5689
5690     // We cannot change a declaration that's been used because IR has already
5691     // been emitted. Dllimported functions will still work though (modulo
5692     // address equality) as they can use the thunk.
5693     if (OldDecl->isUsed())
5694       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5695         JustWarn = false;
5696
5697     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5698                                : diag::err_attribute_dll_redeclaration;
5699     S.Diag(NewDecl->getLocation(), DiagID)
5700         << NewDecl
5701         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5702     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5703     if (!JustWarn) {
5704       NewDecl->setInvalidDecl();
5705       return;
5706     }
5707   }
5708
5709   // A redeclaration is not allowed to drop a dllimport attribute, the only
5710   // exceptions being inline function definitions, local extern declarations,
5711   // qualified friend declarations or special MSVC extension: in the last case,
5712   // the declaration is treated as if it were marked dllexport.
5713   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5714   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5715   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5716     // Ignore static data because out-of-line definitions are diagnosed
5717     // separately.
5718     IsStaticDataMember = VD->isStaticDataMember();
5719     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5720                    VarDecl::DeclarationOnly;
5721   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5722     IsInline = FD->isInlined();
5723     IsQualifiedFriend = FD->getQualifier() &&
5724                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5725   }
5726
5727   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5728       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5729     if (IsMicrosoft && IsDefinition) {
5730       S.Diag(NewDecl->getLocation(),
5731              diag::warn_redeclaration_without_import_attribute)
5732           << NewDecl;
5733       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5734       NewDecl->dropAttr<DLLImportAttr>();
5735       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5736           NewImportAttr->getRange(), S.Context,
5737           NewImportAttr->getSpellingListIndex()));
5738     } else {
5739       S.Diag(NewDecl->getLocation(),
5740              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5741           << NewDecl << OldImportAttr;
5742       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5743       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5744       OldDecl->dropAttr<DLLImportAttr>();
5745       NewDecl->dropAttr<DLLImportAttr>();
5746     }
5747   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5748     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5749     OldDecl->dropAttr<DLLImportAttr>();
5750     NewDecl->dropAttr<DLLImportAttr>();
5751     S.Diag(NewDecl->getLocation(),
5752            diag::warn_dllimport_dropped_from_inline_function)
5753         << NewDecl << OldImportAttr;
5754   }
5755 }
5756
5757 /// Given that we are within the definition of the given function,
5758 /// will that definition behave like C99's 'inline', where the
5759 /// definition is discarded except for optimization purposes?
5760 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5761   // Try to avoid calling GetGVALinkageForFunction.
5762
5763   // All cases of this require the 'inline' keyword.
5764   if (!FD->isInlined()) return false;
5765
5766   // This is only possible in C++ with the gnu_inline attribute.
5767   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5768     return false;
5769
5770   // Okay, go ahead and call the relatively-more-expensive function.
5771   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5772 }
5773
5774 /// Determine whether a variable is extern "C" prior to attaching
5775 /// an initializer. We can't just call isExternC() here, because that
5776 /// will also compute and cache whether the declaration is externally
5777 /// visible, which might change when we attach the initializer.
5778 ///
5779 /// This can only be used if the declaration is known to not be a
5780 /// redeclaration of an internal linkage declaration.
5781 ///
5782 /// For instance:
5783 ///
5784 ///   auto x = []{};
5785 ///
5786 /// Attaching the initializer here makes this declaration not externally
5787 /// visible, because its type has internal linkage.
5788 ///
5789 /// FIXME: This is a hack.
5790 template<typename T>
5791 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5792   if (S.getLangOpts().CPlusPlus) {
5793     // In C++, the overloadable attribute negates the effects of extern "C".
5794     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5795       return false;
5796
5797     // So do CUDA's host/device attributes.
5798     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5799                                  D->template hasAttr<CUDAHostAttr>()))
5800       return false;
5801   }
5802   return D->isExternC();
5803 }
5804
5805 static bool shouldConsiderLinkage(const VarDecl *VD) {
5806   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5807   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5808     return VD->hasExternalStorage();
5809   if (DC->isFileContext())
5810     return true;
5811   if (DC->isRecord())
5812     return false;
5813   llvm_unreachable("Unexpected context");
5814 }
5815
5816 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5817   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5818   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5819       isa<OMPDeclareReductionDecl>(DC))
5820     return true;
5821   if (DC->isRecord())
5822     return false;
5823   llvm_unreachable("Unexpected context");
5824 }
5825
5826 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5827                           AttributeList::Kind Kind) {
5828   for (const AttributeList *L = AttrList; L; L = L->getNext())
5829     if (L->getKind() == Kind)
5830       return true;
5831   return false;
5832 }
5833
5834 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5835                           AttributeList::Kind Kind) {
5836   // Check decl attributes on the DeclSpec.
5837   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5838     return true;
5839
5840   // Walk the declarator structure, checking decl attributes that were in a type
5841   // position to the decl itself.
5842   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5843     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5844       return true;
5845   }
5846
5847   // Finally, check attributes on the decl itself.
5848   return hasParsedAttr(S, PD.getAttributes(), Kind);
5849 }
5850
5851 /// Adjust the \c DeclContext for a function or variable that might be a
5852 /// function-local external declaration.
5853 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5854   if (!DC->isFunctionOrMethod())
5855     return false;
5856
5857   // If this is a local extern function or variable declared within a function
5858   // template, don't add it into the enclosing namespace scope until it is
5859   // instantiated; it might have a dependent type right now.
5860   if (DC->isDependentContext())
5861     return true;
5862
5863   // C++11 [basic.link]p7:
5864   //   When a block scope declaration of an entity with linkage is not found to
5865   //   refer to some other declaration, then that entity is a member of the
5866   //   innermost enclosing namespace.
5867   //
5868   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5869   // semantically-enclosing namespace, not a lexically-enclosing one.
5870   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5871     DC = DC->getParent();
5872   return true;
5873 }
5874
5875 /// \brief Returns true if given declaration has external C language linkage.
5876 static bool isDeclExternC(const Decl *D) {
5877   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5878     return FD->isExternC();
5879   if (const auto *VD = dyn_cast<VarDecl>(D))
5880     return VD->isExternC();
5881
5882   llvm_unreachable("Unknown type of decl!");
5883 }
5884
5885 NamedDecl *Sema::ActOnVariableDeclarator(
5886     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5887     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5888     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5889   QualType R = TInfo->getType();
5890   DeclarationName Name = GetNameForDeclarator(D).getName();
5891
5892   IdentifierInfo *II = Name.getAsIdentifierInfo();
5893
5894   if (D.isDecompositionDeclarator()) {
5895     AddToScope = false;
5896     // Take the name of the first declarator as our name for diagnostic
5897     // purposes.
5898     auto &Decomp = D.getDecompositionDeclarator();
5899     if (!Decomp.bindings().empty()) {
5900       II = Decomp.bindings()[0].Name;
5901       Name = II;
5902     }
5903   } else if (!II) {
5904     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5905       << Name;
5906     return nullptr;
5907   }
5908
5909   if (getLangOpts().OpenCL) {
5910     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5911     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5912     // argument.
5913     if (R->isImageType() || R->isPipeType()) {
5914       Diag(D.getIdentifierLoc(),
5915            diag::err_opencl_type_can_only_be_used_as_function_parameter)
5916           << R;
5917       D.setInvalidType();
5918       return nullptr;
5919     }
5920
5921     // OpenCL v1.2 s6.9.r:
5922     // The event type cannot be used to declare a program scope variable.
5923     // OpenCL v2.0 s6.9.q:
5924     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
5925     if (NULL == S->getParent()) {
5926       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
5927         Diag(D.getIdentifierLoc(),
5928              diag::err_invalid_type_for_program_scope_var) << R;
5929         D.setInvalidType();
5930         return nullptr;
5931       }
5932     }
5933
5934     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5935     QualType NR = R;
5936     while (NR->isPointerType()) {
5937       if (NR->isFunctionPointerType()) {
5938         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5939         D.setInvalidType();
5940         break;
5941       }
5942       NR = NR->getPointeeType();
5943     }
5944
5945     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
5946       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5947       // half array type (unless the cl_khr_fp16 extension is enabled).
5948       if (Context.getBaseElementType(R)->isHalfType()) {
5949         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5950         D.setInvalidType();
5951       }
5952     }
5953
5954     // OpenCL v1.2 s6.9.b p4:
5955     // The sampler type cannot be used with the __local and __global address
5956     // space qualifiers.
5957     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5958       R.getAddressSpace() == LangAS::opencl_global)) {
5959       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5960     }
5961
5962     // OpenCL v1.2 s6.9.r:
5963     // The event type cannot be used with the __local, __constant and __global
5964     // address space qualifiers.
5965     if (R->isEventT()) {
5966       if (R.getAddressSpace()) {
5967         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5968         D.setInvalidType();
5969       }
5970     }
5971   }
5972
5973   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5974   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5975
5976   // dllimport globals without explicit storage class are treated as extern. We
5977   // have to change the storage class this early to get the right DeclContext.
5978   if (SC == SC_None && !DC->isRecord() &&
5979       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5980       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5981     SC = SC_Extern;
5982
5983   DeclContext *OriginalDC = DC;
5984   bool IsLocalExternDecl = SC == SC_Extern &&
5985                            adjustContextForLocalExternDecl(DC);
5986
5987   if (SCSpec == DeclSpec::SCS_mutable) {
5988     // mutable can only appear on non-static class members, so it's always
5989     // an error here
5990     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5991     D.setInvalidType();
5992     SC = SC_None;
5993   }
5994
5995   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5996       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5997                               D.getDeclSpec().getStorageClassSpecLoc())) {
5998     // In C++11, the 'register' storage class specifier is deprecated.
5999     // Suppress the warning in system macros, it's used in macros in some
6000     // popular C system headers, such as in glibc's htonl() macro.
6001     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6002          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6003                                    : diag::warn_deprecated_register)
6004       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6005   }
6006
6007   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6008
6009   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6010     // C99 6.9p2: The storage-class specifiers auto and register shall not
6011     // appear in the declaration specifiers in an external declaration.
6012     // Global Register+Asm is a GNU extension we support.
6013     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6014       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6015       D.setInvalidType();
6016     }
6017   }
6018
6019   bool IsExplicitSpecialization = false;
6020   bool IsVariableTemplateSpecialization = false;
6021   bool IsPartialSpecialization = false;
6022   bool IsVariableTemplate = false;
6023   VarDecl *NewVD = nullptr;
6024   VarTemplateDecl *NewTemplate = nullptr;
6025   TemplateParameterList *TemplateParams = nullptr;
6026   if (!getLangOpts().CPlusPlus) {
6027     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6028                             D.getIdentifierLoc(), II,
6029                             R, TInfo, SC);
6030
6031     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6032       ParsingInitForAutoVars.insert(NewVD);
6033
6034     if (D.isInvalidType())
6035       NewVD->setInvalidDecl();
6036   } else {
6037     bool Invalid = false;
6038
6039     if (DC->isRecord() && !CurContext->isRecord()) {
6040       // This is an out-of-line definition of a static data member.
6041       switch (SC) {
6042       case SC_None:
6043         break;
6044       case SC_Static:
6045         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6046              diag::err_static_out_of_line)
6047           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6048         break;
6049       case SC_Auto:
6050       case SC_Register:
6051       case SC_Extern:
6052         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6053         // to names of variables declared in a block or to function parameters.
6054         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6055         // of class members
6056
6057         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6058              diag::err_storage_class_for_static_member)
6059           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6060         break;
6061       case SC_PrivateExtern:
6062         llvm_unreachable("C storage class in c++!");
6063       }
6064     }
6065
6066     if (SC == SC_Static && CurContext->isRecord()) {
6067       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6068         if (RD->isLocalClass())
6069           Diag(D.getIdentifierLoc(),
6070                diag::err_static_data_member_not_allowed_in_local_class)
6071             << Name << RD->getDeclName();
6072
6073         // C++98 [class.union]p1: If a union contains a static data member,
6074         // the program is ill-formed. C++11 drops this restriction.
6075         if (RD->isUnion())
6076           Diag(D.getIdentifierLoc(),
6077                getLangOpts().CPlusPlus11
6078                  ? diag::warn_cxx98_compat_static_data_member_in_union
6079                  : diag::ext_static_data_member_in_union) << Name;
6080         // We conservatively disallow static data members in anonymous structs.
6081         else if (!RD->getDeclName())
6082           Diag(D.getIdentifierLoc(),
6083                diag::err_static_data_member_not_allowed_in_anon_struct)
6084             << Name << RD->isUnion();
6085       }
6086     }
6087
6088     // Match up the template parameter lists with the scope specifier, then
6089     // determine whether we have a template or a template specialization.
6090     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6091         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6092         D.getCXXScopeSpec(),
6093         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6094             ? D.getName().TemplateId
6095             : nullptr,
6096         TemplateParamLists,
6097         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6098
6099     if (TemplateParams) {
6100       if (!TemplateParams->size() &&
6101           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6102         // There is an extraneous 'template<>' for this variable. Complain
6103         // about it, but allow the declaration of the variable.
6104         Diag(TemplateParams->getTemplateLoc(),
6105              diag::err_template_variable_noparams)
6106           << II
6107           << SourceRange(TemplateParams->getTemplateLoc(),
6108                          TemplateParams->getRAngleLoc());
6109         TemplateParams = nullptr;
6110       } else {
6111         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6112           // This is an explicit specialization or a partial specialization.
6113           // FIXME: Check that we can declare a specialization here.
6114           IsVariableTemplateSpecialization = true;
6115           IsPartialSpecialization = TemplateParams->size() > 0;
6116         } else { // if (TemplateParams->size() > 0)
6117           // This is a template declaration.
6118           IsVariableTemplate = true;
6119
6120           // Check that we can declare a template here.
6121           if (CheckTemplateDeclScope(S, TemplateParams))
6122             return nullptr;
6123
6124           // Only C++1y supports variable templates (N3651).
6125           Diag(D.getIdentifierLoc(),
6126                getLangOpts().CPlusPlus14
6127                    ? diag::warn_cxx11_compat_variable_template
6128                    : diag::ext_variable_template);
6129         }
6130       }
6131     } else {
6132       assert(
6133           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6134           "should have a 'template<>' for this decl");
6135     }
6136
6137     if (IsVariableTemplateSpecialization) {
6138       SourceLocation TemplateKWLoc =
6139           TemplateParamLists.size() > 0
6140               ? TemplateParamLists[0]->getTemplateLoc()
6141               : SourceLocation();
6142       DeclResult Res = ActOnVarTemplateSpecialization(
6143           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6144           IsPartialSpecialization);
6145       if (Res.isInvalid())
6146         return nullptr;
6147       NewVD = cast<VarDecl>(Res.get());
6148       AddToScope = false;
6149     } else if (D.isDecompositionDeclarator()) {
6150       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6151                                         D.getIdentifierLoc(), R, TInfo, SC,
6152                                         Bindings);
6153     } else
6154       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6155                               D.getIdentifierLoc(), II, R, TInfo, SC);
6156
6157     // If this is supposed to be a variable template, create it as such.
6158     if (IsVariableTemplate) {
6159       NewTemplate =
6160           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6161                                   TemplateParams, NewVD);
6162       NewVD->setDescribedVarTemplate(NewTemplate);
6163     }
6164
6165     // If this decl has an auto type in need of deduction, make a note of the
6166     // Decl so we can diagnose uses of it in its own initializer.
6167     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6168       ParsingInitForAutoVars.insert(NewVD);
6169
6170     if (D.isInvalidType() || Invalid) {
6171       NewVD->setInvalidDecl();
6172       if (NewTemplate)
6173         NewTemplate->setInvalidDecl();
6174     }
6175
6176     SetNestedNameSpecifier(NewVD, D);
6177
6178     // If we have any template parameter lists that don't directly belong to
6179     // the variable (matching the scope specifier), store them.
6180     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6181     if (TemplateParamLists.size() > VDTemplateParamLists)
6182       NewVD->setTemplateParameterListsInfo(
6183           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6184
6185     if (D.getDeclSpec().isConstexprSpecified()) {
6186       NewVD->setConstexpr(true);
6187       // C++1z [dcl.spec.constexpr]p1:
6188       //   A static data member declared with the constexpr specifier is
6189       //   implicitly an inline variable.
6190       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6191         NewVD->setImplicitlyInline();
6192     }
6193
6194     if (D.getDeclSpec().isConceptSpecified()) {
6195       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6196         VTD->setConcept();
6197
6198       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6199       // be declared with the thread_local, inline, friend, or constexpr
6200       // specifiers, [...]
6201       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6202         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6203              diag::err_concept_decl_invalid_specifiers)
6204             << 0 << 0;
6205         NewVD->setInvalidDecl(true);
6206       }
6207
6208       if (D.getDeclSpec().isConstexprSpecified()) {
6209         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6210              diag::err_concept_decl_invalid_specifiers)
6211             << 0 << 3;
6212         NewVD->setInvalidDecl(true);
6213       }
6214
6215       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6216       // applied only to the definition of a function template or variable
6217       // template, declared in namespace scope.
6218       if (IsVariableTemplateSpecialization) {
6219         Diag(D.getDeclSpec().getConceptSpecLoc(),
6220              diag::err_concept_specified_specialization)
6221             << (IsPartialSpecialization ? 2 : 1);
6222       }
6223
6224       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6225       // following restrictions:
6226       // - The declared type shall have the type bool.
6227       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6228           !NewVD->isInvalidDecl()) {
6229         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6230         NewVD->setInvalidDecl(true);
6231       }
6232     }
6233   }
6234
6235   if (D.getDeclSpec().isInlineSpecified()) {
6236     if (!getLangOpts().CPlusPlus) {
6237       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6238           << 0;
6239     } else if (CurContext->isFunctionOrMethod()) {
6240       // 'inline' is not allowed on block scope variable declaration.
6241       Diag(D.getDeclSpec().getInlineSpecLoc(),
6242            diag::err_inline_declaration_block_scope) << Name
6243         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6244     } else {
6245       Diag(D.getDeclSpec().getInlineSpecLoc(),
6246            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6247                                      : diag::ext_inline_variable);
6248       NewVD->setInlineSpecified();
6249     }
6250   }
6251
6252   // Set the lexical context. If the declarator has a C++ scope specifier, the
6253   // lexical context will be different from the semantic context.
6254   NewVD->setLexicalDeclContext(CurContext);
6255   if (NewTemplate)
6256     NewTemplate->setLexicalDeclContext(CurContext);
6257
6258   if (IsLocalExternDecl) {
6259     if (D.isDecompositionDeclarator())
6260       for (auto *B : Bindings)
6261         B->setLocalExternDecl();
6262     else
6263       NewVD->setLocalExternDecl();
6264   }
6265
6266   bool EmitTLSUnsupportedError = false;
6267   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6268     // C++11 [dcl.stc]p4:
6269     //   When thread_local is applied to a variable of block scope the
6270     //   storage-class-specifier static is implied if it does not appear
6271     //   explicitly.
6272     // Core issue: 'static' is not implied if the variable is declared
6273     //   'extern'.
6274     if (NewVD->hasLocalStorage() &&
6275         (SCSpec != DeclSpec::SCS_unspecified ||
6276          TSCS != DeclSpec::TSCS_thread_local ||
6277          !DC->isFunctionOrMethod()))
6278       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6279            diag::err_thread_non_global)
6280         << DeclSpec::getSpecifierName(TSCS);
6281     else if (!Context.getTargetInfo().isTLSSupported()) {
6282       if (getLangOpts().CUDA) {
6283         // Postpone error emission until we've collected attributes required to
6284         // figure out whether it's a host or device variable and whether the
6285         // error should be ignored.
6286         EmitTLSUnsupportedError = true;
6287         // We still need to mark the variable as TLS so it shows up in AST with
6288         // proper storage class for other tools to use even if we're not going
6289         // to emit any code for it.
6290         NewVD->setTSCSpec(TSCS);
6291       } else
6292         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6293              diag::err_thread_unsupported);
6294     } else
6295       NewVD->setTSCSpec(TSCS);
6296   }
6297
6298   // C99 6.7.4p3
6299   //   An inline definition of a function with external linkage shall
6300   //   not contain a definition of a modifiable object with static or
6301   //   thread storage duration...
6302   // We only apply this when the function is required to be defined
6303   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6304   // that a local variable with thread storage duration still has to
6305   // be marked 'static'.  Also note that it's possible to get these
6306   // semantics in C++ using __attribute__((gnu_inline)).
6307   if (SC == SC_Static && S->getFnParent() != nullptr &&
6308       !NewVD->getType().isConstQualified()) {
6309     FunctionDecl *CurFD = getCurFunctionDecl();
6310     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6311       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6312            diag::warn_static_local_in_extern_inline);
6313       MaybeSuggestAddingStaticToDecl(CurFD);
6314     }
6315   }
6316
6317   if (D.getDeclSpec().isModulePrivateSpecified()) {
6318     if (IsVariableTemplateSpecialization)
6319       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6320           << (IsPartialSpecialization ? 1 : 0)
6321           << FixItHint::CreateRemoval(
6322                  D.getDeclSpec().getModulePrivateSpecLoc());
6323     else if (IsExplicitSpecialization)
6324       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6325         << 2
6326         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6327     else if (NewVD->hasLocalStorage())
6328       Diag(NewVD->getLocation(), diag::err_module_private_local)
6329         << 0 << NewVD->getDeclName()
6330         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6331         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6332     else {
6333       NewVD->setModulePrivate();
6334       if (NewTemplate)
6335         NewTemplate->setModulePrivate();
6336       for (auto *B : Bindings)
6337         B->setModulePrivate();
6338     }
6339   }
6340
6341   // Handle attributes prior to checking for duplicates in MergeVarDecl
6342   ProcessDeclAttributes(S, NewVD, D);
6343
6344   if (getLangOpts().CUDA) {
6345     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6346       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6347            diag::err_thread_unsupported);
6348     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6349     // storage [duration]."
6350     if (SC == SC_None && S->getFnParent() != nullptr &&
6351         (NewVD->hasAttr<CUDASharedAttr>() ||
6352          NewVD->hasAttr<CUDAConstantAttr>())) {
6353       NewVD->setStorageClass(SC_Static);
6354     }
6355   }
6356
6357   // Ensure that dllimport globals without explicit storage class are treated as
6358   // extern. The storage class is set above using parsed attributes. Now we can
6359   // check the VarDecl itself.
6360   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6361          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6362          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6363
6364   // In auto-retain/release, infer strong retension for variables of
6365   // retainable type.
6366   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6367     NewVD->setInvalidDecl();
6368
6369   // Handle GNU asm-label extension (encoded as an attribute).
6370   if (Expr *E = (Expr*)D.getAsmLabel()) {
6371     // The parser guarantees this is a string.
6372     StringLiteral *SE = cast<StringLiteral>(E);
6373     StringRef Label = SE->getString();
6374     if (S->getFnParent() != nullptr) {
6375       switch (SC) {
6376       case SC_None:
6377       case SC_Auto:
6378         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6379         break;
6380       case SC_Register:
6381         // Local Named register
6382         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6383             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6384           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6385         break;
6386       case SC_Static:
6387       case SC_Extern:
6388       case SC_PrivateExtern:
6389         break;
6390       }
6391     } else if (SC == SC_Register) {
6392       // Global Named register
6393       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6394         const auto &TI = Context.getTargetInfo();
6395         bool HasSizeMismatch;
6396
6397         if (!TI.isValidGCCRegisterName(Label))
6398           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6399         else if (!TI.validateGlobalRegisterVariable(Label,
6400                                                     Context.getTypeSize(R),
6401                                                     HasSizeMismatch))
6402           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6403         else if (HasSizeMismatch)
6404           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6405       }
6406
6407       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6408         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6409         NewVD->setInvalidDecl(true);
6410       }
6411     }
6412
6413     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6414                                                 Context, Label, 0));
6415   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6416     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6417       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6418     if (I != ExtnameUndeclaredIdentifiers.end()) {
6419       if (isDeclExternC(NewVD)) {
6420         NewVD->addAttr(I->second);
6421         ExtnameUndeclaredIdentifiers.erase(I);
6422       } else
6423         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6424             << /*Variable*/1 << NewVD;
6425     }
6426   }
6427
6428   // Diagnose shadowed variables before filtering for scope.
6429   if (D.getCXXScopeSpec().isEmpty())
6430     CheckShadow(S, NewVD, Previous);
6431
6432   // Don't consider existing declarations that are in a different
6433   // scope and are out-of-semantic-context declarations (if the new
6434   // declaration has linkage).
6435   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6436                        D.getCXXScopeSpec().isNotEmpty() ||
6437                        IsExplicitSpecialization ||
6438                        IsVariableTemplateSpecialization);
6439
6440   // Check whether the previous declaration is in the same block scope. This
6441   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6442   if (getLangOpts().CPlusPlus &&
6443       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6444     NewVD->setPreviousDeclInSameBlockScope(
6445         Previous.isSingleResult() && !Previous.isShadowed() &&
6446         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6447
6448   if (!getLangOpts().CPlusPlus) {
6449     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6450   } else {
6451     // If this is an explicit specialization of a static data member, check it.
6452     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6453         CheckMemberSpecialization(NewVD, Previous))
6454       NewVD->setInvalidDecl();
6455
6456     // Merge the decl with the existing one if appropriate.
6457     if (!Previous.empty()) {
6458       if (Previous.isSingleResult() &&
6459           isa<FieldDecl>(Previous.getFoundDecl()) &&
6460           D.getCXXScopeSpec().isSet()) {
6461         // The user tried to define a non-static data member
6462         // out-of-line (C++ [dcl.meaning]p1).
6463         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6464           << D.getCXXScopeSpec().getRange();
6465         Previous.clear();
6466         NewVD->setInvalidDecl();
6467       }
6468     } else if (D.getCXXScopeSpec().isSet()) {
6469       // No previous declaration in the qualifying scope.
6470       Diag(D.getIdentifierLoc(), diag::err_no_member)
6471         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6472         << D.getCXXScopeSpec().getRange();
6473       NewVD->setInvalidDecl();
6474     }
6475
6476     if (!IsVariableTemplateSpecialization)
6477       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6478
6479     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6480     // an explicit specialization (14.8.3) or a partial specialization of a
6481     // concept definition.
6482     if (IsVariableTemplateSpecialization &&
6483         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6484         Previous.isSingleResult()) {
6485       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6486       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6487         if (VarTmpl->isConcept()) {
6488           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6489               << 1                            /*variable*/
6490               << (IsPartialSpecialization ? 2 /*partially specialized*/
6491                                           : 1 /*explicitly specialized*/);
6492           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6493           NewVD->setInvalidDecl();
6494         }
6495       }
6496     }
6497
6498     if (NewTemplate) {
6499       VarTemplateDecl *PrevVarTemplate =
6500           NewVD->getPreviousDecl()
6501               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6502               : nullptr;
6503
6504       // Check the template parameter list of this declaration, possibly
6505       // merging in the template parameter list from the previous variable
6506       // template declaration.
6507       if (CheckTemplateParameterList(
6508               TemplateParams,
6509               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6510                               : nullptr,
6511               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6512                DC->isDependentContext())
6513                   ? TPC_ClassTemplateMember
6514                   : TPC_VarTemplate))
6515         NewVD->setInvalidDecl();
6516
6517       // If we are providing an explicit specialization of a static variable
6518       // template, make a note of that.
6519       if (PrevVarTemplate &&
6520           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6521         PrevVarTemplate->setMemberSpecialization();
6522     }
6523   }
6524
6525   ProcessPragmaWeak(S, NewVD);
6526
6527   // If this is the first declaration of an extern C variable, update
6528   // the map of such variables.
6529   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6530       isIncompleteDeclExternC(*this, NewVD))
6531     RegisterLocallyScopedExternCDecl(NewVD, S);
6532
6533   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6534     Decl *ManglingContextDecl;
6535     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6536             NewVD->getDeclContext(), ManglingContextDecl)) {
6537       Context.setManglingNumber(
6538           NewVD, MCtx->getManglingNumber(
6539                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6540       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6541     }
6542   }
6543
6544   // Special handling of variable named 'main'.
6545   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6546       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6547       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6548
6549     // C++ [basic.start.main]p3
6550     // A program that declares a variable main at global scope is ill-formed.
6551     if (getLangOpts().CPlusPlus)
6552       Diag(D.getLocStart(), diag::err_main_global_variable);
6553
6554     // In C, and external-linkage variable named main results in undefined
6555     // behavior.
6556     else if (NewVD->hasExternalFormalLinkage())
6557       Diag(D.getLocStart(), diag::warn_main_redefined);
6558   }
6559
6560   if (D.isRedeclaration() && !Previous.empty()) {
6561     checkDLLAttributeRedeclaration(
6562         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6563         IsExplicitSpecialization, D.isFunctionDefinition());
6564   }
6565
6566   if (NewTemplate) {
6567     if (NewVD->isInvalidDecl())
6568       NewTemplate->setInvalidDecl();
6569     ActOnDocumentableDecl(NewTemplate);
6570     return NewTemplate;
6571   }
6572
6573   return NewVD;
6574 }
6575
6576 /// Enum describing the %select options in diag::warn_decl_shadow.
6577 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6578
6579 /// Determine what kind of declaration we're shadowing.
6580 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6581                                                 const DeclContext *OldDC) {
6582   if (isa<RecordDecl>(OldDC))
6583     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6584   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6585 }
6586
6587 /// Return the location of the capture if the given lambda captures the given
6588 /// variable \p VD, or an invalid source location otherwise.
6589 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6590                                          const VarDecl *VD) {
6591   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6592     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6593       return Capture.getLocation();
6594   }
6595   return SourceLocation();
6596 }
6597
6598 /// \brief Diagnose variable or built-in function shadowing.  Implements
6599 /// -Wshadow.
6600 ///
6601 /// This method is called whenever a VarDecl is added to a "useful"
6602 /// scope.
6603 ///
6604 /// \param S the scope in which the shadowing name is being declared
6605 /// \param R the lookup of the name
6606 ///
6607 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6608   // Return if warning is ignored.
6609   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6610     return;
6611
6612   // Don't diagnose declarations at file scope.
6613   if (D->hasGlobalStorage())
6614     return;
6615
6616   DeclContext *NewDC = D->getDeclContext();
6617
6618   // Only diagnose if we're shadowing an unambiguous field or variable.
6619   if (R.getResultKind() != LookupResult::Found)
6620     return;
6621
6622   NamedDecl* ShadowedDecl = R.getFoundDecl();
6623   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6624     return;
6625
6626   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6627     // Fields are not shadowed by variables in C++ static methods.
6628     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6629       if (MD->isStatic())
6630         return;
6631
6632     // Fields shadowed by constructor parameters are a special case. Usually
6633     // the constructor initializes the field with the parameter.
6634     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6635       // Remember that this was shadowed so we can either warn about its
6636       // modification or its existence depending on warning settings.
6637       D = D->getCanonicalDecl();
6638       ShadowingDecls.insert({D, FD});
6639       return;
6640     }
6641   }
6642
6643   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6644     if (shadowedVar->isExternC()) {
6645       // For shadowing external vars, make sure that we point to the global
6646       // declaration, not a locally scoped extern declaration.
6647       for (auto I : shadowedVar->redecls())
6648         if (I->isFileVarDecl()) {
6649           ShadowedDecl = I;
6650           break;
6651         }
6652     }
6653
6654   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6655
6656   unsigned WarningDiag = diag::warn_decl_shadow;
6657   SourceLocation CaptureLoc;
6658   if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) {
6659     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6660       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6661         if (RD->getLambdaCaptureDefault() == LCD_None) {
6662           // Try to avoid warnings for lambdas with an explicit capture list.
6663           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6664           // Warn only when the lambda captures the shadowed decl explicitly.
6665           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6666           if (CaptureLoc.isInvalid())
6667             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6668         } else {
6669           // Remember that this was shadowed so we can avoid the warning if the
6670           // shadowed decl isn't captured and the warning settings allow it.
6671           cast<LambdaScopeInfo>(getCurFunction())
6672               ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)});
6673           return;
6674         }
6675       }
6676     }
6677   }
6678
6679   // Only warn about certain kinds of shadowing for class members.
6680   if (NewDC && NewDC->isRecord()) {
6681     // In particular, don't warn about shadowing non-class members.
6682     if (!OldDC->isRecord())
6683       return;
6684
6685     // TODO: should we warn about static data members shadowing
6686     // static data members from base classes?
6687
6688     // TODO: don't diagnose for inaccessible shadowed members.
6689     // This is hard to do perfectly because we might friend the
6690     // shadowing context, but that's just a false negative.
6691   }
6692
6693
6694   DeclarationName Name = R.getLookupName();
6695
6696   // Emit warning and note.
6697   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6698     return;
6699   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6700   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6701   if (!CaptureLoc.isInvalid())
6702     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6703         << Name << /*explicitly*/ 1;
6704   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6705 }
6706
6707 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6708 /// when these variables are captured by the lambda.
6709 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6710   for (const auto &Shadow : LSI->ShadowingDecls) {
6711     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6712     // Try to avoid the warning when the shadowed decl isn't captured.
6713     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6714     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6715     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6716                                        ? diag::warn_decl_shadow_uncaptured_local
6717                                        : diag::warn_decl_shadow)
6718         << Shadow.VD->getDeclName()
6719         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6720     if (!CaptureLoc.isInvalid())
6721       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6722           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6723     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6724   }
6725 }
6726
6727 /// \brief Check -Wshadow without the advantage of a previous lookup.
6728 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6729   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6730     return;
6731
6732   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6733                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6734   LookupName(R, S);
6735   CheckShadow(S, D, R);
6736 }
6737
6738 /// Check if 'E', which is an expression that is about to be modified, refers
6739 /// to a constructor parameter that shadows a field.
6740 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6741   // Quickly ignore expressions that can't be shadowing ctor parameters.
6742   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6743     return;
6744   E = E->IgnoreParenImpCasts();
6745   auto *DRE = dyn_cast<DeclRefExpr>(E);
6746   if (!DRE)
6747     return;
6748   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6749   auto I = ShadowingDecls.find(D);
6750   if (I == ShadowingDecls.end())
6751     return;
6752   const NamedDecl *ShadowedDecl = I->second;
6753   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6754   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6755   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6756   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6757
6758   // Avoid issuing multiple warnings about the same decl.
6759   ShadowingDecls.erase(I);
6760 }
6761
6762 /// Check for conflict between this global or extern "C" declaration and
6763 /// previous global or extern "C" declarations. This is only used in C++.
6764 template<typename T>
6765 static bool checkGlobalOrExternCConflict(
6766     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6767   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6768   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6769
6770   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6771     // The common case: this global doesn't conflict with any extern "C"
6772     // declaration.
6773     return false;
6774   }
6775
6776   if (Prev) {
6777     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6778       // Both the old and new declarations have C language linkage. This is a
6779       // redeclaration.
6780       Previous.clear();
6781       Previous.addDecl(Prev);
6782       return true;
6783     }
6784
6785     // This is a global, non-extern "C" declaration, and there is a previous
6786     // non-global extern "C" declaration. Diagnose if this is a variable
6787     // declaration.
6788     if (!isa<VarDecl>(ND))
6789       return false;
6790   } else {
6791     // The declaration is extern "C". Check for any declaration in the
6792     // translation unit which might conflict.
6793     if (IsGlobal) {
6794       // We have already performed the lookup into the translation unit.
6795       IsGlobal = false;
6796       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6797            I != E; ++I) {
6798         if (isa<VarDecl>(*I)) {
6799           Prev = *I;
6800           break;
6801         }
6802       }
6803     } else {
6804       DeclContext::lookup_result R =
6805           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6806       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6807            I != E; ++I) {
6808         if (isa<VarDecl>(*I)) {
6809           Prev = *I;
6810           break;
6811         }
6812         // FIXME: If we have any other entity with this name in global scope,
6813         // the declaration is ill-formed, but that is a defect: it breaks the
6814         // 'stat' hack, for instance. Only variables can have mangled name
6815         // clashes with extern "C" declarations, so only they deserve a
6816         // diagnostic.
6817       }
6818     }
6819
6820     if (!Prev)
6821       return false;
6822   }
6823
6824   // Use the first declaration's location to ensure we point at something which
6825   // is lexically inside an extern "C" linkage-spec.
6826   assert(Prev && "should have found a previous declaration to diagnose");
6827   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6828     Prev = FD->getFirstDecl();
6829   else
6830     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6831
6832   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6833     << IsGlobal << ND;
6834   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6835     << IsGlobal;
6836   return false;
6837 }
6838
6839 /// Apply special rules for handling extern "C" declarations. Returns \c true
6840 /// if we have found that this is a redeclaration of some prior entity.
6841 ///
6842 /// Per C++ [dcl.link]p6:
6843 ///   Two declarations [for a function or variable] with C language linkage
6844 ///   with the same name that appear in different scopes refer to the same
6845 ///   [entity]. An entity with C language linkage shall not be declared with
6846 ///   the same name as an entity in global scope.
6847 template<typename T>
6848 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6849                                                   LookupResult &Previous) {
6850   if (!S.getLangOpts().CPlusPlus) {
6851     // In C, when declaring a global variable, look for a corresponding 'extern'
6852     // variable declared in function scope. We don't need this in C++, because
6853     // we find local extern decls in the surrounding file-scope DeclContext.
6854     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6855       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6856         Previous.clear();
6857         Previous.addDecl(Prev);
6858         return true;
6859       }
6860     }
6861     return false;
6862   }
6863
6864   // A declaration in the translation unit can conflict with an extern "C"
6865   // declaration.
6866   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6867     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6868
6869   // An extern "C" declaration can conflict with a declaration in the
6870   // translation unit or can be a redeclaration of an extern "C" declaration
6871   // in another scope.
6872   if (isIncompleteDeclExternC(S,ND))
6873     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6874
6875   // Neither global nor extern "C": nothing to do.
6876   return false;
6877 }
6878
6879 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6880   // If the decl is already known invalid, don't check it.
6881   if (NewVD->isInvalidDecl())
6882     return;
6883
6884   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6885   QualType T = TInfo->getType();
6886
6887   // Defer checking an 'auto' type until its initializer is attached.
6888   if (T->isUndeducedType())
6889     return;
6890
6891   if (NewVD->hasAttrs())
6892     CheckAlignasUnderalignment(NewVD);
6893
6894   if (T->isObjCObjectType()) {
6895     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6896       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6897     T = Context.getObjCObjectPointerType(T);
6898     NewVD->setType(T);
6899   }
6900
6901   // Emit an error if an address space was applied to decl with local storage.
6902   // This includes arrays of objects with address space qualifiers, but not
6903   // automatic variables that point to other address spaces.
6904   // ISO/IEC TR 18037 S5.1.2
6905   if (!getLangOpts().OpenCL
6906       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6907     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6908     NewVD->setInvalidDecl();
6909     return;
6910   }
6911
6912   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6913   // scope.
6914   if (getLangOpts().OpenCLVersion == 120 &&
6915       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
6916       NewVD->isStaticLocal()) {
6917     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6918     NewVD->setInvalidDecl();
6919     return;
6920   }
6921
6922   if (getLangOpts().OpenCL) {
6923     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6924     if (NewVD->hasAttr<BlocksAttr>()) {
6925       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6926       return;
6927     }
6928
6929     if (T->isBlockPointerType()) {
6930       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6931       // can't use 'extern' storage class.
6932       if (!T.isConstQualified()) {
6933         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6934             << 0 /*const*/;
6935         NewVD->setInvalidDecl();
6936         return;
6937       }
6938       if (NewVD->hasExternalStorage()) {
6939         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6940         NewVD->setInvalidDecl();
6941         return;
6942       }
6943     }
6944     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6945     // __constant address space.
6946     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6947     // variables inside a function can also be declared in the global
6948     // address space.
6949     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6950         NewVD->hasExternalStorage()) {
6951       if (!T->isSamplerT() &&
6952           !(T.getAddressSpace() == LangAS::opencl_constant ||
6953             (T.getAddressSpace() == LangAS::opencl_global &&
6954              getLangOpts().OpenCLVersion == 200))) {
6955         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6956         if (getLangOpts().OpenCLVersion == 200)
6957           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6958               << Scope << "global or constant";
6959         else
6960           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6961               << Scope << "constant";
6962         NewVD->setInvalidDecl();
6963         return;
6964       }
6965     } else {
6966       if (T.getAddressSpace() == LangAS::opencl_global) {
6967         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6968             << 1 /*is any function*/ << "global";
6969         NewVD->setInvalidDecl();
6970         return;
6971       }
6972       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6973       // in functions.
6974       if (T.getAddressSpace() == LangAS::opencl_constant ||
6975           T.getAddressSpace() == LangAS::opencl_local) {
6976         FunctionDecl *FD = getCurFunctionDecl();
6977         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6978           if (T.getAddressSpace() == LangAS::opencl_constant)
6979             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6980                 << 0 /*non-kernel only*/ << "constant";
6981           else
6982             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6983                 << 0 /*non-kernel only*/ << "local";
6984           NewVD->setInvalidDecl();
6985           return;
6986         }
6987       }
6988     }
6989   }
6990
6991   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6992       && !NewVD->hasAttr<BlocksAttr>()) {
6993     if (getLangOpts().getGC() != LangOptions::NonGC)
6994       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6995     else {
6996       assert(!getLangOpts().ObjCAutoRefCount);
6997       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6998     }
6999   }
7000
7001   bool isVM = T->isVariablyModifiedType();
7002   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7003       NewVD->hasAttr<BlocksAttr>())
7004     getCurFunction()->setHasBranchProtectedScope();
7005
7006   if ((isVM && NewVD->hasLinkage()) ||
7007       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7008     bool SizeIsNegative;
7009     llvm::APSInt Oversized;
7010     TypeSourceInfo *FixedTInfo =
7011       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7012                                                     SizeIsNegative, Oversized);
7013     if (!FixedTInfo && T->isVariableArrayType()) {
7014       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7015       // FIXME: This won't give the correct result for
7016       // int a[10][n];
7017       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7018
7019       if (NewVD->isFileVarDecl())
7020         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7021         << SizeRange;
7022       else if (NewVD->isStaticLocal())
7023         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7024         << SizeRange;
7025       else
7026         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7027         << SizeRange;
7028       NewVD->setInvalidDecl();
7029       return;
7030     }
7031
7032     if (!FixedTInfo) {
7033       if (NewVD->isFileVarDecl())
7034         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7035       else
7036         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7037       NewVD->setInvalidDecl();
7038       return;
7039     }
7040
7041     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7042     NewVD->setType(FixedTInfo->getType());
7043     NewVD->setTypeSourceInfo(FixedTInfo);
7044   }
7045
7046   if (T->isVoidType()) {
7047     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7048     //                    of objects and functions.
7049     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7050       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7051         << T;
7052       NewVD->setInvalidDecl();
7053       return;
7054     }
7055   }
7056
7057   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7058     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7059     NewVD->setInvalidDecl();
7060     return;
7061   }
7062
7063   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7064     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7065     NewVD->setInvalidDecl();
7066     return;
7067   }
7068
7069   if (NewVD->isConstexpr() && !T->isDependentType() &&
7070       RequireLiteralType(NewVD->getLocation(), T,
7071                          diag::err_constexpr_var_non_literal)) {
7072     NewVD->setInvalidDecl();
7073     return;
7074   }
7075 }
7076
7077 /// \brief Perform semantic checking on a newly-created variable
7078 /// declaration.
7079 ///
7080 /// This routine performs all of the type-checking required for a
7081 /// variable declaration once it has been built. It is used both to
7082 /// check variables after they have been parsed and their declarators
7083 /// have been translated into a declaration, and to check variables
7084 /// that have been instantiated from a template.
7085 ///
7086 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7087 ///
7088 /// Returns true if the variable declaration is a redeclaration.
7089 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7090   CheckVariableDeclarationType(NewVD);
7091
7092   // If the decl is already known invalid, don't check it.
7093   if (NewVD->isInvalidDecl())
7094     return false;
7095
7096   // If we did not find anything by this name, look for a non-visible
7097   // extern "C" declaration with the same name.
7098   if (Previous.empty() &&
7099       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7100     Previous.setShadowed();
7101
7102   if (!Previous.empty()) {
7103     MergeVarDecl(NewVD, Previous);
7104     return true;
7105   }
7106   return false;
7107 }
7108
7109 namespace {
7110 struct FindOverriddenMethod {
7111   Sema *S;
7112   CXXMethodDecl *Method;
7113
7114   /// Member lookup function that determines whether a given C++
7115   /// method overrides a method in a base class, to be used with
7116   /// CXXRecordDecl::lookupInBases().
7117   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7118     RecordDecl *BaseRecord =
7119         Specifier->getType()->getAs<RecordType>()->getDecl();
7120
7121     DeclarationName Name = Method->getDeclName();
7122
7123     // FIXME: Do we care about other names here too?
7124     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7125       // We really want to find the base class destructor here.
7126       QualType T = S->Context.getTypeDeclType(BaseRecord);
7127       CanQualType CT = S->Context.getCanonicalType(T);
7128
7129       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7130     }
7131
7132     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7133          Path.Decls = Path.Decls.slice(1)) {
7134       NamedDecl *D = Path.Decls.front();
7135       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7136         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7137           return true;
7138       }
7139     }
7140
7141     return false;
7142   }
7143 };
7144
7145 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7146 } // end anonymous namespace
7147
7148 /// \brief Report an error regarding overriding, along with any relevant
7149 /// overriden methods.
7150 ///
7151 /// \param DiagID the primary error to report.
7152 /// \param MD the overriding method.
7153 /// \param OEK which overrides to include as notes.
7154 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7155                             OverrideErrorKind OEK = OEK_All) {
7156   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7157   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7158                                       E = MD->end_overridden_methods();
7159        I != E; ++I) {
7160     // This check (& the OEK parameter) could be replaced by a predicate, but
7161     // without lambdas that would be overkill. This is still nicer than writing
7162     // out the diag loop 3 times.
7163     if ((OEK == OEK_All) ||
7164         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7165         (OEK == OEK_Deleted && (*I)->isDeleted()))
7166       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7167   }
7168 }
7169
7170 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7171 /// and if so, check that it's a valid override and remember it.
7172 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7173   // Look for methods in base classes that this method might override.
7174   CXXBasePaths Paths;
7175   FindOverriddenMethod FOM;
7176   FOM.Method = MD;
7177   FOM.S = this;
7178   bool hasDeletedOverridenMethods = false;
7179   bool hasNonDeletedOverridenMethods = false;
7180   bool AddedAny = false;
7181   if (DC->lookupInBases(FOM, Paths)) {
7182     for (auto *I : Paths.found_decls()) {
7183       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7184         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7185         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7186             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7187             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7188             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7189           hasDeletedOverridenMethods |= OldMD->isDeleted();
7190           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7191           AddedAny = true;
7192         }
7193       }
7194     }
7195   }
7196
7197   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7198     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7199   }
7200   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7201     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7202   }
7203
7204   return AddedAny;
7205 }
7206
7207 namespace {
7208   // Struct for holding all of the extra arguments needed by
7209   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7210   struct ActOnFDArgs {
7211     Scope *S;
7212     Declarator &D;
7213     MultiTemplateParamsArg TemplateParamLists;
7214     bool AddToScope;
7215   };
7216 } // end anonymous namespace
7217
7218 namespace {
7219
7220 // Callback to only accept typo corrections that have a non-zero edit distance.
7221 // Also only accept corrections that have the same parent decl.
7222 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7223  public:
7224   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7225                             CXXRecordDecl *Parent)
7226       : Context(Context), OriginalFD(TypoFD),
7227         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7228
7229   bool ValidateCandidate(const TypoCorrection &candidate) override {
7230     if (candidate.getEditDistance() == 0)
7231       return false;
7232
7233     SmallVector<unsigned, 1> MismatchedParams;
7234     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7235                                           CDeclEnd = candidate.end();
7236          CDecl != CDeclEnd; ++CDecl) {
7237       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7238
7239       if (FD && !FD->hasBody() &&
7240           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7241         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7242           CXXRecordDecl *Parent = MD->getParent();
7243           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7244             return true;
7245         } else if (!ExpectedParent) {
7246           return true;
7247         }
7248       }
7249     }
7250
7251     return false;
7252   }
7253
7254  private:
7255   ASTContext &Context;
7256   FunctionDecl *OriginalFD;
7257   CXXRecordDecl *ExpectedParent;
7258 };
7259
7260 } // end anonymous namespace
7261
7262 /// \brief Generate diagnostics for an invalid function redeclaration.
7263 ///
7264 /// This routine handles generating the diagnostic messages for an invalid
7265 /// function redeclaration, including finding possible similar declarations
7266 /// or performing typo correction if there are no previous declarations with
7267 /// the same name.
7268 ///
7269 /// Returns a NamedDecl iff typo correction was performed and substituting in
7270 /// the new declaration name does not cause new errors.
7271 static NamedDecl *DiagnoseInvalidRedeclaration(
7272     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7273     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7274   DeclarationName Name = NewFD->getDeclName();
7275   DeclContext *NewDC = NewFD->getDeclContext();
7276   SmallVector<unsigned, 1> MismatchedParams;
7277   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7278   TypoCorrection Correction;
7279   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7280   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7281                                    : diag::err_member_decl_does_not_match;
7282   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7283                     IsLocalFriend ? Sema::LookupLocalFriendName
7284                                   : Sema::LookupOrdinaryName,
7285                     Sema::ForRedeclaration);
7286
7287   NewFD->setInvalidDecl();
7288   if (IsLocalFriend)
7289     SemaRef.LookupName(Prev, S);
7290   else
7291     SemaRef.LookupQualifiedName(Prev, NewDC);
7292   assert(!Prev.isAmbiguous() &&
7293          "Cannot have an ambiguity in previous-declaration lookup");
7294   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7295   if (!Prev.empty()) {
7296     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7297          Func != FuncEnd; ++Func) {
7298       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7299       if (FD &&
7300           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7301         // Add 1 to the index so that 0 can mean the mismatch didn't
7302         // involve a parameter
7303         unsigned ParamNum =
7304             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7305         NearMatches.push_back(std::make_pair(FD, ParamNum));
7306       }
7307     }
7308   // If the qualified name lookup yielded nothing, try typo correction
7309   } else if ((Correction = SemaRef.CorrectTypo(
7310                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7311                   &ExtraArgs.D.getCXXScopeSpec(),
7312                   llvm::make_unique<DifferentNameValidatorCCC>(
7313                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7314                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7315     // Set up everything for the call to ActOnFunctionDeclarator
7316     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7317                               ExtraArgs.D.getIdentifierLoc());
7318     Previous.clear();
7319     Previous.setLookupName(Correction.getCorrection());
7320     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7321                                     CDeclEnd = Correction.end();
7322          CDecl != CDeclEnd; ++CDecl) {
7323       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7324       if (FD && !FD->hasBody() &&
7325           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7326         Previous.addDecl(FD);
7327       }
7328     }
7329     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7330
7331     NamedDecl *Result;
7332     // Retry building the function declaration with the new previous
7333     // declarations, and with errors suppressed.
7334     {
7335       // Trap errors.
7336       Sema::SFINAETrap Trap(SemaRef);
7337
7338       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7339       // pieces need to verify the typo-corrected C++ declaration and hopefully
7340       // eliminate the need for the parameter pack ExtraArgs.
7341       Result = SemaRef.ActOnFunctionDeclarator(
7342           ExtraArgs.S, ExtraArgs.D,
7343           Correction.getCorrectionDecl()->getDeclContext(),
7344           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7345           ExtraArgs.AddToScope);
7346
7347       if (Trap.hasErrorOccurred())
7348         Result = nullptr;
7349     }
7350
7351     if (Result) {
7352       // Determine which correction we picked.
7353       Decl *Canonical = Result->getCanonicalDecl();
7354       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7355            I != E; ++I)
7356         if ((*I)->getCanonicalDecl() == Canonical)
7357           Correction.setCorrectionDecl(*I);
7358
7359       SemaRef.diagnoseTypo(
7360           Correction,
7361           SemaRef.PDiag(IsLocalFriend
7362                           ? diag::err_no_matching_local_friend_suggest
7363                           : diag::err_member_decl_does_not_match_suggest)
7364             << Name << NewDC << IsDefinition);
7365       return Result;
7366     }
7367
7368     // Pretend the typo correction never occurred
7369     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7370                               ExtraArgs.D.getIdentifierLoc());
7371     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7372     Previous.clear();
7373     Previous.setLookupName(Name);
7374   }
7375
7376   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7377       << Name << NewDC << IsDefinition << NewFD->getLocation();
7378
7379   bool NewFDisConst = false;
7380   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7381     NewFDisConst = NewMD->isConst();
7382
7383   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7384        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7385        NearMatch != NearMatchEnd; ++NearMatch) {
7386     FunctionDecl *FD = NearMatch->first;
7387     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7388     bool FDisConst = MD && MD->isConst();
7389     bool IsMember = MD || !IsLocalFriend;
7390
7391     // FIXME: These notes are poorly worded for the local friend case.
7392     if (unsigned Idx = NearMatch->second) {
7393       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7394       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7395       if (Loc.isInvalid()) Loc = FD->getLocation();
7396       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7397                                  : diag::note_local_decl_close_param_match)
7398         << Idx << FDParam->getType()
7399         << NewFD->getParamDecl(Idx - 1)->getType();
7400     } else if (FDisConst != NewFDisConst) {
7401       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7402           << NewFDisConst << FD->getSourceRange().getEnd();
7403     } else
7404       SemaRef.Diag(FD->getLocation(),
7405                    IsMember ? diag::note_member_def_close_match
7406                             : diag::note_local_decl_close_match);
7407   }
7408   return nullptr;
7409 }
7410
7411 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7412   switch (D.getDeclSpec().getStorageClassSpec()) {
7413   default: llvm_unreachable("Unknown storage class!");
7414   case DeclSpec::SCS_auto:
7415   case DeclSpec::SCS_register:
7416   case DeclSpec::SCS_mutable:
7417     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7418                  diag::err_typecheck_sclass_func);
7419     D.setInvalidType();
7420     break;
7421   case DeclSpec::SCS_unspecified: break;
7422   case DeclSpec::SCS_extern:
7423     if (D.getDeclSpec().isExternInLinkageSpec())
7424       return SC_None;
7425     return SC_Extern;
7426   case DeclSpec::SCS_static: {
7427     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7428       // C99 6.7.1p5:
7429       //   The declaration of an identifier for a function that has
7430       //   block scope shall have no explicit storage-class specifier
7431       //   other than extern
7432       // See also (C++ [dcl.stc]p4).
7433       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7434                    diag::err_static_block_func);
7435       break;
7436     } else
7437       return SC_Static;
7438   }
7439   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7440   }
7441
7442   // No explicit storage class has already been returned
7443   return SC_None;
7444 }
7445
7446 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7447                                            DeclContext *DC, QualType &R,
7448                                            TypeSourceInfo *TInfo,
7449                                            StorageClass SC,
7450                                            bool &IsVirtualOkay) {
7451   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7452   DeclarationName Name = NameInfo.getName();
7453
7454   FunctionDecl *NewFD = nullptr;
7455   bool isInline = D.getDeclSpec().isInlineSpecified();
7456
7457   if (!SemaRef.getLangOpts().CPlusPlus) {
7458     // Determine whether the function was written with a
7459     // prototype. This true when:
7460     //   - there is a prototype in the declarator, or
7461     //   - the type R of the function is some kind of typedef or other reference
7462     //     to a type name (which eventually refers to a function type).
7463     bool HasPrototype =
7464       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7465       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7466
7467     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7468                                  D.getLocStart(), NameInfo, R,
7469                                  TInfo, SC, isInline,
7470                                  HasPrototype, false);
7471     if (D.isInvalidType())
7472       NewFD->setInvalidDecl();
7473
7474     return NewFD;
7475   }
7476
7477   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7478   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7479
7480   // Check that the return type is not an abstract class type.
7481   // For record types, this is done by the AbstractClassUsageDiagnoser once
7482   // the class has been completely parsed.
7483   if (!DC->isRecord() &&
7484       SemaRef.RequireNonAbstractType(
7485           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7486           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7487     D.setInvalidType();
7488
7489   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7490     // This is a C++ constructor declaration.
7491     assert(DC->isRecord() &&
7492            "Constructors can only be declared in a member context");
7493
7494     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7495     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7496                                       D.getLocStart(), NameInfo,
7497                                       R, TInfo, isExplicit, isInline,
7498                                       /*isImplicitlyDeclared=*/false,
7499                                       isConstexpr);
7500
7501   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7502     // This is a C++ destructor declaration.
7503     if (DC->isRecord()) {
7504       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7505       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7506       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7507                                         SemaRef.Context, Record,
7508                                         D.getLocStart(),
7509                                         NameInfo, R, TInfo, isInline,
7510                                         /*isImplicitlyDeclared=*/false);
7511
7512       // If the class is complete, then we now create the implicit exception
7513       // specification. If the class is incomplete or dependent, we can't do
7514       // it yet.
7515       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7516           Record->getDefinition() && !Record->isBeingDefined() &&
7517           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7518         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7519       }
7520
7521       IsVirtualOkay = true;
7522       return NewDD;
7523
7524     } else {
7525       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7526       D.setInvalidType();
7527
7528       // Create a FunctionDecl to satisfy the function definition parsing
7529       // code path.
7530       return FunctionDecl::Create(SemaRef.Context, DC,
7531                                   D.getLocStart(),
7532                                   D.getIdentifierLoc(), Name, R, TInfo,
7533                                   SC, isInline,
7534                                   /*hasPrototype=*/true, isConstexpr);
7535     }
7536
7537   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7538     if (!DC->isRecord()) {
7539       SemaRef.Diag(D.getIdentifierLoc(),
7540            diag::err_conv_function_not_member);
7541       return nullptr;
7542     }
7543
7544     SemaRef.CheckConversionDeclarator(D, R, SC);
7545     IsVirtualOkay = true;
7546     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7547                                      D.getLocStart(), NameInfo,
7548                                      R, TInfo, isInline, isExplicit,
7549                                      isConstexpr, SourceLocation());
7550
7551   } else if (DC->isRecord()) {
7552     // If the name of the function is the same as the name of the record,
7553     // then this must be an invalid constructor that has a return type.
7554     // (The parser checks for a return type and makes the declarator a
7555     // constructor if it has no return type).
7556     if (Name.getAsIdentifierInfo() &&
7557         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7558       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7559         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7560         << SourceRange(D.getIdentifierLoc());
7561       return nullptr;
7562     }
7563
7564     // This is a C++ method declaration.
7565     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7566                                                cast<CXXRecordDecl>(DC),
7567                                                D.getLocStart(), NameInfo, R,
7568                                                TInfo, SC, isInline,
7569                                                isConstexpr, SourceLocation());
7570     IsVirtualOkay = !Ret->isStatic();
7571     return Ret;
7572   } else {
7573     bool isFriend =
7574         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7575     if (!isFriend && SemaRef.CurContext->isRecord())
7576       return nullptr;
7577
7578     // Determine whether the function was written with a
7579     // prototype. This true when:
7580     //   - we're in C++ (where every function has a prototype),
7581     return FunctionDecl::Create(SemaRef.Context, DC,
7582                                 D.getLocStart(),
7583                                 NameInfo, R, TInfo, SC, isInline,
7584                                 true/*HasPrototype*/, isConstexpr);
7585   }
7586 }
7587
7588 enum OpenCLParamType {
7589   ValidKernelParam,
7590   PtrPtrKernelParam,
7591   PtrKernelParam,
7592   InvalidAddrSpacePtrKernelParam,
7593   InvalidKernelParam,
7594   RecordKernelParam
7595 };
7596
7597 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7598   if (PT->isPointerType()) {
7599     QualType PointeeType = PT->getPointeeType();
7600     if (PointeeType->isPointerType())
7601       return PtrPtrKernelParam;
7602     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7603         PointeeType.getAddressSpace() == 0)
7604       return InvalidAddrSpacePtrKernelParam;
7605     return PtrKernelParam;
7606   }
7607
7608   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7609   // be used as builtin types.
7610
7611   if (PT->isImageType())
7612     return PtrKernelParam;
7613
7614   if (PT->isBooleanType())
7615     return InvalidKernelParam;
7616
7617   if (PT->isEventT())
7618     return InvalidKernelParam;
7619
7620   // OpenCL extension spec v1.2 s9.5:
7621   // This extension adds support for half scalar and vector types as built-in
7622   // types that can be used for arithmetic operations, conversions etc.
7623   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7624     return InvalidKernelParam;
7625
7626   if (PT->isRecordType())
7627     return RecordKernelParam;
7628
7629   return ValidKernelParam;
7630 }
7631
7632 static void checkIsValidOpenCLKernelParameter(
7633   Sema &S,
7634   Declarator &D,
7635   ParmVarDecl *Param,
7636   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7637   QualType PT = Param->getType();
7638
7639   // Cache the valid types we encounter to avoid rechecking structs that are
7640   // used again
7641   if (ValidTypes.count(PT.getTypePtr()))
7642     return;
7643
7644   switch (getOpenCLKernelParameterType(S, PT)) {
7645   case PtrPtrKernelParam:
7646     // OpenCL v1.2 s6.9.a:
7647     // A kernel function argument cannot be declared as a
7648     // pointer to a pointer type.
7649     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7650     D.setInvalidType();
7651     return;
7652
7653   case InvalidAddrSpacePtrKernelParam:
7654     // OpenCL v1.0 s6.5:
7655     // __kernel function arguments declared to be a pointer of a type can point
7656     // to one of the following address spaces only : __global, __local or
7657     // __constant.
7658     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7659     D.setInvalidType();
7660     return;
7661
7662     // OpenCL v1.2 s6.9.k:
7663     // Arguments to kernel functions in a program cannot be declared with the
7664     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7665     // uintptr_t or a struct and/or union that contain fields declared to be
7666     // one of these built-in scalar types.
7667
7668   case InvalidKernelParam:
7669     // OpenCL v1.2 s6.8 n:
7670     // A kernel function argument cannot be declared
7671     // of event_t type.
7672     // Do not diagnose half type since it is diagnosed as invalid argument
7673     // type for any function elsewhere.
7674     if (!PT->isHalfType())
7675       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7676     D.setInvalidType();
7677     return;
7678
7679   case PtrKernelParam:
7680   case ValidKernelParam:
7681     ValidTypes.insert(PT.getTypePtr());
7682     return;
7683
7684   case RecordKernelParam:
7685     break;
7686   }
7687
7688   // Track nested structs we will inspect
7689   SmallVector<const Decl *, 4> VisitStack;
7690
7691   // Track where we are in the nested structs. Items will migrate from
7692   // VisitStack to HistoryStack as we do the DFS for bad field.
7693   SmallVector<const FieldDecl *, 4> HistoryStack;
7694   HistoryStack.push_back(nullptr);
7695
7696   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7697   VisitStack.push_back(PD);
7698
7699   assert(VisitStack.back() && "First decl null?");
7700
7701   do {
7702     const Decl *Next = VisitStack.pop_back_val();
7703     if (!Next) {
7704       assert(!HistoryStack.empty());
7705       // Found a marker, we have gone up a level
7706       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7707         ValidTypes.insert(Hist->getType().getTypePtr());
7708
7709       continue;
7710     }
7711
7712     // Adds everything except the original parameter declaration (which is not a
7713     // field itself) to the history stack.
7714     const RecordDecl *RD;
7715     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7716       HistoryStack.push_back(Field);
7717       RD = Field->getType()->castAs<RecordType>()->getDecl();
7718     } else {
7719       RD = cast<RecordDecl>(Next);
7720     }
7721
7722     // Add a null marker so we know when we've gone back up a level
7723     VisitStack.push_back(nullptr);
7724
7725     for (const auto *FD : RD->fields()) {
7726       QualType QT = FD->getType();
7727
7728       if (ValidTypes.count(QT.getTypePtr()))
7729         continue;
7730
7731       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7732       if (ParamType == ValidKernelParam)
7733         continue;
7734
7735       if (ParamType == RecordKernelParam) {
7736         VisitStack.push_back(FD);
7737         continue;
7738       }
7739
7740       // OpenCL v1.2 s6.9.p:
7741       // Arguments to kernel functions that are declared to be a struct or union
7742       // do not allow OpenCL objects to be passed as elements of the struct or
7743       // union.
7744       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7745           ParamType == InvalidAddrSpacePtrKernelParam) {
7746         S.Diag(Param->getLocation(),
7747                diag::err_record_with_pointers_kernel_param)
7748           << PT->isUnionType()
7749           << PT;
7750       } else {
7751         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7752       }
7753
7754       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7755         << PD->getDeclName();
7756
7757       // We have an error, now let's go back up through history and show where
7758       // the offending field came from
7759       for (ArrayRef<const FieldDecl *>::const_iterator
7760                I = HistoryStack.begin() + 1,
7761                E = HistoryStack.end();
7762            I != E; ++I) {
7763         const FieldDecl *OuterField = *I;
7764         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7765           << OuterField->getType();
7766       }
7767
7768       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7769         << QT->isPointerType()
7770         << QT;
7771       D.setInvalidType();
7772       return;
7773     }
7774   } while (!VisitStack.empty());
7775 }
7776
7777 /// Find the DeclContext in which a tag is implicitly declared if we see an
7778 /// elaborated type specifier in the specified context, and lookup finds
7779 /// nothing.
7780 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7781   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7782     DC = DC->getParent();
7783   return DC;
7784 }
7785
7786 /// Find the Scope in which a tag is implicitly declared if we see an
7787 /// elaborated type specifier in the specified context, and lookup finds
7788 /// nothing.
7789 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7790   while (S->isClassScope() ||
7791          (LangOpts.CPlusPlus &&
7792           S->isFunctionPrototypeScope()) ||
7793          ((S->getFlags() & Scope::DeclScope) == 0) ||
7794          (S->getEntity() && S->getEntity()->isTransparentContext()))
7795     S = S->getParent();
7796   return S;
7797 }
7798
7799 NamedDecl*
7800 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7801                               TypeSourceInfo *TInfo, LookupResult &Previous,
7802                               MultiTemplateParamsArg TemplateParamLists,
7803                               bool &AddToScope) {
7804   QualType R = TInfo->getType();
7805
7806   assert(R.getTypePtr()->isFunctionType());
7807
7808   // TODO: consider using NameInfo for diagnostic.
7809   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7810   DeclarationName Name = NameInfo.getName();
7811   StorageClass SC = getFunctionStorageClass(*this, D);
7812
7813   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7814     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7815          diag::err_invalid_thread)
7816       << DeclSpec::getSpecifierName(TSCS);
7817
7818   if (D.isFirstDeclarationOfMember())
7819     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7820                            D.getIdentifierLoc());
7821
7822   bool isFriend = false;
7823   FunctionTemplateDecl *FunctionTemplate = nullptr;
7824   bool isExplicitSpecialization = false;
7825   bool isFunctionTemplateSpecialization = false;
7826
7827   bool isDependentClassScopeExplicitSpecialization = false;
7828   bool HasExplicitTemplateArgs = false;
7829   TemplateArgumentListInfo TemplateArgs;
7830
7831   bool isVirtualOkay = false;
7832
7833   DeclContext *OriginalDC = DC;
7834   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7835
7836   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7837                                               isVirtualOkay);
7838   if (!NewFD) return nullptr;
7839
7840   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7841     NewFD->setTopLevelDeclInObjCContainer();
7842
7843   // Set the lexical context. If this is a function-scope declaration, or has a
7844   // C++ scope specifier, or is the object of a friend declaration, the lexical
7845   // context will be different from the semantic context.
7846   NewFD->setLexicalDeclContext(CurContext);
7847
7848   if (IsLocalExternDecl)
7849     NewFD->setLocalExternDecl();
7850
7851   if (getLangOpts().CPlusPlus) {
7852     bool isInline = D.getDeclSpec().isInlineSpecified();
7853     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7854     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7855     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7856     bool isConcept = D.getDeclSpec().isConceptSpecified();
7857     isFriend = D.getDeclSpec().isFriendSpecified();
7858     if (isFriend && !isInline && D.isFunctionDefinition()) {
7859       // C++ [class.friend]p5
7860       //   A function can be defined in a friend declaration of a
7861       //   class . . . . Such a function is implicitly inline.
7862       NewFD->setImplicitlyInline();
7863     }
7864
7865     // If this is a method defined in an __interface, and is not a constructor
7866     // or an overloaded operator, then set the pure flag (isVirtual will already
7867     // return true).
7868     if (const CXXRecordDecl *Parent =
7869           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7870       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7871         NewFD->setPure(true);
7872
7873       // C++ [class.union]p2
7874       //   A union can have member functions, but not virtual functions.
7875       if (isVirtual && Parent->isUnion())
7876         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7877     }
7878
7879     SetNestedNameSpecifier(NewFD, D);
7880     isExplicitSpecialization = false;
7881     isFunctionTemplateSpecialization = false;
7882     if (D.isInvalidType())
7883       NewFD->setInvalidDecl();
7884
7885     // Match up the template parameter lists with the scope specifier, then
7886     // determine whether we have a template or a template specialization.
7887     bool Invalid = false;
7888     if (TemplateParameterList *TemplateParams =
7889             MatchTemplateParametersToScopeSpecifier(
7890                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7891                 D.getCXXScopeSpec(),
7892                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7893                     ? D.getName().TemplateId
7894                     : nullptr,
7895                 TemplateParamLists, isFriend, isExplicitSpecialization,
7896                 Invalid)) {
7897       if (TemplateParams->size() > 0) {
7898         // This is a function template
7899
7900         // Check that we can declare a template here.
7901         if (CheckTemplateDeclScope(S, TemplateParams))
7902           NewFD->setInvalidDecl();
7903
7904         // A destructor cannot be a template.
7905         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7906           Diag(NewFD->getLocation(), diag::err_destructor_template);
7907           NewFD->setInvalidDecl();
7908         }
7909
7910         // If we're adding a template to a dependent context, we may need to
7911         // rebuilding some of the types used within the template parameter list,
7912         // now that we know what the current instantiation is.
7913         if (DC->isDependentContext()) {
7914           ContextRAII SavedContext(*this, DC);
7915           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7916             Invalid = true;
7917         }
7918
7919         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7920                                                         NewFD->getLocation(),
7921                                                         Name, TemplateParams,
7922                                                         NewFD);
7923         FunctionTemplate->setLexicalDeclContext(CurContext);
7924         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7925
7926         // For source fidelity, store the other template param lists.
7927         if (TemplateParamLists.size() > 1) {
7928           NewFD->setTemplateParameterListsInfo(Context,
7929                                                TemplateParamLists.drop_back(1));
7930         }
7931       } else {
7932         // This is a function template specialization.
7933         isFunctionTemplateSpecialization = true;
7934         // For source fidelity, store all the template param lists.
7935         if (TemplateParamLists.size() > 0)
7936           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7937
7938         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7939         if (isFriend) {
7940           // We want to remove the "template<>", found here.
7941           SourceRange RemoveRange = TemplateParams->getSourceRange();
7942
7943           // If we remove the template<> and the name is not a
7944           // template-id, we're actually silently creating a problem:
7945           // the friend declaration will refer to an untemplated decl,
7946           // and clearly the user wants a template specialization.  So
7947           // we need to insert '<>' after the name.
7948           SourceLocation InsertLoc;
7949           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7950             InsertLoc = D.getName().getSourceRange().getEnd();
7951             InsertLoc = getLocForEndOfToken(InsertLoc);
7952           }
7953
7954           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7955             << Name << RemoveRange
7956             << FixItHint::CreateRemoval(RemoveRange)
7957             << FixItHint::CreateInsertion(InsertLoc, "<>");
7958         }
7959       }
7960     }
7961     else {
7962       // All template param lists were matched against the scope specifier:
7963       // this is NOT (an explicit specialization of) a template.
7964       if (TemplateParamLists.size() > 0)
7965         // For source fidelity, store all the template param lists.
7966         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7967     }
7968
7969     if (Invalid) {
7970       NewFD->setInvalidDecl();
7971       if (FunctionTemplate)
7972         FunctionTemplate->setInvalidDecl();
7973     }
7974
7975     // C++ [dcl.fct.spec]p5:
7976     //   The virtual specifier shall only be used in declarations of
7977     //   nonstatic class member functions that appear within a
7978     //   member-specification of a class declaration; see 10.3.
7979     //
7980     if (isVirtual && !NewFD->isInvalidDecl()) {
7981       if (!isVirtualOkay) {
7982         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7983              diag::err_virtual_non_function);
7984       } else if (!CurContext->isRecord()) {
7985         // 'virtual' was specified outside of the class.
7986         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7987              diag::err_virtual_out_of_class)
7988           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7989       } else if (NewFD->getDescribedFunctionTemplate()) {
7990         // C++ [temp.mem]p3:
7991         //  A member function template shall not be virtual.
7992         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7993              diag::err_virtual_member_function_template)
7994           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7995       } else {
7996         // Okay: Add virtual to the method.
7997         NewFD->setVirtualAsWritten(true);
7998       }
7999
8000       if (getLangOpts().CPlusPlus14 &&
8001           NewFD->getReturnType()->isUndeducedType())
8002         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8003     }
8004
8005     if (getLangOpts().CPlusPlus14 &&
8006         (NewFD->isDependentContext() ||
8007          (isFriend && CurContext->isDependentContext())) &&
8008         NewFD->getReturnType()->isUndeducedType()) {
8009       // If the function template is referenced directly (for instance, as a
8010       // member of the current instantiation), pretend it has a dependent type.
8011       // This is not really justified by the standard, but is the only sane
8012       // thing to do.
8013       // FIXME: For a friend function, we have not marked the function as being
8014       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8015       const FunctionProtoType *FPT =
8016           NewFD->getType()->castAs<FunctionProtoType>();
8017       QualType Result =
8018           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8019       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8020                                              FPT->getExtProtoInfo()));
8021     }
8022
8023     // C++ [dcl.fct.spec]p3:
8024     //  The inline specifier shall not appear on a block scope function
8025     //  declaration.
8026     if (isInline && !NewFD->isInvalidDecl()) {
8027       if (CurContext->isFunctionOrMethod()) {
8028         // 'inline' is not allowed on block scope function declaration.
8029         Diag(D.getDeclSpec().getInlineSpecLoc(),
8030              diag::err_inline_declaration_block_scope) << Name
8031           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8032       }
8033     }
8034
8035     // C++ [dcl.fct.spec]p6:
8036     //  The explicit specifier shall be used only in the declaration of a
8037     //  constructor or conversion function within its class definition;
8038     //  see 12.3.1 and 12.3.2.
8039     if (isExplicit && !NewFD->isInvalidDecl()) {
8040       if (!CurContext->isRecord()) {
8041         // 'explicit' was specified outside of the class.
8042         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8043              diag::err_explicit_out_of_class)
8044           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8045       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8046                  !isa<CXXConversionDecl>(NewFD)) {
8047         // 'explicit' was specified on a function that wasn't a constructor
8048         // or conversion function.
8049         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8050              diag::err_explicit_non_ctor_or_conv_function)
8051           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8052       }
8053     }
8054
8055     if (isConstexpr) {
8056       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8057       // are implicitly inline.
8058       NewFD->setImplicitlyInline();
8059
8060       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8061       // be either constructors or to return a literal type. Therefore,
8062       // destructors cannot be declared constexpr.
8063       if (isa<CXXDestructorDecl>(NewFD))
8064         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8065     }
8066
8067     if (isConcept) {
8068       // This is a function concept.
8069       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8070         FTD->setConcept();
8071
8072       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8073       // applied only to the definition of a function template [...]
8074       if (!D.isFunctionDefinition()) {
8075         Diag(D.getDeclSpec().getConceptSpecLoc(),
8076              diag::err_function_concept_not_defined);
8077         NewFD->setInvalidDecl();
8078       }
8079
8080       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8081       // have no exception-specification and is treated as if it were specified
8082       // with noexcept(true) (15.4). [...]
8083       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8084         if (FPT->hasExceptionSpec()) {
8085           SourceRange Range;
8086           if (D.isFunctionDeclarator())
8087             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8088           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8089               << FixItHint::CreateRemoval(Range);
8090           NewFD->setInvalidDecl();
8091         } else {
8092           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8093         }
8094
8095         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8096         // following restrictions:
8097         // - The declared return type shall have the type bool.
8098         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8099           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8100           NewFD->setInvalidDecl();
8101         }
8102
8103         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8104         // following restrictions:
8105         // - The declaration's parameter list shall be equivalent to an empty
8106         //   parameter list.
8107         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8108           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8109       }
8110
8111       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8112       // implicity defined to be a constexpr declaration (implicitly inline)
8113       NewFD->setImplicitlyInline();
8114
8115       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8116       // be declared with the thread_local, inline, friend, or constexpr
8117       // specifiers, [...]
8118       if (isInline) {
8119         Diag(D.getDeclSpec().getInlineSpecLoc(),
8120              diag::err_concept_decl_invalid_specifiers)
8121             << 1 << 1;
8122         NewFD->setInvalidDecl(true);
8123       }
8124
8125       if (isFriend) {
8126         Diag(D.getDeclSpec().getFriendSpecLoc(),
8127              diag::err_concept_decl_invalid_specifiers)
8128             << 1 << 2;
8129         NewFD->setInvalidDecl(true);
8130       }
8131
8132       if (isConstexpr) {
8133         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8134              diag::err_concept_decl_invalid_specifiers)
8135             << 1 << 3;
8136         NewFD->setInvalidDecl(true);
8137       }
8138
8139       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8140       // applied only to the definition of a function template or variable
8141       // template, declared in namespace scope.
8142       if (isFunctionTemplateSpecialization) {
8143         Diag(D.getDeclSpec().getConceptSpecLoc(),
8144              diag::err_concept_specified_specialization) << 1;
8145         NewFD->setInvalidDecl(true);
8146         return NewFD;
8147       }
8148     }
8149
8150     // If __module_private__ was specified, mark the function accordingly.
8151     if (D.getDeclSpec().isModulePrivateSpecified()) {
8152       if (isFunctionTemplateSpecialization) {
8153         SourceLocation ModulePrivateLoc
8154           = D.getDeclSpec().getModulePrivateSpecLoc();
8155         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8156           << 0
8157           << FixItHint::CreateRemoval(ModulePrivateLoc);
8158       } else {
8159         NewFD->setModulePrivate();
8160         if (FunctionTemplate)
8161           FunctionTemplate->setModulePrivate();
8162       }
8163     }
8164
8165     if (isFriend) {
8166       if (FunctionTemplate) {
8167         FunctionTemplate->setObjectOfFriendDecl();
8168         FunctionTemplate->setAccess(AS_public);
8169       }
8170       NewFD->setObjectOfFriendDecl();
8171       NewFD->setAccess(AS_public);
8172     }
8173
8174     // If a function is defined as defaulted or deleted, mark it as such now.
8175     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8176     // definition kind to FDK_Definition.
8177     switch (D.getFunctionDefinitionKind()) {
8178       case FDK_Declaration:
8179       case FDK_Definition:
8180         break;
8181
8182       case FDK_Defaulted:
8183         NewFD->setDefaulted();
8184         break;
8185
8186       case FDK_Deleted:
8187         NewFD->setDeletedAsWritten();
8188         break;
8189     }
8190
8191     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8192         D.isFunctionDefinition()) {
8193       // C++ [class.mfct]p2:
8194       //   A member function may be defined (8.4) in its class definition, in
8195       //   which case it is an inline member function (7.1.2)
8196       NewFD->setImplicitlyInline();
8197     }
8198
8199     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8200         !CurContext->isRecord()) {
8201       // C++ [class.static]p1:
8202       //   A data or function member of a class may be declared static
8203       //   in a class definition, in which case it is a static member of
8204       //   the class.
8205
8206       // Complain about the 'static' specifier if it's on an out-of-line
8207       // member function definition.
8208       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8209            diag::err_static_out_of_line)
8210         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8211     }
8212
8213     // C++11 [except.spec]p15:
8214     //   A deallocation function with no exception-specification is treated
8215     //   as if it were specified with noexcept(true).
8216     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8217     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8218          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8219         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8220       NewFD->setType(Context.getFunctionType(
8221           FPT->getReturnType(), FPT->getParamTypes(),
8222           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8223   }
8224
8225   // Filter out previous declarations that don't match the scope.
8226   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8227                        D.getCXXScopeSpec().isNotEmpty() ||
8228                        isExplicitSpecialization ||
8229                        isFunctionTemplateSpecialization);
8230
8231   // Handle GNU asm-label extension (encoded as an attribute).
8232   if (Expr *E = (Expr*) D.getAsmLabel()) {
8233     // The parser guarantees this is a string.
8234     StringLiteral *SE = cast<StringLiteral>(E);
8235     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8236                                                 SE->getString(), 0));
8237   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8238     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8239       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8240     if (I != ExtnameUndeclaredIdentifiers.end()) {
8241       if (isDeclExternC(NewFD)) {
8242         NewFD->addAttr(I->second);
8243         ExtnameUndeclaredIdentifiers.erase(I);
8244       } else
8245         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8246             << /*Variable*/0 << NewFD;
8247     }
8248   }
8249
8250   // Copy the parameter declarations from the declarator D to the function
8251   // declaration NewFD, if they are available.  First scavenge them into Params.
8252   SmallVector<ParmVarDecl*, 16> Params;
8253   unsigned FTIIdx;
8254   if (D.isFunctionDeclarator(FTIIdx)) {
8255     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8256
8257     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8258     // function that takes no arguments, not a function that takes a
8259     // single void argument.
8260     // We let through "const void" here because Sema::GetTypeForDeclarator
8261     // already checks for that case.
8262     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8263       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8264         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8265         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8266         Param->setDeclContext(NewFD);
8267         Params.push_back(Param);
8268
8269         if (Param->isInvalidDecl())
8270           NewFD->setInvalidDecl();
8271       }
8272     }
8273
8274     if (!getLangOpts().CPlusPlus) {
8275       // In C, find all the tag declarations from the prototype and move them
8276       // into the function DeclContext. Remove them from the surrounding tag
8277       // injection context of the function, which is typically but not always
8278       // the TU.
8279       DeclContext *PrototypeTagContext =
8280           getTagInjectionContext(NewFD->getLexicalDeclContext());
8281       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8282         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8283
8284         // We don't want to reparent enumerators. Look at their parent enum
8285         // instead.
8286         if (!TD) {
8287           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8288             TD = cast<EnumDecl>(ECD->getDeclContext());
8289         }
8290         if (!TD)
8291           continue;
8292         DeclContext *TagDC = TD->getLexicalDeclContext();
8293         if (!TagDC->containsDecl(TD))
8294           continue;
8295         TagDC->removeDecl(TD);
8296         TD->setDeclContext(NewFD);
8297         NewFD->addDecl(TD);
8298
8299         // Preserve the lexical DeclContext if it is not the surrounding tag
8300         // injection context of the FD. In this example, the semantic context of
8301         // E will be f and the lexical context will be S, while both the
8302         // semantic and lexical contexts of S will be f:
8303         //   void f(struct S { enum E { a } f; } s);
8304         if (TagDC != PrototypeTagContext)
8305           TD->setLexicalDeclContext(TagDC);
8306       }
8307     }
8308   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8309     // When we're declaring a function with a typedef, typeof, etc as in the
8310     // following example, we'll need to synthesize (unnamed)
8311     // parameters for use in the declaration.
8312     //
8313     // @code
8314     // typedef void fn(int);
8315     // fn f;
8316     // @endcode
8317
8318     // Synthesize a parameter for each argument type.
8319     for (const auto &AI : FT->param_types()) {
8320       ParmVarDecl *Param =
8321           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8322       Param->setScopeInfo(0, Params.size());
8323       Params.push_back(Param);
8324     }
8325   } else {
8326     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8327            "Should not need args for typedef of non-prototype fn");
8328   }
8329
8330   // Finally, we know we have the right number of parameters, install them.
8331   NewFD->setParams(Params);
8332
8333   if (D.getDeclSpec().isNoreturnSpecified())
8334     NewFD->addAttr(
8335         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8336                                        Context, 0));
8337
8338   // Functions returning a variably modified type violate C99 6.7.5.2p2
8339   // because all functions have linkage.
8340   if (!NewFD->isInvalidDecl() &&
8341       NewFD->getReturnType()->isVariablyModifiedType()) {
8342     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8343     NewFD->setInvalidDecl();
8344   }
8345
8346   // Apply an implicit SectionAttr if #pragma code_seg is active.
8347   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8348       !NewFD->hasAttr<SectionAttr>()) {
8349     NewFD->addAttr(
8350         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8351                                     CodeSegStack.CurrentValue->getString(),
8352                                     CodeSegStack.CurrentPragmaLocation));
8353     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8354                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8355                          ASTContext::PSF_Read,
8356                      NewFD))
8357       NewFD->dropAttr<SectionAttr>();
8358   }
8359
8360   // Handle attributes.
8361   ProcessDeclAttributes(S, NewFD, D);
8362
8363   if (getLangOpts().OpenCL) {
8364     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8365     // type declaration will generate a compilation error.
8366     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8367     if (AddressSpace == LangAS::opencl_local ||
8368         AddressSpace == LangAS::opencl_global ||
8369         AddressSpace == LangAS::opencl_constant) {
8370       Diag(NewFD->getLocation(),
8371            diag::err_opencl_return_value_with_address_space);
8372       NewFD->setInvalidDecl();
8373     }
8374   }
8375
8376   if (!getLangOpts().CPlusPlus) {
8377     // Perform semantic checking on the function declaration.
8378     bool isExplicitSpecialization=false;
8379     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8380       CheckMain(NewFD, D.getDeclSpec());
8381
8382     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8383       CheckMSVCRTEntryPoint(NewFD);
8384
8385     if (!NewFD->isInvalidDecl())
8386       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8387                                                   isExplicitSpecialization));
8388     else if (!Previous.empty())
8389       // Recover gracefully from an invalid redeclaration.
8390       D.setRedeclaration(true);
8391     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8392             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8393            "previous declaration set still overloaded");
8394
8395     // Diagnose no-prototype function declarations with calling conventions that
8396     // don't support variadic calls. Only do this in C and do it after merging
8397     // possibly prototyped redeclarations.
8398     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8399     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8400       CallingConv CC = FT->getExtInfo().getCC();
8401       if (!supportsVariadicCall(CC)) {
8402         // Windows system headers sometimes accidentally use stdcall without
8403         // (void) parameters, so we relax this to a warning.
8404         int DiagID =
8405             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8406         Diag(NewFD->getLocation(), DiagID)
8407             << FunctionType::getNameForCallConv(CC);
8408       }
8409     }
8410   } else {
8411     // C++11 [replacement.functions]p3:
8412     //  The program's definitions shall not be specified as inline.
8413     //
8414     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8415     //
8416     // Suppress the diagnostic if the function is __attribute__((used)), since
8417     // that forces an external definition to be emitted.
8418     if (D.getDeclSpec().isInlineSpecified() &&
8419         NewFD->isReplaceableGlobalAllocationFunction() &&
8420         !NewFD->hasAttr<UsedAttr>())
8421       Diag(D.getDeclSpec().getInlineSpecLoc(),
8422            diag::ext_operator_new_delete_declared_inline)
8423         << NewFD->getDeclName();
8424
8425     // If the declarator is a template-id, translate the parser's template
8426     // argument list into our AST format.
8427     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8428       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8429       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8430       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8431       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8432                                          TemplateId->NumArgs);
8433       translateTemplateArguments(TemplateArgsPtr,
8434                                  TemplateArgs);
8435
8436       HasExplicitTemplateArgs = true;
8437
8438       if (NewFD->isInvalidDecl()) {
8439         HasExplicitTemplateArgs = false;
8440       } else if (FunctionTemplate) {
8441         // Function template with explicit template arguments.
8442         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8443           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8444
8445         HasExplicitTemplateArgs = false;
8446       } else {
8447         assert((isFunctionTemplateSpecialization ||
8448                 D.getDeclSpec().isFriendSpecified()) &&
8449                "should have a 'template<>' for this decl");
8450         // "friend void foo<>(int);" is an implicit specialization decl.
8451         isFunctionTemplateSpecialization = true;
8452       }
8453     } else if (isFriend && isFunctionTemplateSpecialization) {
8454       // This combination is only possible in a recovery case;  the user
8455       // wrote something like:
8456       //   template <> friend void foo(int);
8457       // which we're recovering from as if the user had written:
8458       //   friend void foo<>(int);
8459       // Go ahead and fake up a template id.
8460       HasExplicitTemplateArgs = true;
8461       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8462       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8463     }
8464
8465     // We do not add HD attributes to specializations here because
8466     // they may have different constexpr-ness compared to their
8467     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8468     // may end up with different effective targets. Instead, a
8469     // specialization inherits its target attributes from its template
8470     // in the CheckFunctionTemplateSpecialization() call below.
8471     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8472       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8473
8474     // If it's a friend (and only if it's a friend), it's possible
8475     // that either the specialized function type or the specialized
8476     // template is dependent, and therefore matching will fail.  In
8477     // this case, don't check the specialization yet.
8478     bool InstantiationDependent = false;
8479     if (isFunctionTemplateSpecialization && isFriend &&
8480         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8481          TemplateSpecializationType::anyDependentTemplateArguments(
8482             TemplateArgs,
8483             InstantiationDependent))) {
8484       assert(HasExplicitTemplateArgs &&
8485              "friend function specialization without template args");
8486       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8487                                                        Previous))
8488         NewFD->setInvalidDecl();
8489     } else if (isFunctionTemplateSpecialization) {
8490       if (CurContext->isDependentContext() && CurContext->isRecord()
8491           && !isFriend) {
8492         isDependentClassScopeExplicitSpecialization = true;
8493         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8494           diag::ext_function_specialization_in_class :
8495           diag::err_function_specialization_in_class)
8496           << NewFD->getDeclName();
8497       } else if (CheckFunctionTemplateSpecialization(NewFD,
8498                                   (HasExplicitTemplateArgs ? &TemplateArgs
8499                                                            : nullptr),
8500                                                      Previous))
8501         NewFD->setInvalidDecl();
8502
8503       // C++ [dcl.stc]p1:
8504       //   A storage-class-specifier shall not be specified in an explicit
8505       //   specialization (14.7.3)
8506       FunctionTemplateSpecializationInfo *Info =
8507           NewFD->getTemplateSpecializationInfo();
8508       if (Info && SC != SC_None) {
8509         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8510           Diag(NewFD->getLocation(),
8511                diag::err_explicit_specialization_inconsistent_storage_class)
8512             << SC
8513             << FixItHint::CreateRemoval(
8514                                       D.getDeclSpec().getStorageClassSpecLoc());
8515
8516         else
8517           Diag(NewFD->getLocation(),
8518                diag::ext_explicit_specialization_storage_class)
8519             << FixItHint::CreateRemoval(
8520                                       D.getDeclSpec().getStorageClassSpecLoc());
8521       }
8522     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8523       if (CheckMemberSpecialization(NewFD, Previous))
8524           NewFD->setInvalidDecl();
8525     }
8526
8527     // Perform semantic checking on the function declaration.
8528     if (!isDependentClassScopeExplicitSpecialization) {
8529       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8530         CheckMain(NewFD, D.getDeclSpec());
8531
8532       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8533         CheckMSVCRTEntryPoint(NewFD);
8534
8535       if (!NewFD->isInvalidDecl())
8536         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8537                                                     isExplicitSpecialization));
8538       else if (!Previous.empty())
8539         // Recover gracefully from an invalid redeclaration.
8540         D.setRedeclaration(true);
8541     }
8542
8543     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8544             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8545            "previous declaration set still overloaded");
8546
8547     NamedDecl *PrincipalDecl = (FunctionTemplate
8548                                 ? cast<NamedDecl>(FunctionTemplate)
8549                                 : NewFD);
8550
8551     if (isFriend && NewFD->getPreviousDecl()) {
8552       AccessSpecifier Access = AS_public;
8553       if (!NewFD->isInvalidDecl())
8554         Access = NewFD->getPreviousDecl()->getAccess();
8555
8556       NewFD->setAccess(Access);
8557       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8558     }
8559
8560     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8561         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8562       PrincipalDecl->setNonMemberOperator();
8563
8564     // If we have a function template, check the template parameter
8565     // list. This will check and merge default template arguments.
8566     if (FunctionTemplate) {
8567       FunctionTemplateDecl *PrevTemplate =
8568                                      FunctionTemplate->getPreviousDecl();
8569       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8570                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8571                                     : nullptr,
8572                             D.getDeclSpec().isFriendSpecified()
8573                               ? (D.isFunctionDefinition()
8574                                    ? TPC_FriendFunctionTemplateDefinition
8575                                    : TPC_FriendFunctionTemplate)
8576                               : (D.getCXXScopeSpec().isSet() &&
8577                                  DC && DC->isRecord() &&
8578                                  DC->isDependentContext())
8579                                   ? TPC_ClassTemplateMember
8580                                   : TPC_FunctionTemplate);
8581     }
8582
8583     if (NewFD->isInvalidDecl()) {
8584       // Ignore all the rest of this.
8585     } else if (!D.isRedeclaration()) {
8586       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8587                                        AddToScope };
8588       // Fake up an access specifier if it's supposed to be a class member.
8589       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8590         NewFD->setAccess(AS_public);
8591
8592       // Qualified decls generally require a previous declaration.
8593       if (D.getCXXScopeSpec().isSet()) {
8594         // ...with the major exception of templated-scope or
8595         // dependent-scope friend declarations.
8596
8597         // TODO: we currently also suppress this check in dependent
8598         // contexts because (1) the parameter depth will be off when
8599         // matching friend templates and (2) we might actually be
8600         // selecting a friend based on a dependent factor.  But there
8601         // are situations where these conditions don't apply and we
8602         // can actually do this check immediately.
8603         if (isFriend &&
8604             (TemplateParamLists.size() ||
8605              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8606              CurContext->isDependentContext())) {
8607           // ignore these
8608         } else {
8609           // The user tried to provide an out-of-line definition for a
8610           // function that is a member of a class or namespace, but there
8611           // was no such member function declared (C++ [class.mfct]p2,
8612           // C++ [namespace.memdef]p2). For example:
8613           //
8614           // class X {
8615           //   void f() const;
8616           // };
8617           //
8618           // void X::f() { } // ill-formed
8619           //
8620           // Complain about this problem, and attempt to suggest close
8621           // matches (e.g., those that differ only in cv-qualifiers and
8622           // whether the parameter types are references).
8623
8624           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8625                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8626             AddToScope = ExtraArgs.AddToScope;
8627             return Result;
8628           }
8629         }
8630
8631         // Unqualified local friend declarations are required to resolve
8632         // to something.
8633       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8634         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8635                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8636           AddToScope = ExtraArgs.AddToScope;
8637           return Result;
8638         }
8639       }
8640     } else if (!D.isFunctionDefinition() &&
8641                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8642                !isFriend && !isFunctionTemplateSpecialization &&
8643                !isExplicitSpecialization) {
8644       // An out-of-line member function declaration must also be a
8645       // definition (C++ [class.mfct]p2).
8646       // Note that this is not the case for explicit specializations of
8647       // function templates or member functions of class templates, per
8648       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8649       // extension for compatibility with old SWIG code which likes to
8650       // generate them.
8651       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8652         << D.getCXXScopeSpec().getRange();
8653     }
8654   }
8655
8656   ProcessPragmaWeak(S, NewFD);
8657   checkAttributesAfterMerging(*this, *NewFD);
8658
8659   AddKnownFunctionAttributes(NewFD);
8660
8661   if (NewFD->hasAttr<OverloadableAttr>() &&
8662       !NewFD->getType()->getAs<FunctionProtoType>()) {
8663     Diag(NewFD->getLocation(),
8664          diag::err_attribute_overloadable_no_prototype)
8665       << NewFD;
8666
8667     // Turn this into a variadic function with no parameters.
8668     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8669     FunctionProtoType::ExtProtoInfo EPI(
8670         Context.getDefaultCallingConvention(true, false));
8671     EPI.Variadic = true;
8672     EPI.ExtInfo = FT->getExtInfo();
8673
8674     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8675     NewFD->setType(R);
8676   }
8677
8678   // If there's a #pragma GCC visibility in scope, and this isn't a class
8679   // member, set the visibility of this function.
8680   if (!DC->isRecord() && NewFD->isExternallyVisible())
8681     AddPushedVisibilityAttribute(NewFD);
8682
8683   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8684   // marking the function.
8685   AddCFAuditedAttribute(NewFD);
8686
8687   // If this is a function definition, check if we have to apply optnone due to
8688   // a pragma.
8689   if(D.isFunctionDefinition())
8690     AddRangeBasedOptnone(NewFD);
8691
8692   // If this is the first declaration of an extern C variable, update
8693   // the map of such variables.
8694   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8695       isIncompleteDeclExternC(*this, NewFD))
8696     RegisterLocallyScopedExternCDecl(NewFD, S);
8697
8698   // Set this FunctionDecl's range up to the right paren.
8699   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8700
8701   if (D.isRedeclaration() && !Previous.empty()) {
8702     checkDLLAttributeRedeclaration(
8703         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8704         isExplicitSpecialization || isFunctionTemplateSpecialization,
8705         D.isFunctionDefinition());
8706   }
8707
8708   if (getLangOpts().CUDA) {
8709     IdentifierInfo *II = NewFD->getIdentifier();
8710     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8711         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8712       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8713         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8714
8715       Context.setcudaConfigureCallDecl(NewFD);
8716     }
8717
8718     // Variadic functions, other than a *declaration* of printf, are not allowed
8719     // in device-side CUDA code, unless someone passed
8720     // -fcuda-allow-variadic-functions.
8721     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8722         (NewFD->hasAttr<CUDADeviceAttr>() ||
8723          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8724         !(II && II->isStr("printf") && NewFD->isExternC() &&
8725           !D.isFunctionDefinition())) {
8726       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8727     }
8728   }
8729
8730   if (getLangOpts().CPlusPlus) {
8731     if (FunctionTemplate) {
8732       if (NewFD->isInvalidDecl())
8733         FunctionTemplate->setInvalidDecl();
8734       return FunctionTemplate;
8735     }
8736   }
8737
8738   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8739     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8740     if ((getLangOpts().OpenCLVersion >= 120)
8741         && (SC == SC_Static)) {
8742       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8743       D.setInvalidType();
8744     }
8745
8746     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8747     if (!NewFD->getReturnType()->isVoidType()) {
8748       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8749       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8750           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8751                                 : FixItHint());
8752       D.setInvalidType();
8753     }
8754
8755     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8756     for (auto Param : NewFD->parameters())
8757       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8758   }
8759   for (const ParmVarDecl *Param : NewFD->parameters()) {
8760     QualType PT = Param->getType();
8761
8762     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8763     // types.
8764     if (getLangOpts().OpenCLVersion >= 200) {
8765       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8766         QualType ElemTy = PipeTy->getElementType();
8767           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8768             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8769             D.setInvalidType();
8770           }
8771       }
8772     }
8773   }
8774
8775   MarkUnusedFileScopedDecl(NewFD);
8776
8777   // Here we have an function template explicit specialization at class scope.
8778   // The actually specialization will be postponed to template instatiation
8779   // time via the ClassScopeFunctionSpecializationDecl node.
8780   if (isDependentClassScopeExplicitSpecialization) {
8781     ClassScopeFunctionSpecializationDecl *NewSpec =
8782                          ClassScopeFunctionSpecializationDecl::Create(
8783                                 Context, CurContext, SourceLocation(),
8784                                 cast<CXXMethodDecl>(NewFD),
8785                                 HasExplicitTemplateArgs, TemplateArgs);
8786     CurContext->addDecl(NewSpec);
8787     AddToScope = false;
8788   }
8789
8790   return NewFD;
8791 }
8792
8793 /// \brief Checks if the new declaration declared in dependent context must be
8794 /// put in the same redeclaration chain as the specified declaration.
8795 ///
8796 /// \param D Declaration that is checked.
8797 /// \param PrevDecl Previous declaration found with proper lookup method for the
8798 ///                 same declaration name.
8799 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8800 ///          belongs to.
8801 ///
8802 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8803   // Any declarations should be put into redeclaration chains except for
8804   // friend declaration in a dependent context that names a function in
8805   // namespace scope.
8806   //
8807   // This allows to compile code like:
8808   //
8809   //       void func();
8810   //       template<typename T> class C1 { friend void func() { } };
8811   //       template<typename T> class C2 { friend void func() { } };
8812   //
8813   // This code snippet is a valid code unless both templates are instantiated.
8814   return !(D->getLexicalDeclContext()->isDependentContext() &&
8815            D->getDeclContext()->isFileContext() &&
8816            D->getFriendObjectKind() != Decl::FOK_None);
8817 }
8818
8819 /// \brief Perform semantic checking of a new function declaration.
8820 ///
8821 /// Performs semantic analysis of the new function declaration
8822 /// NewFD. This routine performs all semantic checking that does not
8823 /// require the actual declarator involved in the declaration, and is
8824 /// used both for the declaration of functions as they are parsed
8825 /// (called via ActOnDeclarator) and for the declaration of functions
8826 /// that have been instantiated via C++ template instantiation (called
8827 /// via InstantiateDecl).
8828 ///
8829 /// \param IsExplicitSpecialization whether this new function declaration is
8830 /// an explicit specialization of the previous declaration.
8831 ///
8832 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8833 ///
8834 /// \returns true if the function declaration is a redeclaration.
8835 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8836                                     LookupResult &Previous,
8837                                     bool IsExplicitSpecialization) {
8838   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8839          "Variably modified return types are not handled here");
8840
8841   // Determine whether the type of this function should be merged with
8842   // a previous visible declaration. This never happens for functions in C++,
8843   // and always happens in C if the previous declaration was visible.
8844   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8845                                !Previous.isShadowed();
8846
8847   bool Redeclaration = false;
8848   NamedDecl *OldDecl = nullptr;
8849
8850   // Merge or overload the declaration with an existing declaration of
8851   // the same name, if appropriate.
8852   if (!Previous.empty()) {
8853     // Determine whether NewFD is an overload of PrevDecl or
8854     // a declaration that requires merging. If it's an overload,
8855     // there's no more work to do here; we'll just add the new
8856     // function to the scope.
8857     if (!AllowOverloadingOfFunction(Previous, Context)) {
8858       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8859       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8860         Redeclaration = true;
8861         OldDecl = Candidate;
8862       }
8863     } else {
8864       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8865                             /*NewIsUsingDecl*/ false)) {
8866       case Ovl_Match:
8867         Redeclaration = true;
8868         break;
8869
8870       case Ovl_NonFunction:
8871         Redeclaration = true;
8872         break;
8873
8874       case Ovl_Overload:
8875         Redeclaration = false;
8876         break;
8877       }
8878
8879       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8880         // If a function name is overloadable in C, then every function
8881         // with that name must be marked "overloadable".
8882         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8883           << Redeclaration << NewFD;
8884         NamedDecl *OverloadedDecl = nullptr;
8885         if (Redeclaration)
8886           OverloadedDecl = OldDecl;
8887         else if (!Previous.empty())
8888           OverloadedDecl = Previous.getRepresentativeDecl();
8889         if (OverloadedDecl)
8890           Diag(OverloadedDecl->getLocation(),
8891                diag::note_attribute_overloadable_prev_overload);
8892         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8893       }
8894     }
8895   }
8896
8897   // Check for a previous extern "C" declaration with this name.
8898   if (!Redeclaration &&
8899       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8900     if (!Previous.empty()) {
8901       // This is an extern "C" declaration with the same name as a previous
8902       // declaration, and thus redeclares that entity...
8903       Redeclaration = true;
8904       OldDecl = Previous.getFoundDecl();
8905       MergeTypeWithPrevious = false;
8906
8907       // ... except in the presence of __attribute__((overloadable)).
8908       if (OldDecl->hasAttr<OverloadableAttr>()) {
8909         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8910           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8911             << Redeclaration << NewFD;
8912           Diag(Previous.getFoundDecl()->getLocation(),
8913                diag::note_attribute_overloadable_prev_overload);
8914           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8915         }
8916         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8917           Redeclaration = false;
8918           OldDecl = nullptr;
8919         }
8920       }
8921     }
8922   }
8923
8924   // C++11 [dcl.constexpr]p8:
8925   //   A constexpr specifier for a non-static member function that is not
8926   //   a constructor declares that member function to be const.
8927   //
8928   // This needs to be delayed until we know whether this is an out-of-line
8929   // definition of a static member function.
8930   //
8931   // This rule is not present in C++1y, so we produce a backwards
8932   // compatibility warning whenever it happens in C++11.
8933   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8934   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8935       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8936       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8937     CXXMethodDecl *OldMD = nullptr;
8938     if (OldDecl)
8939       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8940     if (!OldMD || !OldMD->isStatic()) {
8941       const FunctionProtoType *FPT =
8942         MD->getType()->castAs<FunctionProtoType>();
8943       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8944       EPI.TypeQuals |= Qualifiers::Const;
8945       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8946                                           FPT->getParamTypes(), EPI));
8947
8948       // Warn that we did this, if we're not performing template instantiation.
8949       // In that case, we'll have warned already when the template was defined.
8950       if (ActiveTemplateInstantiations.empty()) {
8951         SourceLocation AddConstLoc;
8952         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8953                 .IgnoreParens().getAs<FunctionTypeLoc>())
8954           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8955
8956         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8957           << FixItHint::CreateInsertion(AddConstLoc, " const");
8958       }
8959     }
8960   }
8961
8962   if (Redeclaration) {
8963     // NewFD and OldDecl represent declarations that need to be
8964     // merged.
8965     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8966       NewFD->setInvalidDecl();
8967       return Redeclaration;
8968     }
8969
8970     Previous.clear();
8971     Previous.addDecl(OldDecl);
8972
8973     if (FunctionTemplateDecl *OldTemplateDecl
8974                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8975       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8976       FunctionTemplateDecl *NewTemplateDecl
8977         = NewFD->getDescribedFunctionTemplate();
8978       assert(NewTemplateDecl && "Template/non-template mismatch");
8979       if (CXXMethodDecl *Method
8980             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8981         Method->setAccess(OldTemplateDecl->getAccess());
8982         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8983       }
8984
8985       // If this is an explicit specialization of a member that is a function
8986       // template, mark it as a member specialization.
8987       if (IsExplicitSpecialization &&
8988           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8989         NewTemplateDecl->setMemberSpecialization();
8990         assert(OldTemplateDecl->isMemberSpecialization());
8991         // Explicit specializations of a member template do not inherit deleted
8992         // status from the parent member template that they are specializing.
8993         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8994           FunctionDecl *const OldTemplatedDecl =
8995               OldTemplateDecl->getTemplatedDecl();
8996           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8997           OldTemplatedDecl->setDeletedAsWritten(false);
8998         }
8999       }
9000
9001     } else {
9002       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9003         // This needs to happen first so that 'inline' propagates.
9004         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9005         if (isa<CXXMethodDecl>(NewFD))
9006           NewFD->setAccess(OldDecl->getAccess());
9007       }
9008     }
9009   }
9010
9011   // Semantic checking for this function declaration (in isolation).
9012
9013   if (getLangOpts().CPlusPlus) {
9014     // C++-specific checks.
9015     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9016       CheckConstructor(Constructor);
9017     } else if (CXXDestructorDecl *Destructor =
9018                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9019       CXXRecordDecl *Record = Destructor->getParent();
9020       QualType ClassType = Context.getTypeDeclType(Record);
9021
9022       // FIXME: Shouldn't we be able to perform this check even when the class
9023       // type is dependent? Both gcc and edg can handle that.
9024       if (!ClassType->isDependentType()) {
9025         DeclarationName Name
9026           = Context.DeclarationNames.getCXXDestructorName(
9027                                         Context.getCanonicalType(ClassType));
9028         if (NewFD->getDeclName() != Name) {
9029           Diag(NewFD->getLocation(), diag::err_destructor_name);
9030           NewFD->setInvalidDecl();
9031           return Redeclaration;
9032         }
9033       }
9034     } else if (CXXConversionDecl *Conversion
9035                = dyn_cast<CXXConversionDecl>(NewFD)) {
9036       ActOnConversionDeclarator(Conversion);
9037     }
9038
9039     // Find any virtual functions that this function overrides.
9040     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9041       if (!Method->isFunctionTemplateSpecialization() &&
9042           !Method->getDescribedFunctionTemplate() &&
9043           Method->isCanonicalDecl()) {
9044         if (AddOverriddenMethods(Method->getParent(), Method)) {
9045           // If the function was marked as "static", we have a problem.
9046           if (NewFD->getStorageClass() == SC_Static) {
9047             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9048           }
9049         }
9050       }
9051
9052       if (Method->isStatic())
9053         checkThisInStaticMemberFunctionType(Method);
9054     }
9055
9056     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9057     if (NewFD->isOverloadedOperator() &&
9058         CheckOverloadedOperatorDeclaration(NewFD)) {
9059       NewFD->setInvalidDecl();
9060       return Redeclaration;
9061     }
9062
9063     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9064     if (NewFD->getLiteralIdentifier() &&
9065         CheckLiteralOperatorDeclaration(NewFD)) {
9066       NewFD->setInvalidDecl();
9067       return Redeclaration;
9068     }
9069
9070     // In C++, check default arguments now that we have merged decls. Unless
9071     // the lexical context is the class, because in this case this is done
9072     // during delayed parsing anyway.
9073     if (!CurContext->isRecord())
9074       CheckCXXDefaultArguments(NewFD);
9075
9076     // If this function declares a builtin function, check the type of this
9077     // declaration against the expected type for the builtin.
9078     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9079       ASTContext::GetBuiltinTypeError Error;
9080       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9081       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9082       // If the type of the builtin differs only in its exception
9083       // specification, that's OK.
9084       // FIXME: If the types do differ in this way, it would be better to
9085       // retain the 'noexcept' form of the type.
9086       if (!T.isNull() &&
9087           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9088                                                             NewFD->getType()))
9089         // The type of this function differs from the type of the builtin,
9090         // so forget about the builtin entirely.
9091         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9092     }
9093
9094     // If this function is declared as being extern "C", then check to see if
9095     // the function returns a UDT (class, struct, or union type) that is not C
9096     // compatible, and if it does, warn the user.
9097     // But, issue any diagnostic on the first declaration only.
9098     if (Previous.empty() && NewFD->isExternC()) {
9099       QualType R = NewFD->getReturnType();
9100       if (R->isIncompleteType() && !R->isVoidType())
9101         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9102             << NewFD << R;
9103       else if (!R.isPODType(Context) && !R->isVoidType() &&
9104                !R->isObjCObjectPointerType())
9105         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9106     }
9107
9108     // C++1z [dcl.fct]p6:
9109     //   [...] whether the function has a non-throwing exception-specification
9110     //   [is] part of the function type
9111     //
9112     // This results in an ABI break between C++14 and C++17 for functions whose
9113     // declared type includes an exception-specification in a parameter or
9114     // return type. (Exception specifications on the function itself are OK in
9115     // most cases, and exception specifications are not permitted in most other
9116     // contexts where they could make it into a mangling.)
9117     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9118       auto HasNoexcept = [&](QualType T) -> bool {
9119         // Strip off declarator chunks that could be between us and a function
9120         // type. We don't need to look far, exception specifications are very
9121         // restricted prior to C++17.
9122         if (auto *RT = T->getAs<ReferenceType>())
9123           T = RT->getPointeeType();
9124         else if (T->isAnyPointerType())
9125           T = T->getPointeeType();
9126         else if (auto *MPT = T->getAs<MemberPointerType>())
9127           T = MPT->getPointeeType();
9128         if (auto *FPT = T->getAs<FunctionProtoType>())
9129           if (FPT->isNothrow(Context))
9130             return true;
9131         return false;
9132       };
9133
9134       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9135       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9136       for (QualType T : FPT->param_types())
9137         AnyNoexcept |= HasNoexcept(T);
9138       if (AnyNoexcept)
9139         Diag(NewFD->getLocation(),
9140              diag::warn_cxx1z_compat_exception_spec_in_signature)
9141             << NewFD;
9142     }
9143
9144     if (!Redeclaration && LangOpts.CUDA)
9145       checkCUDATargetOverload(NewFD, Previous);
9146   }
9147   return Redeclaration;
9148 }
9149
9150 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9151   // C++11 [basic.start.main]p3:
9152   //   A program that [...] declares main to be inline, static or
9153   //   constexpr is ill-formed.
9154   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9155   //   appear in a declaration of main.
9156   // static main is not an error under C99, but we should warn about it.
9157   // We accept _Noreturn main as an extension.
9158   if (FD->getStorageClass() == SC_Static)
9159     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9160          ? diag::err_static_main : diag::warn_static_main)
9161       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9162   if (FD->isInlineSpecified())
9163     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9164       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9165   if (DS.isNoreturnSpecified()) {
9166     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9167     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9168     Diag(NoreturnLoc, diag::ext_noreturn_main);
9169     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9170       << FixItHint::CreateRemoval(NoreturnRange);
9171   }
9172   if (FD->isConstexpr()) {
9173     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9174       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9175     FD->setConstexpr(false);
9176   }
9177
9178   if (getLangOpts().OpenCL) {
9179     Diag(FD->getLocation(), diag::err_opencl_no_main)
9180         << FD->hasAttr<OpenCLKernelAttr>();
9181     FD->setInvalidDecl();
9182     return;
9183   }
9184
9185   QualType T = FD->getType();
9186   assert(T->isFunctionType() && "function decl is not of function type");
9187   const FunctionType* FT = T->castAs<FunctionType>();
9188
9189   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9190     // In C with GNU extensions we allow main() to have non-integer return
9191     // type, but we should warn about the extension, and we disable the
9192     // implicit-return-zero rule.
9193
9194     // GCC in C mode accepts qualified 'int'.
9195     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9196       FD->setHasImplicitReturnZero(true);
9197     else {
9198       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9199       SourceRange RTRange = FD->getReturnTypeSourceRange();
9200       if (RTRange.isValid())
9201         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9202             << FixItHint::CreateReplacement(RTRange, "int");
9203     }
9204   } else {
9205     // In C and C++, main magically returns 0 if you fall off the end;
9206     // set the flag which tells us that.
9207     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9208
9209     // All the standards say that main() should return 'int'.
9210     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9211       FD->setHasImplicitReturnZero(true);
9212     else {
9213       // Otherwise, this is just a flat-out error.
9214       SourceRange RTRange = FD->getReturnTypeSourceRange();
9215       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9216           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9217                                 : FixItHint());
9218       FD->setInvalidDecl(true);
9219     }
9220   }
9221
9222   // Treat protoless main() as nullary.
9223   if (isa<FunctionNoProtoType>(FT)) return;
9224
9225   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9226   unsigned nparams = FTP->getNumParams();
9227   assert(FD->getNumParams() == nparams);
9228
9229   bool HasExtraParameters = (nparams > 3);
9230
9231   if (FTP->isVariadic()) {
9232     Diag(FD->getLocation(), diag::ext_variadic_main);
9233     // FIXME: if we had information about the location of the ellipsis, we
9234     // could add a FixIt hint to remove it as a parameter.
9235   }
9236
9237   // Darwin passes an undocumented fourth argument of type char**.  If
9238   // other platforms start sprouting these, the logic below will start
9239   // getting shifty.
9240   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9241     HasExtraParameters = false;
9242
9243   if (HasExtraParameters) {
9244     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9245     FD->setInvalidDecl(true);
9246     nparams = 3;
9247   }
9248
9249   // FIXME: a lot of the following diagnostics would be improved
9250   // if we had some location information about types.
9251
9252   QualType CharPP =
9253     Context.getPointerType(Context.getPointerType(Context.CharTy));
9254   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9255
9256   for (unsigned i = 0; i < nparams; ++i) {
9257     QualType AT = FTP->getParamType(i);
9258
9259     bool mismatch = true;
9260
9261     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9262       mismatch = false;
9263     else if (Expected[i] == CharPP) {
9264       // As an extension, the following forms are okay:
9265       //   char const **
9266       //   char const * const *
9267       //   char * const *
9268
9269       QualifierCollector qs;
9270       const PointerType* PT;
9271       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9272           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9273           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9274                               Context.CharTy)) {
9275         qs.removeConst();
9276         mismatch = !qs.empty();
9277       }
9278     }
9279
9280     if (mismatch) {
9281       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9282       // TODO: suggest replacing given type with expected type
9283       FD->setInvalidDecl(true);
9284     }
9285   }
9286
9287   if (nparams == 1 && !FD->isInvalidDecl()) {
9288     Diag(FD->getLocation(), diag::warn_main_one_arg);
9289   }
9290
9291   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9292     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9293     FD->setInvalidDecl();
9294   }
9295 }
9296
9297 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9298   QualType T = FD->getType();
9299   assert(T->isFunctionType() && "function decl is not of function type");
9300   const FunctionType *FT = T->castAs<FunctionType>();
9301
9302   // Set an implicit return of 'zero' if the function can return some integral,
9303   // enumeration, pointer or nullptr type.
9304   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9305       FT->getReturnType()->isAnyPointerType() ||
9306       FT->getReturnType()->isNullPtrType())
9307     // DllMain is exempt because a return value of zero means it failed.
9308     if (FD->getName() != "DllMain")
9309       FD->setHasImplicitReturnZero(true);
9310
9311   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9312     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9313     FD->setInvalidDecl();
9314   }
9315 }
9316
9317 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9318   // FIXME: Need strict checking.  In C89, we need to check for
9319   // any assignment, increment, decrement, function-calls, or
9320   // commas outside of a sizeof.  In C99, it's the same list,
9321   // except that the aforementioned are allowed in unevaluated
9322   // expressions.  Everything else falls under the
9323   // "may accept other forms of constant expressions" exception.
9324   // (We never end up here for C++, so the constant expression
9325   // rules there don't matter.)
9326   const Expr *Culprit;
9327   if (Init->isConstantInitializer(Context, false, &Culprit))
9328     return false;
9329   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9330     << Culprit->getSourceRange();
9331   return true;
9332 }
9333
9334 namespace {
9335   // Visits an initialization expression to see if OrigDecl is evaluated in
9336   // its own initialization and throws a warning if it does.
9337   class SelfReferenceChecker
9338       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9339     Sema &S;
9340     Decl *OrigDecl;
9341     bool isRecordType;
9342     bool isPODType;
9343     bool isReferenceType;
9344
9345     bool isInitList;
9346     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9347
9348   public:
9349     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9350
9351     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9352                                                     S(S), OrigDecl(OrigDecl) {
9353       isPODType = false;
9354       isRecordType = false;
9355       isReferenceType = false;
9356       isInitList = false;
9357       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9358         isPODType = VD->getType().isPODType(S.Context);
9359         isRecordType = VD->getType()->isRecordType();
9360         isReferenceType = VD->getType()->isReferenceType();
9361       }
9362     }
9363
9364     // For most expressions, just call the visitor.  For initializer lists,
9365     // track the index of the field being initialized since fields are
9366     // initialized in order allowing use of previously initialized fields.
9367     void CheckExpr(Expr *E) {
9368       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9369       if (!InitList) {
9370         Visit(E);
9371         return;
9372       }
9373
9374       // Track and increment the index here.
9375       isInitList = true;
9376       InitFieldIndex.push_back(0);
9377       for (auto Child : InitList->children()) {
9378         CheckExpr(cast<Expr>(Child));
9379         ++InitFieldIndex.back();
9380       }
9381       InitFieldIndex.pop_back();
9382     }
9383
9384     // Returns true if MemberExpr is checked and no futher checking is needed.
9385     // Returns false if additional checking is required.
9386     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9387       llvm::SmallVector<FieldDecl*, 4> Fields;
9388       Expr *Base = E;
9389       bool ReferenceField = false;
9390
9391       // Get the field memebers used.
9392       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9393         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9394         if (!FD)
9395           return false;
9396         Fields.push_back(FD);
9397         if (FD->getType()->isReferenceType())
9398           ReferenceField = true;
9399         Base = ME->getBase()->IgnoreParenImpCasts();
9400       }
9401
9402       // Keep checking only if the base Decl is the same.
9403       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9404       if (!DRE || DRE->getDecl() != OrigDecl)
9405         return false;
9406
9407       // A reference field can be bound to an unininitialized field.
9408       if (CheckReference && !ReferenceField)
9409         return true;
9410
9411       // Convert FieldDecls to their index number.
9412       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9413       for (const FieldDecl *I : llvm::reverse(Fields))
9414         UsedFieldIndex.push_back(I->getFieldIndex());
9415
9416       // See if a warning is needed by checking the first difference in index
9417       // numbers.  If field being used has index less than the field being
9418       // initialized, then the use is safe.
9419       for (auto UsedIter = UsedFieldIndex.begin(),
9420                 UsedEnd = UsedFieldIndex.end(),
9421                 OrigIter = InitFieldIndex.begin(),
9422                 OrigEnd = InitFieldIndex.end();
9423            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9424         if (*UsedIter < *OrigIter)
9425           return true;
9426         if (*UsedIter > *OrigIter)
9427           break;
9428       }
9429
9430       // TODO: Add a different warning which will print the field names.
9431       HandleDeclRefExpr(DRE);
9432       return true;
9433     }
9434
9435     // For most expressions, the cast is directly above the DeclRefExpr.
9436     // For conditional operators, the cast can be outside the conditional
9437     // operator if both expressions are DeclRefExpr's.
9438     void HandleValue(Expr *E) {
9439       E = E->IgnoreParens();
9440       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9441         HandleDeclRefExpr(DRE);
9442         return;
9443       }
9444
9445       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9446         Visit(CO->getCond());
9447         HandleValue(CO->getTrueExpr());
9448         HandleValue(CO->getFalseExpr());
9449         return;
9450       }
9451
9452       if (BinaryConditionalOperator *BCO =
9453               dyn_cast<BinaryConditionalOperator>(E)) {
9454         Visit(BCO->getCond());
9455         HandleValue(BCO->getFalseExpr());
9456         return;
9457       }
9458
9459       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9460         HandleValue(OVE->getSourceExpr());
9461         return;
9462       }
9463
9464       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9465         if (BO->getOpcode() == BO_Comma) {
9466           Visit(BO->getLHS());
9467           HandleValue(BO->getRHS());
9468           return;
9469         }
9470       }
9471
9472       if (isa<MemberExpr>(E)) {
9473         if (isInitList) {
9474           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9475                                       false /*CheckReference*/))
9476             return;
9477         }
9478
9479         Expr *Base = E->IgnoreParenImpCasts();
9480         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9481           // Check for static member variables and don't warn on them.
9482           if (!isa<FieldDecl>(ME->getMemberDecl()))
9483             return;
9484           Base = ME->getBase()->IgnoreParenImpCasts();
9485         }
9486         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9487           HandleDeclRefExpr(DRE);
9488         return;
9489       }
9490
9491       Visit(E);
9492     }
9493
9494     // Reference types not handled in HandleValue are handled here since all
9495     // uses of references are bad, not just r-value uses.
9496     void VisitDeclRefExpr(DeclRefExpr *E) {
9497       if (isReferenceType)
9498         HandleDeclRefExpr(E);
9499     }
9500
9501     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9502       if (E->getCastKind() == CK_LValueToRValue) {
9503         HandleValue(E->getSubExpr());
9504         return;
9505       }
9506
9507       Inherited::VisitImplicitCastExpr(E);
9508     }
9509
9510     void VisitMemberExpr(MemberExpr *E) {
9511       if (isInitList) {
9512         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9513           return;
9514       }
9515
9516       // Don't warn on arrays since they can be treated as pointers.
9517       if (E->getType()->canDecayToPointerType()) return;
9518
9519       // Warn when a non-static method call is followed by non-static member
9520       // field accesses, which is followed by a DeclRefExpr.
9521       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9522       bool Warn = (MD && !MD->isStatic());
9523       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9524       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9525         if (!isa<FieldDecl>(ME->getMemberDecl()))
9526           Warn = false;
9527         Base = ME->getBase()->IgnoreParenImpCasts();
9528       }
9529
9530       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9531         if (Warn)
9532           HandleDeclRefExpr(DRE);
9533         return;
9534       }
9535
9536       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9537       // Visit that expression.
9538       Visit(Base);
9539     }
9540
9541     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9542       Expr *Callee = E->getCallee();
9543
9544       if (isa<UnresolvedLookupExpr>(Callee))
9545         return Inherited::VisitCXXOperatorCallExpr(E);
9546
9547       Visit(Callee);
9548       for (auto Arg: E->arguments())
9549         HandleValue(Arg->IgnoreParenImpCasts());
9550     }
9551
9552     void VisitUnaryOperator(UnaryOperator *E) {
9553       // For POD record types, addresses of its own members are well-defined.
9554       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9555           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9556         if (!isPODType)
9557           HandleValue(E->getSubExpr());
9558         return;
9559       }
9560
9561       if (E->isIncrementDecrementOp()) {
9562         HandleValue(E->getSubExpr());
9563         return;
9564       }
9565
9566       Inherited::VisitUnaryOperator(E);
9567     }
9568
9569     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9570
9571     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9572       if (E->getConstructor()->isCopyConstructor()) {
9573         Expr *ArgExpr = E->getArg(0);
9574         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9575           if (ILE->getNumInits() == 1)
9576             ArgExpr = ILE->getInit(0);
9577         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9578           if (ICE->getCastKind() == CK_NoOp)
9579             ArgExpr = ICE->getSubExpr();
9580         HandleValue(ArgExpr);
9581         return;
9582       }
9583       Inherited::VisitCXXConstructExpr(E);
9584     }
9585
9586     void VisitCallExpr(CallExpr *E) {
9587       // Treat std::move as a use.
9588       if (E->getNumArgs() == 1) {
9589         if (FunctionDecl *FD = E->getDirectCallee()) {
9590           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9591               FD->getIdentifier()->isStr("move")) {
9592             HandleValue(E->getArg(0));
9593             return;
9594           }
9595         }
9596       }
9597
9598       Inherited::VisitCallExpr(E);
9599     }
9600
9601     void VisitBinaryOperator(BinaryOperator *E) {
9602       if (E->isCompoundAssignmentOp()) {
9603         HandleValue(E->getLHS());
9604         Visit(E->getRHS());
9605         return;
9606       }
9607
9608       Inherited::VisitBinaryOperator(E);
9609     }
9610
9611     // A custom visitor for BinaryConditionalOperator is needed because the
9612     // regular visitor would check the condition and true expression separately
9613     // but both point to the same place giving duplicate diagnostics.
9614     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9615       Visit(E->getCond());
9616       Visit(E->getFalseExpr());
9617     }
9618
9619     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9620       Decl* ReferenceDecl = DRE->getDecl();
9621       if (OrigDecl != ReferenceDecl) return;
9622       unsigned diag;
9623       if (isReferenceType) {
9624         diag = diag::warn_uninit_self_reference_in_reference_init;
9625       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9626         diag = diag::warn_static_self_reference_in_init;
9627       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9628                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9629                  DRE->getDecl()->getType()->isRecordType()) {
9630         diag = diag::warn_uninit_self_reference_in_init;
9631       } else {
9632         // Local variables will be handled by the CFG analysis.
9633         return;
9634       }
9635
9636       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9637                             S.PDiag(diag)
9638                               << DRE->getNameInfo().getName()
9639                               << OrigDecl->getLocation()
9640                               << DRE->getSourceRange());
9641     }
9642   };
9643
9644   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9645   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9646                                  bool DirectInit) {
9647     // Parameters arguments are occassionially constructed with itself,
9648     // for instance, in recursive functions.  Skip them.
9649     if (isa<ParmVarDecl>(OrigDecl))
9650       return;
9651
9652     E = E->IgnoreParens();
9653
9654     // Skip checking T a = a where T is not a record or reference type.
9655     // Doing so is a way to silence uninitialized warnings.
9656     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9657       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9658         if (ICE->getCastKind() == CK_LValueToRValue)
9659           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9660             if (DRE->getDecl() == OrigDecl)
9661               return;
9662
9663     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9664   }
9665 } // end anonymous namespace
9666
9667 namespace {
9668   // Simple wrapper to add the name of a variable or (if no variable is
9669   // available) a DeclarationName into a diagnostic.
9670   struct VarDeclOrName {
9671     VarDecl *VDecl;
9672     DeclarationName Name;
9673
9674     friend const Sema::SemaDiagnosticBuilder &
9675     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9676       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9677     }
9678   };
9679 } // end anonymous namespace
9680
9681 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9682                                             DeclarationName Name, QualType Type,
9683                                             TypeSourceInfo *TSI,
9684                                             SourceRange Range, bool DirectInit,
9685                                             Expr *Init) {
9686   bool IsInitCapture = !VDecl;
9687   assert((!VDecl || !VDecl->isInitCapture()) &&
9688          "init captures are expected to be deduced prior to initialization");
9689
9690   VarDeclOrName VN{VDecl, Name};
9691
9692   ArrayRef<Expr *> DeduceInits = Init;
9693   if (DirectInit) {
9694     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9695       DeduceInits = PL->exprs();
9696     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9697       DeduceInits = IL->inits();
9698   }
9699
9700   // Deduction only works if we have exactly one source expression.
9701   if (DeduceInits.empty()) {
9702     // It isn't possible to write this directly, but it is possible to
9703     // end up in this situation with "auto x(some_pack...);"
9704     Diag(Init->getLocStart(), IsInitCapture
9705                                   ? diag::err_init_capture_no_expression
9706                                   : diag::err_auto_var_init_no_expression)
9707         << VN << Type << Range;
9708     return QualType();
9709   }
9710
9711   if (DeduceInits.size() > 1) {
9712     Diag(DeduceInits[1]->getLocStart(),
9713          IsInitCapture ? diag::err_init_capture_multiple_expressions
9714                        : diag::err_auto_var_init_multiple_expressions)
9715         << VN << Type << Range;
9716     return QualType();
9717   }
9718
9719   Expr *DeduceInit = DeduceInits[0];
9720   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9721     Diag(Init->getLocStart(), IsInitCapture
9722                                   ? diag::err_init_capture_paren_braces
9723                                   : diag::err_auto_var_init_paren_braces)
9724         << isa<InitListExpr>(Init) << VN << Type << Range;
9725     return QualType();
9726   }
9727
9728   // Expressions default to 'id' when we're in a debugger.
9729   bool DefaultedAnyToId = false;
9730   if (getLangOpts().DebuggerCastResultToId &&
9731       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9732     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9733     if (Result.isInvalid()) {
9734       return QualType();
9735     }
9736     Init = Result.get();
9737     DefaultedAnyToId = true;
9738   }
9739
9740   // C++ [dcl.decomp]p1:
9741   //   If the assignment-expression [...] has array type A and no ref-qualifier
9742   //   is present, e has type cv A
9743   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9744       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9745       DeduceInit->getType()->isConstantArrayType())
9746     return Context.getQualifiedType(DeduceInit->getType(),
9747                                     Type.getQualifiers());
9748
9749   QualType DeducedType;
9750   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9751     if (!IsInitCapture)
9752       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9753     else if (isa<InitListExpr>(Init))
9754       Diag(Range.getBegin(),
9755            diag::err_init_capture_deduction_failure_from_init_list)
9756           << VN
9757           << (DeduceInit->getType().isNull() ? TSI->getType()
9758                                              : DeduceInit->getType())
9759           << DeduceInit->getSourceRange();
9760     else
9761       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9762           << VN << TSI->getType()
9763           << (DeduceInit->getType().isNull() ? TSI->getType()
9764                                              : DeduceInit->getType())
9765           << DeduceInit->getSourceRange();
9766   }
9767
9768   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9769   // 'id' instead of a specific object type prevents most of our usual
9770   // checks.
9771   // We only want to warn outside of template instantiations, though:
9772   // inside a template, the 'id' could have come from a parameter.
9773   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9774       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9775     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9776     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9777   }
9778
9779   return DeducedType;
9780 }
9781
9782 /// AddInitializerToDecl - Adds the initializer Init to the
9783 /// declaration dcl. If DirectInit is true, this is C++ direct
9784 /// initialization rather than copy initialization.
9785 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9786                                 bool DirectInit, bool TypeMayContainAuto) {
9787   // If there is no declaration, there was an error parsing it.  Just ignore
9788   // the initializer.
9789   if (!RealDecl || RealDecl->isInvalidDecl()) {
9790     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9791     return;
9792   }
9793
9794   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9795     // Pure-specifiers are handled in ActOnPureSpecifier.
9796     Diag(Method->getLocation(), diag::err_member_function_initialization)
9797       << Method->getDeclName() << Init->getSourceRange();
9798     Method->setInvalidDecl();
9799     return;
9800   }
9801
9802   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9803   if (!VDecl) {
9804     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9805     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9806     RealDecl->setInvalidDecl();
9807     return;
9808   }
9809
9810   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9811   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9812     // Attempt typo correction early so that the type of the init expression can
9813     // be deduced based on the chosen correction if the original init contains a
9814     // TypoExpr.
9815     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9816     if (!Res.isUsable()) {
9817       RealDecl->setInvalidDecl();
9818       return;
9819     }
9820     Init = Res.get();
9821
9822     QualType DeducedType = deduceVarTypeFromInitializer(
9823         VDecl, VDecl->getDeclName(), VDecl->getType(),
9824         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9825     if (DeducedType.isNull()) {
9826       RealDecl->setInvalidDecl();
9827       return;
9828     }
9829
9830     VDecl->setType(DeducedType);
9831     assert(VDecl->isLinkageValid());
9832
9833     // In ARC, infer lifetime.
9834     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9835       VDecl->setInvalidDecl();
9836
9837     // If this is a redeclaration, check that the type we just deduced matches
9838     // the previously declared type.
9839     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9840       // We never need to merge the type, because we cannot form an incomplete
9841       // array of auto, nor deduce such a type.
9842       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9843     }
9844
9845     // Check the deduced type is valid for a variable declaration.
9846     CheckVariableDeclarationType(VDecl);
9847     if (VDecl->isInvalidDecl())
9848       return;
9849   }
9850
9851   // dllimport cannot be used on variable definitions.
9852   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9853     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9854     VDecl->setInvalidDecl();
9855     return;
9856   }
9857
9858   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9859     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9860     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9861     VDecl->setInvalidDecl();
9862     return;
9863   }
9864
9865   if (!VDecl->getType()->isDependentType()) {
9866     // A definition must end up with a complete type, which means it must be
9867     // complete with the restriction that an array type might be completed by
9868     // the initializer; note that later code assumes this restriction.
9869     QualType BaseDeclType = VDecl->getType();
9870     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9871       BaseDeclType = Array->getElementType();
9872     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9873                             diag::err_typecheck_decl_incomplete_type)) {
9874       RealDecl->setInvalidDecl();
9875       return;
9876     }
9877
9878     // The variable can not have an abstract class type.
9879     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9880                                diag::err_abstract_type_in_decl,
9881                                AbstractVariableType))
9882       VDecl->setInvalidDecl();
9883   }
9884
9885   // If adding the initializer will turn this declaration into a definition,
9886   // and we already have a definition for this variable, diagnose or otherwise
9887   // handle the situation.
9888   VarDecl *Def;
9889   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
9890       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
9891       !VDecl->isThisDeclarationADemotedDefinition() &&
9892       checkVarDeclRedefinition(Def, VDecl))
9893     return;
9894
9895   if (getLangOpts().CPlusPlus) {
9896     // C++ [class.static.data]p4
9897     //   If a static data member is of const integral or const
9898     //   enumeration type, its declaration in the class definition can
9899     //   specify a constant-initializer which shall be an integral
9900     //   constant expression (5.19). In that case, the member can appear
9901     //   in integral constant expressions. The member shall still be
9902     //   defined in a namespace scope if it is used in the program and the
9903     //   namespace scope definition shall not contain an initializer.
9904     //
9905     // We already performed a redefinition check above, but for static
9906     // data members we also need to check whether there was an in-class
9907     // declaration with an initializer.
9908     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9909       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9910           << VDecl->getDeclName();
9911       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9912            diag::note_previous_initializer)
9913           << 0;
9914       return;
9915     }
9916
9917     if (VDecl->hasLocalStorage())
9918       getCurFunction()->setHasBranchProtectedScope();
9919
9920     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9921       VDecl->setInvalidDecl();
9922       return;
9923     }
9924   }
9925
9926   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9927   // a kernel function cannot be initialized."
9928   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9929     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9930     VDecl->setInvalidDecl();
9931     return;
9932   }
9933
9934   // Get the decls type and save a reference for later, since
9935   // CheckInitializerTypes may change it.
9936   QualType DclT = VDecl->getType(), SavT = DclT;
9937
9938   // Expressions default to 'id' when we're in a debugger
9939   // and we are assigning it to a variable of Objective-C pointer type.
9940   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9941       Init->getType() == Context.UnknownAnyTy) {
9942     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9943     if (Result.isInvalid()) {
9944       VDecl->setInvalidDecl();
9945       return;
9946     }
9947     Init = Result.get();
9948   }
9949
9950   // Perform the initialization.
9951   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9952   if (!VDecl->isInvalidDecl()) {
9953     // Handle errors like: int a({0})
9954     if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 &&
9955         !canInitializeWithParenthesizedList(VDecl->getType()))
9956       if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) {
9957         Diag(VDecl->getLocation(), diag::err_list_init_in_parens)
9958             << VDecl->getType() << CXXDirectInit->getSourceRange()
9959             << FixItHint::CreateRemoval(CXXDirectInit->getLocStart())
9960             << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd());
9961         Init = IList;
9962         CXXDirectInit = nullptr;
9963       }
9964
9965     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9966     InitializationKind Kind =
9967         DirectInit
9968             ? CXXDirectInit
9969                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9970                                                      Init->getLocStart(),
9971                                                      Init->getLocEnd())
9972                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9973             : InitializationKind::CreateCopy(VDecl->getLocation(),
9974                                              Init->getLocStart());
9975
9976     MultiExprArg Args = Init;
9977     if (CXXDirectInit)
9978       Args = MultiExprArg(CXXDirectInit->getExprs(),
9979                           CXXDirectInit->getNumExprs());
9980
9981     // Try to correct any TypoExprs in the initialization arguments.
9982     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9983       ExprResult Res = CorrectDelayedTyposInExpr(
9984           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9985             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9986             return Init.Failed() ? ExprError() : E;
9987           });
9988       if (Res.isInvalid()) {
9989         VDecl->setInvalidDecl();
9990       } else if (Res.get() != Args[Idx]) {
9991         Args[Idx] = Res.get();
9992       }
9993     }
9994     if (VDecl->isInvalidDecl())
9995       return;
9996
9997     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9998                                    /*TopLevelOfInitList=*/false,
9999                                    /*TreatUnavailableAsInvalid=*/false);
10000     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10001     if (Result.isInvalid()) {
10002       VDecl->setInvalidDecl();
10003       return;
10004     }
10005
10006     Init = Result.getAs<Expr>();
10007   }
10008
10009   // Check for self-references within variable initializers.
10010   // Variables declared within a function/method body (except for references)
10011   // are handled by a dataflow analysis.
10012   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10013       VDecl->getType()->isReferenceType()) {
10014     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10015   }
10016
10017   // If the type changed, it means we had an incomplete type that was
10018   // completed by the initializer. For example:
10019   //   int ary[] = { 1, 3, 5 };
10020   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10021   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10022     VDecl->setType(DclT);
10023
10024   if (!VDecl->isInvalidDecl()) {
10025     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10026
10027     if (VDecl->hasAttr<BlocksAttr>())
10028       checkRetainCycles(VDecl, Init);
10029
10030     // It is safe to assign a weak reference into a strong variable.
10031     // Although this code can still have problems:
10032     //   id x = self.weakProp;
10033     //   id y = self.weakProp;
10034     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10035     // paths through the function. This should be revisited if
10036     // -Wrepeated-use-of-weak is made flow-sensitive.
10037     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
10038         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10039                          Init->getLocStart()))
10040       getCurFunction()->markSafeWeakUse(Init);
10041   }
10042
10043   // The initialization is usually a full-expression.
10044   //
10045   // FIXME: If this is a braced initialization of an aggregate, it is not
10046   // an expression, and each individual field initializer is a separate
10047   // full-expression. For instance, in:
10048   //
10049   //   struct Temp { ~Temp(); };
10050   //   struct S { S(Temp); };
10051   //   struct T { S a, b; } t = { Temp(), Temp() }
10052   //
10053   // we should destroy the first Temp before constructing the second.
10054   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10055                                           false,
10056                                           VDecl->isConstexpr());
10057   if (Result.isInvalid()) {
10058     VDecl->setInvalidDecl();
10059     return;
10060   }
10061   Init = Result.get();
10062
10063   // Attach the initializer to the decl.
10064   VDecl->setInit(Init);
10065
10066   if (VDecl->isLocalVarDecl()) {
10067     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10068     // static storage duration shall be constant expressions or string literals.
10069     // C++ does not have this restriction.
10070     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10071       const Expr *Culprit;
10072       if (VDecl->getStorageClass() == SC_Static)
10073         CheckForConstantInitializer(Init, DclT);
10074       // C89 is stricter than C99 for non-static aggregate types.
10075       // C89 6.5.7p3: All the expressions [...] in an initializer list
10076       // for an object that has aggregate or union type shall be
10077       // constant expressions.
10078       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10079                isa<InitListExpr>(Init) &&
10080                !Init->isConstantInitializer(Context, false, &Culprit))
10081         Diag(Culprit->getExprLoc(),
10082              diag::ext_aggregate_init_not_constant)
10083           << Culprit->getSourceRange();
10084     }
10085   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10086              VDecl->getLexicalDeclContext()->isRecord()) {
10087     // This is an in-class initialization for a static data member, e.g.,
10088     //
10089     // struct S {
10090     //   static const int value = 17;
10091     // };
10092
10093     // C++ [class.mem]p4:
10094     //   A member-declarator can contain a constant-initializer only
10095     //   if it declares a static member (9.4) of const integral or
10096     //   const enumeration type, see 9.4.2.
10097     //
10098     // C++11 [class.static.data]p3:
10099     //   If a non-volatile non-inline const static data member is of integral
10100     //   or enumeration type, its declaration in the class definition can
10101     //   specify a brace-or-equal-initializer in which every initalizer-clause
10102     //   that is an assignment-expression is a constant expression. A static
10103     //   data member of literal type can be declared in the class definition
10104     //   with the constexpr specifier; if so, its declaration shall specify a
10105     //   brace-or-equal-initializer in which every initializer-clause that is
10106     //   an assignment-expression is a constant expression.
10107
10108     // Do nothing on dependent types.
10109     if (DclT->isDependentType()) {
10110
10111     // Allow any 'static constexpr' members, whether or not they are of literal
10112     // type. We separately check that every constexpr variable is of literal
10113     // type.
10114     } else if (VDecl->isConstexpr()) {
10115
10116     // Require constness.
10117     } else if (!DclT.isConstQualified()) {
10118       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10119         << Init->getSourceRange();
10120       VDecl->setInvalidDecl();
10121
10122     // We allow integer constant expressions in all cases.
10123     } else if (DclT->isIntegralOrEnumerationType()) {
10124       // Check whether the expression is a constant expression.
10125       SourceLocation Loc;
10126       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10127         // In C++11, a non-constexpr const static data member with an
10128         // in-class initializer cannot be volatile.
10129         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10130       else if (Init->isValueDependent())
10131         ; // Nothing to check.
10132       else if (Init->isIntegerConstantExpr(Context, &Loc))
10133         ; // Ok, it's an ICE!
10134       else if (Init->isEvaluatable(Context)) {
10135         // If we can constant fold the initializer through heroics, accept it,
10136         // but report this as a use of an extension for -pedantic.
10137         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10138           << Init->getSourceRange();
10139       } else {
10140         // Otherwise, this is some crazy unknown case.  Report the issue at the
10141         // location provided by the isIntegerConstantExpr failed check.
10142         Diag(Loc, diag::err_in_class_initializer_non_constant)
10143           << Init->getSourceRange();
10144         VDecl->setInvalidDecl();
10145       }
10146
10147     // We allow foldable floating-point constants as an extension.
10148     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10149       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10150       // it anyway and provide a fixit to add the 'constexpr'.
10151       if (getLangOpts().CPlusPlus11) {
10152         Diag(VDecl->getLocation(),
10153              diag::ext_in_class_initializer_float_type_cxx11)
10154             << DclT << Init->getSourceRange();
10155         Diag(VDecl->getLocStart(),
10156              diag::note_in_class_initializer_float_type_cxx11)
10157             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10158       } else {
10159         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10160           << DclT << Init->getSourceRange();
10161
10162         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10163           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10164             << Init->getSourceRange();
10165           VDecl->setInvalidDecl();
10166         }
10167       }
10168
10169     // Suggest adding 'constexpr' in C++11 for literal types.
10170     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10171       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10172         << DclT << Init->getSourceRange()
10173         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10174       VDecl->setConstexpr(true);
10175
10176     } else {
10177       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10178         << DclT << Init->getSourceRange();
10179       VDecl->setInvalidDecl();
10180     }
10181   } else if (VDecl->isFileVarDecl()) {
10182     // In C, extern is typically used to avoid tentative definitions when
10183     // declaring variables in headers, but adding an intializer makes it a
10184     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10185     // In C++, extern is often used to give implictly static const variables
10186     // external linkage, so don't warn in that case. If selectany is present,
10187     // this might be header code intended for C and C++ inclusion, so apply the
10188     // C++ rules.
10189     if (VDecl->getStorageClass() == SC_Extern &&
10190         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10191          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10192         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10193         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10194       Diag(VDecl->getLocation(), diag::warn_extern_init);
10195
10196     // C99 6.7.8p4. All file scoped initializers need to be constant.
10197     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10198       CheckForConstantInitializer(Init, DclT);
10199   }
10200
10201   // We will represent direct-initialization similarly to copy-initialization:
10202   //    int x(1);  -as-> int x = 1;
10203   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10204   //
10205   // Clients that want to distinguish between the two forms, can check for
10206   // direct initializer using VarDecl::getInitStyle().
10207   // A major benefit is that clients that don't particularly care about which
10208   // exactly form was it (like the CodeGen) can handle both cases without
10209   // special case code.
10210
10211   // C++ 8.5p11:
10212   // The form of initialization (using parentheses or '=') is generally
10213   // insignificant, but does matter when the entity being initialized has a
10214   // class type.
10215   if (CXXDirectInit) {
10216     assert(DirectInit && "Call-style initializer must be direct init.");
10217     VDecl->setInitStyle(VarDecl::CallInit);
10218   } else if (DirectInit) {
10219     // This must be list-initialization. No other way is direct-initialization.
10220     VDecl->setInitStyle(VarDecl::ListInit);
10221   }
10222
10223   CheckCompleteVariableDeclaration(VDecl);
10224 }
10225
10226 /// ActOnInitializerError - Given that there was an error parsing an
10227 /// initializer for the given declaration, try to return to some form
10228 /// of sanity.
10229 void Sema::ActOnInitializerError(Decl *D) {
10230   // Our main concern here is re-establishing invariants like "a
10231   // variable's type is either dependent or complete".
10232   if (!D || D->isInvalidDecl()) return;
10233
10234   VarDecl *VD = dyn_cast<VarDecl>(D);
10235   if (!VD) return;
10236
10237   // Bindings are not usable if we can't make sense of the initializer.
10238   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10239     for (auto *BD : DD->bindings())
10240       BD->setInvalidDecl();
10241
10242   // Auto types are meaningless if we can't make sense of the initializer.
10243   if (ParsingInitForAutoVars.count(D)) {
10244     D->setInvalidDecl();
10245     return;
10246   }
10247
10248   QualType Ty = VD->getType();
10249   if (Ty->isDependentType()) return;
10250
10251   // Require a complete type.
10252   if (RequireCompleteType(VD->getLocation(),
10253                           Context.getBaseElementType(Ty),
10254                           diag::err_typecheck_decl_incomplete_type)) {
10255     VD->setInvalidDecl();
10256     return;
10257   }
10258
10259   // Require a non-abstract type.
10260   if (RequireNonAbstractType(VD->getLocation(), Ty,
10261                              diag::err_abstract_type_in_decl,
10262                              AbstractVariableType)) {
10263     VD->setInvalidDecl();
10264     return;
10265   }
10266
10267   // Don't bother complaining about constructors or destructors,
10268   // though.
10269 }
10270
10271 /// Checks if an object of the given type can be initialized with parenthesized
10272 /// init-list.
10273 ///
10274 /// \param TargetType Type of object being initialized.
10275 ///
10276 /// The function is used to detect wrong initializations, such as 'int({0})'.
10277 ///
10278 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) {
10279   return TargetType->isDependentType() || TargetType->isRecordType() ||
10280          TargetType->getContainedAutoType();
10281 }
10282
10283 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
10284                                   bool TypeMayContainAuto) {
10285   // If there is no declaration, there was an error parsing it. Just ignore it.
10286   if (!RealDecl)
10287     return;
10288
10289   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10290     QualType Type = Var->getType();
10291
10292     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10293     if (isa<DecompositionDecl>(RealDecl)) {
10294       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10295       Var->setInvalidDecl();
10296       return;
10297     }
10298
10299     // C++11 [dcl.spec.auto]p3
10300     if (TypeMayContainAuto && Type->getContainedAutoType()) {
10301       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
10302         << Var->getDeclName() << Type;
10303       Var->setInvalidDecl();
10304       return;
10305     }
10306
10307     // C++11 [class.static.data]p3: A static data member can be declared with
10308     // the constexpr specifier; if so, its declaration shall specify
10309     // a brace-or-equal-initializer.
10310     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10311     // the definition of a variable [...] or the declaration of a static data
10312     // member.
10313     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10314         !Var->isThisDeclarationADemotedDefinition()) {
10315       if (Var->isStaticDataMember()) {
10316         // C++1z removes the relevant rule; the in-class declaration is always
10317         // a definition there.
10318         if (!getLangOpts().CPlusPlus1z) {
10319           Diag(Var->getLocation(),
10320                diag::err_constexpr_static_mem_var_requires_init)
10321             << Var->getDeclName();
10322           Var->setInvalidDecl();
10323           return;
10324         }
10325       } else {
10326         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10327         Var->setInvalidDecl();
10328         return;
10329       }
10330     }
10331
10332     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10333     // definition having the concept specifier is called a variable concept. A
10334     // concept definition refers to [...] a variable concept and its initializer.
10335     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10336       if (VTD->isConcept()) {
10337         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10338         Var->setInvalidDecl();
10339         return;
10340       }
10341     }
10342
10343     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10344     // be initialized.
10345     if (!Var->isInvalidDecl() &&
10346         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10347         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10348       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10349       Var->setInvalidDecl();
10350       return;
10351     }
10352
10353     switch (Var->isThisDeclarationADefinition()) {
10354     case VarDecl::Definition:
10355       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10356         break;
10357
10358       // We have an out-of-line definition of a static data member
10359       // that has an in-class initializer, so we type-check this like
10360       // a declaration.
10361       //
10362       // Fall through
10363
10364     case VarDecl::DeclarationOnly:
10365       // It's only a declaration.
10366
10367       // Block scope. C99 6.7p7: If an identifier for an object is
10368       // declared with no linkage (C99 6.2.2p6), the type for the
10369       // object shall be complete.
10370       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10371           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10372           RequireCompleteType(Var->getLocation(), Type,
10373                               diag::err_typecheck_decl_incomplete_type))
10374         Var->setInvalidDecl();
10375
10376       // Make sure that the type is not abstract.
10377       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10378           RequireNonAbstractType(Var->getLocation(), Type,
10379                                  diag::err_abstract_type_in_decl,
10380                                  AbstractVariableType))
10381         Var->setInvalidDecl();
10382       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10383           Var->getStorageClass() == SC_PrivateExtern) {
10384         Diag(Var->getLocation(), diag::warn_private_extern);
10385         Diag(Var->getLocation(), diag::note_private_extern);
10386       }
10387
10388       return;
10389
10390     case VarDecl::TentativeDefinition:
10391       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10392       // object that has file scope without an initializer, and without a
10393       // storage-class specifier or with the storage-class specifier "static",
10394       // constitutes a tentative definition. Note: A tentative definition with
10395       // external linkage is valid (C99 6.2.2p5).
10396       if (!Var->isInvalidDecl()) {
10397         if (const IncompleteArrayType *ArrayT
10398                                     = Context.getAsIncompleteArrayType(Type)) {
10399           if (RequireCompleteType(Var->getLocation(),
10400                                   ArrayT->getElementType(),
10401                                   diag::err_illegal_decl_array_incomplete_type))
10402             Var->setInvalidDecl();
10403         } else if (Var->getStorageClass() == SC_Static) {
10404           // C99 6.9.2p3: If the declaration of an identifier for an object is
10405           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10406           // declared type shall not be an incomplete type.
10407           // NOTE: code such as the following
10408           //     static struct s;
10409           //     struct s { int a; };
10410           // is accepted by gcc. Hence here we issue a warning instead of
10411           // an error and we do not invalidate the static declaration.
10412           // NOTE: to avoid multiple warnings, only check the first declaration.
10413           if (Var->isFirstDecl())
10414             RequireCompleteType(Var->getLocation(), Type,
10415                                 diag::ext_typecheck_decl_incomplete_type);
10416         }
10417       }
10418
10419       // Record the tentative definition; we're done.
10420       if (!Var->isInvalidDecl())
10421         TentativeDefinitions.push_back(Var);
10422       return;
10423     }
10424
10425     // Provide a specific diagnostic for uninitialized variable
10426     // definitions with incomplete array type.
10427     if (Type->isIncompleteArrayType()) {
10428       Diag(Var->getLocation(),
10429            diag::err_typecheck_incomplete_array_needs_initializer);
10430       Var->setInvalidDecl();
10431       return;
10432     }
10433
10434     // Provide a specific diagnostic for uninitialized variable
10435     // definitions with reference type.
10436     if (Type->isReferenceType()) {
10437       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10438         << Var->getDeclName()
10439         << SourceRange(Var->getLocation(), Var->getLocation());
10440       Var->setInvalidDecl();
10441       return;
10442     }
10443
10444     // Do not attempt to type-check the default initializer for a
10445     // variable with dependent type.
10446     if (Type->isDependentType())
10447       return;
10448
10449     if (Var->isInvalidDecl())
10450       return;
10451
10452     if (!Var->hasAttr<AliasAttr>()) {
10453       if (RequireCompleteType(Var->getLocation(),
10454                               Context.getBaseElementType(Type),
10455                               diag::err_typecheck_decl_incomplete_type)) {
10456         Var->setInvalidDecl();
10457         return;
10458       }
10459     } else {
10460       return;
10461     }
10462
10463     // The variable can not have an abstract class type.
10464     if (RequireNonAbstractType(Var->getLocation(), Type,
10465                                diag::err_abstract_type_in_decl,
10466                                AbstractVariableType)) {
10467       Var->setInvalidDecl();
10468       return;
10469     }
10470
10471     // Check for jumps past the implicit initializer.  C++0x
10472     // clarifies that this applies to a "variable with automatic
10473     // storage duration", not a "local variable".
10474     // C++11 [stmt.dcl]p3
10475     //   A program that jumps from a point where a variable with automatic
10476     //   storage duration is not in scope to a point where it is in scope is
10477     //   ill-formed unless the variable has scalar type, class type with a
10478     //   trivial default constructor and a trivial destructor, a cv-qualified
10479     //   version of one of these types, or an array of one of the preceding
10480     //   types and is declared without an initializer.
10481     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10482       if (const RecordType *Record
10483             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10484         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10485         // Mark the function for further checking even if the looser rules of
10486         // C++11 do not require such checks, so that we can diagnose
10487         // incompatibilities with C++98.
10488         if (!CXXRecord->isPOD())
10489           getCurFunction()->setHasBranchProtectedScope();
10490       }
10491     }
10492
10493     // C++03 [dcl.init]p9:
10494     //   If no initializer is specified for an object, and the
10495     //   object is of (possibly cv-qualified) non-POD class type (or
10496     //   array thereof), the object shall be default-initialized; if
10497     //   the object is of const-qualified type, the underlying class
10498     //   type shall have a user-declared default
10499     //   constructor. Otherwise, if no initializer is specified for
10500     //   a non- static object, the object and its subobjects, if
10501     //   any, have an indeterminate initial value); if the object
10502     //   or any of its subobjects are of const-qualified type, the
10503     //   program is ill-formed.
10504     // C++0x [dcl.init]p11:
10505     //   If no initializer is specified for an object, the object is
10506     //   default-initialized; [...].
10507     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10508     InitializationKind Kind
10509       = InitializationKind::CreateDefault(Var->getLocation());
10510
10511     InitializationSequence InitSeq(*this, Entity, Kind, None);
10512     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10513     if (Init.isInvalid())
10514       Var->setInvalidDecl();
10515     else if (Init.get()) {
10516       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10517       // This is important for template substitution.
10518       Var->setInitStyle(VarDecl::CallInit);
10519     }
10520
10521     CheckCompleteVariableDeclaration(Var);
10522   }
10523 }
10524
10525 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10526   // If there is no declaration, there was an error parsing it. Ignore it.
10527   if (!D)
10528     return;
10529
10530   VarDecl *VD = dyn_cast<VarDecl>(D);
10531   if (!VD) {
10532     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10533     D->setInvalidDecl();
10534     return;
10535   }
10536
10537   VD->setCXXForRangeDecl(true);
10538
10539   // for-range-declaration cannot be given a storage class specifier.
10540   int Error = -1;
10541   switch (VD->getStorageClass()) {
10542   case SC_None:
10543     break;
10544   case SC_Extern:
10545     Error = 0;
10546     break;
10547   case SC_Static:
10548     Error = 1;
10549     break;
10550   case SC_PrivateExtern:
10551     Error = 2;
10552     break;
10553   case SC_Auto:
10554     Error = 3;
10555     break;
10556   case SC_Register:
10557     Error = 4;
10558     break;
10559   }
10560   if (Error != -1) {
10561     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10562       << VD->getDeclName() << Error;
10563     D->setInvalidDecl();
10564   }
10565 }
10566
10567 StmtResult
10568 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10569                                  IdentifierInfo *Ident,
10570                                  ParsedAttributes &Attrs,
10571                                  SourceLocation AttrEnd) {
10572   // C++1y [stmt.iter]p1:
10573   //   A range-based for statement of the form
10574   //      for ( for-range-identifier : for-range-initializer ) statement
10575   //   is equivalent to
10576   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10577   DeclSpec DS(Attrs.getPool().getFactory());
10578
10579   const char *PrevSpec;
10580   unsigned DiagID;
10581   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10582                      getPrintingPolicy());
10583
10584   Declarator D(DS, Declarator::ForContext);
10585   D.SetIdentifier(Ident, IdentLoc);
10586   D.takeAttributes(Attrs, AttrEnd);
10587
10588   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10589   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10590                 EmptyAttrs, IdentLoc);
10591   Decl *Var = ActOnDeclarator(S, D);
10592   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10593   FinalizeDeclaration(Var);
10594   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10595                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10596 }
10597
10598 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10599   if (var->isInvalidDecl()) return;
10600
10601   if (getLangOpts().OpenCL) {
10602     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10603     // initialiser
10604     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10605         !var->hasInit()) {
10606       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10607           << 1 /*Init*/;
10608       var->setInvalidDecl();
10609       return;
10610     }
10611   }
10612
10613   // In Objective-C, don't allow jumps past the implicit initialization of a
10614   // local retaining variable.
10615   if (getLangOpts().ObjC1 &&
10616       var->hasLocalStorage()) {
10617     switch (var->getType().getObjCLifetime()) {
10618     case Qualifiers::OCL_None:
10619     case Qualifiers::OCL_ExplicitNone:
10620     case Qualifiers::OCL_Autoreleasing:
10621       break;
10622
10623     case Qualifiers::OCL_Weak:
10624     case Qualifiers::OCL_Strong:
10625       getCurFunction()->setHasBranchProtectedScope();
10626       break;
10627     }
10628   }
10629
10630   // Warn about externally-visible variables being defined without a
10631   // prior declaration.  We only want to do this for global
10632   // declarations, but we also specifically need to avoid doing it for
10633   // class members because the linkage of an anonymous class can
10634   // change if it's later given a typedef name.
10635   if (var->isThisDeclarationADefinition() &&
10636       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10637       var->isExternallyVisible() && var->hasLinkage() &&
10638       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10639                                   var->getLocation())) {
10640     // Find a previous declaration that's not a definition.
10641     VarDecl *prev = var->getPreviousDecl();
10642     while (prev && prev->isThisDeclarationADefinition())
10643       prev = prev->getPreviousDecl();
10644
10645     if (!prev)
10646       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10647   }
10648
10649   // Cache the result of checking for constant initialization.
10650   Optional<bool> CacheHasConstInit;
10651   const Expr *CacheCulprit;
10652   auto checkConstInit = [&]() mutable {
10653     if (!CacheHasConstInit)
10654       CacheHasConstInit = var->getInit()->isConstantInitializer(
10655             Context, var->getType()->isReferenceType(), &CacheCulprit);
10656     return *CacheHasConstInit;
10657   };
10658
10659   if (var->getTLSKind() == VarDecl::TLS_Static) {
10660     if (var->getType().isDestructedType()) {
10661       // GNU C++98 edits for __thread, [basic.start.term]p3:
10662       //   The type of an object with thread storage duration shall not
10663       //   have a non-trivial destructor.
10664       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10665       if (getLangOpts().CPlusPlus11)
10666         Diag(var->getLocation(), diag::note_use_thread_local);
10667     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10668       if (!checkConstInit()) {
10669         // GNU C++98 edits for __thread, [basic.start.init]p4:
10670         //   An object of thread storage duration shall not require dynamic
10671         //   initialization.
10672         // FIXME: Need strict checking here.
10673         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10674           << CacheCulprit->getSourceRange();
10675         if (getLangOpts().CPlusPlus11)
10676           Diag(var->getLocation(), diag::note_use_thread_local);
10677       }
10678     }
10679   }
10680
10681   // Apply section attributes and pragmas to global variables.
10682   bool GlobalStorage = var->hasGlobalStorage();
10683   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10684       ActiveTemplateInstantiations.empty()) {
10685     PragmaStack<StringLiteral *> *Stack = nullptr;
10686     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10687     if (var->getType().isConstQualified())
10688       Stack = &ConstSegStack;
10689     else if (!var->getInit()) {
10690       Stack = &BSSSegStack;
10691       SectionFlags |= ASTContext::PSF_Write;
10692     } else {
10693       Stack = &DataSegStack;
10694       SectionFlags |= ASTContext::PSF_Write;
10695     }
10696     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10697       var->addAttr(SectionAttr::CreateImplicit(
10698           Context, SectionAttr::Declspec_allocate,
10699           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10700     }
10701     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10702       if (UnifySection(SA->getName(), SectionFlags, var))
10703         var->dropAttr<SectionAttr>();
10704
10705     // Apply the init_seg attribute if this has an initializer.  If the
10706     // initializer turns out to not be dynamic, we'll end up ignoring this
10707     // attribute.
10708     if (CurInitSeg && var->getInit())
10709       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10710                                                CurInitSegLoc));
10711   }
10712
10713   // All the following checks are C++ only.
10714   if (!getLangOpts().CPlusPlus) {
10715       // If this variable must be emitted, add it as an initializer for the
10716       // current module.
10717      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10718        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10719      return;
10720   }
10721
10722   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10723     CheckCompleteDecompositionDeclaration(DD);
10724
10725   QualType type = var->getType();
10726   if (type->isDependentType()) return;
10727
10728   // __block variables might require us to capture a copy-initializer.
10729   if (var->hasAttr<BlocksAttr>()) {
10730     // It's currently invalid to ever have a __block variable with an
10731     // array type; should we diagnose that here?
10732
10733     // Regardless, we don't want to ignore array nesting when
10734     // constructing this copy.
10735     if (type->isStructureOrClassType()) {
10736       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10737       SourceLocation poi = var->getLocation();
10738       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10739       ExprResult result
10740         = PerformMoveOrCopyInitialization(
10741             InitializedEntity::InitializeBlock(poi, type, false),
10742             var, var->getType(), varRef, /*AllowNRVO=*/true);
10743       if (!result.isInvalid()) {
10744         result = MaybeCreateExprWithCleanups(result);
10745         Expr *init = result.getAs<Expr>();
10746         Context.setBlockVarCopyInits(var, init);
10747       }
10748     }
10749   }
10750
10751   Expr *Init = var->getInit();
10752   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10753   QualType baseType = Context.getBaseElementType(type);
10754
10755   if (!var->getDeclContext()->isDependentContext() &&
10756       Init && !Init->isValueDependent()) {
10757
10758     if (var->isConstexpr()) {
10759       SmallVector<PartialDiagnosticAt, 8> Notes;
10760       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10761         SourceLocation DiagLoc = var->getLocation();
10762         // If the note doesn't add any useful information other than a source
10763         // location, fold it into the primary diagnostic.
10764         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10765               diag::note_invalid_subexpr_in_const_expr) {
10766           DiagLoc = Notes[0].first;
10767           Notes.clear();
10768         }
10769         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10770           << var << Init->getSourceRange();
10771         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10772           Diag(Notes[I].first, Notes[I].second);
10773       }
10774     } else if (var->isUsableInConstantExpressions(Context)) {
10775       // Check whether the initializer of a const variable of integral or
10776       // enumeration type is an ICE now, since we can't tell whether it was
10777       // initialized by a constant expression if we check later.
10778       var->checkInitIsICE();
10779     }
10780
10781     // Don't emit further diagnostics about constexpr globals since they
10782     // were just diagnosed.
10783     if (!var->isConstexpr() && GlobalStorage &&
10784             var->hasAttr<RequireConstantInitAttr>()) {
10785       // FIXME: Need strict checking in C++03 here.
10786       bool DiagErr = getLangOpts().CPlusPlus11
10787           ? !var->checkInitIsICE() : !checkConstInit();
10788       if (DiagErr) {
10789         auto attr = var->getAttr<RequireConstantInitAttr>();
10790         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10791           << Init->getSourceRange();
10792         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10793           << attr->getRange();
10794       }
10795     }
10796     else if (!var->isConstexpr() && IsGlobal &&
10797              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10798                                     var->getLocation())) {
10799       // Warn about globals which don't have a constant initializer.  Don't
10800       // warn about globals with a non-trivial destructor because we already
10801       // warned about them.
10802       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10803       if (!(RD && !RD->hasTrivialDestructor())) {
10804         if (!checkConstInit())
10805           Diag(var->getLocation(), diag::warn_global_constructor)
10806             << Init->getSourceRange();
10807       }
10808     }
10809   }
10810
10811   // Require the destructor.
10812   if (const RecordType *recordType = baseType->getAs<RecordType>())
10813     FinalizeVarWithDestructor(var, recordType);
10814
10815   // If this variable must be emitted, add it as an initializer for the current
10816   // module.
10817   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10818     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10819 }
10820
10821 /// \brief Determines if a variable's alignment is dependent.
10822 static bool hasDependentAlignment(VarDecl *VD) {
10823   if (VD->getType()->isDependentType())
10824     return true;
10825   for (auto *I : VD->specific_attrs<AlignedAttr>())
10826     if (I->isAlignmentDependent())
10827       return true;
10828   return false;
10829 }
10830
10831 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10832 /// any semantic actions necessary after any initializer has been attached.
10833 void
10834 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10835   // Note that we are no longer parsing the initializer for this declaration.
10836   ParsingInitForAutoVars.erase(ThisDecl);
10837
10838   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10839   if (!VD)
10840     return;
10841
10842   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10843     for (auto *BD : DD->bindings()) {
10844       FinalizeDeclaration(BD);
10845     }
10846   }
10847
10848   checkAttributesAfterMerging(*this, *VD);
10849
10850   // Perform TLS alignment check here after attributes attached to the variable
10851   // which may affect the alignment have been processed. Only perform the check
10852   // if the target has a maximum TLS alignment (zero means no constraints).
10853   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10854     // Protect the check so that it's not performed on dependent types and
10855     // dependent alignments (we can't determine the alignment in that case).
10856     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10857       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10858       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10859         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10860           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10861           << (unsigned)MaxAlignChars.getQuantity();
10862       }
10863     }
10864   }
10865
10866   if (VD->isStaticLocal()) {
10867     if (FunctionDecl *FD =
10868             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10869       // Static locals inherit dll attributes from their function.
10870       if (Attr *A = getDLLAttr(FD)) {
10871         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10872         NewAttr->setInherited(true);
10873         VD->addAttr(NewAttr);
10874       }
10875       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10876       // function, only __shared__ variables may be declared with
10877       // static storage class.
10878       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
10879           CUDADiagIfDeviceCode(VD->getLocation(),
10880                                diag::err_device_static_local_var)
10881               << CurrentCUDATarget())
10882         VD->setInvalidDecl();
10883     }
10884   }
10885
10886   // Perform check for initializers of device-side global variables.
10887   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10888   // 7.5). We must also apply the same checks to all __shared__
10889   // variables whether they are local or not. CUDA also allows
10890   // constant initializers for __constant__ and __device__ variables.
10891   if (getLangOpts().CUDA) {
10892     const Expr *Init = VD->getInit();
10893     if (Init && VD->hasGlobalStorage()) {
10894       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10895           VD->hasAttr<CUDASharedAttr>()) {
10896         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
10897         bool AllowedInit = false;
10898         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10899           AllowedInit =
10900               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10901         // We'll allow constant initializers even if it's a non-empty
10902         // constructor according to CUDA rules. This deviates from NVCC,
10903         // but allows us to handle things like constexpr constructors.
10904         if (!AllowedInit &&
10905             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10906           AllowedInit = VD->getInit()->isConstantInitializer(
10907               Context, VD->getType()->isReferenceType());
10908
10909         // Also make sure that destructor, if there is one, is empty.
10910         if (AllowedInit)
10911           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10912             AllowedInit =
10913                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10914
10915         if (!AllowedInit) {
10916           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10917                                       ? diag::err_shared_var_init
10918                                       : diag::err_dynamic_var_init)
10919               << Init->getSourceRange();
10920           VD->setInvalidDecl();
10921         }
10922       } else {
10923         // This is a host-side global variable.  Check that the initializer is
10924         // callable from the host side.
10925         const FunctionDecl *InitFn = nullptr;
10926         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
10927           InitFn = CE->getConstructor();
10928         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
10929           InitFn = CE->getDirectCallee();
10930         }
10931         if (InitFn) {
10932           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
10933           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
10934             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
10935                 << InitFnTarget << InitFn;
10936             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
10937             VD->setInvalidDecl();
10938           }
10939         }
10940       }
10941     }
10942   }
10943
10944   // Grab the dllimport or dllexport attribute off of the VarDecl.
10945   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10946
10947   // Imported static data members cannot be defined out-of-line.
10948   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10949     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10950         VD->isThisDeclarationADefinition()) {
10951       // We allow definitions of dllimport class template static data members
10952       // with a warning.
10953       CXXRecordDecl *Context =
10954         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10955       bool IsClassTemplateMember =
10956           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10957           Context->getDescribedClassTemplate();
10958
10959       Diag(VD->getLocation(),
10960            IsClassTemplateMember
10961                ? diag::warn_attribute_dllimport_static_field_definition
10962                : diag::err_attribute_dllimport_static_field_definition);
10963       Diag(IA->getLocation(), diag::note_attribute);
10964       if (!IsClassTemplateMember)
10965         VD->setInvalidDecl();
10966     }
10967   }
10968
10969   // dllimport/dllexport variables cannot be thread local, their TLS index
10970   // isn't exported with the variable.
10971   if (DLLAttr && VD->getTLSKind()) {
10972     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10973     if (F && getDLLAttr(F)) {
10974       assert(VD->isStaticLocal());
10975       // But if this is a static local in a dlimport/dllexport function, the
10976       // function will never be inlined, which means the var would never be
10977       // imported, so having it marked import/export is safe.
10978     } else {
10979       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10980                                                                     << DLLAttr;
10981       VD->setInvalidDecl();
10982     }
10983   }
10984
10985   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10986     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10987       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10988       VD->dropAttr<UsedAttr>();
10989     }
10990   }
10991
10992   const DeclContext *DC = VD->getDeclContext();
10993   // If there's a #pragma GCC visibility in scope, and this isn't a class
10994   // member, set the visibility of this variable.
10995   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10996     AddPushedVisibilityAttribute(VD);
10997
10998   // FIXME: Warn on unused templates.
10999   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11000       !isa<VarTemplatePartialSpecializationDecl>(VD))
11001     MarkUnusedFileScopedDecl(VD);
11002
11003   // Now we have parsed the initializer and can update the table of magic
11004   // tag values.
11005   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11006       !VD->getType()->isIntegralOrEnumerationType())
11007     return;
11008
11009   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11010     const Expr *MagicValueExpr = VD->getInit();
11011     if (!MagicValueExpr) {
11012       continue;
11013     }
11014     llvm::APSInt MagicValueInt;
11015     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11016       Diag(I->getRange().getBegin(),
11017            diag::err_type_tag_for_datatype_not_ice)
11018         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11019       continue;
11020     }
11021     if (MagicValueInt.getActiveBits() > 64) {
11022       Diag(I->getRange().getBegin(),
11023            diag::err_type_tag_for_datatype_too_large)
11024         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11025       continue;
11026     }
11027     uint64_t MagicValue = MagicValueInt.getZExtValue();
11028     RegisterTypeTagForDatatype(I->getArgumentKind(),
11029                                MagicValue,
11030                                I->getMatchingCType(),
11031                                I->getLayoutCompatible(),
11032                                I->getMustBeNull());
11033   }
11034 }
11035
11036 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11037                                                    ArrayRef<Decl *> Group) {
11038   SmallVector<Decl*, 8> Decls;
11039
11040   if (DS.isTypeSpecOwned())
11041     Decls.push_back(DS.getRepAsDecl());
11042
11043   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11044   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11045   bool DiagnosedMultipleDecomps = false;
11046
11047   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11048     if (Decl *D = Group[i]) {
11049       auto *DD = dyn_cast<DeclaratorDecl>(D);
11050       if (DD && !FirstDeclaratorInGroup)
11051         FirstDeclaratorInGroup = DD;
11052
11053       auto *Decomp = dyn_cast<DecompositionDecl>(D);
11054       if (Decomp && !FirstDecompDeclaratorInGroup)
11055         FirstDecompDeclaratorInGroup = Decomp;
11056
11057       // A decomposition declaration cannot be combined with any other
11058       // declaration in the same group.
11059       auto *OtherDD = FirstDeclaratorInGroup;
11060       if (OtherDD == FirstDecompDeclaratorInGroup)
11061         OtherDD = DD;
11062       if (OtherDD && FirstDecompDeclaratorInGroup &&
11063           OtherDD != FirstDecompDeclaratorInGroup &&
11064           !DiagnosedMultipleDecomps) {
11065         Diag(FirstDecompDeclaratorInGroup->getLocation(),
11066              diag::err_decomp_decl_not_alone)
11067           << OtherDD->getSourceRange();
11068         DiagnosedMultipleDecomps = true;
11069       }
11070
11071       Decls.push_back(D);
11072     }
11073   }
11074
11075   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11076     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11077       handleTagNumbering(Tag, S);
11078       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11079           getLangOpts().CPlusPlus)
11080         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11081     }
11082   }
11083
11084   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
11085 }
11086
11087 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11088 /// group, performing any necessary semantic checking.
11089 Sema::DeclGroupPtrTy
11090 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
11091                            bool TypeMayContainAuto) {
11092   // C++0x [dcl.spec.auto]p7:
11093   //   If the type deduced for the template parameter U is not the same in each
11094   //   deduction, the program is ill-formed.
11095   // FIXME: When initializer-list support is added, a distinction is needed
11096   // between the deduced type U and the deduced type which 'auto' stands for.
11097   //   auto a = 0, b = { 1, 2, 3 };
11098   // is legal because the deduced type U is 'int' in both cases.
11099   if (TypeMayContainAuto && Group.size() > 1) {
11100     QualType Deduced;
11101     CanQualType DeducedCanon;
11102     VarDecl *DeducedDecl = nullptr;
11103     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11104       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
11105         AutoType *AT = D->getType()->getContainedAutoType();
11106         // Don't reissue diagnostics when instantiating a template.
11107         if (AT && D->isInvalidDecl())
11108           break;
11109         QualType U = AT ? AT->getDeducedType() : QualType();
11110         if (!U.isNull()) {
11111           CanQualType UCanon = Context.getCanonicalType(U);
11112           if (Deduced.isNull()) {
11113             Deduced = U;
11114             DeducedCanon = UCanon;
11115             DeducedDecl = D;
11116           } else if (DeducedCanon != UCanon) {
11117             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11118                  diag::err_auto_different_deductions)
11119               << (unsigned)AT->getKeyword()
11120               << Deduced << DeducedDecl->getDeclName()
11121               << U << D->getDeclName()
11122               << DeducedDecl->getInit()->getSourceRange()
11123               << D->getInit()->getSourceRange();
11124             D->setInvalidDecl();
11125             break;
11126           }
11127         }
11128       }
11129     }
11130   }
11131
11132   ActOnDocumentableDecls(Group);
11133
11134   return DeclGroupPtrTy::make(
11135       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11136 }
11137
11138 void Sema::ActOnDocumentableDecl(Decl *D) {
11139   ActOnDocumentableDecls(D);
11140 }
11141
11142 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11143   // Don't parse the comment if Doxygen diagnostics are ignored.
11144   if (Group.empty() || !Group[0])
11145     return;
11146
11147   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11148                       Group[0]->getLocation()) &&
11149       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11150                       Group[0]->getLocation()))
11151     return;
11152
11153   if (Group.size() >= 2) {
11154     // This is a decl group.  Normally it will contain only declarations
11155     // produced from declarator list.  But in case we have any definitions or
11156     // additional declaration references:
11157     //   'typedef struct S {} S;'
11158     //   'typedef struct S *S;'
11159     //   'struct S *pS;'
11160     // FinalizeDeclaratorGroup adds these as separate declarations.
11161     Decl *MaybeTagDecl = Group[0];
11162     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11163       Group = Group.slice(1);
11164     }
11165   }
11166
11167   // See if there are any new comments that are not attached to a decl.
11168   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11169   if (!Comments.empty() &&
11170       !Comments.back()->isAttached()) {
11171     // There is at least one comment that not attached to a decl.
11172     // Maybe it should be attached to one of these decls?
11173     //
11174     // Note that this way we pick up not only comments that precede the
11175     // declaration, but also comments that *follow* the declaration -- thanks to
11176     // the lookahead in the lexer: we've consumed the semicolon and looked
11177     // ahead through comments.
11178     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11179       Context.getCommentForDecl(Group[i], &PP);
11180   }
11181 }
11182
11183 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11184 /// to introduce parameters into function prototype scope.
11185 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11186   const DeclSpec &DS = D.getDeclSpec();
11187
11188   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11189
11190   // C++03 [dcl.stc]p2 also permits 'auto'.
11191   StorageClass SC = SC_None;
11192   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11193     SC = SC_Register;
11194   } else if (getLangOpts().CPlusPlus &&
11195              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11196     SC = SC_Auto;
11197   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11198     Diag(DS.getStorageClassSpecLoc(),
11199          diag::err_invalid_storage_class_in_func_decl);
11200     D.getMutableDeclSpec().ClearStorageClassSpecs();
11201   }
11202
11203   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11204     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11205       << DeclSpec::getSpecifierName(TSCS);
11206   if (DS.isInlineSpecified())
11207     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11208         << getLangOpts().CPlusPlus1z;
11209   if (DS.isConstexprSpecified())
11210     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11211       << 0;
11212   if (DS.isConceptSpecified())
11213     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11214
11215   DiagnoseFunctionSpecifiers(DS);
11216
11217   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11218   QualType parmDeclType = TInfo->getType();
11219
11220   if (getLangOpts().CPlusPlus) {
11221     // Check that there are no default arguments inside the type of this
11222     // parameter.
11223     CheckExtraCXXDefaultArguments(D);
11224
11225     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11226     if (D.getCXXScopeSpec().isSet()) {
11227       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11228         << D.getCXXScopeSpec().getRange();
11229       D.getCXXScopeSpec().clear();
11230     }
11231   }
11232
11233   // Ensure we have a valid name
11234   IdentifierInfo *II = nullptr;
11235   if (D.hasName()) {
11236     II = D.getIdentifier();
11237     if (!II) {
11238       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11239         << GetNameForDeclarator(D).getName();
11240       D.setInvalidType(true);
11241     }
11242   }
11243
11244   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11245   if (II) {
11246     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11247                    ForRedeclaration);
11248     LookupName(R, S);
11249     if (R.isSingleResult()) {
11250       NamedDecl *PrevDecl = R.getFoundDecl();
11251       if (PrevDecl->isTemplateParameter()) {
11252         // Maybe we will complain about the shadowed template parameter.
11253         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11254         // Just pretend that we didn't see the previous declaration.
11255         PrevDecl = nullptr;
11256       } else if (S->isDeclScope(PrevDecl)) {
11257         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11258         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11259
11260         // Recover by removing the name
11261         II = nullptr;
11262         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11263         D.setInvalidType(true);
11264       }
11265     }
11266   }
11267
11268   // Temporarily put parameter variables in the translation unit, not
11269   // the enclosing context.  This prevents them from accidentally
11270   // looking like class members in C++.
11271   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11272                                     D.getLocStart(),
11273                                     D.getIdentifierLoc(), II,
11274                                     parmDeclType, TInfo,
11275                                     SC);
11276
11277   if (D.isInvalidType())
11278     New->setInvalidDecl();
11279
11280   assert(S->isFunctionPrototypeScope());
11281   assert(S->getFunctionPrototypeDepth() >= 1);
11282   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11283                     S->getNextFunctionPrototypeIndex());
11284
11285   // Add the parameter declaration into this scope.
11286   S->AddDecl(New);
11287   if (II)
11288     IdResolver.AddDecl(New);
11289
11290   ProcessDeclAttributes(S, New, D);
11291
11292   if (D.getDeclSpec().isModulePrivateSpecified())
11293     Diag(New->getLocation(), diag::err_module_private_local)
11294       << 1 << New->getDeclName()
11295       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11296       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11297
11298   if (New->hasAttr<BlocksAttr>()) {
11299     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11300   }
11301   return New;
11302 }
11303
11304 /// \brief Synthesizes a variable for a parameter arising from a
11305 /// typedef.
11306 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11307                                               SourceLocation Loc,
11308                                               QualType T) {
11309   /* FIXME: setting StartLoc == Loc.
11310      Would it be worth to modify callers so as to provide proper source
11311      location for the unnamed parameters, embedding the parameter's type? */
11312   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11313                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11314                                            SC_None, nullptr);
11315   Param->setImplicit();
11316   return Param;
11317 }
11318
11319 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11320   // Don't diagnose unused-parameter errors in template instantiations; we
11321   // will already have done so in the template itself.
11322   if (!ActiveTemplateInstantiations.empty())
11323     return;
11324
11325   for (const ParmVarDecl *Parameter : Parameters) {
11326     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11327         !Parameter->hasAttr<UnusedAttr>()) {
11328       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11329         << Parameter->getDeclName();
11330     }
11331   }
11332 }
11333
11334 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11335     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11336   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11337     return;
11338
11339   // Warn if the return value is pass-by-value and larger than the specified
11340   // threshold.
11341   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11342     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11343     if (Size > LangOpts.NumLargeByValueCopy)
11344       Diag(D->getLocation(), diag::warn_return_value_size)
11345           << D->getDeclName() << Size;
11346   }
11347
11348   // Warn if any parameter is pass-by-value and larger than the specified
11349   // threshold.
11350   for (const ParmVarDecl *Parameter : Parameters) {
11351     QualType T = Parameter->getType();
11352     if (T->isDependentType() || !T.isPODType(Context))
11353       continue;
11354     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11355     if (Size > LangOpts.NumLargeByValueCopy)
11356       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11357           << Parameter->getDeclName() << Size;
11358   }
11359 }
11360
11361 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11362                                   SourceLocation NameLoc, IdentifierInfo *Name,
11363                                   QualType T, TypeSourceInfo *TSInfo,
11364                                   StorageClass SC) {
11365   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11366   if (getLangOpts().ObjCAutoRefCount &&
11367       T.getObjCLifetime() == Qualifiers::OCL_None &&
11368       T->isObjCLifetimeType()) {
11369
11370     Qualifiers::ObjCLifetime lifetime;
11371
11372     // Special cases for arrays:
11373     //   - if it's const, use __unsafe_unretained
11374     //   - otherwise, it's an error
11375     if (T->isArrayType()) {
11376       if (!T.isConstQualified()) {
11377         DelayedDiagnostics.add(
11378             sema::DelayedDiagnostic::makeForbiddenType(
11379             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11380       }
11381       lifetime = Qualifiers::OCL_ExplicitNone;
11382     } else {
11383       lifetime = T->getObjCARCImplicitLifetime();
11384     }
11385     T = Context.getLifetimeQualifiedType(T, lifetime);
11386   }
11387
11388   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11389                                          Context.getAdjustedParameterType(T),
11390                                          TSInfo, SC, nullptr);
11391
11392   // Parameters can not be abstract class types.
11393   // For record types, this is done by the AbstractClassUsageDiagnoser once
11394   // the class has been completely parsed.
11395   if (!CurContext->isRecord() &&
11396       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11397                              AbstractParamType))
11398     New->setInvalidDecl();
11399
11400   // Parameter declarators cannot be interface types. All ObjC objects are
11401   // passed by reference.
11402   if (T->isObjCObjectType()) {
11403     SourceLocation TypeEndLoc =
11404         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11405     Diag(NameLoc,
11406          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11407       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11408     T = Context.getObjCObjectPointerType(T);
11409     New->setType(T);
11410   }
11411
11412   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11413   // duration shall not be qualified by an address-space qualifier."
11414   // Since all parameters have automatic store duration, they can not have
11415   // an address space.
11416   if (T.getAddressSpace() != 0) {
11417     // OpenCL allows function arguments declared to be an array of a type
11418     // to be qualified with an address space.
11419     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11420       Diag(NameLoc, diag::err_arg_with_address_space);
11421       New->setInvalidDecl();
11422     }
11423   }
11424
11425   return New;
11426 }
11427
11428 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11429                                            SourceLocation LocAfterDecls) {
11430   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11431
11432   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11433   // for a K&R function.
11434   if (!FTI.hasPrototype) {
11435     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11436       --i;
11437       if (FTI.Params[i].Param == nullptr) {
11438         SmallString<256> Code;
11439         llvm::raw_svector_ostream(Code)
11440             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11441         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11442             << FTI.Params[i].Ident
11443             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11444
11445         // Implicitly declare the argument as type 'int' for lack of a better
11446         // type.
11447         AttributeFactory attrs;
11448         DeclSpec DS(attrs);
11449         const char* PrevSpec; // unused
11450         unsigned DiagID; // unused
11451         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11452                            DiagID, Context.getPrintingPolicy());
11453         // Use the identifier location for the type source range.
11454         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11455         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11456         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11457         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11458         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11459       }
11460     }
11461   }
11462 }
11463
11464 Decl *
11465 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11466                               MultiTemplateParamsArg TemplateParameterLists,
11467                               SkipBodyInfo *SkipBody) {
11468   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11469   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11470   Scope *ParentScope = FnBodyScope->getParent();
11471
11472   D.setFunctionDefinitionKind(FDK_Definition);
11473   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11474   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11475 }
11476
11477 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11478   Consumer.HandleInlineFunctionDefinition(D);
11479 }
11480
11481 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11482                              const FunctionDecl*& PossibleZeroParamPrototype) {
11483   // Don't warn about invalid declarations.
11484   if (FD->isInvalidDecl())
11485     return false;
11486
11487   // Or declarations that aren't global.
11488   if (!FD->isGlobal())
11489     return false;
11490
11491   // Don't warn about C++ member functions.
11492   if (isa<CXXMethodDecl>(FD))
11493     return false;
11494
11495   // Don't warn about 'main'.
11496   if (FD->isMain())
11497     return false;
11498
11499   // Don't warn about inline functions.
11500   if (FD->isInlined())
11501     return false;
11502
11503   // Don't warn about function templates.
11504   if (FD->getDescribedFunctionTemplate())
11505     return false;
11506
11507   // Don't warn about function template specializations.
11508   if (FD->isFunctionTemplateSpecialization())
11509     return false;
11510
11511   // Don't warn for OpenCL kernels.
11512   if (FD->hasAttr<OpenCLKernelAttr>())
11513     return false;
11514
11515   // Don't warn on explicitly deleted functions.
11516   if (FD->isDeleted())
11517     return false;
11518
11519   bool MissingPrototype = true;
11520   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11521        Prev; Prev = Prev->getPreviousDecl()) {
11522     // Ignore any declarations that occur in function or method
11523     // scope, because they aren't visible from the header.
11524     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11525       continue;
11526
11527     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11528     if (FD->getNumParams() == 0)
11529       PossibleZeroParamPrototype = Prev;
11530     break;
11531   }
11532
11533   return MissingPrototype;
11534 }
11535
11536 void
11537 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11538                                    const FunctionDecl *EffectiveDefinition,
11539                                    SkipBodyInfo *SkipBody) {
11540   // Don't complain if we're in GNU89 mode and the previous definition
11541   // was an extern inline function.
11542   const FunctionDecl *Definition = EffectiveDefinition;
11543   if (!Definition)
11544     if (!FD->isDefined(Definition))
11545       return;
11546
11547   if (canRedefineFunction(Definition, getLangOpts()))
11548     return;
11549
11550   // If we don't have a visible definition of the function, and it's inline or
11551   // a template, skip the new definition.
11552   if (SkipBody && !hasVisibleDefinition(Definition) &&
11553       (Definition->getFormalLinkage() == InternalLinkage ||
11554        Definition->isInlined() ||
11555        Definition->getDescribedFunctionTemplate() ||
11556        Definition->getNumTemplateParameterLists())) {
11557     SkipBody->ShouldSkip = true;
11558     if (auto *TD = Definition->getDescribedFunctionTemplate())
11559       makeMergedDefinitionVisible(TD, FD->getLocation());
11560     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11561                                 FD->getLocation());
11562     return;
11563   }
11564
11565   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11566       Definition->getStorageClass() == SC_Extern)
11567     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11568         << FD->getDeclName() << getLangOpts().CPlusPlus;
11569   else
11570     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11571
11572   Diag(Definition->getLocation(), diag::note_previous_definition);
11573   FD->setInvalidDecl();
11574 }
11575
11576 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11577                                    Sema &S) {
11578   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11579
11580   LambdaScopeInfo *LSI = S.PushLambdaScope();
11581   LSI->CallOperator = CallOperator;
11582   LSI->Lambda = LambdaClass;
11583   LSI->ReturnType = CallOperator->getReturnType();
11584   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11585
11586   if (LCD == LCD_None)
11587     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11588   else if (LCD == LCD_ByCopy)
11589     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11590   else if (LCD == LCD_ByRef)
11591     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11592   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11593
11594   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11595   LSI->Mutable = !CallOperator->isConst();
11596
11597   // Add the captures to the LSI so they can be noted as already
11598   // captured within tryCaptureVar.
11599   auto I = LambdaClass->field_begin();
11600   for (const auto &C : LambdaClass->captures()) {
11601     if (C.capturesVariable()) {
11602       VarDecl *VD = C.getCapturedVar();
11603       if (VD->isInitCapture())
11604         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11605       QualType CaptureType = VD->getType();
11606       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11607       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11608           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11609           /*EllipsisLoc*/C.isPackExpansion()
11610                          ? C.getEllipsisLoc() : SourceLocation(),
11611           CaptureType, /*Expr*/ nullptr);
11612
11613     } else if (C.capturesThis()) {
11614       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11615                               /*Expr*/ nullptr,
11616                               C.getCaptureKind() == LCK_StarThis);
11617     } else {
11618       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11619     }
11620     ++I;
11621   }
11622 }
11623
11624 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11625                                     SkipBodyInfo *SkipBody) {
11626   // Clear the last template instantiation error context.
11627   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11628
11629   if (!D)
11630     return D;
11631   FunctionDecl *FD = nullptr;
11632
11633   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11634     FD = FunTmpl->getTemplatedDecl();
11635   else
11636     FD = cast<FunctionDecl>(D);
11637
11638   // See if this is a redefinition.
11639   if (!FD->isLateTemplateParsed()) {
11640     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11641
11642     // If we're skipping the body, we're done. Don't enter the scope.
11643     if (SkipBody && SkipBody->ShouldSkip)
11644       return D;
11645   }
11646
11647   // Mark this function as "will have a body eventually".  This lets users to
11648   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11649   // this function.
11650   FD->setWillHaveBody();
11651
11652   // If we are instantiating a generic lambda call operator, push
11653   // a LambdaScopeInfo onto the function stack.  But use the information
11654   // that's already been calculated (ActOnLambdaExpr) to prime the current
11655   // LambdaScopeInfo.
11656   // When the template operator is being specialized, the LambdaScopeInfo,
11657   // has to be properly restored so that tryCaptureVariable doesn't try
11658   // and capture any new variables. In addition when calculating potential
11659   // captures during transformation of nested lambdas, it is necessary to
11660   // have the LSI properly restored.
11661   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11662     assert(ActiveTemplateInstantiations.size() &&
11663       "There should be an active template instantiation on the stack "
11664       "when instantiating a generic lambda!");
11665     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11666   }
11667   else
11668     // Enter a new function scope
11669     PushFunctionScope();
11670
11671   // Builtin functions cannot be defined.
11672   if (unsigned BuiltinID = FD->getBuiltinID()) {
11673     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11674         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11675       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11676       FD->setInvalidDecl();
11677     }
11678   }
11679
11680   // The return type of a function definition must be complete
11681   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11682   QualType ResultType = FD->getReturnType();
11683   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11684       !FD->isInvalidDecl() &&
11685       RequireCompleteType(FD->getLocation(), ResultType,
11686                           diag::err_func_def_incomplete_result))
11687     FD->setInvalidDecl();
11688
11689   if (FnBodyScope)
11690     PushDeclContext(FnBodyScope, FD);
11691
11692   // Check the validity of our function parameters
11693   CheckParmsForFunctionDef(FD->parameters(),
11694                            /*CheckParameterNames=*/true);
11695
11696   // Add non-parameter declarations already in the function to the current
11697   // scope.
11698   if (FnBodyScope) {
11699     for (Decl *NPD : FD->decls()) {
11700       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11701       if (!NonParmDecl)
11702         continue;
11703       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11704              "parameters should not be in newly created FD yet");
11705
11706       // If the decl has a name, make it accessible in the current scope.
11707       if (NonParmDecl->getDeclName())
11708         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11709
11710       // Similarly, dive into enums and fish their constants out, making them
11711       // accessible in this scope.
11712       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11713         for (auto *EI : ED->enumerators())
11714           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11715       }
11716     }
11717   }
11718
11719   // Introduce our parameters into the function scope
11720   for (auto Param : FD->parameters()) {
11721     Param->setOwningFunction(FD);
11722
11723     // If this has an identifier, add it to the scope stack.
11724     if (Param->getIdentifier() && FnBodyScope) {
11725       CheckShadow(FnBodyScope, Param);
11726
11727       PushOnScopeChains(Param, FnBodyScope);
11728     }
11729   }
11730
11731   // Ensure that the function's exception specification is instantiated.
11732   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11733     ResolveExceptionSpec(D->getLocation(), FPT);
11734
11735   // dllimport cannot be applied to non-inline function definitions.
11736   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11737       !FD->isTemplateInstantiation()) {
11738     assert(!FD->hasAttr<DLLExportAttr>());
11739     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11740     FD->setInvalidDecl();
11741     return D;
11742   }
11743   // We want to attach documentation to original Decl (which might be
11744   // a function template).
11745   ActOnDocumentableDecl(D);
11746   if (getCurLexicalContext()->isObjCContainer() &&
11747       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11748       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11749     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11750
11751   return D;
11752 }
11753
11754 /// \brief Given the set of return statements within a function body,
11755 /// compute the variables that are subject to the named return value
11756 /// optimization.
11757 ///
11758 /// Each of the variables that is subject to the named return value
11759 /// optimization will be marked as NRVO variables in the AST, and any
11760 /// return statement that has a marked NRVO variable as its NRVO candidate can
11761 /// use the named return value optimization.
11762 ///
11763 /// This function applies a very simplistic algorithm for NRVO: if every return
11764 /// statement in the scope of a variable has the same NRVO candidate, that
11765 /// candidate is an NRVO variable.
11766 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11767   ReturnStmt **Returns = Scope->Returns.data();
11768
11769   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11770     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11771       if (!NRVOCandidate->isNRVOVariable())
11772         Returns[I]->setNRVOCandidate(nullptr);
11773     }
11774   }
11775 }
11776
11777 bool Sema::canDelayFunctionBody(const Declarator &D) {
11778   // We can't delay parsing the body of a constexpr function template (yet).
11779   if (D.getDeclSpec().isConstexprSpecified())
11780     return false;
11781
11782   // We can't delay parsing the body of a function template with a deduced
11783   // return type (yet).
11784   if (D.getDeclSpec().containsPlaceholderType()) {
11785     // If the placeholder introduces a non-deduced trailing return type,
11786     // we can still delay parsing it.
11787     if (D.getNumTypeObjects()) {
11788       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11789       if (Outer.Kind == DeclaratorChunk::Function &&
11790           Outer.Fun.hasTrailingReturnType()) {
11791         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11792         return Ty.isNull() || !Ty->isUndeducedType();
11793       }
11794     }
11795     return false;
11796   }
11797
11798   return true;
11799 }
11800
11801 bool Sema::canSkipFunctionBody(Decl *D) {
11802   // We cannot skip the body of a function (or function template) which is
11803   // constexpr, since we may need to evaluate its body in order to parse the
11804   // rest of the file.
11805   // We cannot skip the body of a function with an undeduced return type,
11806   // because any callers of that function need to know the type.
11807   if (const FunctionDecl *FD = D->getAsFunction())
11808     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11809       return false;
11810   return Consumer.shouldSkipFunctionBody(D);
11811 }
11812
11813 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11814   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11815     FD->setHasSkippedBody();
11816   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11817     MD->setHasSkippedBody();
11818   return Decl;
11819 }
11820
11821 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11822   return ActOnFinishFunctionBody(D, BodyArg, false);
11823 }
11824
11825 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11826                                     bool IsInstantiation) {
11827   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11828
11829   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11830   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11831
11832   if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
11833     CheckCompletedCoroutineBody(FD, Body);
11834
11835   if (FD) {
11836     FD->setBody(Body);
11837
11838     if (getLangOpts().CPlusPlus14) {
11839       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11840           FD->getReturnType()->isUndeducedType()) {
11841         // If the function has a deduced result type but contains no 'return'
11842         // statements, the result type as written must be exactly 'auto', and
11843         // the deduced result type is 'void'.
11844         if (!FD->getReturnType()->getAs<AutoType>()) {
11845           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11846               << FD->getReturnType();
11847           FD->setInvalidDecl();
11848         } else {
11849           // Substitute 'void' for the 'auto' in the type.
11850           TypeLoc ResultType = getReturnTypeLoc(FD);
11851           Context.adjustDeducedFunctionResultType(
11852               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11853         }
11854       }
11855     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11856       // In C++11, we don't use 'auto' deduction rules for lambda call
11857       // operators because we don't support return type deduction.
11858       auto *LSI = getCurLambda();
11859       if (LSI->HasImplicitReturnType) {
11860         deduceClosureReturnType(*LSI);
11861
11862         // C++11 [expr.prim.lambda]p4:
11863         //   [...] if there are no return statements in the compound-statement
11864         //   [the deduced type is] the type void
11865         QualType RetType =
11866             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11867
11868         // Update the return type to the deduced type.
11869         const FunctionProtoType *Proto =
11870             FD->getType()->getAs<FunctionProtoType>();
11871         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11872                                             Proto->getExtProtoInfo()));
11873       }
11874     }
11875
11876     // The only way to be included in UndefinedButUsed is if there is an
11877     // ODR use before the definition. Avoid the expensive map lookup if this
11878     // is the first declaration.
11879     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11880       if (!FD->isExternallyVisible())
11881         UndefinedButUsed.erase(FD);
11882       else if (FD->isInlined() &&
11883                !LangOpts.GNUInline &&
11884                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11885         UndefinedButUsed.erase(FD);
11886     }
11887
11888     // If the function implicitly returns zero (like 'main') or is naked,
11889     // don't complain about missing return statements.
11890     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11891       WP.disableCheckFallThrough();
11892
11893     // MSVC permits the use of pure specifier (=0) on function definition,
11894     // defined at class scope, warn about this non-standard construct.
11895     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11896       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11897
11898     if (!FD->isInvalidDecl()) {
11899       // Don't diagnose unused parameters of defaulted or deleted functions.
11900       if (!FD->isDeleted() && !FD->isDefaulted())
11901         DiagnoseUnusedParameters(FD->parameters());
11902       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11903                                              FD->getReturnType(), FD);
11904
11905       // If this is a structor, we need a vtable.
11906       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11907         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11908       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11909         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11910
11911       // Try to apply the named return value optimization. We have to check
11912       // if we can do this here because lambdas keep return statements around
11913       // to deduce an implicit return type.
11914       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11915           !FD->isDependentContext())
11916         computeNRVO(Body, getCurFunction());
11917     }
11918
11919     // GNU warning -Wmissing-prototypes:
11920     //   Warn if a global function is defined without a previous
11921     //   prototype declaration. This warning is issued even if the
11922     //   definition itself provides a prototype. The aim is to detect
11923     //   global functions that fail to be declared in header files.
11924     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11925     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11926       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11927
11928       if (PossibleZeroParamPrototype) {
11929         // We found a declaration that is not a prototype,
11930         // but that could be a zero-parameter prototype
11931         if (TypeSourceInfo *TI =
11932                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11933           TypeLoc TL = TI->getTypeLoc();
11934           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11935             Diag(PossibleZeroParamPrototype->getLocation(),
11936                  diag::note_declaration_not_a_prototype)
11937                 << PossibleZeroParamPrototype
11938                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11939         }
11940       }
11941
11942       // GNU warning -Wstrict-prototypes
11943       //   Warn if K&R function is defined without a previous declaration.
11944       //   This warning is issued only if the definition itself does not provide
11945       //   a prototype. Only K&R definitions do not provide a prototype.
11946       //   An empty list in a function declarator that is part of a definition
11947       //   of that function specifies that the function has no parameters
11948       //   (C99 6.7.5.3p14)
11949       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
11950           !LangOpts.CPlusPlus) {
11951         TypeSourceInfo *TI = FD->getTypeSourceInfo();
11952         TypeLoc TL = TI->getTypeLoc();
11953         FunctionTypeLoc FTL = TL.castAs<FunctionTypeLoc>();
11954         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
11955       }
11956     }
11957
11958     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11959       const CXXMethodDecl *KeyFunction;
11960       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11961           MD->isVirtual() &&
11962           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11963           MD == KeyFunction->getCanonicalDecl()) {
11964         // Update the key-function state if necessary for this ABI.
11965         if (FD->isInlined() &&
11966             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11967           Context.setNonKeyFunction(MD);
11968
11969           // If the newly-chosen key function is already defined, then we
11970           // need to mark the vtable as used retroactively.
11971           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11972           const FunctionDecl *Definition;
11973           if (KeyFunction && KeyFunction->isDefined(Definition))
11974             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11975         } else {
11976           // We just defined they key function; mark the vtable as used.
11977           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11978         }
11979       }
11980     }
11981
11982     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11983            "Function parsing confused");
11984   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11985     assert(MD == getCurMethodDecl() && "Method parsing confused");
11986     MD->setBody(Body);
11987     if (!MD->isInvalidDecl()) {
11988       DiagnoseUnusedParameters(MD->parameters());
11989       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
11990                                              MD->getReturnType(), MD);
11991
11992       if (Body)
11993         computeNRVO(Body, getCurFunction());
11994     }
11995     if (getCurFunction()->ObjCShouldCallSuper) {
11996       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11997         << MD->getSelector().getAsString();
11998       getCurFunction()->ObjCShouldCallSuper = false;
11999     }
12000     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12001       const ObjCMethodDecl *InitMethod = nullptr;
12002       bool isDesignated =
12003           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12004       assert(isDesignated && InitMethod);
12005       (void)isDesignated;
12006
12007       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12008         auto IFace = MD->getClassInterface();
12009         if (!IFace)
12010           return false;
12011         auto SuperD = IFace->getSuperClass();
12012         if (!SuperD)
12013           return false;
12014         return SuperD->getIdentifier() ==
12015             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12016       };
12017       // Don't issue this warning for unavailable inits or direct subclasses
12018       // of NSObject.
12019       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12020         Diag(MD->getLocation(),
12021              diag::warn_objc_designated_init_missing_super_call);
12022         Diag(InitMethod->getLocation(),
12023              diag::note_objc_designated_init_marked_here);
12024       }
12025       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12026     }
12027     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12028       // Don't issue this warning for unavaialable inits.
12029       if (!MD->isUnavailable())
12030         Diag(MD->getLocation(),
12031              diag::warn_objc_secondary_init_missing_init_call);
12032       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12033     }
12034   } else {
12035     return nullptr;
12036   }
12037
12038   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12039     DiagnoseUnguardedAvailabilityViolations(dcl);
12040
12041   assert(!getCurFunction()->ObjCShouldCallSuper &&
12042          "This should only be set for ObjC methods, which should have been "
12043          "handled in the block above.");
12044
12045   // Verify and clean out per-function state.
12046   if (Body && (!FD || !FD->isDefaulted())) {
12047     // C++ constructors that have function-try-blocks can't have return
12048     // statements in the handlers of that block. (C++ [except.handle]p14)
12049     // Verify this.
12050     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12051       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12052
12053     // Verify that gotos and switch cases don't jump into scopes illegally.
12054     if (getCurFunction()->NeedsScopeChecking() &&
12055         !PP.isCodeCompletionEnabled())
12056       DiagnoseInvalidJumps(Body);
12057
12058     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12059       if (!Destructor->getParent()->isDependentType())
12060         CheckDestructor(Destructor);
12061
12062       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12063                                              Destructor->getParent());
12064     }
12065
12066     // If any errors have occurred, clear out any temporaries that may have
12067     // been leftover. This ensures that these temporaries won't be picked up for
12068     // deletion in some later function.
12069     if (getDiagnostics().hasErrorOccurred() ||
12070         getDiagnostics().getSuppressAllDiagnostics()) {
12071       DiscardCleanupsInEvaluationContext();
12072     }
12073     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12074         !isa<FunctionTemplateDecl>(dcl)) {
12075       // Since the body is valid, issue any analysis-based warnings that are
12076       // enabled.
12077       ActivePolicy = &WP;
12078     }
12079
12080     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12081         (!CheckConstexprFunctionDecl(FD) ||
12082          !CheckConstexprFunctionBody(FD, Body)))
12083       FD->setInvalidDecl();
12084
12085     if (FD && FD->hasAttr<NakedAttr>()) {
12086       for (const Stmt *S : Body->children()) {
12087         // Allow local register variables without initializer as they don't
12088         // require prologue.
12089         bool RegisterVariables = false;
12090         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12091           for (const auto *Decl : DS->decls()) {
12092             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12093               RegisterVariables =
12094                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12095               if (!RegisterVariables)
12096                 break;
12097             }
12098           }
12099         }
12100         if (RegisterVariables)
12101           continue;
12102         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12103           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12104           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12105           FD->setInvalidDecl();
12106           break;
12107         }
12108       }
12109     }
12110
12111     assert(ExprCleanupObjects.size() ==
12112                ExprEvalContexts.back().NumCleanupObjects &&
12113            "Leftover temporaries in function");
12114     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12115     assert(MaybeODRUseExprs.empty() &&
12116            "Leftover expressions for odr-use checking");
12117   }
12118
12119   if (!IsInstantiation)
12120     PopDeclContext();
12121
12122   PopFunctionScopeInfo(ActivePolicy, dcl);
12123   // If any errors have occurred, clear out any temporaries that may have
12124   // been leftover. This ensures that these temporaries won't be picked up for
12125   // deletion in some later function.
12126   if (getDiagnostics().hasErrorOccurred()) {
12127     DiscardCleanupsInEvaluationContext();
12128   }
12129
12130   return dcl;
12131 }
12132
12133 /// When we finish delayed parsing of an attribute, we must attach it to the
12134 /// relevant Decl.
12135 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12136                                        ParsedAttributes &Attrs) {
12137   // Always attach attributes to the underlying decl.
12138   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12139     D = TD->getTemplatedDecl();
12140   ProcessDeclAttributeList(S, D, Attrs.getList());
12141
12142   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12143     if (Method->isStatic())
12144       checkThisInStaticMemberFunctionAttributes(Method);
12145 }
12146
12147 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12148 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12149 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12150                                           IdentifierInfo &II, Scope *S) {
12151   // Before we produce a declaration for an implicitly defined
12152   // function, see whether there was a locally-scoped declaration of
12153   // this name as a function or variable. If so, use that
12154   // (non-visible) declaration, and complain about it.
12155   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12156     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12157     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12158     return ExternCPrev;
12159   }
12160
12161   // Extension in C99.  Legal in C90, but warn about it.
12162   unsigned diag_id;
12163   if (II.getName().startswith("__builtin_"))
12164     diag_id = diag::warn_builtin_unknown;
12165   else if (getLangOpts().C99)
12166     diag_id = diag::ext_implicit_function_decl;
12167   else
12168     diag_id = diag::warn_implicit_function_decl;
12169   Diag(Loc, diag_id) << &II;
12170
12171   // Because typo correction is expensive, only do it if the implicit
12172   // function declaration is going to be treated as an error.
12173   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12174     TypoCorrection Corrected;
12175     if (S &&
12176         (Corrected = CorrectTypo(
12177              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12178              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12179       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12180                    /*ErrorRecovery*/false);
12181   }
12182
12183   // Set a Declarator for the implicit definition: int foo();
12184   const char *Dummy;
12185   AttributeFactory attrFactory;
12186   DeclSpec DS(attrFactory);
12187   unsigned DiagID;
12188   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12189                                   Context.getPrintingPolicy());
12190   (void)Error; // Silence warning.
12191   assert(!Error && "Error setting up implicit decl!");
12192   SourceLocation NoLoc;
12193   Declarator D(DS, Declarator::BlockContext);
12194   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12195                                              /*IsAmbiguous=*/false,
12196                                              /*LParenLoc=*/NoLoc,
12197                                              /*Params=*/nullptr,
12198                                              /*NumParams=*/0,
12199                                              /*EllipsisLoc=*/NoLoc,
12200                                              /*RParenLoc=*/NoLoc,
12201                                              /*TypeQuals=*/0,
12202                                              /*RefQualifierIsLvalueRef=*/true,
12203                                              /*RefQualifierLoc=*/NoLoc,
12204                                              /*ConstQualifierLoc=*/NoLoc,
12205                                              /*VolatileQualifierLoc=*/NoLoc,
12206                                              /*RestrictQualifierLoc=*/NoLoc,
12207                                              /*MutableLoc=*/NoLoc,
12208                                              EST_None,
12209                                              /*ESpecRange=*/SourceRange(),
12210                                              /*Exceptions=*/nullptr,
12211                                              /*ExceptionRanges=*/nullptr,
12212                                              /*NumExceptions=*/0,
12213                                              /*NoexceptExpr=*/nullptr,
12214                                              /*ExceptionSpecTokens=*/nullptr,
12215                                              /*DeclsInPrototype=*/None,
12216                                              Loc, Loc, D),
12217                 DS.getAttributes(),
12218                 SourceLocation());
12219   D.SetIdentifier(&II, Loc);
12220
12221   // Insert this function into translation-unit scope.
12222
12223   DeclContext *PrevDC = CurContext;
12224   CurContext = Context.getTranslationUnitDecl();
12225
12226   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12227   FD->setImplicit();
12228
12229   CurContext = PrevDC;
12230
12231   AddKnownFunctionAttributes(FD);
12232
12233   return FD;
12234 }
12235
12236 /// \brief Adds any function attributes that we know a priori based on
12237 /// the declaration of this function.
12238 ///
12239 /// These attributes can apply both to implicitly-declared builtins
12240 /// (like __builtin___printf_chk) or to library-declared functions
12241 /// like NSLog or printf.
12242 ///
12243 /// We need to check for duplicate attributes both here and where user-written
12244 /// attributes are applied to declarations.
12245 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12246   if (FD->isInvalidDecl())
12247     return;
12248
12249   // If this is a built-in function, map its builtin attributes to
12250   // actual attributes.
12251   if (unsigned BuiltinID = FD->getBuiltinID()) {
12252     // Handle printf-formatting attributes.
12253     unsigned FormatIdx;
12254     bool HasVAListArg;
12255     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12256       if (!FD->hasAttr<FormatAttr>()) {
12257         const char *fmt = "printf";
12258         unsigned int NumParams = FD->getNumParams();
12259         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12260             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12261           fmt = "NSString";
12262         FD->addAttr(FormatAttr::CreateImplicit(Context,
12263                                                &Context.Idents.get(fmt),
12264                                                FormatIdx+1,
12265                                                HasVAListArg ? 0 : FormatIdx+2,
12266                                                FD->getLocation()));
12267       }
12268     }
12269     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12270                                              HasVAListArg)) {
12271      if (!FD->hasAttr<FormatAttr>())
12272        FD->addAttr(FormatAttr::CreateImplicit(Context,
12273                                               &Context.Idents.get("scanf"),
12274                                               FormatIdx+1,
12275                                               HasVAListArg ? 0 : FormatIdx+2,
12276                                               FD->getLocation()));
12277     }
12278
12279     // Mark const if we don't care about errno and that is the only
12280     // thing preventing the function from being const. This allows
12281     // IRgen to use LLVM intrinsics for such functions.
12282     if (!getLangOpts().MathErrno &&
12283         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12284       if (!FD->hasAttr<ConstAttr>())
12285         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12286     }
12287
12288     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12289         !FD->hasAttr<ReturnsTwiceAttr>())
12290       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12291                                          FD->getLocation()));
12292     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12293       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12294     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12295       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12296     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12297       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12298     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12299         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12300       // Add the appropriate attribute, depending on the CUDA compilation mode
12301       // and which target the builtin belongs to. For example, during host
12302       // compilation, aux builtins are __device__, while the rest are __host__.
12303       if (getLangOpts().CUDAIsDevice !=
12304           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12305         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12306       else
12307         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12308     }
12309   }
12310
12311   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12312   // throw, add an implicit nothrow attribute to any extern "C" function we come
12313   // across.
12314   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12315       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12316     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12317     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12318       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12319   }
12320
12321   IdentifierInfo *Name = FD->getIdentifier();
12322   if (!Name)
12323     return;
12324   if ((!getLangOpts().CPlusPlus &&
12325        FD->getDeclContext()->isTranslationUnit()) ||
12326       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12327        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12328        LinkageSpecDecl::lang_c)) {
12329     // Okay: this could be a libc/libm/Objective-C function we know
12330     // about.
12331   } else
12332     return;
12333
12334   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12335     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12336     // target-specific builtins, perhaps?
12337     if (!FD->hasAttr<FormatAttr>())
12338       FD->addAttr(FormatAttr::CreateImplicit(Context,
12339                                              &Context.Idents.get("printf"), 2,
12340                                              Name->isStr("vasprintf") ? 0 : 3,
12341                                              FD->getLocation()));
12342   }
12343
12344   if (Name->isStr("__CFStringMakeConstantString")) {
12345     // We already have a __builtin___CFStringMakeConstantString,
12346     // but builds that use -fno-constant-cfstrings don't go through that.
12347     if (!FD->hasAttr<FormatArgAttr>())
12348       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12349                                                 FD->getLocation()));
12350   }
12351 }
12352
12353 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12354                                     TypeSourceInfo *TInfo) {
12355   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12356   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12357
12358   if (!TInfo) {
12359     assert(D.isInvalidType() && "no declarator info for valid type");
12360     TInfo = Context.getTrivialTypeSourceInfo(T);
12361   }
12362
12363   // Scope manipulation handled by caller.
12364   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12365                                            D.getLocStart(),
12366                                            D.getIdentifierLoc(),
12367                                            D.getIdentifier(),
12368                                            TInfo);
12369
12370   // Bail out immediately if we have an invalid declaration.
12371   if (D.isInvalidType()) {
12372     NewTD->setInvalidDecl();
12373     return NewTD;
12374   }
12375
12376   if (D.getDeclSpec().isModulePrivateSpecified()) {
12377     if (CurContext->isFunctionOrMethod())
12378       Diag(NewTD->getLocation(), diag::err_module_private_local)
12379         << 2 << NewTD->getDeclName()
12380         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12381         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12382     else
12383       NewTD->setModulePrivate();
12384   }
12385
12386   // C++ [dcl.typedef]p8:
12387   //   If the typedef declaration defines an unnamed class (or
12388   //   enum), the first typedef-name declared by the declaration
12389   //   to be that class type (or enum type) is used to denote the
12390   //   class type (or enum type) for linkage purposes only.
12391   // We need to check whether the type was declared in the declaration.
12392   switch (D.getDeclSpec().getTypeSpecType()) {
12393   case TST_enum:
12394   case TST_struct:
12395   case TST_interface:
12396   case TST_union:
12397   case TST_class: {
12398     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12399     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12400     break;
12401   }
12402
12403   default:
12404     break;
12405   }
12406
12407   return NewTD;
12408 }
12409
12410 /// \brief Check that this is a valid underlying type for an enum declaration.
12411 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12412   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12413   QualType T = TI->getType();
12414
12415   if (T->isDependentType())
12416     return false;
12417
12418   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12419     if (BT->isInteger())
12420       return false;
12421
12422   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12423   return true;
12424 }
12425
12426 /// Check whether this is a valid redeclaration of a previous enumeration.
12427 /// \return true if the redeclaration was invalid.
12428 bool Sema::CheckEnumRedeclaration(
12429     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12430     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12431   bool IsFixed = !EnumUnderlyingTy.isNull();
12432
12433   if (IsScoped != Prev->isScoped()) {
12434     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12435       << Prev->isScoped();
12436     Diag(Prev->getLocation(), diag::note_previous_declaration);
12437     return true;
12438   }
12439
12440   if (IsFixed && Prev->isFixed()) {
12441     if (!EnumUnderlyingTy->isDependentType() &&
12442         !Prev->getIntegerType()->isDependentType() &&
12443         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12444                                         Prev->getIntegerType())) {
12445       // TODO: Highlight the underlying type of the redeclaration.
12446       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12447         << EnumUnderlyingTy << Prev->getIntegerType();
12448       Diag(Prev->getLocation(), diag::note_previous_declaration)
12449           << Prev->getIntegerTypeRange();
12450       return true;
12451     }
12452   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12453     ;
12454   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12455     ;
12456   } else if (IsFixed != Prev->isFixed()) {
12457     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12458       << Prev->isFixed();
12459     Diag(Prev->getLocation(), diag::note_previous_declaration);
12460     return true;
12461   }
12462
12463   return false;
12464 }
12465
12466 /// \brief Get diagnostic %select index for tag kind for
12467 /// redeclaration diagnostic message.
12468 /// WARNING: Indexes apply to particular diagnostics only!
12469 ///
12470 /// \returns diagnostic %select index.
12471 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12472   switch (Tag) {
12473   case TTK_Struct: return 0;
12474   case TTK_Interface: return 1;
12475   case TTK_Class:  return 2;
12476   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12477   }
12478 }
12479
12480 /// \brief Determine if tag kind is a class-key compatible with
12481 /// class for redeclaration (class, struct, or __interface).
12482 ///
12483 /// \returns true iff the tag kind is compatible.
12484 static bool isClassCompatTagKind(TagTypeKind Tag)
12485 {
12486   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12487 }
12488
12489 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12490                                              TagTypeKind TTK) {
12491   if (isa<TypedefDecl>(PrevDecl))
12492     return NTK_Typedef;
12493   else if (isa<TypeAliasDecl>(PrevDecl))
12494     return NTK_TypeAlias;
12495   else if (isa<ClassTemplateDecl>(PrevDecl))
12496     return NTK_Template;
12497   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12498     return NTK_TypeAliasTemplate;
12499   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12500     return NTK_TemplateTemplateArgument;
12501   switch (TTK) {
12502   case TTK_Struct:
12503   case TTK_Interface:
12504   case TTK_Class:
12505     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12506   case TTK_Union:
12507     return NTK_NonUnion;
12508   case TTK_Enum:
12509     return NTK_NonEnum;
12510   }
12511   llvm_unreachable("invalid TTK");
12512 }
12513
12514 /// \brief Determine whether a tag with a given kind is acceptable
12515 /// as a redeclaration of the given tag declaration.
12516 ///
12517 /// \returns true if the new tag kind is acceptable, false otherwise.
12518 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12519                                         TagTypeKind NewTag, bool isDefinition,
12520                                         SourceLocation NewTagLoc,
12521                                         const IdentifierInfo *Name) {
12522   // C++ [dcl.type.elab]p3:
12523   //   The class-key or enum keyword present in the
12524   //   elaborated-type-specifier shall agree in kind with the
12525   //   declaration to which the name in the elaborated-type-specifier
12526   //   refers. This rule also applies to the form of
12527   //   elaborated-type-specifier that declares a class-name or
12528   //   friend class since it can be construed as referring to the
12529   //   definition of the class. Thus, in any
12530   //   elaborated-type-specifier, the enum keyword shall be used to
12531   //   refer to an enumeration (7.2), the union class-key shall be
12532   //   used to refer to a union (clause 9), and either the class or
12533   //   struct class-key shall be used to refer to a class (clause 9)
12534   //   declared using the class or struct class-key.
12535   TagTypeKind OldTag = Previous->getTagKind();
12536   if (!isDefinition || !isClassCompatTagKind(NewTag))
12537     if (OldTag == NewTag)
12538       return true;
12539
12540   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12541     // Warn about the struct/class tag mismatch.
12542     bool isTemplate = false;
12543     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12544       isTemplate = Record->getDescribedClassTemplate();
12545
12546     if (!ActiveTemplateInstantiations.empty()) {
12547       // In a template instantiation, do not offer fix-its for tag mismatches
12548       // since they usually mess up the template instead of fixing the problem.
12549       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12550         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12551         << getRedeclDiagFromTagKind(OldTag);
12552       return true;
12553     }
12554
12555     if (isDefinition) {
12556       // On definitions, check previous tags and issue a fix-it for each
12557       // one that doesn't match the current tag.
12558       if (Previous->getDefinition()) {
12559         // Don't suggest fix-its for redefinitions.
12560         return true;
12561       }
12562
12563       bool previousMismatch = false;
12564       for (auto I : Previous->redecls()) {
12565         if (I->getTagKind() != NewTag) {
12566           if (!previousMismatch) {
12567             previousMismatch = true;
12568             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12569               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12570               << getRedeclDiagFromTagKind(I->getTagKind());
12571           }
12572           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12573             << getRedeclDiagFromTagKind(NewTag)
12574             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12575                  TypeWithKeyword::getTagTypeKindName(NewTag));
12576         }
12577       }
12578       return true;
12579     }
12580
12581     // Check for a previous definition.  If current tag and definition
12582     // are same type, do nothing.  If no definition, but disagree with
12583     // with previous tag type, give a warning, but no fix-it.
12584     const TagDecl *Redecl = Previous->getDefinition() ?
12585                             Previous->getDefinition() : Previous;
12586     if (Redecl->getTagKind() == NewTag) {
12587       return true;
12588     }
12589
12590     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12591       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12592       << getRedeclDiagFromTagKind(OldTag);
12593     Diag(Redecl->getLocation(), diag::note_previous_use);
12594
12595     // If there is a previous definition, suggest a fix-it.
12596     if (Previous->getDefinition()) {
12597         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12598           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12599           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12600                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12601     }
12602
12603     return true;
12604   }
12605   return false;
12606 }
12607
12608 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12609 /// from an outer enclosing namespace or file scope inside a friend declaration.
12610 /// This should provide the commented out code in the following snippet:
12611 ///   namespace N {
12612 ///     struct X;
12613 ///     namespace M {
12614 ///       struct Y { friend struct /*N::*/ X; };
12615 ///     }
12616 ///   }
12617 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12618                                          SourceLocation NameLoc) {
12619   // While the decl is in a namespace, do repeated lookup of that name and see
12620   // if we get the same namespace back.  If we do not, continue until
12621   // translation unit scope, at which point we have a fully qualified NNS.
12622   SmallVector<IdentifierInfo *, 4> Namespaces;
12623   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12624   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12625     // This tag should be declared in a namespace, which can only be enclosed by
12626     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12627     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12628     if (!Namespace || Namespace->isAnonymousNamespace())
12629       return FixItHint();
12630     IdentifierInfo *II = Namespace->getIdentifier();
12631     Namespaces.push_back(II);
12632     NamedDecl *Lookup = SemaRef.LookupSingleName(
12633         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12634     if (Lookup == Namespace)
12635       break;
12636   }
12637
12638   // Once we have all the namespaces, reverse them to go outermost first, and
12639   // build an NNS.
12640   SmallString<64> Insertion;
12641   llvm::raw_svector_ostream OS(Insertion);
12642   if (DC->isTranslationUnit())
12643     OS << "::";
12644   std::reverse(Namespaces.begin(), Namespaces.end());
12645   for (auto *II : Namespaces)
12646     OS << II->getName() << "::";
12647   return FixItHint::CreateInsertion(NameLoc, Insertion);
12648 }
12649
12650 /// \brief Determine whether a tag originally declared in context \p OldDC can
12651 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12652 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12653 /// using-declaration).
12654 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12655                                          DeclContext *NewDC) {
12656   OldDC = OldDC->getRedeclContext();
12657   NewDC = NewDC->getRedeclContext();
12658
12659   if (OldDC->Equals(NewDC))
12660     return true;
12661
12662   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12663   // encloses the other).
12664   if (S.getLangOpts().MSVCCompat &&
12665       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12666     return true;
12667
12668   return false;
12669 }
12670
12671 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12672 /// former case, Name will be non-null.  In the later case, Name will be null.
12673 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12674 /// reference/declaration/definition of a tag.
12675 ///
12676 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12677 /// trailing-type-specifier) other than one in an alias-declaration.
12678 ///
12679 /// \param SkipBody If non-null, will be set to indicate if the caller should
12680 /// skip the definition of this tag and treat it as if it were a declaration.
12681 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12682                      SourceLocation KWLoc, CXXScopeSpec &SS,
12683                      IdentifierInfo *Name, SourceLocation NameLoc,
12684                      AttributeList *Attr, AccessSpecifier AS,
12685                      SourceLocation ModulePrivateLoc,
12686                      MultiTemplateParamsArg TemplateParameterLists,
12687                      bool &OwnedDecl, bool &IsDependent,
12688                      SourceLocation ScopedEnumKWLoc,
12689                      bool ScopedEnumUsesClassTag,
12690                      TypeResult UnderlyingType,
12691                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12692   // If this is not a definition, it must have a name.
12693   IdentifierInfo *OrigName = Name;
12694   assert((Name != nullptr || TUK == TUK_Definition) &&
12695          "Nameless record must be a definition!");
12696   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12697
12698   OwnedDecl = false;
12699   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12700   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12701
12702   // FIXME: Check explicit specializations more carefully.
12703   bool isExplicitSpecialization = false;
12704   bool Invalid = false;
12705
12706   // We only need to do this matching if we have template parameters
12707   // or a scope specifier, which also conveniently avoids this work
12708   // for non-C++ cases.
12709   if (TemplateParameterLists.size() > 0 ||
12710       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12711     if (TemplateParameterList *TemplateParams =
12712             MatchTemplateParametersToScopeSpecifier(
12713                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12714                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12715       if (Kind == TTK_Enum) {
12716         Diag(KWLoc, diag::err_enum_template);
12717         return nullptr;
12718       }
12719
12720       if (TemplateParams->size() > 0) {
12721         // This is a declaration or definition of a class template (which may
12722         // be a member of another template).
12723
12724         if (Invalid)
12725           return nullptr;
12726
12727         OwnedDecl = false;
12728         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12729                                                SS, Name, NameLoc, Attr,
12730                                                TemplateParams, AS,
12731                                                ModulePrivateLoc,
12732                                                /*FriendLoc*/SourceLocation(),
12733                                                TemplateParameterLists.size()-1,
12734                                                TemplateParameterLists.data(),
12735                                                SkipBody);
12736         return Result.get();
12737       } else {
12738         // The "template<>" header is extraneous.
12739         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12740           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12741         isExplicitSpecialization = true;
12742       }
12743     }
12744   }
12745
12746   // Figure out the underlying type if this a enum declaration. We need to do
12747   // this early, because it's needed to detect if this is an incompatible
12748   // redeclaration.
12749   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12750   bool EnumUnderlyingIsImplicit = false;
12751
12752   if (Kind == TTK_Enum) {
12753     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12754       // No underlying type explicitly specified, or we failed to parse the
12755       // type, default to int.
12756       EnumUnderlying = Context.IntTy.getTypePtr();
12757     else if (UnderlyingType.get()) {
12758       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12759       // integral type; any cv-qualification is ignored.
12760       TypeSourceInfo *TI = nullptr;
12761       GetTypeFromParser(UnderlyingType.get(), &TI);
12762       EnumUnderlying = TI;
12763
12764       if (CheckEnumUnderlyingType(TI))
12765         // Recover by falling back to int.
12766         EnumUnderlying = Context.IntTy.getTypePtr();
12767
12768       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12769                                           UPPC_FixedUnderlyingType))
12770         EnumUnderlying = Context.IntTy.getTypePtr();
12771
12772     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12773       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12774         // Microsoft enums are always of int type.
12775         EnumUnderlying = Context.IntTy.getTypePtr();
12776         EnumUnderlyingIsImplicit = true;
12777       }
12778     }
12779   }
12780
12781   DeclContext *SearchDC = CurContext;
12782   DeclContext *DC = CurContext;
12783   bool isStdBadAlloc = false;
12784   bool isStdAlignValT = false;
12785
12786   RedeclarationKind Redecl = ForRedeclaration;
12787   if (TUK == TUK_Friend || TUK == TUK_Reference)
12788     Redecl = NotForRedeclaration;
12789
12790   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12791   if (Name && SS.isNotEmpty()) {
12792     // We have a nested-name tag ('struct foo::bar').
12793
12794     // Check for invalid 'foo::'.
12795     if (SS.isInvalid()) {
12796       Name = nullptr;
12797       goto CreateNewDecl;
12798     }
12799
12800     // If this is a friend or a reference to a class in a dependent
12801     // context, don't try to make a decl for it.
12802     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12803       DC = computeDeclContext(SS, false);
12804       if (!DC) {
12805         IsDependent = true;
12806         return nullptr;
12807       }
12808     } else {
12809       DC = computeDeclContext(SS, true);
12810       if (!DC) {
12811         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12812           << SS.getRange();
12813         return nullptr;
12814       }
12815     }
12816
12817     if (RequireCompleteDeclContext(SS, DC))
12818       return nullptr;
12819
12820     SearchDC = DC;
12821     // Look-up name inside 'foo::'.
12822     LookupQualifiedName(Previous, DC);
12823
12824     if (Previous.isAmbiguous())
12825       return nullptr;
12826
12827     if (Previous.empty()) {
12828       // Name lookup did not find anything. However, if the
12829       // nested-name-specifier refers to the current instantiation,
12830       // and that current instantiation has any dependent base
12831       // classes, we might find something at instantiation time: treat
12832       // this as a dependent elaborated-type-specifier.
12833       // But this only makes any sense for reference-like lookups.
12834       if (Previous.wasNotFoundInCurrentInstantiation() &&
12835           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12836         IsDependent = true;
12837         return nullptr;
12838       }
12839
12840       // A tag 'foo::bar' must already exist.
12841       Diag(NameLoc, diag::err_not_tag_in_scope)
12842         << Kind << Name << DC << SS.getRange();
12843       Name = nullptr;
12844       Invalid = true;
12845       goto CreateNewDecl;
12846     }
12847   } else if (Name) {
12848     // C++14 [class.mem]p14:
12849     //   If T is the name of a class, then each of the following shall have a
12850     //   name different from T:
12851     //    -- every member of class T that is itself a type
12852     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12853         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12854       return nullptr;
12855
12856     // If this is a named struct, check to see if there was a previous forward
12857     // declaration or definition.
12858     // FIXME: We're looking into outer scopes here, even when we
12859     // shouldn't be. Doing so can result in ambiguities that we
12860     // shouldn't be diagnosing.
12861     LookupName(Previous, S);
12862
12863     // When declaring or defining a tag, ignore ambiguities introduced
12864     // by types using'ed into this scope.
12865     if (Previous.isAmbiguous() &&
12866         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12867       LookupResult::Filter F = Previous.makeFilter();
12868       while (F.hasNext()) {
12869         NamedDecl *ND = F.next();
12870         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12871                 SearchDC->getRedeclContext()))
12872           F.erase();
12873       }
12874       F.done();
12875     }
12876
12877     // C++11 [namespace.memdef]p3:
12878     //   If the name in a friend declaration is neither qualified nor
12879     //   a template-id and the declaration is a function or an
12880     //   elaborated-type-specifier, the lookup to determine whether
12881     //   the entity has been previously declared shall not consider
12882     //   any scopes outside the innermost enclosing namespace.
12883     //
12884     // MSVC doesn't implement the above rule for types, so a friend tag
12885     // declaration may be a redeclaration of a type declared in an enclosing
12886     // scope.  They do implement this rule for friend functions.
12887     //
12888     // Does it matter that this should be by scope instead of by
12889     // semantic context?
12890     if (!Previous.empty() && TUK == TUK_Friend) {
12891       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12892       LookupResult::Filter F = Previous.makeFilter();
12893       bool FriendSawTagOutsideEnclosingNamespace = false;
12894       while (F.hasNext()) {
12895         NamedDecl *ND = F.next();
12896         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12897         if (DC->isFileContext() &&
12898             !EnclosingNS->Encloses(ND->getDeclContext())) {
12899           if (getLangOpts().MSVCCompat)
12900             FriendSawTagOutsideEnclosingNamespace = true;
12901           else
12902             F.erase();
12903         }
12904       }
12905       F.done();
12906
12907       // Diagnose this MSVC extension in the easy case where lookup would have
12908       // unambiguously found something outside the enclosing namespace.
12909       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12910         NamedDecl *ND = Previous.getFoundDecl();
12911         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12912             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12913       }
12914     }
12915
12916     // Note:  there used to be some attempt at recovery here.
12917     if (Previous.isAmbiguous())
12918       return nullptr;
12919
12920     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12921       // FIXME: This makes sure that we ignore the contexts associated
12922       // with C structs, unions, and enums when looking for a matching
12923       // tag declaration or definition. See the similar lookup tweak
12924       // in Sema::LookupName; is there a better way to deal with this?
12925       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12926         SearchDC = SearchDC->getParent();
12927     }
12928   }
12929
12930   if (Previous.isSingleResult() &&
12931       Previous.getFoundDecl()->isTemplateParameter()) {
12932     // Maybe we will complain about the shadowed template parameter.
12933     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12934     // Just pretend that we didn't see the previous declaration.
12935     Previous.clear();
12936   }
12937
12938   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12939       DC->Equals(getStdNamespace())) {
12940     if (Name->isStr("bad_alloc")) {
12941       // This is a declaration of or a reference to "std::bad_alloc".
12942       isStdBadAlloc = true;
12943
12944       // If std::bad_alloc has been implicitly declared (but made invisible to
12945       // name lookup), fill in this implicit declaration as the previous
12946       // declaration, so that the declarations get chained appropriately.
12947       if (Previous.empty() && StdBadAlloc)
12948         Previous.addDecl(getStdBadAlloc());
12949     } else if (Name->isStr("align_val_t")) {
12950       isStdAlignValT = true;
12951       if (Previous.empty() && StdAlignValT)
12952         Previous.addDecl(getStdAlignValT());
12953     }
12954   }
12955
12956   // If we didn't find a previous declaration, and this is a reference
12957   // (or friend reference), move to the correct scope.  In C++, we
12958   // also need to do a redeclaration lookup there, just in case
12959   // there's a shadow friend decl.
12960   if (Name && Previous.empty() &&
12961       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12962     if (Invalid) goto CreateNewDecl;
12963     assert(SS.isEmpty());
12964
12965     if (TUK == TUK_Reference) {
12966       // C++ [basic.scope.pdecl]p5:
12967       //   -- for an elaborated-type-specifier of the form
12968       //
12969       //          class-key identifier
12970       //
12971       //      if the elaborated-type-specifier is used in the
12972       //      decl-specifier-seq or parameter-declaration-clause of a
12973       //      function defined in namespace scope, the identifier is
12974       //      declared as a class-name in the namespace that contains
12975       //      the declaration; otherwise, except as a friend
12976       //      declaration, the identifier is declared in the smallest
12977       //      non-class, non-function-prototype scope that contains the
12978       //      declaration.
12979       //
12980       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12981       // C structs and unions.
12982       //
12983       // It is an error in C++ to declare (rather than define) an enum
12984       // type, including via an elaborated type specifier.  We'll
12985       // diagnose that later; for now, declare the enum in the same
12986       // scope as we would have picked for any other tag type.
12987       //
12988       // GNU C also supports this behavior as part of its incomplete
12989       // enum types extension, while GNU C++ does not.
12990       //
12991       // Find the context where we'll be declaring the tag.
12992       // FIXME: We would like to maintain the current DeclContext as the
12993       // lexical context,
12994       SearchDC = getTagInjectionContext(SearchDC);
12995
12996       // Find the scope where we'll be declaring the tag.
12997       S = getTagInjectionScope(S, getLangOpts());
12998     } else {
12999       assert(TUK == TUK_Friend);
13000       // C++ [namespace.memdef]p3:
13001       //   If a friend declaration in a non-local class first declares a
13002       //   class or function, the friend class or function is a member of
13003       //   the innermost enclosing namespace.
13004       SearchDC = SearchDC->getEnclosingNamespaceContext();
13005     }
13006
13007     // In C++, we need to do a redeclaration lookup to properly
13008     // diagnose some problems.
13009     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13010     // hidden declaration so that we don't get ambiguity errors when using a
13011     // type declared by an elaborated-type-specifier.  In C that is not correct
13012     // and we should instead merge compatible types found by lookup.
13013     if (getLangOpts().CPlusPlus) {
13014       Previous.setRedeclarationKind(ForRedeclaration);
13015       LookupQualifiedName(Previous, SearchDC);
13016     } else {
13017       Previous.setRedeclarationKind(ForRedeclaration);
13018       LookupName(Previous, S);
13019     }
13020   }
13021
13022   // If we have a known previous declaration to use, then use it.
13023   if (Previous.empty() && SkipBody && SkipBody->Previous)
13024     Previous.addDecl(SkipBody->Previous);
13025
13026   if (!Previous.empty()) {
13027     NamedDecl *PrevDecl = Previous.getFoundDecl();
13028     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13029
13030     // It's okay to have a tag decl in the same scope as a typedef
13031     // which hides a tag decl in the same scope.  Finding this
13032     // insanity with a redeclaration lookup can only actually happen
13033     // in C++.
13034     //
13035     // This is also okay for elaborated-type-specifiers, which is
13036     // technically forbidden by the current standard but which is
13037     // okay according to the likely resolution of an open issue;
13038     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13039     if (getLangOpts().CPlusPlus) {
13040       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13041         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13042           TagDecl *Tag = TT->getDecl();
13043           if (Tag->getDeclName() == Name &&
13044               Tag->getDeclContext()->getRedeclContext()
13045                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13046             PrevDecl = Tag;
13047             Previous.clear();
13048             Previous.addDecl(Tag);
13049             Previous.resolveKind();
13050           }
13051         }
13052       }
13053     }
13054
13055     // If this is a redeclaration of a using shadow declaration, it must
13056     // declare a tag in the same context. In MSVC mode, we allow a
13057     // redefinition if either context is within the other.
13058     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13059       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13060       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13061           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
13062           !(OldTag && isAcceptableTagRedeclContext(
13063                           *this, OldTag->getDeclContext(), SearchDC))) {
13064         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13065         Diag(Shadow->getTargetDecl()->getLocation(),
13066              diag::note_using_decl_target);
13067         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13068             << 0;
13069         // Recover by ignoring the old declaration.
13070         Previous.clear();
13071         goto CreateNewDecl;
13072       }
13073     }
13074
13075     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13076       // If this is a use of a previous tag, or if the tag is already declared
13077       // in the same scope (so that the definition/declaration completes or
13078       // rementions the tag), reuse the decl.
13079       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13080           isDeclInScope(DirectPrevDecl, SearchDC, S,
13081                         SS.isNotEmpty() || isExplicitSpecialization)) {
13082         // Make sure that this wasn't declared as an enum and now used as a
13083         // struct or something similar.
13084         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13085                                           TUK == TUK_Definition, KWLoc,
13086                                           Name)) {
13087           bool SafeToContinue
13088             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13089                Kind != TTK_Enum);
13090           if (SafeToContinue)
13091             Diag(KWLoc, diag::err_use_with_wrong_tag)
13092               << Name
13093               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13094                                               PrevTagDecl->getKindName());
13095           else
13096             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13097           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13098
13099           if (SafeToContinue)
13100             Kind = PrevTagDecl->getTagKind();
13101           else {
13102             // Recover by making this an anonymous redefinition.
13103             Name = nullptr;
13104             Previous.clear();
13105             Invalid = true;
13106           }
13107         }
13108
13109         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13110           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13111
13112           // If this is an elaborated-type-specifier for a scoped enumeration,
13113           // the 'class' keyword is not necessary and not permitted.
13114           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13115             if (ScopedEnum)
13116               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13117                 << PrevEnum->isScoped()
13118                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13119             return PrevTagDecl;
13120           }
13121
13122           QualType EnumUnderlyingTy;
13123           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13124             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13125           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13126             EnumUnderlyingTy = QualType(T, 0);
13127
13128           // All conflicts with previous declarations are recovered by
13129           // returning the previous declaration, unless this is a definition,
13130           // in which case we want the caller to bail out.
13131           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13132                                      ScopedEnum, EnumUnderlyingTy,
13133                                      EnumUnderlyingIsImplicit, PrevEnum))
13134             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13135         }
13136
13137         // C++11 [class.mem]p1:
13138         //   A member shall not be declared twice in the member-specification,
13139         //   except that a nested class or member class template can be declared
13140         //   and then later defined.
13141         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13142             S->isDeclScope(PrevDecl)) {
13143           Diag(NameLoc, diag::ext_member_redeclared);
13144           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13145         }
13146
13147         if (!Invalid) {
13148           // If this is a use, just return the declaration we found, unless
13149           // we have attributes.
13150           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13151             if (Attr) {
13152               // FIXME: Diagnose these attributes. For now, we create a new
13153               // declaration to hold them.
13154             } else if (TUK == TUK_Reference &&
13155                        (PrevTagDecl->getFriendObjectKind() ==
13156                             Decl::FOK_Undeclared ||
13157                         PP.getModuleContainingLocation(
13158                             PrevDecl->getLocation()) !=
13159                             PP.getModuleContainingLocation(KWLoc)) &&
13160                        SS.isEmpty()) {
13161               // This declaration is a reference to an existing entity, but
13162               // has different visibility from that entity: it either makes
13163               // a friend visible or it makes a type visible in a new module.
13164               // In either case, create a new declaration. We only do this if
13165               // the declaration would have meant the same thing if no prior
13166               // declaration were found, that is, if it was found in the same
13167               // scope where we would have injected a declaration.
13168               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13169                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13170                 return PrevTagDecl;
13171               // This is in the injected scope, create a new declaration in
13172               // that scope.
13173               S = getTagInjectionScope(S, getLangOpts());
13174             } else {
13175               return PrevTagDecl;
13176             }
13177           }
13178
13179           // Diagnose attempts to redefine a tag.
13180           if (TUK == TUK_Definition) {
13181             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13182               // If we're defining a specialization and the previous definition
13183               // is from an implicit instantiation, don't emit an error
13184               // here; we'll catch this in the general case below.
13185               bool IsExplicitSpecializationAfterInstantiation = false;
13186               if (isExplicitSpecialization) {
13187                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13188                   IsExplicitSpecializationAfterInstantiation =
13189                     RD->getTemplateSpecializationKind() !=
13190                     TSK_ExplicitSpecialization;
13191                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13192                   IsExplicitSpecializationAfterInstantiation =
13193                     ED->getTemplateSpecializationKind() !=
13194                     TSK_ExplicitSpecialization;
13195               }
13196
13197               NamedDecl *Hidden = nullptr;
13198               if (SkipBody && getLangOpts().CPlusPlus &&
13199                   !hasVisibleDefinition(Def, &Hidden)) {
13200                 // There is a definition of this tag, but it is not visible. We
13201                 // explicitly make use of C++'s one definition rule here, and
13202                 // assume that this definition is identical to the hidden one
13203                 // we already have. Make the existing definition visible and
13204                 // use it in place of this one.
13205                 SkipBody->ShouldSkip = true;
13206                 makeMergedDefinitionVisible(Hidden, KWLoc);
13207                 return Def;
13208               } else if (!IsExplicitSpecializationAfterInstantiation) {
13209                 // A redeclaration in function prototype scope in C isn't
13210                 // visible elsewhere, so merely issue a warning.
13211                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13212                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13213                 else
13214                   Diag(NameLoc, diag::err_redefinition) << Name;
13215                 Diag(Def->getLocation(), diag::note_previous_definition);
13216                 // If this is a redefinition, recover by making this
13217                 // struct be anonymous, which will make any later
13218                 // references get the previous definition.
13219                 Name = nullptr;
13220                 Previous.clear();
13221                 Invalid = true;
13222               }
13223             } else {
13224               // If the type is currently being defined, complain
13225               // about a nested redefinition.
13226               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13227               if (TD->isBeingDefined()) {
13228                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13229                 Diag(PrevTagDecl->getLocation(),
13230                      diag::note_previous_definition);
13231                 Name = nullptr;
13232                 Previous.clear();
13233                 Invalid = true;
13234               }
13235             }
13236
13237             // Okay, this is definition of a previously declared or referenced
13238             // tag. We're going to create a new Decl for it.
13239           }
13240
13241           // Okay, we're going to make a redeclaration.  If this is some kind
13242           // of reference, make sure we build the redeclaration in the same DC
13243           // as the original, and ignore the current access specifier.
13244           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13245             SearchDC = PrevTagDecl->getDeclContext();
13246             AS = AS_none;
13247           }
13248         }
13249         // If we get here we have (another) forward declaration or we
13250         // have a definition.  Just create a new decl.
13251
13252       } else {
13253         // If we get here, this is a definition of a new tag type in a nested
13254         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13255         // new decl/type.  We set PrevDecl to NULL so that the entities
13256         // have distinct types.
13257         Previous.clear();
13258       }
13259       // If we get here, we're going to create a new Decl. If PrevDecl
13260       // is non-NULL, it's a definition of the tag declared by
13261       // PrevDecl. If it's NULL, we have a new definition.
13262
13263     // Otherwise, PrevDecl is not a tag, but was found with tag
13264     // lookup.  This is only actually possible in C++, where a few
13265     // things like templates still live in the tag namespace.
13266     } else {
13267       // Use a better diagnostic if an elaborated-type-specifier
13268       // found the wrong kind of type on the first
13269       // (non-redeclaration) lookup.
13270       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13271           !Previous.isForRedeclaration()) {
13272         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13273         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13274                                                        << Kind;
13275         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13276         Invalid = true;
13277
13278       // Otherwise, only diagnose if the declaration is in scope.
13279       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13280                                 SS.isNotEmpty() || isExplicitSpecialization)) {
13281         // do nothing
13282
13283       // Diagnose implicit declarations introduced by elaborated types.
13284       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13285         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13286         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13287         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13288         Invalid = true;
13289
13290       // Otherwise it's a declaration.  Call out a particularly common
13291       // case here.
13292       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13293         unsigned Kind = 0;
13294         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13295         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13296           << Name << Kind << TND->getUnderlyingType();
13297         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13298         Invalid = true;
13299
13300       // Otherwise, diagnose.
13301       } else {
13302         // The tag name clashes with something else in the target scope,
13303         // issue an error and recover by making this tag be anonymous.
13304         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13305         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13306         Name = nullptr;
13307         Invalid = true;
13308       }
13309
13310       // The existing declaration isn't relevant to us; we're in a
13311       // new scope, so clear out the previous declaration.
13312       Previous.clear();
13313     }
13314   }
13315
13316 CreateNewDecl:
13317
13318   TagDecl *PrevDecl = nullptr;
13319   if (Previous.isSingleResult())
13320     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13321
13322   // If there is an identifier, use the location of the identifier as the
13323   // location of the decl, otherwise use the location of the struct/union
13324   // keyword.
13325   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13326
13327   // Otherwise, create a new declaration. If there is a previous
13328   // declaration of the same entity, the two will be linked via
13329   // PrevDecl.
13330   TagDecl *New;
13331
13332   bool IsForwardReference = false;
13333   if (Kind == TTK_Enum) {
13334     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13335     // enum X { A, B, C } D;    D should chain to X.
13336     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13337                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13338                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13339
13340     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13341       StdAlignValT = cast<EnumDecl>(New);
13342
13343     // If this is an undefined enum, warn.
13344     if (TUK != TUK_Definition && !Invalid) {
13345       TagDecl *Def;
13346       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13347           cast<EnumDecl>(New)->isFixed()) {
13348         // C++0x: 7.2p2: opaque-enum-declaration.
13349         // Conflicts are diagnosed above. Do nothing.
13350       }
13351       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13352         Diag(Loc, diag::ext_forward_ref_enum_def)
13353           << New;
13354         Diag(Def->getLocation(), diag::note_previous_definition);
13355       } else {
13356         unsigned DiagID = diag::ext_forward_ref_enum;
13357         if (getLangOpts().MSVCCompat)
13358           DiagID = diag::ext_ms_forward_ref_enum;
13359         else if (getLangOpts().CPlusPlus)
13360           DiagID = diag::err_forward_ref_enum;
13361         Diag(Loc, DiagID);
13362
13363         // If this is a forward-declared reference to an enumeration, make a
13364         // note of it; we won't actually be introducing the declaration into
13365         // the declaration context.
13366         if (TUK == TUK_Reference)
13367           IsForwardReference = true;
13368       }
13369     }
13370
13371     if (EnumUnderlying) {
13372       EnumDecl *ED = cast<EnumDecl>(New);
13373       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13374         ED->setIntegerTypeSourceInfo(TI);
13375       else
13376         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13377       ED->setPromotionType(ED->getIntegerType());
13378     }
13379   } else {
13380     // struct/union/class
13381
13382     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13383     // struct X { int A; } D;    D should chain to X.
13384     if (getLangOpts().CPlusPlus) {
13385       // FIXME: Look for a way to use RecordDecl for simple structs.
13386       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13387                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13388
13389       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13390         StdBadAlloc = cast<CXXRecordDecl>(New);
13391     } else
13392       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13393                                cast_or_null<RecordDecl>(PrevDecl));
13394   }
13395
13396   // C++11 [dcl.type]p3:
13397   //   A type-specifier-seq shall not define a class or enumeration [...].
13398   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13399     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13400       << Context.getTagDeclType(New);
13401     Invalid = true;
13402   }
13403
13404   // Maybe add qualifier info.
13405   if (SS.isNotEmpty()) {
13406     if (SS.isSet()) {
13407       // If this is either a declaration or a definition, check the
13408       // nested-name-specifier against the current context. We don't do this
13409       // for explicit specializations, because they have similar checking
13410       // (with more specific diagnostics) in the call to
13411       // CheckMemberSpecialization, below.
13412       if (!isExplicitSpecialization &&
13413           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13414           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13415         Invalid = true;
13416
13417       New->setQualifierInfo(SS.getWithLocInContext(Context));
13418       if (TemplateParameterLists.size() > 0) {
13419         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13420       }
13421     }
13422     else
13423       Invalid = true;
13424   }
13425
13426   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13427     // Add alignment attributes if necessary; these attributes are checked when
13428     // the ASTContext lays out the structure.
13429     //
13430     // It is important for implementing the correct semantics that this
13431     // happen here (in act on tag decl). The #pragma pack stack is
13432     // maintained as a result of parser callbacks which can occur at
13433     // many points during the parsing of a struct declaration (because
13434     // the #pragma tokens are effectively skipped over during the
13435     // parsing of the struct).
13436     if (TUK == TUK_Definition) {
13437       AddAlignmentAttributesForRecord(RD);
13438       AddMsStructLayoutForRecord(RD);
13439     }
13440   }
13441
13442   if (ModulePrivateLoc.isValid()) {
13443     if (isExplicitSpecialization)
13444       Diag(New->getLocation(), diag::err_module_private_specialization)
13445         << 2
13446         << FixItHint::CreateRemoval(ModulePrivateLoc);
13447     // __module_private__ does not apply to local classes. However, we only
13448     // diagnose this as an error when the declaration specifiers are
13449     // freestanding. Here, we just ignore the __module_private__.
13450     else if (!SearchDC->isFunctionOrMethod())
13451       New->setModulePrivate();
13452   }
13453
13454   // If this is a specialization of a member class (of a class template),
13455   // check the specialization.
13456   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13457     Invalid = true;
13458
13459   // If we're declaring or defining a tag in function prototype scope in C,
13460   // note that this type can only be used within the function and add it to
13461   // the list of decls to inject into the function definition scope.
13462   if ((Name || Kind == TTK_Enum) &&
13463       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13464     if (getLangOpts().CPlusPlus) {
13465       // C++ [dcl.fct]p6:
13466       //   Types shall not be defined in return or parameter types.
13467       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13468         Diag(Loc, diag::err_type_defined_in_param_type)
13469             << Name;
13470         Invalid = true;
13471       }
13472     } else if (!PrevDecl) {
13473       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13474     }
13475   }
13476
13477   if (Invalid)
13478     New->setInvalidDecl();
13479
13480   if (Attr)
13481     ProcessDeclAttributeList(S, New, Attr);
13482
13483   // Set the lexical context. If the tag has a C++ scope specifier, the
13484   // lexical context will be different from the semantic context.
13485   New->setLexicalDeclContext(CurContext);
13486
13487   // Mark this as a friend decl if applicable.
13488   // In Microsoft mode, a friend declaration also acts as a forward
13489   // declaration so we always pass true to setObjectOfFriendDecl to make
13490   // the tag name visible.
13491   if (TUK == TUK_Friend)
13492     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13493
13494   // Set the access specifier.
13495   if (!Invalid && SearchDC->isRecord())
13496     SetMemberAccessSpecifier(New, PrevDecl, AS);
13497
13498   if (TUK == TUK_Definition)
13499     New->startDefinition();
13500
13501   // If this has an identifier, add it to the scope stack.
13502   if (TUK == TUK_Friend) {
13503     // We might be replacing an existing declaration in the lookup tables;
13504     // if so, borrow its access specifier.
13505     if (PrevDecl)
13506       New->setAccess(PrevDecl->getAccess());
13507
13508     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13509     DC->makeDeclVisibleInContext(New);
13510     if (Name) // can be null along some error paths
13511       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13512         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13513   } else if (Name) {
13514     S = getNonFieldDeclScope(S);
13515     PushOnScopeChains(New, S, !IsForwardReference);
13516     if (IsForwardReference)
13517       SearchDC->makeDeclVisibleInContext(New);
13518   } else {
13519     CurContext->addDecl(New);
13520   }
13521
13522   // If this is the C FILE type, notify the AST context.
13523   if (IdentifierInfo *II = New->getIdentifier())
13524     if (!New->isInvalidDecl() &&
13525         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13526         II->isStr("FILE"))
13527       Context.setFILEDecl(New);
13528
13529   if (PrevDecl)
13530     mergeDeclAttributes(New, PrevDecl);
13531
13532   // If there's a #pragma GCC visibility in scope, set the visibility of this
13533   // record.
13534   AddPushedVisibilityAttribute(New);
13535
13536   OwnedDecl = true;
13537   // In C++, don't return an invalid declaration. We can't recover well from
13538   // the cases where we make the type anonymous.
13539   if (Invalid && getLangOpts().CPlusPlus) {
13540     if (New->isBeingDefined())
13541       if (auto RD = dyn_cast<RecordDecl>(New))
13542         RD->completeDefinition();
13543     return nullptr;
13544   } else {
13545     return New;
13546   }
13547 }
13548
13549 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13550   AdjustDeclIfTemplate(TagD);
13551   TagDecl *Tag = cast<TagDecl>(TagD);
13552
13553   // Enter the tag context.
13554   PushDeclContext(S, Tag);
13555
13556   ActOnDocumentableDecl(TagD);
13557
13558   // If there's a #pragma GCC visibility in scope, set the visibility of this
13559   // record.
13560   AddPushedVisibilityAttribute(Tag);
13561 }
13562
13563 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13564   assert(isa<ObjCContainerDecl>(IDecl) &&
13565          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13566   DeclContext *OCD = cast<DeclContext>(IDecl);
13567   assert(getContainingDC(OCD) == CurContext &&
13568       "The next DeclContext should be lexically contained in the current one.");
13569   CurContext = OCD;
13570   return IDecl;
13571 }
13572
13573 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13574                                            SourceLocation FinalLoc,
13575                                            bool IsFinalSpelledSealed,
13576                                            SourceLocation LBraceLoc) {
13577   AdjustDeclIfTemplate(TagD);
13578   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13579
13580   FieldCollector->StartClass();
13581
13582   if (!Record->getIdentifier())
13583     return;
13584
13585   if (FinalLoc.isValid())
13586     Record->addAttr(new (Context)
13587                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13588
13589   // C++ [class]p2:
13590   //   [...] The class-name is also inserted into the scope of the
13591   //   class itself; this is known as the injected-class-name. For
13592   //   purposes of access checking, the injected-class-name is treated
13593   //   as if it were a public member name.
13594   CXXRecordDecl *InjectedClassName
13595     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13596                             Record->getLocStart(), Record->getLocation(),
13597                             Record->getIdentifier(),
13598                             /*PrevDecl=*/nullptr,
13599                             /*DelayTypeCreation=*/true);
13600   Context.getTypeDeclType(InjectedClassName, Record);
13601   InjectedClassName->setImplicit();
13602   InjectedClassName->setAccess(AS_public);
13603   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13604       InjectedClassName->setDescribedClassTemplate(Template);
13605   PushOnScopeChains(InjectedClassName, S);
13606   assert(InjectedClassName->isInjectedClassName() &&
13607          "Broken injected-class-name");
13608 }
13609
13610 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13611                                     SourceRange BraceRange) {
13612   AdjustDeclIfTemplate(TagD);
13613   TagDecl *Tag = cast<TagDecl>(TagD);
13614   Tag->setBraceRange(BraceRange);
13615
13616   // Make sure we "complete" the definition even it is invalid.
13617   if (Tag->isBeingDefined()) {
13618     assert(Tag->isInvalidDecl() && "We should already have completed it");
13619     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13620       RD->completeDefinition();
13621   }
13622
13623   if (isa<CXXRecordDecl>(Tag))
13624     FieldCollector->FinishClass();
13625
13626   // Exit this scope of this tag's definition.
13627   PopDeclContext();
13628
13629   if (getCurLexicalContext()->isObjCContainer() &&
13630       Tag->getDeclContext()->isFileContext())
13631     Tag->setTopLevelDeclInObjCContainer();
13632
13633   // Notify the consumer that we've defined a tag.
13634   if (!Tag->isInvalidDecl())
13635     Consumer.HandleTagDeclDefinition(Tag);
13636 }
13637
13638 void Sema::ActOnObjCContainerFinishDefinition() {
13639   // Exit this scope of this interface definition.
13640   PopDeclContext();
13641 }
13642
13643 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13644   assert(DC == CurContext && "Mismatch of container contexts");
13645   OriginalLexicalContext = DC;
13646   ActOnObjCContainerFinishDefinition();
13647 }
13648
13649 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13650   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13651   OriginalLexicalContext = nullptr;
13652 }
13653
13654 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13655   AdjustDeclIfTemplate(TagD);
13656   TagDecl *Tag = cast<TagDecl>(TagD);
13657   Tag->setInvalidDecl();
13658
13659   // Make sure we "complete" the definition even it is invalid.
13660   if (Tag->isBeingDefined()) {
13661     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13662       RD->completeDefinition();
13663   }
13664
13665   // We're undoing ActOnTagStartDefinition here, not
13666   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13667   // the FieldCollector.
13668
13669   PopDeclContext();
13670 }
13671
13672 // Note that FieldName may be null for anonymous bitfields.
13673 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13674                                 IdentifierInfo *FieldName,
13675                                 QualType FieldTy, bool IsMsStruct,
13676                                 Expr *BitWidth, bool *ZeroWidth) {
13677   // Default to true; that shouldn't confuse checks for emptiness
13678   if (ZeroWidth)
13679     *ZeroWidth = true;
13680
13681   // C99 6.7.2.1p4 - verify the field type.
13682   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13683   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13684     // Handle incomplete types with specific error.
13685     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13686       return ExprError();
13687     if (FieldName)
13688       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13689         << FieldName << FieldTy << BitWidth->getSourceRange();
13690     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13691       << FieldTy << BitWidth->getSourceRange();
13692   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13693                                              UPPC_BitFieldWidth))
13694     return ExprError();
13695
13696   // If the bit-width is type- or value-dependent, don't try to check
13697   // it now.
13698   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13699     return BitWidth;
13700
13701   llvm::APSInt Value;
13702   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13703   if (ICE.isInvalid())
13704     return ICE;
13705   BitWidth = ICE.get();
13706
13707   if (Value != 0 && ZeroWidth)
13708     *ZeroWidth = false;
13709
13710   // Zero-width bitfield is ok for anonymous field.
13711   if (Value == 0 && FieldName)
13712     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13713
13714   if (Value.isSigned() && Value.isNegative()) {
13715     if (FieldName)
13716       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13717                << FieldName << Value.toString(10);
13718     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13719       << Value.toString(10);
13720   }
13721
13722   if (!FieldTy->isDependentType()) {
13723     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13724     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13725     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13726
13727     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13728     // ABI.
13729     bool CStdConstraintViolation =
13730         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13731     bool MSBitfieldViolation =
13732         Value.ugt(TypeStorageSize) &&
13733         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13734     if (CStdConstraintViolation || MSBitfieldViolation) {
13735       unsigned DiagWidth =
13736           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13737       if (FieldName)
13738         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13739                << FieldName << (unsigned)Value.getZExtValue()
13740                << !CStdConstraintViolation << DiagWidth;
13741
13742       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13743              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13744              << DiagWidth;
13745     }
13746
13747     // Warn on types where the user might conceivably expect to get all
13748     // specified bits as value bits: that's all integral types other than
13749     // 'bool'.
13750     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13751       if (FieldName)
13752         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13753             << FieldName << (unsigned)Value.getZExtValue()
13754             << (unsigned)TypeWidth;
13755       else
13756         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13757             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13758     }
13759   }
13760
13761   return BitWidth;
13762 }
13763
13764 /// ActOnField - Each field of a C struct/union is passed into this in order
13765 /// to create a FieldDecl object for it.
13766 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13767                        Declarator &D, Expr *BitfieldWidth) {
13768   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13769                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13770                                /*InitStyle=*/ICIS_NoInit, AS_public);
13771   return Res;
13772 }
13773
13774 /// HandleField - Analyze a field of a C struct or a C++ data member.
13775 ///
13776 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13777                              SourceLocation DeclStart,
13778                              Declarator &D, Expr *BitWidth,
13779                              InClassInitStyle InitStyle,
13780                              AccessSpecifier AS) {
13781   if (D.isDecompositionDeclarator()) {
13782     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13783     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13784       << Decomp.getSourceRange();
13785     return nullptr;
13786   }
13787
13788   IdentifierInfo *II = D.getIdentifier();
13789   SourceLocation Loc = DeclStart;
13790   if (II) Loc = D.getIdentifierLoc();
13791
13792   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13793   QualType T = TInfo->getType();
13794   if (getLangOpts().CPlusPlus) {
13795     CheckExtraCXXDefaultArguments(D);
13796
13797     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13798                                         UPPC_DataMemberType)) {
13799       D.setInvalidType();
13800       T = Context.IntTy;
13801       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13802     }
13803   }
13804
13805   // TR 18037 does not allow fields to be declared with address spaces.
13806   if (T.getQualifiers().hasAddressSpace()) {
13807     Diag(Loc, diag::err_field_with_address_space);
13808     D.setInvalidType();
13809   }
13810
13811   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13812   // used as structure or union field: image, sampler, event or block types.
13813   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13814                           T->isSamplerT() || T->isBlockPointerType())) {
13815     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13816     D.setInvalidType();
13817   }
13818
13819   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13820
13821   if (D.getDeclSpec().isInlineSpecified())
13822     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13823         << getLangOpts().CPlusPlus1z;
13824   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13825     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13826          diag::err_invalid_thread)
13827       << DeclSpec::getSpecifierName(TSCS);
13828
13829   // Check to see if this name was declared as a member previously
13830   NamedDecl *PrevDecl = nullptr;
13831   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13832   LookupName(Previous, S);
13833   switch (Previous.getResultKind()) {
13834     case LookupResult::Found:
13835     case LookupResult::FoundUnresolvedValue:
13836       PrevDecl = Previous.getAsSingle<NamedDecl>();
13837       break;
13838
13839     case LookupResult::FoundOverloaded:
13840       PrevDecl = Previous.getRepresentativeDecl();
13841       break;
13842
13843     case LookupResult::NotFound:
13844     case LookupResult::NotFoundInCurrentInstantiation:
13845     case LookupResult::Ambiguous:
13846       break;
13847   }
13848   Previous.suppressDiagnostics();
13849
13850   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13851     // Maybe we will complain about the shadowed template parameter.
13852     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13853     // Just pretend that we didn't see the previous declaration.
13854     PrevDecl = nullptr;
13855   }
13856
13857   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13858     PrevDecl = nullptr;
13859
13860   bool Mutable
13861     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13862   SourceLocation TSSL = D.getLocStart();
13863   FieldDecl *NewFD
13864     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13865                      TSSL, AS, PrevDecl, &D);
13866
13867   if (NewFD->isInvalidDecl())
13868     Record->setInvalidDecl();
13869
13870   if (D.getDeclSpec().isModulePrivateSpecified())
13871     NewFD->setModulePrivate();
13872
13873   if (NewFD->isInvalidDecl() && PrevDecl) {
13874     // Don't introduce NewFD into scope; there's already something
13875     // with the same name in the same scope.
13876   } else if (II) {
13877     PushOnScopeChains(NewFD, S);
13878   } else
13879     Record->addDecl(NewFD);
13880
13881   return NewFD;
13882 }
13883
13884 /// \brief Build a new FieldDecl and check its well-formedness.
13885 ///
13886 /// This routine builds a new FieldDecl given the fields name, type,
13887 /// record, etc. \p PrevDecl should refer to any previous declaration
13888 /// with the same name and in the same scope as the field to be
13889 /// created.
13890 ///
13891 /// \returns a new FieldDecl.
13892 ///
13893 /// \todo The Declarator argument is a hack. It will be removed once
13894 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13895                                 TypeSourceInfo *TInfo,
13896                                 RecordDecl *Record, SourceLocation Loc,
13897                                 bool Mutable, Expr *BitWidth,
13898                                 InClassInitStyle InitStyle,
13899                                 SourceLocation TSSL,
13900                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13901                                 Declarator *D) {
13902   IdentifierInfo *II = Name.getAsIdentifierInfo();
13903   bool InvalidDecl = false;
13904   if (D) InvalidDecl = D->isInvalidType();
13905
13906   // If we receive a broken type, recover by assuming 'int' and
13907   // marking this declaration as invalid.
13908   if (T.isNull()) {
13909     InvalidDecl = true;
13910     T = Context.IntTy;
13911   }
13912
13913   QualType EltTy = Context.getBaseElementType(T);
13914   if (!EltTy->isDependentType()) {
13915     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13916       // Fields of incomplete type force their record to be invalid.
13917       Record->setInvalidDecl();
13918       InvalidDecl = true;
13919     } else {
13920       NamedDecl *Def;
13921       EltTy->isIncompleteType(&Def);
13922       if (Def && Def->isInvalidDecl()) {
13923         Record->setInvalidDecl();
13924         InvalidDecl = true;
13925       }
13926     }
13927   }
13928
13929   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13930   if (BitWidth && getLangOpts().OpenCL) {
13931     Diag(Loc, diag::err_opencl_bitfields);
13932     InvalidDecl = true;
13933   }
13934
13935   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13936   // than a variably modified type.
13937   if (!InvalidDecl && T->isVariablyModifiedType()) {
13938     bool SizeIsNegative;
13939     llvm::APSInt Oversized;
13940
13941     TypeSourceInfo *FixedTInfo =
13942       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13943                                                     SizeIsNegative,
13944                                                     Oversized);
13945     if (FixedTInfo) {
13946       Diag(Loc, diag::warn_illegal_constant_array_size);
13947       TInfo = FixedTInfo;
13948       T = FixedTInfo->getType();
13949     } else {
13950       if (SizeIsNegative)
13951         Diag(Loc, diag::err_typecheck_negative_array_size);
13952       else if (Oversized.getBoolValue())
13953         Diag(Loc, diag::err_array_too_large)
13954           << Oversized.toString(10);
13955       else
13956         Diag(Loc, diag::err_typecheck_field_variable_size);
13957       InvalidDecl = true;
13958     }
13959   }
13960
13961   // Fields can not have abstract class types
13962   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13963                                              diag::err_abstract_type_in_decl,
13964                                              AbstractFieldType))
13965     InvalidDecl = true;
13966
13967   bool ZeroWidth = false;
13968   if (InvalidDecl)
13969     BitWidth = nullptr;
13970   // If this is declared as a bit-field, check the bit-field.
13971   if (BitWidth) {
13972     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13973                               &ZeroWidth).get();
13974     if (!BitWidth) {
13975       InvalidDecl = true;
13976       BitWidth = nullptr;
13977       ZeroWidth = false;
13978     }
13979   }
13980
13981   // Check that 'mutable' is consistent with the type of the declaration.
13982   if (!InvalidDecl && Mutable) {
13983     unsigned DiagID = 0;
13984     if (T->isReferenceType())
13985       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13986                                         : diag::err_mutable_reference;
13987     else if (T.isConstQualified())
13988       DiagID = diag::err_mutable_const;
13989
13990     if (DiagID) {
13991       SourceLocation ErrLoc = Loc;
13992       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13993         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13994       Diag(ErrLoc, DiagID);
13995       if (DiagID != diag::ext_mutable_reference) {
13996         Mutable = false;
13997         InvalidDecl = true;
13998       }
13999     }
14000   }
14001
14002   // C++11 [class.union]p8 (DR1460):
14003   //   At most one variant member of a union may have a
14004   //   brace-or-equal-initializer.
14005   if (InitStyle != ICIS_NoInit)
14006     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14007
14008   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14009                                        BitWidth, Mutable, InitStyle);
14010   if (InvalidDecl)
14011     NewFD->setInvalidDecl();
14012
14013   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14014     Diag(Loc, diag::err_duplicate_member) << II;
14015     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14016     NewFD->setInvalidDecl();
14017   }
14018
14019   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14020     if (Record->isUnion()) {
14021       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14022         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14023         if (RDecl->getDefinition()) {
14024           // C++ [class.union]p1: An object of a class with a non-trivial
14025           // constructor, a non-trivial copy constructor, a non-trivial
14026           // destructor, or a non-trivial copy assignment operator
14027           // cannot be a member of a union, nor can an array of such
14028           // objects.
14029           if (CheckNontrivialField(NewFD))
14030             NewFD->setInvalidDecl();
14031         }
14032       }
14033
14034       // C++ [class.union]p1: If a union contains a member of reference type,
14035       // the program is ill-formed, except when compiling with MSVC extensions
14036       // enabled.
14037       if (EltTy->isReferenceType()) {
14038         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14039                                     diag::ext_union_member_of_reference_type :
14040                                     diag::err_union_member_of_reference_type)
14041           << NewFD->getDeclName() << EltTy;
14042         if (!getLangOpts().MicrosoftExt)
14043           NewFD->setInvalidDecl();
14044       }
14045     }
14046   }
14047
14048   // FIXME: We need to pass in the attributes given an AST
14049   // representation, not a parser representation.
14050   if (D) {
14051     // FIXME: The current scope is almost... but not entirely... correct here.
14052     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14053
14054     if (NewFD->hasAttrs())
14055       CheckAlignasUnderalignment(NewFD);
14056   }
14057
14058   // In auto-retain/release, infer strong retension for fields of
14059   // retainable type.
14060   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14061     NewFD->setInvalidDecl();
14062
14063   if (T.isObjCGCWeak())
14064     Diag(Loc, diag::warn_attribute_weak_on_field);
14065
14066   NewFD->setAccess(AS);
14067   return NewFD;
14068 }
14069
14070 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14071   assert(FD);
14072   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14073
14074   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14075     return false;
14076
14077   QualType EltTy = Context.getBaseElementType(FD->getType());
14078   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14079     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14080     if (RDecl->getDefinition()) {
14081       // We check for copy constructors before constructors
14082       // because otherwise we'll never get complaints about
14083       // copy constructors.
14084
14085       CXXSpecialMember member = CXXInvalid;
14086       // We're required to check for any non-trivial constructors. Since the
14087       // implicit default constructor is suppressed if there are any
14088       // user-declared constructors, we just need to check that there is a
14089       // trivial default constructor and a trivial copy constructor. (We don't
14090       // worry about move constructors here, since this is a C++98 check.)
14091       if (RDecl->hasNonTrivialCopyConstructor())
14092         member = CXXCopyConstructor;
14093       else if (!RDecl->hasTrivialDefaultConstructor())
14094         member = CXXDefaultConstructor;
14095       else if (RDecl->hasNonTrivialCopyAssignment())
14096         member = CXXCopyAssignment;
14097       else if (RDecl->hasNonTrivialDestructor())
14098         member = CXXDestructor;
14099
14100       if (member != CXXInvalid) {
14101         if (!getLangOpts().CPlusPlus11 &&
14102             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14103           // Objective-C++ ARC: it is an error to have a non-trivial field of
14104           // a union. However, system headers in Objective-C programs
14105           // occasionally have Objective-C lifetime objects within unions,
14106           // and rather than cause the program to fail, we make those
14107           // members unavailable.
14108           SourceLocation Loc = FD->getLocation();
14109           if (getSourceManager().isInSystemHeader(Loc)) {
14110             if (!FD->hasAttr<UnavailableAttr>())
14111               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14112                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14113             return false;
14114           }
14115         }
14116
14117         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14118                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14119                diag::err_illegal_union_or_anon_struct_member)
14120           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14121         DiagnoseNontrivial(RDecl, member);
14122         return !getLangOpts().CPlusPlus11;
14123       }
14124     }
14125   }
14126
14127   return false;
14128 }
14129
14130 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14131 ///  AST enum value.
14132 static ObjCIvarDecl::AccessControl
14133 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14134   switch (ivarVisibility) {
14135   default: llvm_unreachable("Unknown visitibility kind");
14136   case tok::objc_private: return ObjCIvarDecl::Private;
14137   case tok::objc_public: return ObjCIvarDecl::Public;
14138   case tok::objc_protected: return ObjCIvarDecl::Protected;
14139   case tok::objc_package: return ObjCIvarDecl::Package;
14140   }
14141 }
14142
14143 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14144 /// in order to create an IvarDecl object for it.
14145 Decl *Sema::ActOnIvar(Scope *S,
14146                                 SourceLocation DeclStart,
14147                                 Declarator &D, Expr *BitfieldWidth,
14148                                 tok::ObjCKeywordKind Visibility) {
14149
14150   IdentifierInfo *II = D.getIdentifier();
14151   Expr *BitWidth = (Expr*)BitfieldWidth;
14152   SourceLocation Loc = DeclStart;
14153   if (II) Loc = D.getIdentifierLoc();
14154
14155   // FIXME: Unnamed fields can be handled in various different ways, for
14156   // example, unnamed unions inject all members into the struct namespace!
14157
14158   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14159   QualType T = TInfo->getType();
14160
14161   if (BitWidth) {
14162     // 6.7.2.1p3, 6.7.2.1p4
14163     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14164     if (!BitWidth)
14165       D.setInvalidType();
14166   } else {
14167     // Not a bitfield.
14168
14169     // validate II.
14170
14171   }
14172   if (T->isReferenceType()) {
14173     Diag(Loc, diag::err_ivar_reference_type);
14174     D.setInvalidType();
14175   }
14176   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14177   // than a variably modified type.
14178   else if (T->isVariablyModifiedType()) {
14179     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14180     D.setInvalidType();
14181   }
14182
14183   // Get the visibility (access control) for this ivar.
14184   ObjCIvarDecl::AccessControl ac =
14185     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14186                                         : ObjCIvarDecl::None;
14187   // Must set ivar's DeclContext to its enclosing interface.
14188   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14189   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14190     return nullptr;
14191   ObjCContainerDecl *EnclosingContext;
14192   if (ObjCImplementationDecl *IMPDecl =
14193       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14194     if (LangOpts.ObjCRuntime.isFragile()) {
14195     // Case of ivar declared in an implementation. Context is that of its class.
14196       EnclosingContext = IMPDecl->getClassInterface();
14197       assert(EnclosingContext && "Implementation has no class interface!");
14198     }
14199     else
14200       EnclosingContext = EnclosingDecl;
14201   } else {
14202     if (ObjCCategoryDecl *CDecl =
14203         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14204       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14205         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14206         return nullptr;
14207       }
14208     }
14209     EnclosingContext = EnclosingDecl;
14210   }
14211
14212   // Construct the decl.
14213   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14214                                              DeclStart, Loc, II, T,
14215                                              TInfo, ac, (Expr *)BitfieldWidth);
14216
14217   if (II) {
14218     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14219                                            ForRedeclaration);
14220     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14221         && !isa<TagDecl>(PrevDecl)) {
14222       Diag(Loc, diag::err_duplicate_member) << II;
14223       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14224       NewID->setInvalidDecl();
14225     }
14226   }
14227
14228   // Process attributes attached to the ivar.
14229   ProcessDeclAttributes(S, NewID, D);
14230
14231   if (D.isInvalidType())
14232     NewID->setInvalidDecl();
14233
14234   // In ARC, infer 'retaining' for ivars of retainable type.
14235   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14236     NewID->setInvalidDecl();
14237
14238   if (D.getDeclSpec().isModulePrivateSpecified())
14239     NewID->setModulePrivate();
14240
14241   if (II) {
14242     // FIXME: When interfaces are DeclContexts, we'll need to add
14243     // these to the interface.
14244     S->AddDecl(NewID);
14245     IdResolver.AddDecl(NewID);
14246   }
14247
14248   if (LangOpts.ObjCRuntime.isNonFragile() &&
14249       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14250     Diag(Loc, diag::warn_ivars_in_interface);
14251
14252   return NewID;
14253 }
14254
14255 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14256 /// class and class extensions. For every class \@interface and class
14257 /// extension \@interface, if the last ivar is a bitfield of any type,
14258 /// then add an implicit `char :0` ivar to the end of that interface.
14259 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14260                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14261   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14262     return;
14263
14264   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14265   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14266
14267   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14268     return;
14269   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14270   if (!ID) {
14271     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14272       if (!CD->IsClassExtension())
14273         return;
14274     }
14275     // No need to add this to end of @implementation.
14276     else
14277       return;
14278   }
14279   // All conditions are met. Add a new bitfield to the tail end of ivars.
14280   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14281   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14282
14283   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14284                               DeclLoc, DeclLoc, nullptr,
14285                               Context.CharTy,
14286                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14287                                                                DeclLoc),
14288                               ObjCIvarDecl::Private, BW,
14289                               true);
14290   AllIvarDecls.push_back(Ivar);
14291 }
14292
14293 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14294                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14295                        SourceLocation RBrac, AttributeList *Attr) {
14296   assert(EnclosingDecl && "missing record or interface decl");
14297
14298   // If this is an Objective-C @implementation or category and we have
14299   // new fields here we should reset the layout of the interface since
14300   // it will now change.
14301   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14302     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14303     switch (DC->getKind()) {
14304     default: break;
14305     case Decl::ObjCCategory:
14306       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14307       break;
14308     case Decl::ObjCImplementation:
14309       Context.
14310         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14311       break;
14312     }
14313   }
14314
14315   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14316
14317   // Start counting up the number of named members; make sure to include
14318   // members of anonymous structs and unions in the total.
14319   unsigned NumNamedMembers = 0;
14320   if (Record) {
14321     for (const auto *I : Record->decls()) {
14322       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14323         if (IFD->getDeclName())
14324           ++NumNamedMembers;
14325     }
14326   }
14327
14328   // Verify that all the fields are okay.
14329   SmallVector<FieldDecl*, 32> RecFields;
14330
14331   bool ARCErrReported = false;
14332   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14333        i != end; ++i) {
14334     FieldDecl *FD = cast<FieldDecl>(*i);
14335
14336     // Get the type for the field.
14337     const Type *FDTy = FD->getType().getTypePtr();
14338
14339     if (!FD->isAnonymousStructOrUnion()) {
14340       // Remember all fields written by the user.
14341       RecFields.push_back(FD);
14342     }
14343
14344     // If the field is already invalid for some reason, don't emit more
14345     // diagnostics about it.
14346     if (FD->isInvalidDecl()) {
14347       EnclosingDecl->setInvalidDecl();
14348       continue;
14349     }
14350
14351     // C99 6.7.2.1p2:
14352     //   A structure or union shall not contain a member with
14353     //   incomplete or function type (hence, a structure shall not
14354     //   contain an instance of itself, but may contain a pointer to
14355     //   an instance of itself), except that the last member of a
14356     //   structure with more than one named member may have incomplete
14357     //   array type; such a structure (and any union containing,
14358     //   possibly recursively, a member that is such a structure)
14359     //   shall not be a member of a structure or an element of an
14360     //   array.
14361     if (FDTy->isFunctionType()) {
14362       // Field declared as a function.
14363       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14364         << FD->getDeclName();
14365       FD->setInvalidDecl();
14366       EnclosingDecl->setInvalidDecl();
14367       continue;
14368     } else if (FDTy->isIncompleteArrayType() && Record &&
14369                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14370                 ((getLangOpts().MicrosoftExt ||
14371                   getLangOpts().CPlusPlus) &&
14372                  (i + 1 == Fields.end() || Record->isUnion())))) {
14373       // Flexible array member.
14374       // Microsoft and g++ is more permissive regarding flexible array.
14375       // It will accept flexible array in union and also
14376       // as the sole element of a struct/class.
14377       unsigned DiagID = 0;
14378       if (Record->isUnion())
14379         DiagID = getLangOpts().MicrosoftExt
14380                      ? diag::ext_flexible_array_union_ms
14381                      : getLangOpts().CPlusPlus
14382                            ? diag::ext_flexible_array_union_gnu
14383                            : diag::err_flexible_array_union;
14384       else if (NumNamedMembers < 1)
14385         DiagID = getLangOpts().MicrosoftExt
14386                      ? diag::ext_flexible_array_empty_aggregate_ms
14387                      : getLangOpts().CPlusPlus
14388                            ? diag::ext_flexible_array_empty_aggregate_gnu
14389                            : diag::err_flexible_array_empty_aggregate;
14390
14391       if (DiagID)
14392         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14393                                         << Record->getTagKind();
14394       // While the layout of types that contain virtual bases is not specified
14395       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14396       // virtual bases after the derived members.  This would make a flexible
14397       // array member declared at the end of an object not adjacent to the end
14398       // of the type.
14399       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14400         if (RD->getNumVBases() != 0)
14401           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14402             << FD->getDeclName() << Record->getTagKind();
14403       if (!getLangOpts().C99)
14404         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14405           << FD->getDeclName() << Record->getTagKind();
14406
14407       // If the element type has a non-trivial destructor, we would not
14408       // implicitly destroy the elements, so disallow it for now.
14409       //
14410       // FIXME: GCC allows this. We should probably either implicitly delete
14411       // the destructor of the containing class, or just allow this.
14412       QualType BaseElem = Context.getBaseElementType(FD->getType());
14413       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14414         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14415           << FD->getDeclName() << FD->getType();
14416         FD->setInvalidDecl();
14417         EnclosingDecl->setInvalidDecl();
14418         continue;
14419       }
14420       // Okay, we have a legal flexible array member at the end of the struct.
14421       Record->setHasFlexibleArrayMember(true);
14422     } else if (!FDTy->isDependentType() &&
14423                RequireCompleteType(FD->getLocation(), FD->getType(),
14424                                    diag::err_field_incomplete)) {
14425       // Incomplete type
14426       FD->setInvalidDecl();
14427       EnclosingDecl->setInvalidDecl();
14428       continue;
14429     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14430       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14431         // A type which contains a flexible array member is considered to be a
14432         // flexible array member.
14433         Record->setHasFlexibleArrayMember(true);
14434         if (!Record->isUnion()) {
14435           // If this is a struct/class and this is not the last element, reject
14436           // it.  Note that GCC supports variable sized arrays in the middle of
14437           // structures.
14438           if (i + 1 != Fields.end())
14439             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14440               << FD->getDeclName() << FD->getType();
14441           else {
14442             // We support flexible arrays at the end of structs in
14443             // other structs as an extension.
14444             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14445               << FD->getDeclName();
14446           }
14447         }
14448       }
14449       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14450           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14451                                  diag::err_abstract_type_in_decl,
14452                                  AbstractIvarType)) {
14453         // Ivars can not have abstract class types
14454         FD->setInvalidDecl();
14455       }
14456       if (Record && FDTTy->getDecl()->hasObjectMember())
14457         Record->setHasObjectMember(true);
14458       if (Record && FDTTy->getDecl()->hasVolatileMember())
14459         Record->setHasVolatileMember(true);
14460     } else if (FDTy->isObjCObjectType()) {
14461       /// A field cannot be an Objective-c object
14462       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14463         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14464       QualType T = Context.getObjCObjectPointerType(FD->getType());
14465       FD->setType(T);
14466     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14467                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14468       // It's an error in ARC if a field has lifetime.
14469       // We don't want to report this in a system header, though,
14470       // so we just make the field unavailable.
14471       // FIXME: that's really not sufficient; we need to make the type
14472       // itself invalid to, say, initialize or copy.
14473       QualType T = FD->getType();
14474       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14475       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14476         SourceLocation loc = FD->getLocation();
14477         if (getSourceManager().isInSystemHeader(loc)) {
14478           if (!FD->hasAttr<UnavailableAttr>()) {
14479             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14480                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14481           }
14482         } else {
14483           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14484             << T->isBlockPointerType() << Record->getTagKind();
14485         }
14486         ARCErrReported = true;
14487       }
14488     } else if (getLangOpts().ObjC1 &&
14489                getLangOpts().getGC() != LangOptions::NonGC &&
14490                Record && !Record->hasObjectMember()) {
14491       if (FD->getType()->isObjCObjectPointerType() ||
14492           FD->getType().isObjCGCStrong())
14493         Record->setHasObjectMember(true);
14494       else if (Context.getAsArrayType(FD->getType())) {
14495         QualType BaseType = Context.getBaseElementType(FD->getType());
14496         if (BaseType->isRecordType() &&
14497             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14498           Record->setHasObjectMember(true);
14499         else if (BaseType->isObjCObjectPointerType() ||
14500                  BaseType.isObjCGCStrong())
14501                Record->setHasObjectMember(true);
14502       }
14503     }
14504     if (Record && FD->getType().isVolatileQualified())
14505       Record->setHasVolatileMember(true);
14506     // Keep track of the number of named members.
14507     if (FD->getIdentifier())
14508       ++NumNamedMembers;
14509   }
14510
14511   // Okay, we successfully defined 'Record'.
14512   if (Record) {
14513     bool Completed = false;
14514     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14515       if (!CXXRecord->isInvalidDecl()) {
14516         // Set access bits correctly on the directly-declared conversions.
14517         for (CXXRecordDecl::conversion_iterator
14518                I = CXXRecord->conversion_begin(),
14519                E = CXXRecord->conversion_end(); I != E; ++I)
14520           I.setAccess((*I)->getAccess());
14521       }
14522
14523       if (!CXXRecord->isDependentType()) {
14524         if (CXXRecord->hasUserDeclaredDestructor()) {
14525           // Adjust user-defined destructor exception spec.
14526           if (getLangOpts().CPlusPlus11)
14527             AdjustDestructorExceptionSpec(CXXRecord,
14528                                           CXXRecord->getDestructor());
14529         }
14530
14531         if (!CXXRecord->isInvalidDecl()) {
14532           // Add any implicitly-declared members to this class.
14533           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14534
14535           // If we have virtual base classes, we may end up finding multiple
14536           // final overriders for a given virtual function. Check for this
14537           // problem now.
14538           if (CXXRecord->getNumVBases()) {
14539             CXXFinalOverriderMap FinalOverriders;
14540             CXXRecord->getFinalOverriders(FinalOverriders);
14541
14542             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14543                                              MEnd = FinalOverriders.end();
14544                  M != MEnd; ++M) {
14545               for (OverridingMethods::iterator SO = M->second.begin(),
14546                                             SOEnd = M->second.end();
14547                    SO != SOEnd; ++SO) {
14548                 assert(SO->second.size() > 0 &&
14549                        "Virtual function without overridding functions?");
14550                 if (SO->second.size() == 1)
14551                   continue;
14552
14553                 // C++ [class.virtual]p2:
14554                 //   In a derived class, if a virtual member function of a base
14555                 //   class subobject has more than one final overrider the
14556                 //   program is ill-formed.
14557                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14558                   << (const NamedDecl *)M->first << Record;
14559                 Diag(M->first->getLocation(),
14560                      diag::note_overridden_virtual_function);
14561                 for (OverridingMethods::overriding_iterator
14562                           OM = SO->second.begin(),
14563                        OMEnd = SO->second.end();
14564                      OM != OMEnd; ++OM)
14565                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14566                     << (const NamedDecl *)M->first << OM->Method->getParent();
14567
14568                 Record->setInvalidDecl();
14569               }
14570             }
14571             CXXRecord->completeDefinition(&FinalOverriders);
14572             Completed = true;
14573           }
14574         }
14575       }
14576     }
14577
14578     if (!Completed)
14579       Record->completeDefinition();
14580
14581     // We may have deferred checking for a deleted destructor. Check now.
14582     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14583       auto *Dtor = CXXRecord->getDestructor();
14584       if (Dtor && Dtor->isImplicit() &&
14585           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14586         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14587     }
14588
14589     if (Record->hasAttrs()) {
14590       CheckAlignasUnderalignment(Record);
14591
14592       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14593         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14594                                            IA->getRange(), IA->getBestCase(),
14595                                            IA->getSemanticSpelling());
14596     }
14597
14598     // Check if the structure/union declaration is a type that can have zero
14599     // size in C. For C this is a language extension, for C++ it may cause
14600     // compatibility problems.
14601     bool CheckForZeroSize;
14602     if (!getLangOpts().CPlusPlus) {
14603       CheckForZeroSize = true;
14604     } else {
14605       // For C++ filter out types that cannot be referenced in C code.
14606       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14607       CheckForZeroSize =
14608           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14609           !CXXRecord->isDependentType() &&
14610           CXXRecord->isCLike();
14611     }
14612     if (CheckForZeroSize) {
14613       bool ZeroSize = true;
14614       bool IsEmpty = true;
14615       unsigned NonBitFields = 0;
14616       for (RecordDecl::field_iterator I = Record->field_begin(),
14617                                       E = Record->field_end();
14618            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14619         IsEmpty = false;
14620         if (I->isUnnamedBitfield()) {
14621           if (I->getBitWidthValue(Context) > 0)
14622             ZeroSize = false;
14623         } else {
14624           ++NonBitFields;
14625           QualType FieldType = I->getType();
14626           if (FieldType->isIncompleteType() ||
14627               !Context.getTypeSizeInChars(FieldType).isZero())
14628             ZeroSize = false;
14629         }
14630       }
14631
14632       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14633       // allowed in C++, but warn if its declaration is inside
14634       // extern "C" block.
14635       if (ZeroSize) {
14636         Diag(RecLoc, getLangOpts().CPlusPlus ?
14637                          diag::warn_zero_size_struct_union_in_extern_c :
14638                          diag::warn_zero_size_struct_union_compat)
14639           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14640       }
14641
14642       // Structs without named members are extension in C (C99 6.7.2.1p7),
14643       // but are accepted by GCC.
14644       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14645         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14646                                diag::ext_no_named_members_in_struct_union)
14647           << Record->isUnion();
14648       }
14649     }
14650   } else {
14651     ObjCIvarDecl **ClsFields =
14652       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14653     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14654       ID->setEndOfDefinitionLoc(RBrac);
14655       // Add ivar's to class's DeclContext.
14656       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14657         ClsFields[i]->setLexicalDeclContext(ID);
14658         ID->addDecl(ClsFields[i]);
14659       }
14660       // Must enforce the rule that ivars in the base classes may not be
14661       // duplicates.
14662       if (ID->getSuperClass())
14663         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14664     } else if (ObjCImplementationDecl *IMPDecl =
14665                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14666       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14667       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14668         // Ivar declared in @implementation never belongs to the implementation.
14669         // Only it is in implementation's lexical context.
14670         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14671       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14672       IMPDecl->setIvarLBraceLoc(LBrac);
14673       IMPDecl->setIvarRBraceLoc(RBrac);
14674     } else if (ObjCCategoryDecl *CDecl =
14675                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14676       // case of ivars in class extension; all other cases have been
14677       // reported as errors elsewhere.
14678       // FIXME. Class extension does not have a LocEnd field.
14679       // CDecl->setLocEnd(RBrac);
14680       // Add ivar's to class extension's DeclContext.
14681       // Diagnose redeclaration of private ivars.
14682       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14683       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14684         if (IDecl) {
14685           if (const ObjCIvarDecl *ClsIvar =
14686               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14687             Diag(ClsFields[i]->getLocation(),
14688                  diag::err_duplicate_ivar_declaration);
14689             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14690             continue;
14691           }
14692           for (const auto *Ext : IDecl->known_extensions()) {
14693             if (const ObjCIvarDecl *ClsExtIvar
14694                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14695               Diag(ClsFields[i]->getLocation(),
14696                    diag::err_duplicate_ivar_declaration);
14697               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14698               continue;
14699             }
14700           }
14701         }
14702         ClsFields[i]->setLexicalDeclContext(CDecl);
14703         CDecl->addDecl(ClsFields[i]);
14704       }
14705       CDecl->setIvarLBraceLoc(LBrac);
14706       CDecl->setIvarRBraceLoc(RBrac);
14707     }
14708   }
14709
14710   if (Attr)
14711     ProcessDeclAttributeList(S, Record, Attr);
14712 }
14713
14714 /// \brief Determine whether the given integral value is representable within
14715 /// the given type T.
14716 static bool isRepresentableIntegerValue(ASTContext &Context,
14717                                         llvm::APSInt &Value,
14718                                         QualType T) {
14719   assert(T->isIntegralType(Context) && "Integral type required!");
14720   unsigned BitWidth = Context.getIntWidth(T);
14721
14722   if (Value.isUnsigned() || Value.isNonNegative()) {
14723     if (T->isSignedIntegerOrEnumerationType())
14724       --BitWidth;
14725     return Value.getActiveBits() <= BitWidth;
14726   }
14727   return Value.getMinSignedBits() <= BitWidth;
14728 }
14729
14730 // \brief Given an integral type, return the next larger integral type
14731 // (or a NULL type of no such type exists).
14732 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14733   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14734   // enum checking below.
14735   assert(T->isIntegralType(Context) && "Integral type required!");
14736   const unsigned NumTypes = 4;
14737   QualType SignedIntegralTypes[NumTypes] = {
14738     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14739   };
14740   QualType UnsignedIntegralTypes[NumTypes] = {
14741     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14742     Context.UnsignedLongLongTy
14743   };
14744
14745   unsigned BitWidth = Context.getTypeSize(T);
14746   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14747                                                         : UnsignedIntegralTypes;
14748   for (unsigned I = 0; I != NumTypes; ++I)
14749     if (Context.getTypeSize(Types[I]) > BitWidth)
14750       return Types[I];
14751
14752   return QualType();
14753 }
14754
14755 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14756                                           EnumConstantDecl *LastEnumConst,
14757                                           SourceLocation IdLoc,
14758                                           IdentifierInfo *Id,
14759                                           Expr *Val) {
14760   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14761   llvm::APSInt EnumVal(IntWidth);
14762   QualType EltTy;
14763
14764   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14765     Val = nullptr;
14766
14767   if (Val)
14768     Val = DefaultLvalueConversion(Val).get();
14769
14770   if (Val) {
14771     if (Enum->isDependentType() || Val->isTypeDependent())
14772       EltTy = Context.DependentTy;
14773     else {
14774       SourceLocation ExpLoc;
14775       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14776           !getLangOpts().MSVCCompat) {
14777         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14778         // constant-expression in the enumerator-definition shall be a converted
14779         // constant expression of the underlying type.
14780         EltTy = Enum->getIntegerType();
14781         ExprResult Converted =
14782           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14783                                            CCEK_Enumerator);
14784         if (Converted.isInvalid())
14785           Val = nullptr;
14786         else
14787           Val = Converted.get();
14788       } else if (!Val->isValueDependent() &&
14789                  !(Val = VerifyIntegerConstantExpression(Val,
14790                                                          &EnumVal).get())) {
14791         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14792       } else {
14793         if (Enum->isFixed()) {
14794           EltTy = Enum->getIntegerType();
14795
14796           // In Obj-C and Microsoft mode, require the enumeration value to be
14797           // representable in the underlying type of the enumeration. In C++11,
14798           // we perform a non-narrowing conversion as part of converted constant
14799           // expression checking.
14800           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14801             if (getLangOpts().MSVCCompat) {
14802               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14803               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14804             } else
14805               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14806           } else
14807             Val = ImpCastExprToType(Val, EltTy,
14808                                     EltTy->isBooleanType() ?
14809                                     CK_IntegralToBoolean : CK_IntegralCast)
14810                     .get();
14811         } else if (getLangOpts().CPlusPlus) {
14812           // C++11 [dcl.enum]p5:
14813           //   If the underlying type is not fixed, the type of each enumerator
14814           //   is the type of its initializing value:
14815           //     - If an initializer is specified for an enumerator, the
14816           //       initializing value has the same type as the expression.
14817           EltTy = Val->getType();
14818         } else {
14819           // C99 6.7.2.2p2:
14820           //   The expression that defines the value of an enumeration constant
14821           //   shall be an integer constant expression that has a value
14822           //   representable as an int.
14823
14824           // Complain if the value is not representable in an int.
14825           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14826             Diag(IdLoc, diag::ext_enum_value_not_int)
14827               << EnumVal.toString(10) << Val->getSourceRange()
14828               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14829           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14830             // Force the type of the expression to 'int'.
14831             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14832           }
14833           EltTy = Val->getType();
14834         }
14835       }
14836     }
14837   }
14838
14839   if (!Val) {
14840     if (Enum->isDependentType())
14841       EltTy = Context.DependentTy;
14842     else if (!LastEnumConst) {
14843       // C++0x [dcl.enum]p5:
14844       //   If the underlying type is not fixed, the type of each enumerator
14845       //   is the type of its initializing value:
14846       //     - If no initializer is specified for the first enumerator, the
14847       //       initializing value has an unspecified integral type.
14848       //
14849       // GCC uses 'int' for its unspecified integral type, as does
14850       // C99 6.7.2.2p3.
14851       if (Enum->isFixed()) {
14852         EltTy = Enum->getIntegerType();
14853       }
14854       else {
14855         EltTy = Context.IntTy;
14856       }
14857     } else {
14858       // Assign the last value + 1.
14859       EnumVal = LastEnumConst->getInitVal();
14860       ++EnumVal;
14861       EltTy = LastEnumConst->getType();
14862
14863       // Check for overflow on increment.
14864       if (EnumVal < LastEnumConst->getInitVal()) {
14865         // C++0x [dcl.enum]p5:
14866         //   If the underlying type is not fixed, the type of each enumerator
14867         //   is the type of its initializing value:
14868         //
14869         //     - Otherwise the type of the initializing value is the same as
14870         //       the type of the initializing value of the preceding enumerator
14871         //       unless the incremented value is not representable in that type,
14872         //       in which case the type is an unspecified integral type
14873         //       sufficient to contain the incremented value. If no such type
14874         //       exists, the program is ill-formed.
14875         QualType T = getNextLargerIntegralType(Context, EltTy);
14876         if (T.isNull() || Enum->isFixed()) {
14877           // There is no integral type larger enough to represent this
14878           // value. Complain, then allow the value to wrap around.
14879           EnumVal = LastEnumConst->getInitVal();
14880           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14881           ++EnumVal;
14882           if (Enum->isFixed())
14883             // When the underlying type is fixed, this is ill-formed.
14884             Diag(IdLoc, diag::err_enumerator_wrapped)
14885               << EnumVal.toString(10)
14886               << EltTy;
14887           else
14888             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14889               << EnumVal.toString(10);
14890         } else {
14891           EltTy = T;
14892         }
14893
14894         // Retrieve the last enumerator's value, extent that type to the
14895         // type that is supposed to be large enough to represent the incremented
14896         // value, then increment.
14897         EnumVal = LastEnumConst->getInitVal();
14898         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14899         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14900         ++EnumVal;
14901
14902         // If we're not in C++, diagnose the overflow of enumerator values,
14903         // which in C99 means that the enumerator value is not representable in
14904         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14905         // permits enumerator values that are representable in some larger
14906         // integral type.
14907         if (!getLangOpts().CPlusPlus && !T.isNull())
14908           Diag(IdLoc, diag::warn_enum_value_overflow);
14909       } else if (!getLangOpts().CPlusPlus &&
14910                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14911         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14912         Diag(IdLoc, diag::ext_enum_value_not_int)
14913           << EnumVal.toString(10) << 1;
14914       }
14915     }
14916   }
14917
14918   if (!EltTy->isDependentType()) {
14919     // Make the enumerator value match the signedness and size of the
14920     // enumerator's type.
14921     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14922     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14923   }
14924
14925   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14926                                   Val, EnumVal);
14927 }
14928
14929 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14930                                                 SourceLocation IILoc) {
14931   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14932       !getLangOpts().CPlusPlus)
14933     return SkipBodyInfo();
14934
14935   // We have an anonymous enum definition. Look up the first enumerator to
14936   // determine if we should merge the definition with an existing one and
14937   // skip the body.
14938   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14939                                          ForRedeclaration);
14940   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14941   if (!PrevECD)
14942     return SkipBodyInfo();
14943
14944   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14945   NamedDecl *Hidden;
14946   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14947     SkipBodyInfo Skip;
14948     Skip.Previous = Hidden;
14949     return Skip;
14950   }
14951
14952   return SkipBodyInfo();
14953 }
14954
14955 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14956                               SourceLocation IdLoc, IdentifierInfo *Id,
14957                               AttributeList *Attr,
14958                               SourceLocation EqualLoc, Expr *Val) {
14959   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14960   EnumConstantDecl *LastEnumConst =
14961     cast_or_null<EnumConstantDecl>(lastEnumConst);
14962
14963   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14964   // we find one that is.
14965   S = getNonFieldDeclScope(S);
14966
14967   // Verify that there isn't already something declared with this name in this
14968   // scope.
14969   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14970                                          ForRedeclaration);
14971   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14972     // Maybe we will complain about the shadowed template parameter.
14973     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14974     // Just pretend that we didn't see the previous declaration.
14975     PrevDecl = nullptr;
14976   }
14977
14978   // C++ [class.mem]p15:
14979   // If T is the name of a class, then each of the following shall have a name
14980   // different from T:
14981   // - every enumerator of every member of class T that is an unscoped
14982   // enumerated type
14983   if (!TheEnumDecl->isScoped())
14984     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14985                             DeclarationNameInfo(Id, IdLoc));
14986
14987   EnumConstantDecl *New =
14988     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14989   if (!New)
14990     return nullptr;
14991
14992   if (PrevDecl) {
14993     // When in C++, we may get a TagDecl with the same name; in this case the
14994     // enum constant will 'hide' the tag.
14995     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14996            "Received TagDecl when not in C++!");
14997     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14998         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14999       if (isa<EnumConstantDecl>(PrevDecl))
15000         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15001       else
15002         Diag(IdLoc, diag::err_redefinition) << Id;
15003       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15004       return nullptr;
15005     }
15006   }
15007
15008   // Process attributes.
15009   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15010
15011   // Register this decl in the current scope stack.
15012   New->setAccess(TheEnumDecl->getAccess());
15013   PushOnScopeChains(New, S);
15014
15015   ActOnDocumentableDecl(New);
15016
15017   return New;
15018 }
15019
15020 // Returns true when the enum initial expression does not trigger the
15021 // duplicate enum warning.  A few common cases are exempted as follows:
15022 // Element2 = Element1
15023 // Element2 = Element1 + 1
15024 // Element2 = Element1 - 1
15025 // Where Element2 and Element1 are from the same enum.
15026 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15027   Expr *InitExpr = ECD->getInitExpr();
15028   if (!InitExpr)
15029     return true;
15030   InitExpr = InitExpr->IgnoreImpCasts();
15031
15032   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15033     if (!BO->isAdditiveOp())
15034       return true;
15035     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15036     if (!IL)
15037       return true;
15038     if (IL->getValue() != 1)
15039       return true;
15040
15041     InitExpr = BO->getLHS();
15042   }
15043
15044   // This checks if the elements are from the same enum.
15045   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15046   if (!DRE)
15047     return true;
15048
15049   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15050   if (!EnumConstant)
15051     return true;
15052
15053   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15054       Enum)
15055     return true;
15056
15057   return false;
15058 }
15059
15060 namespace {
15061 struct DupKey {
15062   int64_t val;
15063   bool isTombstoneOrEmptyKey;
15064   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15065     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15066 };
15067
15068 static DupKey GetDupKey(const llvm::APSInt& Val) {
15069   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15070                 false);
15071 }
15072
15073 struct DenseMapInfoDupKey {
15074   static DupKey getEmptyKey() { return DupKey(0, true); }
15075   static DupKey getTombstoneKey() { return DupKey(1, true); }
15076   static unsigned getHashValue(const DupKey Key) {
15077     return (unsigned)(Key.val * 37);
15078   }
15079   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15080     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15081            LHS.val == RHS.val;
15082   }
15083 };
15084 } // end anonymous namespace
15085
15086 // Emits a warning when an element is implicitly set a value that
15087 // a previous element has already been set to.
15088 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15089                                         EnumDecl *Enum,
15090                                         QualType EnumType) {
15091   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15092     return;
15093   // Avoid anonymous enums
15094   if (!Enum->getIdentifier())
15095     return;
15096
15097   // Only check for small enums.
15098   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15099     return;
15100
15101   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15102   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15103
15104   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15105   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15106           ValueToVectorMap;
15107
15108   DuplicatesVector DupVector;
15109   ValueToVectorMap EnumMap;
15110
15111   // Populate the EnumMap with all values represented by enum constants without
15112   // an initialier.
15113   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15114     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15115
15116     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15117     // this constant.  Skip this enum since it may be ill-formed.
15118     if (!ECD) {
15119       return;
15120     }
15121
15122     if (ECD->getInitExpr())
15123       continue;
15124
15125     DupKey Key = GetDupKey(ECD->getInitVal());
15126     DeclOrVector &Entry = EnumMap[Key];
15127
15128     // First time encountering this value.
15129     if (Entry.isNull())
15130       Entry = ECD;
15131   }
15132
15133   // Create vectors for any values that has duplicates.
15134   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15135     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15136     if (!ValidDuplicateEnum(ECD, Enum))
15137       continue;
15138
15139     DupKey Key = GetDupKey(ECD->getInitVal());
15140
15141     DeclOrVector& Entry = EnumMap[Key];
15142     if (Entry.isNull())
15143       continue;
15144
15145     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15146       // Ensure constants are different.
15147       if (D == ECD)
15148         continue;
15149
15150       // Create new vector and push values onto it.
15151       ECDVector *Vec = new ECDVector();
15152       Vec->push_back(D);
15153       Vec->push_back(ECD);
15154
15155       // Update entry to point to the duplicates vector.
15156       Entry = Vec;
15157
15158       // Store the vector somewhere we can consult later for quick emission of
15159       // diagnostics.
15160       DupVector.push_back(Vec);
15161       continue;
15162     }
15163
15164     ECDVector *Vec = Entry.get<ECDVector*>();
15165     // Make sure constants are not added more than once.
15166     if (*Vec->begin() == ECD)
15167       continue;
15168
15169     Vec->push_back(ECD);
15170   }
15171
15172   // Emit diagnostics.
15173   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15174                                   DupVectorEnd = DupVector.end();
15175        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15176     ECDVector *Vec = *DupVectorIter;
15177     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15178
15179     // Emit warning for one enum constant.
15180     ECDVector::iterator I = Vec->begin();
15181     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15182       << (*I)->getName() << (*I)->getInitVal().toString(10)
15183       << (*I)->getSourceRange();
15184     ++I;
15185
15186     // Emit one note for each of the remaining enum constants with
15187     // the same value.
15188     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15189       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15190         << (*I)->getName() << (*I)->getInitVal().toString(10)
15191         << (*I)->getSourceRange();
15192     delete Vec;
15193   }
15194 }
15195
15196 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15197                              bool AllowMask) const {
15198   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
15199   assert(ED->isCompleteDefinition() && "expected enum definition");
15200
15201   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15202   llvm::APInt &FlagBits = R.first->second;
15203
15204   if (R.second) {
15205     for (auto *E : ED->enumerators()) {
15206       const auto &EVal = E->getInitVal();
15207       // Only single-bit enumerators introduce new flag values.
15208       if (EVal.isPowerOf2())
15209         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15210     }
15211   }
15212
15213   // A value is in a flag enum if either its bits are a subset of the enum's
15214   // flag bits (the first condition) or we are allowing masks and the same is
15215   // true of its complement (the second condition). When masks are allowed, we
15216   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15217   //
15218   // While it's true that any value could be used as a mask, the assumption is
15219   // that a mask will have all of the insignificant bits set. Anything else is
15220   // likely a logic error.
15221   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15222   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15223 }
15224
15225 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15226                          Decl *EnumDeclX,
15227                          ArrayRef<Decl *> Elements,
15228                          Scope *S, AttributeList *Attr) {
15229   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15230   QualType EnumType = Context.getTypeDeclType(Enum);
15231
15232   if (Attr)
15233     ProcessDeclAttributeList(S, Enum, Attr);
15234
15235   if (Enum->isDependentType()) {
15236     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15237       EnumConstantDecl *ECD =
15238         cast_or_null<EnumConstantDecl>(Elements[i]);
15239       if (!ECD) continue;
15240
15241       ECD->setType(EnumType);
15242     }
15243
15244     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15245     return;
15246   }
15247
15248   // TODO: If the result value doesn't fit in an int, it must be a long or long
15249   // long value.  ISO C does not support this, but GCC does as an extension,
15250   // emit a warning.
15251   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15252   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15253   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15254
15255   // Verify that all the values are okay, compute the size of the values, and
15256   // reverse the list.
15257   unsigned NumNegativeBits = 0;
15258   unsigned NumPositiveBits = 0;
15259
15260   // Keep track of whether all elements have type int.
15261   bool AllElementsInt = true;
15262
15263   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15264     EnumConstantDecl *ECD =
15265       cast_or_null<EnumConstantDecl>(Elements[i]);
15266     if (!ECD) continue;  // Already issued a diagnostic.
15267
15268     const llvm::APSInt &InitVal = ECD->getInitVal();
15269
15270     // Keep track of the size of positive and negative values.
15271     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15272       NumPositiveBits = std::max(NumPositiveBits,
15273                                  (unsigned)InitVal.getActiveBits());
15274     else
15275       NumNegativeBits = std::max(NumNegativeBits,
15276                                  (unsigned)InitVal.getMinSignedBits());
15277
15278     // Keep track of whether every enum element has type int (very commmon).
15279     if (AllElementsInt)
15280       AllElementsInt = ECD->getType() == Context.IntTy;
15281   }
15282
15283   // Figure out the type that should be used for this enum.
15284   QualType BestType;
15285   unsigned BestWidth;
15286
15287   // C++0x N3000 [conv.prom]p3:
15288   //   An rvalue of an unscoped enumeration type whose underlying
15289   //   type is not fixed can be converted to an rvalue of the first
15290   //   of the following types that can represent all the values of
15291   //   the enumeration: int, unsigned int, long int, unsigned long
15292   //   int, long long int, or unsigned long long int.
15293   // C99 6.4.4.3p2:
15294   //   An identifier declared as an enumeration constant has type int.
15295   // The C99 rule is modified by a gcc extension
15296   QualType BestPromotionType;
15297
15298   bool Packed = Enum->hasAttr<PackedAttr>();
15299   // -fshort-enums is the equivalent to specifying the packed attribute on all
15300   // enum definitions.
15301   if (LangOpts.ShortEnums)
15302     Packed = true;
15303
15304   if (Enum->isFixed()) {
15305     BestType = Enum->getIntegerType();
15306     if (BestType->isPromotableIntegerType())
15307       BestPromotionType = Context.getPromotedIntegerType(BestType);
15308     else
15309       BestPromotionType = BestType;
15310
15311     BestWidth = Context.getIntWidth(BestType);
15312   }
15313   else if (NumNegativeBits) {
15314     // If there is a negative value, figure out the smallest integer type (of
15315     // int/long/longlong) that fits.
15316     // If it's packed, check also if it fits a char or a short.
15317     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15318       BestType = Context.SignedCharTy;
15319       BestWidth = CharWidth;
15320     } else if (Packed && NumNegativeBits <= ShortWidth &&
15321                NumPositiveBits < ShortWidth) {
15322       BestType = Context.ShortTy;
15323       BestWidth = ShortWidth;
15324     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15325       BestType = Context.IntTy;
15326       BestWidth = IntWidth;
15327     } else {
15328       BestWidth = Context.getTargetInfo().getLongWidth();
15329
15330       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15331         BestType = Context.LongTy;
15332       } else {
15333         BestWidth = Context.getTargetInfo().getLongLongWidth();
15334
15335         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15336           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15337         BestType = Context.LongLongTy;
15338       }
15339     }
15340     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15341   } else {
15342     // If there is no negative value, figure out the smallest type that fits
15343     // all of the enumerator values.
15344     // If it's packed, check also if it fits a char or a short.
15345     if (Packed && NumPositiveBits <= CharWidth) {
15346       BestType = Context.UnsignedCharTy;
15347       BestPromotionType = Context.IntTy;
15348       BestWidth = CharWidth;
15349     } else if (Packed && NumPositiveBits <= ShortWidth) {
15350       BestType = Context.UnsignedShortTy;
15351       BestPromotionType = Context.IntTy;
15352       BestWidth = ShortWidth;
15353     } else if (NumPositiveBits <= IntWidth) {
15354       BestType = Context.UnsignedIntTy;
15355       BestWidth = IntWidth;
15356       BestPromotionType
15357         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15358                            ? Context.UnsignedIntTy : Context.IntTy;
15359     } else if (NumPositiveBits <=
15360                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15361       BestType = Context.UnsignedLongTy;
15362       BestPromotionType
15363         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15364                            ? Context.UnsignedLongTy : Context.LongTy;
15365     } else {
15366       BestWidth = Context.getTargetInfo().getLongLongWidth();
15367       assert(NumPositiveBits <= BestWidth &&
15368              "How could an initializer get larger than ULL?");
15369       BestType = Context.UnsignedLongLongTy;
15370       BestPromotionType
15371         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15372                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15373     }
15374   }
15375
15376   // Loop over all of the enumerator constants, changing their types to match
15377   // the type of the enum if needed.
15378   for (auto *D : Elements) {
15379     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15380     if (!ECD) continue;  // Already issued a diagnostic.
15381
15382     // Standard C says the enumerators have int type, but we allow, as an
15383     // extension, the enumerators to be larger than int size.  If each
15384     // enumerator value fits in an int, type it as an int, otherwise type it the
15385     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15386     // that X has type 'int', not 'unsigned'.
15387
15388     // Determine whether the value fits into an int.
15389     llvm::APSInt InitVal = ECD->getInitVal();
15390
15391     // If it fits into an integer type, force it.  Otherwise force it to match
15392     // the enum decl type.
15393     QualType NewTy;
15394     unsigned NewWidth;
15395     bool NewSign;
15396     if (!getLangOpts().CPlusPlus &&
15397         !Enum->isFixed() &&
15398         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15399       NewTy = Context.IntTy;
15400       NewWidth = IntWidth;
15401       NewSign = true;
15402     } else if (ECD->getType() == BestType) {
15403       // Already the right type!
15404       if (getLangOpts().CPlusPlus)
15405         // C++ [dcl.enum]p4: Following the closing brace of an
15406         // enum-specifier, each enumerator has the type of its
15407         // enumeration.
15408         ECD->setType(EnumType);
15409       continue;
15410     } else {
15411       NewTy = BestType;
15412       NewWidth = BestWidth;
15413       NewSign = BestType->isSignedIntegerOrEnumerationType();
15414     }
15415
15416     // Adjust the APSInt value.
15417     InitVal = InitVal.extOrTrunc(NewWidth);
15418     InitVal.setIsSigned(NewSign);
15419     ECD->setInitVal(InitVal);
15420
15421     // Adjust the Expr initializer and type.
15422     if (ECD->getInitExpr() &&
15423         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15424       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15425                                                 CK_IntegralCast,
15426                                                 ECD->getInitExpr(),
15427                                                 /*base paths*/ nullptr,
15428                                                 VK_RValue));
15429     if (getLangOpts().CPlusPlus)
15430       // C++ [dcl.enum]p4: Following the closing brace of an
15431       // enum-specifier, each enumerator has the type of its
15432       // enumeration.
15433       ECD->setType(EnumType);
15434     else
15435       ECD->setType(NewTy);
15436   }
15437
15438   Enum->completeDefinition(BestType, BestPromotionType,
15439                            NumPositiveBits, NumNegativeBits);
15440
15441   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15442
15443   if (Enum->hasAttr<FlagEnumAttr>()) {
15444     for (Decl *D : Elements) {
15445       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15446       if (!ECD) continue;  // Already issued a diagnostic.
15447
15448       llvm::APSInt InitVal = ECD->getInitVal();
15449       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15450           !IsValueInFlagEnum(Enum, InitVal, true))
15451         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15452           << ECD << Enum;
15453     }
15454   }
15455
15456   // Now that the enum type is defined, ensure it's not been underaligned.
15457   if (Enum->hasAttrs())
15458     CheckAlignasUnderalignment(Enum);
15459 }
15460
15461 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15462                                   SourceLocation StartLoc,
15463                                   SourceLocation EndLoc) {
15464   StringLiteral *AsmString = cast<StringLiteral>(expr);
15465
15466   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15467                                                    AsmString, StartLoc,
15468                                                    EndLoc);
15469   CurContext->addDecl(New);
15470   return New;
15471 }
15472
15473 static void checkModuleImportContext(Sema &S, Module *M,
15474                                      SourceLocation ImportLoc, DeclContext *DC,
15475                                      bool FromInclude = false) {
15476   SourceLocation ExternCLoc;
15477
15478   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15479     switch (LSD->getLanguage()) {
15480     case LinkageSpecDecl::lang_c:
15481       if (ExternCLoc.isInvalid())
15482         ExternCLoc = LSD->getLocStart();
15483       break;
15484     case LinkageSpecDecl::lang_cxx:
15485       break;
15486     }
15487     DC = LSD->getParent();
15488   }
15489
15490   while (isa<LinkageSpecDecl>(DC))
15491     DC = DC->getParent();
15492
15493   if (!isa<TranslationUnitDecl>(DC)) {
15494     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15495                           ? diag::ext_module_import_not_at_top_level_noop
15496                           : diag::err_module_import_not_at_top_level_fatal)
15497         << M->getFullModuleName() << DC;
15498     S.Diag(cast<Decl>(DC)->getLocStart(),
15499            diag::note_module_import_not_at_top_level) << DC;
15500   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15501     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15502       << M->getFullModuleName();
15503     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15504   }
15505 }
15506
15507 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15508                                            ModuleDeclKind MDK,
15509                                            ModuleIdPath Path) {
15510   // 'module implementation' requires that we are not compiling a module of any
15511   // kind. 'module' and 'module partition' require that we are compiling a
15512   // module inteface (not a module map).
15513   auto CMK = getLangOpts().getCompilingModule();
15514   if (MDK == ModuleDeclKind::Implementation
15515           ? CMK != LangOptions::CMK_None
15516           : CMK != LangOptions::CMK_ModuleInterface) {
15517     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15518       << (unsigned)MDK;
15519     return nullptr;
15520   }
15521
15522   // FIXME: Create a ModuleDecl and return it.
15523
15524   // FIXME: Most of this work should be done by the preprocessor rather than
15525   // here, in case we look ahead across something where the current
15526   // module matters (eg a #include).
15527
15528   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15529   // hierarchical module map modules, the dots here are just another character
15530   // that can appear in a module name. Flatten down to the actual module name.
15531   std::string ModuleName;
15532   for (auto &Piece : Path) {
15533     if (!ModuleName.empty())
15534       ModuleName += ".";
15535     ModuleName += Piece.first->getName();
15536   }
15537
15538   // If a module name was explicitly specified on the command line, it must be
15539   // correct.
15540   if (!getLangOpts().CurrentModule.empty() &&
15541       getLangOpts().CurrentModule != ModuleName) {
15542     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15543         << SourceRange(Path.front().second, Path.back().second)
15544         << getLangOpts().CurrentModule;
15545     return nullptr;
15546   }
15547   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15548
15549   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15550
15551   switch (MDK) {
15552   case ModuleDeclKind::Module: {
15553     // FIXME: Check we're not in a submodule.
15554
15555     // We can't have imported a definition of this module or parsed a module
15556     // map defining it already.
15557     if (auto *M = Map.findModule(ModuleName)) {
15558       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15559       if (M->DefinitionLoc.isValid())
15560         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15561       else if (const auto *FE = M->getASTFile())
15562         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15563             << FE->getName();
15564       return nullptr;
15565     }
15566
15567     // Create a Module for the module that we're defining.
15568     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15569     assert(Mod && "module creation should not fail");
15570
15571     // Enter the semantic scope of the module.
15572     ActOnModuleBegin(ModuleLoc, Mod);
15573     return nullptr;
15574   }
15575
15576   case ModuleDeclKind::Partition:
15577     // FIXME: Check we are in a submodule of the named module.
15578     return nullptr;
15579
15580   case ModuleDeclKind::Implementation:
15581     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15582         PP.getIdentifierInfo(ModuleName), Path[0].second);
15583
15584     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15585     if (Import.isInvalid())
15586       return nullptr;
15587     return ConvertDeclToDeclGroup(Import.get());
15588   }
15589
15590   llvm_unreachable("unexpected module decl kind");
15591 }
15592
15593 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15594                                    SourceLocation ImportLoc,
15595                                    ModuleIdPath Path) {
15596   Module *Mod =
15597       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15598                                    /*IsIncludeDirective=*/false);
15599   if (!Mod)
15600     return true;
15601
15602   VisibleModules.setVisible(Mod, ImportLoc);
15603
15604   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15605
15606   // FIXME: we should support importing a submodule within a different submodule
15607   // of the same top-level module. Until we do, make it an error rather than
15608   // silently ignoring the import.
15609   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15610   // warn on a redundant import of the current module?
15611   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15612       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15613     Diag(ImportLoc, getLangOpts().isCompilingModule()
15614                         ? diag::err_module_self_import
15615                         : diag::err_module_import_in_implementation)
15616         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15617
15618   SmallVector<SourceLocation, 2> IdentifierLocs;
15619   Module *ModCheck = Mod;
15620   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15621     // If we've run out of module parents, just drop the remaining identifiers.
15622     // We need the length to be consistent.
15623     if (!ModCheck)
15624       break;
15625     ModCheck = ModCheck->Parent;
15626
15627     IdentifierLocs.push_back(Path[I].second);
15628   }
15629
15630   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15631   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15632                                           Mod, IdentifierLocs);
15633   if (!ModuleScopes.empty())
15634     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15635   TU->addDecl(Import);
15636   return Import;
15637 }
15638
15639 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15640   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15641   BuildModuleInclude(DirectiveLoc, Mod);
15642 }
15643
15644 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15645   // Determine whether we're in the #include buffer for a module. The #includes
15646   // in that buffer do not qualify as module imports; they're just an
15647   // implementation detail of us building the module.
15648   //
15649   // FIXME: Should we even get ActOnModuleInclude calls for those?
15650   bool IsInModuleIncludes =
15651       TUKind == TU_Module &&
15652       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15653
15654   bool ShouldAddImport = !IsInModuleIncludes;
15655
15656   // If this module import was due to an inclusion directive, create an
15657   // implicit import declaration to capture it in the AST.
15658   if (ShouldAddImport) {
15659     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15660     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15661                                                      DirectiveLoc, Mod,
15662                                                      DirectiveLoc);
15663     if (!ModuleScopes.empty())
15664       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15665     TU->addDecl(ImportD);
15666     Consumer.HandleImplicitImportDecl(ImportD);
15667   }
15668
15669   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15670   VisibleModules.setVisible(Mod, DirectiveLoc);
15671 }
15672
15673 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15674   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15675
15676   ModuleScopes.push_back({});
15677   ModuleScopes.back().Module = Mod;
15678   if (getLangOpts().ModulesLocalVisibility)
15679     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15680
15681   VisibleModules.setVisible(Mod, DirectiveLoc);
15682 }
15683
15684 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15685   if (getLangOpts().ModulesLocalVisibility) {
15686     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15687     // Leaving a module hides namespace names, so our visible namespace cache
15688     // is now out of date.
15689     VisibleNamespaceCache.clear();
15690   }
15691
15692   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15693          "left the wrong module scope");
15694   ModuleScopes.pop_back();
15695
15696   // We got to the end of processing a #include of a local module. Create an
15697   // ImportDecl as we would for an imported module.
15698   FileID File = getSourceManager().getFileID(EofLoc);
15699   assert(File != getSourceManager().getMainFileID() &&
15700          "end of submodule in main source file");
15701   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15702   BuildModuleInclude(DirectiveLoc, Mod);
15703 }
15704
15705 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15706                                                       Module *Mod) {
15707   // Bail if we're not allowed to implicitly import a module here.
15708   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15709     return;
15710
15711   // Create the implicit import declaration.
15712   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15713   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15714                                                    Loc, Mod, Loc);
15715   TU->addDecl(ImportD);
15716   Consumer.HandleImplicitImportDecl(ImportD);
15717
15718   // Make the module visible.
15719   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15720   VisibleModules.setVisible(Mod, Loc);
15721 }
15722
15723 /// We have parsed the start of an export declaration, including the '{'
15724 /// (if present).
15725 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15726                                  SourceLocation LBraceLoc) {
15727   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15728
15729   // C++ Modules TS draft:
15730   //   An export-declaration [...] shall not contain more than one
15731   //   export keyword.
15732   //
15733   // The intent here is that an export-declaration cannot appear within another
15734   // export-declaration.
15735   if (D->isExported())
15736     Diag(ExportLoc, diag::err_export_within_export);
15737
15738   CurContext->addDecl(D);
15739   PushDeclContext(S, D);
15740   return D;
15741 }
15742
15743 /// Complete the definition of an export declaration.
15744 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15745   auto *ED = cast<ExportDecl>(D);
15746   if (RBraceLoc.isValid())
15747     ED->setRBraceLoc(RBraceLoc);
15748
15749   // FIXME: Diagnose export of internal-linkage declaration (including
15750   // anonymous namespace).
15751
15752   PopDeclContext();
15753   return D;
15754 }
15755
15756 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15757                                       IdentifierInfo* AliasName,
15758                                       SourceLocation PragmaLoc,
15759                                       SourceLocation NameLoc,
15760                                       SourceLocation AliasNameLoc) {
15761   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15762                                          LookupOrdinaryName);
15763   AsmLabelAttr *Attr =
15764       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15765
15766   // If a declaration that:
15767   // 1) declares a function or a variable
15768   // 2) has external linkage
15769   // already exists, add a label attribute to it.
15770   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15771     if (isDeclExternC(PrevDecl))
15772       PrevDecl->addAttr(Attr);
15773     else
15774       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15775           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15776   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15777   } else
15778     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15779 }
15780
15781 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15782                              SourceLocation PragmaLoc,
15783                              SourceLocation NameLoc) {
15784   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15785
15786   if (PrevDecl) {
15787     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15788   } else {
15789     (void)WeakUndeclaredIdentifiers.insert(
15790       std::pair<IdentifierInfo*,WeakInfo>
15791         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15792   }
15793 }
15794
15795 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15796                                 IdentifierInfo* AliasName,
15797                                 SourceLocation PragmaLoc,
15798                                 SourceLocation NameLoc,
15799                                 SourceLocation AliasNameLoc) {
15800   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15801                                     LookupOrdinaryName);
15802   WeakInfo W = WeakInfo(Name, NameLoc);
15803
15804   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15805     if (!PrevDecl->hasAttr<AliasAttr>())
15806       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15807         DeclApplyPragmaWeak(TUScope, ND, W);
15808   } else {
15809     (void)WeakUndeclaredIdentifiers.insert(
15810       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15811   }
15812 }
15813
15814 Decl *Sema::getObjCDeclContext() const {
15815   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15816 }