1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
32 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
34 #include "clang/Parse/ParseDiagnostic.h"
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/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 using namespace clang;
50 using namespace sema;
51 
52 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
53   if (OwnedType) {
54     Decl *Group[2] = { OwnedType, Ptr };
55     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
56   }
57 
58   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
59 }
60 
61 namespace {
62 
63 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64  public:
65   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
66                        bool AllowTemplates=false)
67       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
68         AllowClassTemplates(AllowTemplates) {
69     WantExpressionKeywords = false;
70     WantCXXNamedCasts = false;
71     WantRemainingKeywords = false;
72   }
73 
74   bool ValidateCandidate(const TypoCorrection &candidate) override {
75     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
76       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
77       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
78       return (IsType || AllowedTemplate) &&
79              (AllowInvalidDecl || !ND->isInvalidDecl());
80     }
81     return !WantClassName && candidate.isKeyword();
82   }
83 
84  private:
85   bool AllowInvalidDecl;
86   bool WantClassName;
87   bool AllowClassTemplates;
88 };
89 
90 }
91 
92 /// \brief Determine whether the token kind starts a simple-type-specifier.
93 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
94   switch (Kind) {
95   // FIXME: Take into account the current language when deciding whether a
96   // token kind is a valid type specifier
97   case tok::kw_short:
98   case tok::kw_long:
99   case tok::kw___int64:
100   case tok::kw___int128:
101   case tok::kw_signed:
102   case tok::kw_unsigned:
103   case tok::kw_void:
104   case tok::kw_char:
105   case tok::kw_int:
106   case tok::kw_half:
107   case tok::kw_float:
108   case tok::kw_double:
109   case tok::kw_wchar_t:
110   case tok::kw_bool:
111   case tok::kw___underlying_type:
112     return true;
113 
114   case tok::annot_typename:
115   case tok::kw_char16_t:
116   case tok::kw_char32_t:
117   case tok::kw_typeof:
118   case tok::annot_decltype:
119   case tok::kw_decltype:
120     return getLangOpts().CPlusPlus;
121 
122   default:
123     break;
124   }
125 
126   return false;
127 }
128 
129 /// \brief If the identifier refers to a type name within this scope,
130 /// return the declaration of that type.
131 ///
132 /// This routine performs ordinary name lookup of the identifier II
133 /// within the given scope, with optional C++ scope specifier SS, to
134 /// determine whether the name refers to a type. If so, returns an
135 /// opaque pointer (actually a QualType) corresponding to that
136 /// type. Otherwise, returns NULL.
137 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
138                              Scope *S, CXXScopeSpec *SS,
139                              bool isClassName, bool HasTrailingDot,
140                              ParsedType ObjectTypePtr,
141                              bool IsCtorOrDtorName,
142                              bool WantNontrivialTypeSourceInfo,
143                              IdentifierInfo **CorrectedII) {
144   // Determine where we will perform name lookup.
145   DeclContext *LookupCtx = 0;
146   if (ObjectTypePtr) {
147     QualType ObjectType = ObjectTypePtr.get();
148     if (ObjectType->isRecordType())
149       LookupCtx = computeDeclContext(ObjectType);
150   } else if (SS && SS->isNotEmpty()) {
151     LookupCtx = computeDeclContext(*SS, false);
152 
153     if (!LookupCtx) {
154       if (isDependentScopeSpecifier(*SS)) {
155         // C++ [temp.res]p3:
156         //   A qualified-id that refers to a type and in which the
157         //   nested-name-specifier depends on a template-parameter (14.6.2)
158         //   shall be prefixed by the keyword typename to indicate that the
159         //   qualified-id denotes a type, forming an
160         //   elaborated-type-specifier (7.1.5.3).
161         //
162         // We therefore do not perform any name lookup if the result would
163         // refer to a member of an unknown specialization.
164         if (!isClassName && !IsCtorOrDtorName)
165           return ParsedType();
166 
167         // We know from the grammar that this name refers to a type,
168         // so build a dependent node to describe the type.
169         if (WantNontrivialTypeSourceInfo)
170           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
171 
172         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
173         QualType T =
174           CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
175                             II, NameLoc);
176 
177           return ParsedType::make(T);
178       }
179 
180       return ParsedType();
181     }
182 
183     if (!LookupCtx->isDependentContext() &&
184         RequireCompleteDeclContext(*SS, LookupCtx))
185       return ParsedType();
186   }
187 
188   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
189   // lookup for class-names.
190   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
191                                       LookupOrdinaryName;
192   LookupResult Result(*this, &II, NameLoc, Kind);
193   if (LookupCtx) {
194     // Perform "qualified" name lookup into the declaration context we
195     // computed, which is either the type of the base of a member access
196     // expression or the declaration context associated with a prior
197     // nested-name-specifier.
198     LookupQualifiedName(Result, LookupCtx);
199 
200     if (ObjectTypePtr && Result.empty()) {
201       // C++ [basic.lookup.classref]p3:
202       //   If the unqualified-id is ~type-name, the type-name is looked up
203       //   in the context of the entire postfix-expression. If the type T of
204       //   the object expression is of a class type C, the type-name is also
205       //   looked up in the scope of class C. At least one of the lookups shall
206       //   find a name that refers to (possibly cv-qualified) T.
207       LookupName(Result, S);
208     }
209   } else {
210     // Perform unqualified name lookup.
211     LookupName(Result, S);
212   }
213 
214   NamedDecl *IIDecl = 0;
215   switch (Result.getResultKind()) {
216   case LookupResult::NotFound:
217   case LookupResult::NotFoundInCurrentInstantiation:
218     if (CorrectedII) {
219       TypeNameValidatorCCC Validator(true, isClassName);
220       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
221                                               Kind, S, SS, Validator);
222       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
223       TemplateTy Template;
224       bool MemberOfUnknownSpecialization;
225       UnqualifiedId TemplateName;
226       TemplateName.setIdentifier(NewII, NameLoc);
227       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
228       CXXScopeSpec NewSS, *NewSSPtr = SS;
229       if (SS && NNS) {
230         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
231         NewSSPtr = &NewSS;
232       }
233       if (Correction && (NNS || NewII != &II) &&
234           // Ignore a correction to a template type as the to-be-corrected
235           // identifier is not a template (typo correction for template names
236           // is handled elsewhere).
237           !(getLangOpts().CPlusPlus && NewSSPtr &&
238             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
239                            false, Template, MemberOfUnknownSpecialization))) {
240         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
241                                     isClassName, HasTrailingDot, ObjectTypePtr,
242                                     IsCtorOrDtorName,
243                                     WantNontrivialTypeSourceInfo);
244         if (Ty) {
245           diagnoseTypo(Correction,
246                        PDiag(diag::err_unknown_type_or_class_name_suggest)
247                          << Result.getLookupName() << isClassName);
248           if (SS && NNS)
249             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
250           *CorrectedII = NewII;
251           return Ty;
252         }
253       }
254     }
255     // If typo correction failed or was not performed, fall through
256   case LookupResult::FoundOverloaded:
257   case LookupResult::FoundUnresolvedValue:
258     Result.suppressDiagnostics();
259     return ParsedType();
260 
261   case LookupResult::Ambiguous:
262     // Recover from type-hiding ambiguities by hiding the type.  We'll
263     // do the lookup again when looking for an object, and we can
264     // diagnose the error then.  If we don't do this, then the error
265     // about hiding the type will be immediately followed by an error
266     // that only makes sense if the identifier was treated like a type.
267     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
268       Result.suppressDiagnostics();
269       return ParsedType();
270     }
271 
272     // Look to see if we have a type anywhere in the list of results.
273     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
274          Res != ResEnd; ++Res) {
275       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
276         if (!IIDecl ||
277             (*Res)->getLocation().getRawEncoding() <
278               IIDecl->getLocation().getRawEncoding())
279           IIDecl = *Res;
280       }
281     }
282 
283     if (!IIDecl) {
284       // None of the entities we found is a type, so there is no way
285       // to even assume that the result is a type. In this case, don't
286       // complain about the ambiguity. The parser will either try to
287       // perform this lookup again (e.g., as an object name), which
288       // will produce the ambiguity, or will complain that it expected
289       // a type name.
290       Result.suppressDiagnostics();
291       return ParsedType();
292     }
293 
294     // We found a type within the ambiguous lookup; diagnose the
295     // ambiguity and then return that type. This might be the right
296     // answer, or it might not be, but it suppresses any attempt to
297     // perform the name lookup again.
298     break;
299 
300   case LookupResult::Found:
301     IIDecl = Result.getFoundDecl();
302     break;
303   }
304 
305   assert(IIDecl && "Didn't find decl");
306 
307   QualType T;
308   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
309     DiagnoseUseOfDecl(IIDecl, NameLoc);
310 
311     if (T.isNull())
312       T = Context.getTypeDeclType(TD);
313 
314     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
315     // constructor or destructor name (in such a case, the scope specifier
316     // will be attached to the enclosing Expr or Decl node).
317     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
318       if (WantNontrivialTypeSourceInfo) {
319         // Construct a type with type-source information.
320         TypeLocBuilder Builder;
321         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
322 
323         T = getElaboratedType(ETK_None, *SS, T);
324         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
325         ElabTL.setElaboratedKeywordLoc(SourceLocation());
326         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
327         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
328       } else {
329         T = getElaboratedType(ETK_None, *SS, T);
330       }
331     }
332   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
333     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
334     if (!HasTrailingDot)
335       T = Context.getObjCInterfaceType(IDecl);
336   }
337 
338   if (T.isNull()) {
339     // If it's not plausibly a type, suppress diagnostics.
340     Result.suppressDiagnostics();
341     return ParsedType();
342   }
343   return ParsedType::make(T);
344 }
345 
346 /// isTagName() - This method is called *for error recovery purposes only*
347 /// to determine if the specified name is a valid tag name ("struct foo").  If
348 /// so, this returns the TST for the tag corresponding to it (TST_enum,
349 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
350 /// cases in C where the user forgot to specify the tag.
351 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
352   // Do a tag name lookup in this scope.
353   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
354   LookupName(R, S, false);
355   R.suppressDiagnostics();
356   if (R.getResultKind() == LookupResult::Found)
357     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
358       switch (TD->getTagKind()) {
359       case TTK_Struct: return DeclSpec::TST_struct;
360       case TTK_Interface: return DeclSpec::TST_interface;
361       case TTK_Union:  return DeclSpec::TST_union;
362       case TTK_Class:  return DeclSpec::TST_class;
363       case TTK_Enum:   return DeclSpec::TST_enum;
364       }
365     }
366 
367   return DeclSpec::TST_unspecified;
368 }
369 
370 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
371 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
372 /// then downgrade the missing typename error to a warning.
373 /// This is needed for MSVC compatibility; Example:
374 /// @code
375 /// template<class T> class A {
376 /// public:
377 ///   typedef int TYPE;
378 /// };
379 /// template<class T> class B : public A<T> {
380 /// public:
381 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
382 /// };
383 /// @endcode
384 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
385   if (CurContext->isRecord()) {
386     const Type *Ty = SS->getScopeRep()->getAsType();
387 
388     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
389     for (const auto &Base : RD->bases())
390       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
391         return true;
392     return S->isFunctionPrototypeScope();
393   }
394   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
395 }
396 
397 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
398                                    SourceLocation IILoc,
399                                    Scope *S,
400                                    CXXScopeSpec *SS,
401                                    ParsedType &SuggestedType,
402                                    bool AllowClassTemplates) {
403   // We don't have anything to suggest (yet).
404   SuggestedType = ParsedType();
405 
406   // There may have been a typo in the name of the type. Look up typo
407   // results, in case we have something that we can suggest.
408   TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
409   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
410                                              LookupOrdinaryName, S, SS,
411                                              Validator)) {
412     if (Corrected.isKeyword()) {
413       // We corrected to a keyword.
414       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
415       II = Corrected.getCorrectionAsIdentifierInfo();
416     } else {
417       // We found a similarly-named type or interface; suggest that.
418       if (!SS || !SS->isSet()) {
419         diagnoseTypo(Corrected,
420                      PDiag(diag::err_unknown_typename_suggest) << II);
421       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
422         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
423         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
424                                 II->getName().equals(CorrectedStr);
425         diagnoseTypo(Corrected,
426                      PDiag(diag::err_unknown_nested_typename_suggest)
427                        << II << DC << DroppedSpecifier << SS->getRange());
428       } else {
429         llvm_unreachable("could not have corrected a typo here");
430       }
431 
432       CXXScopeSpec tmpSS;
433       if (Corrected.getCorrectionSpecifier())
434         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
435                           SourceRange(IILoc));
436       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
437                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
438                                   false, ParsedType(),
439                                   /*IsCtorOrDtorName=*/false,
440                                   /*NonTrivialTypeSourceInfo=*/true);
441     }
442     return true;
443   }
444 
445   if (getLangOpts().CPlusPlus) {
446     // See if II is a class template that the user forgot to pass arguments to.
447     UnqualifiedId Name;
448     Name.setIdentifier(II, IILoc);
449     CXXScopeSpec EmptySS;
450     TemplateTy TemplateResult;
451     bool MemberOfUnknownSpecialization;
452     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
453                        Name, ParsedType(), true, TemplateResult,
454                        MemberOfUnknownSpecialization) == TNK_Type_template) {
455       TemplateName TplName = TemplateResult.get();
456       Diag(IILoc, diag::err_template_missing_args) << TplName;
457       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
458         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
459           << TplDecl->getTemplateParameters()->getSourceRange();
460       }
461       return true;
462     }
463   }
464 
465   // FIXME: Should we move the logic that tries to recover from a missing tag
466   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
467 
468   if (!SS || (!SS->isSet() && !SS->isInvalid()))
469     Diag(IILoc, diag::err_unknown_typename) << II;
470   else if (DeclContext *DC = computeDeclContext(*SS, false))
471     Diag(IILoc, diag::err_typename_nested_not_found)
472       << II << DC << SS->getRange();
473   else if (isDependentScopeSpecifier(*SS)) {
474     unsigned DiagID = diag::err_typename_missing;
475     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
476       DiagID = diag::warn_typename_missing;
477 
478     Diag(SS->getRange().getBegin(), DiagID)
479       << SS->getScopeRep() << II->getName()
480       << SourceRange(SS->getRange().getBegin(), IILoc)
481       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
482     SuggestedType = ActOnTypenameType(S, SourceLocation(),
483                                       *SS, *II, IILoc).get();
484   } else {
485     assert(SS && SS->isInvalid() &&
486            "Invalid scope specifier has already been diagnosed");
487   }
488 
489   return true;
490 }
491 
492 /// \brief Determine whether the given result set contains either a type name
493 /// or
494 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
495   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
496                        NextToken.is(tok::less);
497 
498   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
499     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
500       return true;
501 
502     if (CheckTemplate && isa<TemplateDecl>(*I))
503       return true;
504   }
505 
506   return false;
507 }
508 
509 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
510                                     Scope *S, CXXScopeSpec &SS,
511                                     IdentifierInfo *&Name,
512                                     SourceLocation NameLoc) {
513   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
514   SemaRef.LookupParsedName(R, S, &SS);
515   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
516     const char *TagName = 0;
517     const char *FixItTagName = 0;
518     switch (Tag->getTagKind()) {
519       case TTK_Class:
520         TagName = "class";
521         FixItTagName = "class ";
522         break;
523 
524       case TTK_Enum:
525         TagName = "enum";
526         FixItTagName = "enum ";
527         break;
528 
529       case TTK_Struct:
530         TagName = "struct";
531         FixItTagName = "struct ";
532         break;
533 
534       case TTK_Interface:
535         TagName = "__interface";
536         FixItTagName = "__interface ";
537         break;
538 
539       case TTK_Union:
540         TagName = "union";
541         FixItTagName = "union ";
542         break;
543     }
544 
545     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
546       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
547       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
548 
549     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
550          I != IEnd; ++I)
551       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
552         << Name << TagName;
553 
554     // Replace lookup results with just the tag decl.
555     Result.clear(Sema::LookupTagName);
556     SemaRef.LookupParsedName(Result, S, &SS);
557     return true;
558   }
559 
560   return false;
561 }
562 
563 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
564 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
565                                   QualType T, SourceLocation NameLoc) {
566   ASTContext &Context = S.Context;
567 
568   TypeLocBuilder Builder;
569   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
570 
571   T = S.getElaboratedType(ETK_None, SS, T);
572   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
573   ElabTL.setElaboratedKeywordLoc(SourceLocation());
574   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
575   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
576 }
577 
578 Sema::NameClassification Sema::ClassifyName(Scope *S,
579                                             CXXScopeSpec &SS,
580                                             IdentifierInfo *&Name,
581                                             SourceLocation NameLoc,
582                                             const Token &NextToken,
583                                             bool IsAddressOfOperand,
584                                             CorrectionCandidateCallback *CCC) {
585   DeclarationNameInfo NameInfo(Name, NameLoc);
586   ObjCMethodDecl *CurMethod = getCurMethodDecl();
587 
588   if (NextToken.is(tok::coloncolon)) {
589     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
590                                 QualType(), false, SS, 0, false);
591 
592   }
593 
594   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
595   LookupParsedName(Result, S, &SS, !CurMethod);
596 
597   // Perform lookup for Objective-C instance variables (including automatically
598   // synthesized instance variables), if we're in an Objective-C method.
599   // FIXME: This lookup really, really needs to be folded in to the normal
600   // unqualified lookup mechanism.
601   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
602     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
603     if (E.get() || E.isInvalid())
604       return E;
605   }
606 
607   bool SecondTry = false;
608   bool IsFilteredTemplateName = false;
609 
610 Corrected:
611   switch (Result.getResultKind()) {
612   case LookupResult::NotFound:
613     // If an unqualified-id is followed by a '(', then we have a function
614     // call.
615     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
616       // In C++, this is an ADL-only call.
617       // FIXME: Reference?
618       if (getLangOpts().CPlusPlus)
619         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
620 
621       // C90 6.3.2.2:
622       //   If the expression that precedes the parenthesized argument list in a
623       //   function call consists solely of an identifier, and if no
624       //   declaration is visible for this identifier, the identifier is
625       //   implicitly declared exactly as if, in the innermost block containing
626       //   the function call, the declaration
627       //
628       //     extern int identifier ();
629       //
630       //   appeared.
631       //
632       // We also allow this in C99 as an extension.
633       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
634         Result.addDecl(D);
635         Result.resolveKind();
636         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
637       }
638     }
639 
640     // In C, we first see whether there is a tag type by the same name, in
641     // which case it's likely that the user just forget to write "enum",
642     // "struct", or "union".
643     if (!getLangOpts().CPlusPlus && !SecondTry &&
644         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
645       break;
646     }
647 
648     // Perform typo correction to determine if there is another name that is
649     // close to this name.
650     if (!SecondTry && CCC) {
651       SecondTry = true;
652       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
653                                                  Result.getLookupKind(), S,
654                                                  &SS, *CCC)) {
655         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
656         unsigned QualifiedDiag = diag::err_no_member_suggest;
657 
658         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
659         NamedDecl *UnderlyingFirstDecl
660           = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
661         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
662             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
663           UnqualifiedDiag = diag::err_no_template_suggest;
664           QualifiedDiag = diag::err_no_member_template_suggest;
665         } else if (UnderlyingFirstDecl &&
666                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
667                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
668                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
669           UnqualifiedDiag = diag::err_unknown_typename_suggest;
670           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
671         }
672 
673         if (SS.isEmpty()) {
674           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
675         } else {// FIXME: is this even reachable? Test it.
676           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
677           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
678                                   Name->getName().equals(CorrectedStr);
679           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
680                                     << Name << computeDeclContext(SS, false)
681                                     << DroppedSpecifier << SS.getRange());
682         }
683 
684         // Update the name, so that the caller has the new name.
685         Name = Corrected.getCorrectionAsIdentifierInfo();
686 
687         // Typo correction corrected to a keyword.
688         if (Corrected.isKeyword())
689           return Name;
690 
691         // Also update the LookupResult...
692         // FIXME: This should probably go away at some point
693         Result.clear();
694         Result.setLookupName(Corrected.getCorrection());
695         if (FirstDecl)
696           Result.addDecl(FirstDecl);
697 
698         // If we found an Objective-C instance variable, let
699         // LookupInObjCMethod build the appropriate expression to
700         // reference the ivar.
701         // FIXME: This is a gross hack.
702         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
703           Result.clear();
704           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
705           return E;
706         }
707 
708         goto Corrected;
709       }
710     }
711 
712     // We failed to correct; just fall through and let the parser deal with it.
713     Result.suppressDiagnostics();
714     return NameClassification::Unknown();
715 
716   case LookupResult::NotFoundInCurrentInstantiation: {
717     // We performed name lookup into the current instantiation, and there were
718     // dependent bases, so we treat this result the same way as any other
719     // dependent nested-name-specifier.
720 
721     // C++ [temp.res]p2:
722     //   A name used in a template declaration or definition and that is
723     //   dependent on a template-parameter is assumed not to name a type
724     //   unless the applicable name lookup finds a type name or the name is
725     //   qualified by the keyword typename.
726     //
727     // FIXME: If the next token is '<', we might want to ask the parser to
728     // perform some heroics to see if we actually have a
729     // template-argument-list, which would indicate a missing 'template'
730     // keyword here.
731     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
732                                       NameInfo, IsAddressOfOperand,
733                                       /*TemplateArgs=*/0);
734   }
735 
736   case LookupResult::Found:
737   case LookupResult::FoundOverloaded:
738   case LookupResult::FoundUnresolvedValue:
739     break;
740 
741   case LookupResult::Ambiguous:
742     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
743         hasAnyAcceptableTemplateNames(Result)) {
744       // C++ [temp.local]p3:
745       //   A lookup that finds an injected-class-name (10.2) can result in an
746       //   ambiguity in certain cases (for example, if it is found in more than
747       //   one base class). If all of the injected-class-names that are found
748       //   refer to specializations of the same class template, and if the name
749       //   is followed by a template-argument-list, the reference refers to the
750       //   class template itself and not a specialization thereof, and is not
751       //   ambiguous.
752       //
753       // This filtering can make an ambiguous result into an unambiguous one,
754       // so try again after filtering out template names.
755       FilterAcceptableTemplateNames(Result);
756       if (!Result.isAmbiguous()) {
757         IsFilteredTemplateName = true;
758         break;
759       }
760     }
761 
762     // Diagnose the ambiguity and return an error.
763     return NameClassification::Error();
764   }
765 
766   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
767       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
768     // C++ [temp.names]p3:
769     //   After name lookup (3.4) finds that a name is a template-name or that
770     //   an operator-function-id or a literal- operator-id refers to a set of
771     //   overloaded functions any member of which is a function template if
772     //   this is followed by a <, the < is always taken as the delimiter of a
773     //   template-argument-list and never as the less-than operator.
774     if (!IsFilteredTemplateName)
775       FilterAcceptableTemplateNames(Result);
776 
777     if (!Result.empty()) {
778       bool IsFunctionTemplate;
779       bool IsVarTemplate;
780       TemplateName Template;
781       if (Result.end() - Result.begin() > 1) {
782         IsFunctionTemplate = true;
783         Template = Context.getOverloadedTemplateName(Result.begin(),
784                                                      Result.end());
785       } else {
786         TemplateDecl *TD
787           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
788         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
789         IsVarTemplate = isa<VarTemplateDecl>(TD);
790 
791         if (SS.isSet() && !SS.isInvalid())
792           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
793                                                     /*TemplateKeyword=*/false,
794                                                       TD);
795         else
796           Template = TemplateName(TD);
797       }
798 
799       if (IsFunctionTemplate) {
800         // Function templates always go through overload resolution, at which
801         // point we'll perform the various checks (e.g., accessibility) we need
802         // to based on which function we selected.
803         Result.suppressDiagnostics();
804 
805         return NameClassification::FunctionTemplate(Template);
806       }
807 
808       return IsVarTemplate ? NameClassification::VarTemplate(Template)
809                            : NameClassification::TypeTemplate(Template);
810     }
811   }
812 
813   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
814   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
815     DiagnoseUseOfDecl(Type, NameLoc);
816     QualType T = Context.getTypeDeclType(Type);
817     if (SS.isNotEmpty())
818       return buildNestedType(*this, SS, T, NameLoc);
819     return ParsedType::make(T);
820   }
821 
822   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
823   if (!Class) {
824     // FIXME: It's unfortunate that we don't have a Type node for handling this.
825     if (ObjCCompatibleAliasDecl *Alias
826                                 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
827       Class = Alias->getClassInterface();
828   }
829 
830   if (Class) {
831     DiagnoseUseOfDecl(Class, NameLoc);
832 
833     if (NextToken.is(tok::period)) {
834       // Interface. <something> is parsed as a property reference expression.
835       // Just return "unknown" as a fall-through for now.
836       Result.suppressDiagnostics();
837       return NameClassification::Unknown();
838     }
839 
840     QualType T = Context.getObjCInterfaceType(Class);
841     return ParsedType::make(T);
842   }
843 
844   // We can have a type template here if we're classifying a template argument.
845   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
846     return NameClassification::TypeTemplate(
847         TemplateName(cast<TemplateDecl>(FirstDecl)));
848 
849   // Check for a tag type hidden by a non-type decl in a few cases where it
850   // seems likely a type is wanted instead of the non-type that was found.
851   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
852   if ((NextToken.is(tok::identifier) ||
853        (NextIsOp &&
854         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
855       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
856     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
857     DiagnoseUseOfDecl(Type, NameLoc);
858     QualType T = Context.getTypeDeclType(Type);
859     if (SS.isNotEmpty())
860       return buildNestedType(*this, SS, T, NameLoc);
861     return ParsedType::make(T);
862   }
863 
864   if (FirstDecl->isCXXClassMember())
865     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
866 
867   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
868   return BuildDeclarationNameExpr(SS, Result, ADL);
869 }
870 
871 // Determines the context to return to after temporarily entering a
872 // context.  This depends in an unnecessarily complicated way on the
873 // exact ordering of callbacks from the parser.
874 DeclContext *Sema::getContainingDC(DeclContext *DC) {
875 
876   // Functions defined inline within classes aren't parsed until we've
877   // finished parsing the top-level class, so the top-level class is
878   // the context we'll need to return to.
879   // A Lambda call operator whose parent is a class must not be treated
880   // as an inline member function.  A Lambda can be used legally
881   // either as an in-class member initializer or a default argument.  These
882   // are parsed once the class has been marked complete and so the containing
883   // context would be the nested class (when the lambda is defined in one);
884   // If the class is not complete, then the lambda is being used in an
885   // ill-formed fashion (such as to specify the width of a bit-field, or
886   // in an array-bound) - in which case we still want to return the
887   // lexically containing DC (which could be a nested class).
888   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
889     DC = DC->getLexicalParent();
890 
891     // A function not defined within a class will always return to its
892     // lexical context.
893     if (!isa<CXXRecordDecl>(DC))
894       return DC;
895 
896     // A C++ inline method/friend is parsed *after* the topmost class
897     // it was declared in is fully parsed ("complete");  the topmost
898     // class is the context we need to return to.
899     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
900       DC = RD;
901 
902     // Return the declaration context of the topmost class the inline method is
903     // declared in.
904     return DC;
905   }
906 
907   return DC->getLexicalParent();
908 }
909 
910 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
911   assert(getContainingDC(DC) == CurContext &&
912       "The next DeclContext should be lexically contained in the current one.");
913   CurContext = DC;
914   S->setEntity(DC);
915 }
916 
917 void Sema::PopDeclContext() {
918   assert(CurContext && "DeclContext imbalance!");
919 
920   CurContext = getContainingDC(CurContext);
921   assert(CurContext && "Popped translation unit!");
922 }
923 
924 /// EnterDeclaratorContext - Used when we must lookup names in the context
925 /// of a declarator's nested name specifier.
926 ///
927 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
928   // C++0x [basic.lookup.unqual]p13:
929   //   A name used in the definition of a static data member of class
930   //   X (after the qualified-id of the static member) is looked up as
931   //   if the name was used in a member function of X.
932   // C++0x [basic.lookup.unqual]p14:
933   //   If a variable member of a namespace is defined outside of the
934   //   scope of its namespace then any name used in the definition of
935   //   the variable member (after the declarator-id) is looked up as
936   //   if the definition of the variable member occurred in its
937   //   namespace.
938   // Both of these imply that we should push a scope whose context
939   // is the semantic context of the declaration.  We can't use
940   // PushDeclContext here because that context is not necessarily
941   // lexically contained in the current context.  Fortunately,
942   // the containing scope should have the appropriate information.
943 
944   assert(!S->getEntity() && "scope already has entity");
945 
946 #ifndef NDEBUG
947   Scope *Ancestor = S->getParent();
948   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
949   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
950 #endif
951 
952   CurContext = DC;
953   S->setEntity(DC);
954 }
955 
956 void Sema::ExitDeclaratorContext(Scope *S) {
957   assert(S->getEntity() == CurContext && "Context imbalance!");
958 
959   // Switch back to the lexical context.  The safety of this is
960   // enforced by an assert in EnterDeclaratorContext.
961   Scope *Ancestor = S->getParent();
962   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
963   CurContext = Ancestor->getEntity();
964 
965   // We don't need to do anything with the scope, which is going to
966   // disappear.
967 }
968 
969 
970 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
971   // We assume that the caller has already called
972   // ActOnReenterTemplateScope so getTemplatedDecl() works.
973   FunctionDecl *FD = D->getAsFunction();
974   if (!FD)
975     return;
976 
977   // Same implementation as PushDeclContext, but enters the context
978   // from the lexical parent, rather than the top-level class.
979   assert(CurContext == FD->getLexicalParent() &&
980     "The next DeclContext should be lexically contained in the current one.");
981   CurContext = FD;
982   S->setEntity(CurContext);
983 
984   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
985     ParmVarDecl *Param = FD->getParamDecl(P);
986     // If the parameter has an identifier, then add it to the scope
987     if (Param->getIdentifier()) {
988       S->AddDecl(Param);
989       IdResolver.AddDecl(Param);
990     }
991   }
992 }
993 
994 
995 void Sema::ActOnExitFunctionContext() {
996   // Same implementation as PopDeclContext, but returns to the lexical parent,
997   // rather than the top-level class.
998   assert(CurContext && "DeclContext imbalance!");
999   CurContext = CurContext->getLexicalParent();
1000   assert(CurContext && "Popped translation unit!");
1001 }
1002 
1003 
1004 /// \brief Determine whether we allow overloading of the function
1005 /// PrevDecl with another declaration.
1006 ///
1007 /// This routine determines whether overloading is possible, not
1008 /// whether some new function is actually an overload. It will return
1009 /// true in C++ (where we can always provide overloads) or, as an
1010 /// extension, in C when the previous function is already an
1011 /// overloaded function declaration or has the "overloadable"
1012 /// attribute.
1013 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1014                                        ASTContext &Context) {
1015   if (Context.getLangOpts().CPlusPlus)
1016     return true;
1017 
1018   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1019     return true;
1020 
1021   return (Previous.getResultKind() == LookupResult::Found
1022           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1023 }
1024 
1025 /// Add this decl to the scope shadowed decl chains.
1026 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1027   // Move up the scope chain until we find the nearest enclosing
1028   // non-transparent context. The declaration will be introduced into this
1029   // scope.
1030   while (S->getEntity() && S->getEntity()->isTransparentContext())
1031     S = S->getParent();
1032 
1033   // Add scoped declarations into their context, so that they can be
1034   // found later. Declarations without a context won't be inserted
1035   // into any context.
1036   if (AddToContext)
1037     CurContext->addDecl(D);
1038 
1039   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1040   // are function-local declarations.
1041   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1042       !D->getDeclContext()->getRedeclContext()->Equals(
1043         D->getLexicalDeclContext()->getRedeclContext()) &&
1044       !D->getLexicalDeclContext()->isFunctionOrMethod())
1045     return;
1046 
1047   // Template instantiations should also not be pushed into scope.
1048   if (isa<FunctionDecl>(D) &&
1049       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1050     return;
1051 
1052   // If this replaces anything in the current scope,
1053   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1054                                IEnd = IdResolver.end();
1055   for (; I != IEnd; ++I) {
1056     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1057       S->RemoveDecl(*I);
1058       IdResolver.RemoveDecl(*I);
1059 
1060       // Should only need to replace one decl.
1061       break;
1062     }
1063   }
1064 
1065   S->AddDecl(D);
1066 
1067   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1068     // Implicitly-generated labels may end up getting generated in an order that
1069     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1070     // the label at the appropriate place in the identifier chain.
1071     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1072       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1073       if (IDC == CurContext) {
1074         if (!S->isDeclScope(*I))
1075           continue;
1076       } else if (IDC->Encloses(CurContext))
1077         break;
1078     }
1079 
1080     IdResolver.InsertDeclAfter(I, D);
1081   } else {
1082     IdResolver.AddDecl(D);
1083   }
1084 }
1085 
1086 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1087   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1088     TUScope->AddDecl(D);
1089 }
1090 
1091 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1092                          bool AllowInlineNamespace) {
1093   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1094 }
1095 
1096 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1097   DeclContext *TargetDC = DC->getPrimaryContext();
1098   do {
1099     if (DeclContext *ScopeDC = S->getEntity())
1100       if (ScopeDC->getPrimaryContext() == TargetDC)
1101         return S;
1102   } while ((S = S->getParent()));
1103 
1104   return 0;
1105 }
1106 
1107 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1108                                             DeclContext*,
1109                                             ASTContext&);
1110 
1111 /// Filters out lookup results that don't fall within the given scope
1112 /// as determined by isDeclInScope.
1113 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1114                                 bool ConsiderLinkage,
1115                                 bool AllowInlineNamespace) {
1116   LookupResult::Filter F = R.makeFilter();
1117   while (F.hasNext()) {
1118     NamedDecl *D = F.next();
1119 
1120     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1121       continue;
1122 
1123     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1124       continue;
1125 
1126     F.erase();
1127   }
1128 
1129   F.done();
1130 }
1131 
1132 static bool isUsingDecl(NamedDecl *D) {
1133   return isa<UsingShadowDecl>(D) ||
1134          isa<UnresolvedUsingTypenameDecl>(D) ||
1135          isa<UnresolvedUsingValueDecl>(D);
1136 }
1137 
1138 /// Removes using shadow declarations from the lookup results.
1139 static void RemoveUsingDecls(LookupResult &R) {
1140   LookupResult::Filter F = R.makeFilter();
1141   while (F.hasNext())
1142     if (isUsingDecl(F.next()))
1143       F.erase();
1144 
1145   F.done();
1146 }
1147 
1148 /// \brief Check for this common pattern:
1149 /// @code
1150 /// class S {
1151 ///   S(const S&); // DO NOT IMPLEMENT
1152 ///   void operator=(const S&); // DO NOT IMPLEMENT
1153 /// };
1154 /// @endcode
1155 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1156   // FIXME: Should check for private access too but access is set after we get
1157   // the decl here.
1158   if (D->doesThisDeclarationHaveABody())
1159     return false;
1160 
1161   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1162     return CD->isCopyConstructor();
1163   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1164     return Method->isCopyAssignmentOperator();
1165   return false;
1166 }
1167 
1168 // We need this to handle
1169 //
1170 // typedef struct {
1171 //   void *foo() { return 0; }
1172 // } A;
1173 //
1174 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1175 // for example. If 'A', foo will have external linkage. If we have '*A',
1176 // foo will have no linkage. Since we can't know until we get to the end
1177 // of the typedef, this function finds out if D might have non-external linkage.
1178 // Callers should verify at the end of the TU if it D has external linkage or
1179 // not.
1180 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1181   const DeclContext *DC = D->getDeclContext();
1182   while (!DC->isTranslationUnit()) {
1183     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1184       if (!RD->hasNameForLinkage())
1185         return true;
1186     }
1187     DC = DC->getParent();
1188   }
1189 
1190   return !D->isExternallyVisible();
1191 }
1192 
1193 // FIXME: This needs to be refactored; some other isInMainFile users want
1194 // these semantics.
1195 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1196   if (S.TUKind != TU_Complete)
1197     return false;
1198   return S.SourceMgr.isInMainFile(Loc);
1199 }
1200 
1201 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1202   assert(D);
1203 
1204   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1205     return false;
1206 
1207   // Ignore all entities declared within templates, and out-of-line definitions
1208   // of members of class templates.
1209   if (D->getDeclContext()->isDependentContext() ||
1210       D->getLexicalDeclContext()->isDependentContext())
1211     return false;
1212 
1213   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1214     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1215       return false;
1216 
1217     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1218       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1219         return false;
1220     } else {
1221       // 'static inline' functions are defined in headers; don't warn.
1222       if (FD->isInlineSpecified() &&
1223           !isMainFileLoc(*this, FD->getLocation()))
1224         return false;
1225     }
1226 
1227     if (FD->doesThisDeclarationHaveABody() &&
1228         Context.DeclMustBeEmitted(FD))
1229       return false;
1230   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1231     // Constants and utility variables are defined in headers with internal
1232     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1233     // like "inline".)
1234     if (!isMainFileLoc(*this, VD->getLocation()))
1235       return false;
1236 
1237     if (Context.DeclMustBeEmitted(VD))
1238       return false;
1239 
1240     if (VD->isStaticDataMember() &&
1241         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1242       return false;
1243   } else {
1244     return false;
1245   }
1246 
1247   // Only warn for unused decls internal to the translation unit.
1248   return mightHaveNonExternalLinkage(D);
1249 }
1250 
1251 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1252   if (!D)
1253     return;
1254 
1255   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1256     const FunctionDecl *First = FD->getFirstDecl();
1257     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1258       return; // First should already be in the vector.
1259   }
1260 
1261   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1262     const VarDecl *First = VD->getFirstDecl();
1263     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1264       return; // First should already be in the vector.
1265   }
1266 
1267   if (ShouldWarnIfUnusedFileScopedDecl(D))
1268     UnusedFileScopedDecls.push_back(D);
1269 }
1270 
1271 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1272   if (D->isInvalidDecl())
1273     return false;
1274 
1275   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1276       D->hasAttr<ObjCPreciseLifetimeAttr>())
1277     return false;
1278 
1279   if (isa<LabelDecl>(D))
1280     return true;
1281 
1282   // White-list anything that isn't a local variable.
1283   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1284       !D->getDeclContext()->isFunctionOrMethod())
1285     return false;
1286 
1287   // Types of valid local variables should be complete, so this should succeed.
1288   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1289 
1290     // White-list anything with an __attribute__((unused)) type.
1291     QualType Ty = VD->getType();
1292 
1293     // Only look at the outermost level of typedef.
1294     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1295       if (TT->getDecl()->hasAttr<UnusedAttr>())
1296         return false;
1297     }
1298 
1299     // If we failed to complete the type for some reason, or if the type is
1300     // dependent, don't diagnose the variable.
1301     if (Ty->isIncompleteType() || Ty->isDependentType())
1302       return false;
1303 
1304     if (const TagType *TT = Ty->getAs<TagType>()) {
1305       const TagDecl *Tag = TT->getDecl();
1306       if (Tag->hasAttr<UnusedAttr>())
1307         return false;
1308 
1309       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1310         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1311           return false;
1312 
1313         if (const Expr *Init = VD->getInit()) {
1314           if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1315             Init = Cleanups->getSubExpr();
1316           const CXXConstructExpr *Construct =
1317             dyn_cast<CXXConstructExpr>(Init);
1318           if (Construct && !Construct->isElidable()) {
1319             CXXConstructorDecl *CD = Construct->getConstructor();
1320             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1321               return false;
1322           }
1323         }
1324       }
1325     }
1326 
1327     // TODO: __attribute__((unused)) templates?
1328   }
1329 
1330   return true;
1331 }
1332 
1333 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1334                                      FixItHint &Hint) {
1335   if (isa<LabelDecl>(D)) {
1336     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1337                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1338     if (AfterColon.isInvalid())
1339       return;
1340     Hint = FixItHint::CreateRemoval(CharSourceRange::
1341                                     getCharRange(D->getLocStart(), AfterColon));
1342   }
1343   return;
1344 }
1345 
1346 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1347 /// unless they are marked attr(unused).
1348 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1349   FixItHint Hint;
1350   if (!ShouldDiagnoseUnusedDecl(D))
1351     return;
1352 
1353   GenerateFixForUnusedDecl(D, Context, Hint);
1354 
1355   unsigned DiagID;
1356   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1357     DiagID = diag::warn_unused_exception_param;
1358   else if (isa<LabelDecl>(D))
1359     DiagID = diag::warn_unused_label;
1360   else
1361     DiagID = diag::warn_unused_variable;
1362 
1363   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1364 }
1365 
1366 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1367   // Verify that we have no forward references left.  If so, there was a goto
1368   // or address of a label taken, but no definition of it.  Label fwd
1369   // definitions are indicated with a null substmt.
1370   if (L->getStmt() == 0)
1371     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1372 }
1373 
1374 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1375   if (S->decl_empty()) return;
1376   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1377          "Scope shouldn't contain decls!");
1378 
1379   for (auto *TmpD : S->decls()) {
1380     assert(TmpD && "This decl didn't get pushed??");
1381 
1382     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1383     NamedDecl *D = cast<NamedDecl>(TmpD);
1384 
1385     if (!D->getDeclName()) continue;
1386 
1387     // Diagnose unused variables in this scope.
1388     if (!S->hasUnrecoverableErrorOccurred())
1389       DiagnoseUnusedDecl(D);
1390 
1391     // If this was a forward reference to a label, verify it was defined.
1392     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1393       CheckPoppedLabel(LD, *this);
1394 
1395     // Remove this name from our lexical scope.
1396     IdResolver.RemoveDecl(D);
1397   }
1398 }
1399 
1400 /// \brief Look for an Objective-C class in the translation unit.
1401 ///
1402 /// \param Id The name of the Objective-C class we're looking for. If
1403 /// typo-correction fixes this name, the Id will be updated
1404 /// to the fixed name.
1405 ///
1406 /// \param IdLoc The location of the name in the translation unit.
1407 ///
1408 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1409 /// if there is no class with the given name.
1410 ///
1411 /// \returns The declaration of the named Objective-C class, or NULL if the
1412 /// class could not be found.
1413 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1414                                               SourceLocation IdLoc,
1415                                               bool DoTypoCorrection) {
1416   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1417   // creation from this context.
1418   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1419 
1420   if (!IDecl && DoTypoCorrection) {
1421     // Perform typo correction at the given location, but only if we
1422     // find an Objective-C class name.
1423     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1424     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1425                                        LookupOrdinaryName, TUScope, NULL,
1426                                        Validator)) {
1427       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1428       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1429       Id = IDecl->getIdentifier();
1430     }
1431   }
1432   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1433   // This routine must always return a class definition, if any.
1434   if (Def && Def->getDefinition())
1435       Def = Def->getDefinition();
1436   return Def;
1437 }
1438 
1439 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1440 /// from S, where a non-field would be declared. This routine copes
1441 /// with the difference between C and C++ scoping rules in structs and
1442 /// unions. For example, the following code is well-formed in C but
1443 /// ill-formed in C++:
1444 /// @code
1445 /// struct S6 {
1446 ///   enum { BAR } e;
1447 /// };
1448 ///
1449 /// void test_S6() {
1450 ///   struct S6 a;
1451 ///   a.e = BAR;
1452 /// }
1453 /// @endcode
1454 /// For the declaration of BAR, this routine will return a different
1455 /// scope. The scope S will be the scope of the unnamed enumeration
1456 /// within S6. In C++, this routine will return the scope associated
1457 /// with S6, because the enumeration's scope is a transparent
1458 /// context but structures can contain non-field names. In C, this
1459 /// routine will return the translation unit scope, since the
1460 /// enumeration's scope is a transparent context and structures cannot
1461 /// contain non-field names.
1462 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1463   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1464          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1465          (S->isClassScope() && !getLangOpts().CPlusPlus))
1466     S = S->getParent();
1467   return S;
1468 }
1469 
1470 /// \brief Looks up the declaration of "struct objc_super" and
1471 /// saves it for later use in building builtin declaration of
1472 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1473 /// pre-existing declaration exists no action takes place.
1474 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1475                                         IdentifierInfo *II) {
1476   if (!II->isStr("objc_msgSendSuper"))
1477     return;
1478   ASTContext &Context = ThisSema.Context;
1479 
1480   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1481                       SourceLocation(), Sema::LookupTagName);
1482   ThisSema.LookupName(Result, S);
1483   if (Result.getResultKind() == LookupResult::Found)
1484     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1485       Context.setObjCSuperType(Context.getTagDeclType(TD));
1486 }
1487 
1488 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1489 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1490 /// if we're creating this built-in in anticipation of redeclaring the
1491 /// built-in.
1492 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1493                                      Scope *S, bool ForRedeclaration,
1494                                      SourceLocation Loc) {
1495   LookupPredefedObjCSuperType(*this, S, II);
1496 
1497   Builtin::ID BID = (Builtin::ID)bid;
1498 
1499   ASTContext::GetBuiltinTypeError Error;
1500   QualType R = Context.GetBuiltinType(BID, Error);
1501   switch (Error) {
1502   case ASTContext::GE_None:
1503     // Okay
1504     break;
1505 
1506   case ASTContext::GE_Missing_stdio:
1507     if (ForRedeclaration)
1508       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1509         << Context.BuiltinInfo.GetName(BID);
1510     return 0;
1511 
1512   case ASTContext::GE_Missing_setjmp:
1513     if (ForRedeclaration)
1514       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1515         << Context.BuiltinInfo.GetName(BID);
1516     return 0;
1517 
1518   case ASTContext::GE_Missing_ucontext:
1519     if (ForRedeclaration)
1520       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1521         << Context.BuiltinInfo.GetName(BID);
1522     return 0;
1523   }
1524 
1525   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1526     Diag(Loc, diag::ext_implicit_lib_function_decl)
1527       << Context.BuiltinInfo.GetName(BID)
1528       << R;
1529     if (Context.BuiltinInfo.getHeaderName(BID) &&
1530         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1531           != DiagnosticsEngine::Ignored)
1532       Diag(Loc, diag::note_please_include_header)
1533         << Context.BuiltinInfo.getHeaderName(BID)
1534         << Context.BuiltinInfo.GetName(BID);
1535   }
1536 
1537   DeclContext *Parent = Context.getTranslationUnitDecl();
1538   if (getLangOpts().CPlusPlus) {
1539     LinkageSpecDecl *CLinkageDecl =
1540         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1541                                 LinkageSpecDecl::lang_c, false);
1542     CLinkageDecl->setImplicit();
1543     Parent->addDecl(CLinkageDecl);
1544     Parent = CLinkageDecl;
1545   }
1546 
1547   FunctionDecl *New = FunctionDecl::Create(Context,
1548                                            Parent,
1549                                            Loc, Loc, II, R, /*TInfo=*/0,
1550                                            SC_Extern,
1551                                            false,
1552                                            /*hasPrototype=*/true);
1553   New->setImplicit();
1554 
1555   // Create Decl objects for each parameter, adding them to the
1556   // FunctionDecl.
1557   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1558     SmallVector<ParmVarDecl*, 16> Params;
1559     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1560       ParmVarDecl *parm =
1561           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1562                               0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0);
1563       parm->setScopeInfo(0, i);
1564       Params.push_back(parm);
1565     }
1566     New->setParams(Params);
1567   }
1568 
1569   AddKnownFunctionAttributes(New);
1570   RegisterLocallyScopedExternCDecl(New, S);
1571 
1572   // TUScope is the translation-unit scope to insert this function into.
1573   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1574   // relate Scopes to DeclContexts, and probably eliminate CurContext
1575   // entirely, but we're not there yet.
1576   DeclContext *SavedContext = CurContext;
1577   CurContext = Parent;
1578   PushOnScopeChains(New, TUScope);
1579   CurContext = SavedContext;
1580   return New;
1581 }
1582 
1583 /// \brief Filter out any previous declarations that the given declaration
1584 /// should not consider because they are not permitted to conflict, e.g.,
1585 /// because they come from hidden sub-modules and do not refer to the same
1586 /// entity.
1587 static void filterNonConflictingPreviousDecls(ASTContext &context,
1588                                               NamedDecl *decl,
1589                                               LookupResult &previous){
1590   // This is only interesting when modules are enabled.
1591   if (!context.getLangOpts().Modules)
1592     return;
1593 
1594   // Empty sets are uninteresting.
1595   if (previous.empty())
1596     return;
1597 
1598   LookupResult::Filter filter = previous.makeFilter();
1599   while (filter.hasNext()) {
1600     NamedDecl *old = filter.next();
1601 
1602     // Non-hidden declarations are never ignored.
1603     if (!old->isHidden())
1604       continue;
1605 
1606     if (!old->isExternallyVisible())
1607       filter.erase();
1608   }
1609 
1610   filter.done();
1611 }
1612 
1613 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1614   QualType OldType;
1615   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1616     OldType = OldTypedef->getUnderlyingType();
1617   else
1618     OldType = Context.getTypeDeclType(Old);
1619   QualType NewType = New->getUnderlyingType();
1620 
1621   if (NewType->isVariablyModifiedType()) {
1622     // Must not redefine a typedef with a variably-modified type.
1623     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1624     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1625       << Kind << NewType;
1626     if (Old->getLocation().isValid())
1627       Diag(Old->getLocation(), diag::note_previous_definition);
1628     New->setInvalidDecl();
1629     return true;
1630   }
1631 
1632   if (OldType != NewType &&
1633       !OldType->isDependentType() &&
1634       !NewType->isDependentType() &&
1635       !Context.hasSameType(OldType, NewType)) {
1636     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1637     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1638       << Kind << NewType << OldType;
1639     if (Old->getLocation().isValid())
1640       Diag(Old->getLocation(), diag::note_previous_definition);
1641     New->setInvalidDecl();
1642     return true;
1643   }
1644   return false;
1645 }
1646 
1647 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1648 /// same name and scope as a previous declaration 'Old'.  Figure out
1649 /// how to resolve this situation, merging decls or emitting
1650 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1651 ///
1652 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1653   // If the new decl is known invalid already, don't bother doing any
1654   // merging checks.
1655   if (New->isInvalidDecl()) return;
1656 
1657   // Allow multiple definitions for ObjC built-in typedefs.
1658   // FIXME: Verify the underlying types are equivalent!
1659   if (getLangOpts().ObjC1) {
1660     const IdentifierInfo *TypeID = New->getIdentifier();
1661     switch (TypeID->getLength()) {
1662     default: break;
1663     case 2:
1664       {
1665         if (!TypeID->isStr("id"))
1666           break;
1667         QualType T = New->getUnderlyingType();
1668         if (!T->isPointerType())
1669           break;
1670         if (!T->isVoidPointerType()) {
1671           QualType PT = T->getAs<PointerType>()->getPointeeType();
1672           if (!PT->isStructureType())
1673             break;
1674         }
1675         Context.setObjCIdRedefinitionType(T);
1676         // Install the built-in type for 'id', ignoring the current definition.
1677         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1678         return;
1679       }
1680     case 5:
1681       if (!TypeID->isStr("Class"))
1682         break;
1683       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1684       // Install the built-in type for 'Class', ignoring the current definition.
1685       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1686       return;
1687     case 3:
1688       if (!TypeID->isStr("SEL"))
1689         break;
1690       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1691       // Install the built-in type for 'SEL', ignoring the current definition.
1692       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1693       return;
1694     }
1695     // Fall through - the typedef name was not a builtin type.
1696   }
1697 
1698   // Verify the old decl was also a type.
1699   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1700   if (!Old) {
1701     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1702       << New->getDeclName();
1703 
1704     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1705     if (OldD->getLocation().isValid())
1706       Diag(OldD->getLocation(), diag::note_previous_definition);
1707 
1708     return New->setInvalidDecl();
1709   }
1710 
1711   // If the old declaration is invalid, just give up here.
1712   if (Old->isInvalidDecl())
1713     return New->setInvalidDecl();
1714 
1715   // If the typedef types are not identical, reject them in all languages and
1716   // with any extensions enabled.
1717   if (isIncompatibleTypedef(Old, New))
1718     return;
1719 
1720   // The types match.  Link up the redeclaration chain and merge attributes if
1721   // the old declaration was a typedef.
1722   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1723     New->setPreviousDecl(Typedef);
1724     mergeDeclAttributes(New, Old);
1725   }
1726 
1727   if (getLangOpts().MicrosoftExt)
1728     return;
1729 
1730   if (getLangOpts().CPlusPlus) {
1731     // C++ [dcl.typedef]p2:
1732     //   In a given non-class scope, a typedef specifier can be used to
1733     //   redefine the name of any type declared in that scope to refer
1734     //   to the type to which it already refers.
1735     if (!isa<CXXRecordDecl>(CurContext))
1736       return;
1737 
1738     // C++0x [dcl.typedef]p4:
1739     //   In a given class scope, a typedef specifier can be used to redefine
1740     //   any class-name declared in that scope that is not also a typedef-name
1741     //   to refer to the type to which it already refers.
1742     //
1743     // This wording came in via DR424, which was a correction to the
1744     // wording in DR56, which accidentally banned code like:
1745     //
1746     //   struct S {
1747     //     typedef struct A { } A;
1748     //   };
1749     //
1750     // in the C++03 standard. We implement the C++0x semantics, which
1751     // allow the above but disallow
1752     //
1753     //   struct S {
1754     //     typedef int I;
1755     //     typedef int I;
1756     //   };
1757     //
1758     // since that was the intent of DR56.
1759     if (!isa<TypedefNameDecl>(Old))
1760       return;
1761 
1762     Diag(New->getLocation(), diag::err_redefinition)
1763       << New->getDeclName();
1764     Diag(Old->getLocation(), diag::note_previous_definition);
1765     return New->setInvalidDecl();
1766   }
1767 
1768   // Modules always permit redefinition of typedefs, as does C11.
1769   if (getLangOpts().Modules || getLangOpts().C11)
1770     return;
1771 
1772   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1773   // is normally mapped to an error, but can be controlled with
1774   // -Wtypedef-redefinition.  If either the original or the redefinition is
1775   // in a system header, don't emit this for compatibility with GCC.
1776   if (getDiagnostics().getSuppressSystemWarnings() &&
1777       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1778        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1779     return;
1780 
1781   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1782     << New->getDeclName();
1783   Diag(Old->getLocation(), diag::note_previous_definition);
1784   return;
1785 }
1786 
1787 /// DeclhasAttr - returns true if decl Declaration already has the target
1788 /// attribute.
1789 static bool DeclHasAttr(const Decl *D, const Attr *A) {
1790   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1791   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1792   for (const auto *i : D->attrs())
1793     if (i->getKind() == A->getKind()) {
1794       if (Ann) {
1795         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
1796           return true;
1797         continue;
1798       }
1799       // FIXME: Don't hardcode this check
1800       if (OA && isa<OwnershipAttr>(i))
1801         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
1802       return true;
1803     }
1804 
1805   return false;
1806 }
1807 
1808 static bool isAttributeTargetADefinition(Decl *D) {
1809   if (VarDecl *VD = dyn_cast<VarDecl>(D))
1810     return VD->isThisDeclarationADefinition();
1811   if (TagDecl *TD = dyn_cast<TagDecl>(D))
1812     return TD->isCompleteDefinition() || TD->isBeingDefined();
1813   return true;
1814 }
1815 
1816 /// Merge alignment attributes from \p Old to \p New, taking into account the
1817 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1818 ///
1819 /// \return \c true if any attributes were added to \p New.
1820 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1821   // Look for alignas attributes on Old, and pick out whichever attribute
1822   // specifies the strictest alignment requirement.
1823   AlignedAttr *OldAlignasAttr = 0;
1824   AlignedAttr *OldStrictestAlignAttr = 0;
1825   unsigned OldAlign = 0;
1826   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
1827     // FIXME: We have no way of representing inherited dependent alignments
1828     // in a case like:
1829     //   template<int A, int B> struct alignas(A) X;
1830     //   template<int A, int B> struct alignas(B) X {};
1831     // For now, we just ignore any alignas attributes which are not on the
1832     // definition in such a case.
1833     if (I->isAlignmentDependent())
1834       return false;
1835 
1836     if (I->isAlignas())
1837       OldAlignasAttr = I;
1838 
1839     unsigned Align = I->getAlignment(S.Context);
1840     if (Align > OldAlign) {
1841       OldAlign = Align;
1842       OldStrictestAlignAttr = I;
1843     }
1844   }
1845 
1846   // Look for alignas attributes on New.
1847   AlignedAttr *NewAlignasAttr = 0;
1848   unsigned NewAlign = 0;
1849   for (auto *I : New->specific_attrs<AlignedAttr>()) {
1850     if (I->isAlignmentDependent())
1851       return false;
1852 
1853     if (I->isAlignas())
1854       NewAlignasAttr = I;
1855 
1856     unsigned Align = I->getAlignment(S.Context);
1857     if (Align > NewAlign)
1858       NewAlign = Align;
1859   }
1860 
1861   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1862     // Both declarations have 'alignas' attributes. We require them to match.
1863     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1864     // fall short. (If two declarations both have alignas, they must both match
1865     // every definition, and so must match each other if there is a definition.)
1866 
1867     // If either declaration only contains 'alignas(0)' specifiers, then it
1868     // specifies the natural alignment for the type.
1869     if (OldAlign == 0 || NewAlign == 0) {
1870       QualType Ty;
1871       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1872         Ty = VD->getType();
1873       else
1874         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1875 
1876       if (OldAlign == 0)
1877         OldAlign = S.Context.getTypeAlign(Ty);
1878       if (NewAlign == 0)
1879         NewAlign = S.Context.getTypeAlign(Ty);
1880     }
1881 
1882     if (OldAlign != NewAlign) {
1883       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1884         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1885         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1886       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1887     }
1888   }
1889 
1890   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1891     // C++11 [dcl.align]p6:
1892     //   if any declaration of an entity has an alignment-specifier,
1893     //   every defining declaration of that entity shall specify an
1894     //   equivalent alignment.
1895     // C11 6.7.5/7:
1896     //   If the definition of an object does not have an alignment
1897     //   specifier, any other declaration of that object shall also
1898     //   have no alignment specifier.
1899     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1900       << OldAlignasAttr;
1901     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1902       << OldAlignasAttr;
1903   }
1904 
1905   bool AnyAdded = false;
1906 
1907   // Ensure we have an attribute representing the strictest alignment.
1908   if (OldAlign > NewAlign) {
1909     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1910     Clone->setInherited(true);
1911     New->addAttr(Clone);
1912     AnyAdded = true;
1913   }
1914 
1915   // Ensure we have an alignas attribute if the old declaration had one.
1916   if (OldAlignasAttr && !NewAlignasAttr &&
1917       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1918     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1919     Clone->setInherited(true);
1920     New->addAttr(Clone);
1921     AnyAdded = true;
1922   }
1923 
1924   return AnyAdded;
1925 }
1926 
1927 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1928                                bool Override) {
1929   InheritableAttr *NewAttr = NULL;
1930   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1931   if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1932     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1933                                       AA->getIntroduced(), AA->getDeprecated(),
1934                                       AA->getObsoleted(), AA->getUnavailable(),
1935                                       AA->getMessage(), Override,
1936                                       AttrSpellingListIndex);
1937   else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1938     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1939                                     AttrSpellingListIndex);
1940   else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1941     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1942                                         AttrSpellingListIndex);
1943   else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1944     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1945                                    AttrSpellingListIndex);
1946   else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1947     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1948                                    AttrSpellingListIndex);
1949   else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1950     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1951                                 FA->getFormatIdx(), FA->getFirstArg(),
1952                                 AttrSpellingListIndex);
1953   else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1954     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1955                                  AttrSpellingListIndex);
1956   else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr))
1957     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
1958                                        AttrSpellingListIndex,
1959                                        IA->getSemanticSpelling());
1960   else if (isa<AlignedAttr>(Attr))
1961     // AlignedAttrs are handled separately, because we need to handle all
1962     // such attributes on a declaration at the same time.
1963     NewAttr = 0;
1964   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
1965     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
1966 
1967   if (NewAttr) {
1968     NewAttr->setInherited(true);
1969     D->addAttr(NewAttr);
1970     return true;
1971   }
1972 
1973   return false;
1974 }
1975 
1976 static const Decl *getDefinition(const Decl *D) {
1977   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
1978     return TD->getDefinition();
1979   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1980     const VarDecl *Def = VD->getDefinition();
1981     if (Def)
1982       return Def;
1983     return VD->getActingDefinition();
1984   }
1985   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1986     const FunctionDecl* Def;
1987     if (FD->isDefined(Def))
1988       return Def;
1989   }
1990   return NULL;
1991 }
1992 
1993 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
1994   for (const auto *Attribute : D->attrs())
1995     if (Attribute->getKind() == Kind)
1996       return true;
1997   return false;
1998 }
1999 
2000 /// checkNewAttributesAfterDef - If we already have a definition, check that
2001 /// there are no new attributes in this declaration.
2002 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2003   if (!New->hasAttrs())
2004     return;
2005 
2006   const Decl *Def = getDefinition(Old);
2007   if (!Def || Def == New)
2008     return;
2009 
2010   AttrVec &NewAttributes = New->getAttrs();
2011   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2012     const Attr *NewAttribute = NewAttributes[I];
2013 
2014     if (isa<AliasAttr>(NewAttribute)) {
2015       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2016         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2017       else {
2018         VarDecl *VD = cast<VarDecl>(New);
2019         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2020                                 VarDecl::TentativeDefinition
2021                             ? diag::err_alias_after_tentative
2022                             : diag::err_redefinition;
2023         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2024         S.Diag(Def->getLocation(), diag::note_previous_definition);
2025         VD->setInvalidDecl();
2026       }
2027       ++I;
2028       continue;
2029     }
2030 
2031     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2032       // Tentative definitions are only interesting for the alias check above.
2033       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2034         ++I;
2035         continue;
2036       }
2037     }
2038 
2039     if (hasAttribute(Def, NewAttribute->getKind())) {
2040       ++I;
2041       continue; // regular attr merging will take care of validating this.
2042     }
2043 
2044     if (isa<C11NoReturnAttr>(NewAttribute)) {
2045       // C's _Noreturn is allowed to be added to a function after it is defined.
2046       ++I;
2047       continue;
2048     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2049       if (AA->isAlignas()) {
2050         // C++11 [dcl.align]p6:
2051         //   if any declaration of an entity has an alignment-specifier,
2052         //   every defining declaration of that entity shall specify an
2053         //   equivalent alignment.
2054         // C11 6.7.5/7:
2055         //   If the definition of an object does not have an alignment
2056         //   specifier, any other declaration of that object shall also
2057         //   have no alignment specifier.
2058         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2059           << AA;
2060         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2061           << AA;
2062         NewAttributes.erase(NewAttributes.begin() + I);
2063         --E;
2064         continue;
2065       }
2066     }
2067 
2068     S.Diag(NewAttribute->getLocation(),
2069            diag::warn_attribute_precede_definition);
2070     S.Diag(Def->getLocation(), diag::note_previous_definition);
2071     NewAttributes.erase(NewAttributes.begin() + I);
2072     --E;
2073   }
2074 }
2075 
2076 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2077 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2078                                AvailabilityMergeKind AMK) {
2079   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2080     UsedAttr *NewAttr = OldAttr->clone(Context);
2081     NewAttr->setInherited(true);
2082     New->addAttr(NewAttr);
2083   }
2084 
2085   if (!Old->hasAttrs() && !New->hasAttrs())
2086     return;
2087 
2088   // attributes declared post-definition are currently ignored
2089   checkNewAttributesAfterDef(*this, New, Old);
2090 
2091   if (!Old->hasAttrs())
2092     return;
2093 
2094   bool foundAny = New->hasAttrs();
2095 
2096   // Ensure that any moving of objects within the allocated map is done before
2097   // we process them.
2098   if (!foundAny) New->setAttrs(AttrVec());
2099 
2100   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2101     bool Override = false;
2102     // Ignore deprecated/unavailable/availability attributes if requested.
2103     if (isa<DeprecatedAttr>(I) ||
2104         isa<UnavailableAttr>(I) ||
2105         isa<AvailabilityAttr>(I)) {
2106       switch (AMK) {
2107       case AMK_None:
2108         continue;
2109 
2110       case AMK_Redeclaration:
2111         break;
2112 
2113       case AMK_Override:
2114         Override = true;
2115         break;
2116       }
2117     }
2118 
2119     // Already handled.
2120     if (isa<UsedAttr>(I))
2121       continue;
2122 
2123     if (mergeDeclAttribute(*this, New, I, Override))
2124       foundAny = true;
2125   }
2126 
2127   if (mergeAlignedAttrs(*this, New, Old))
2128     foundAny = true;
2129 
2130   if (!foundAny) New->dropAttrs();
2131 }
2132 
2133 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2134 /// to the new one.
2135 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2136                                      const ParmVarDecl *oldDecl,
2137                                      Sema &S) {
2138   // C++11 [dcl.attr.depend]p2:
2139   //   The first declaration of a function shall specify the
2140   //   carries_dependency attribute for its declarator-id if any declaration
2141   //   of the function specifies the carries_dependency attribute.
2142   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2143   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2144     S.Diag(CDA->getLocation(),
2145            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2146     // Find the first declaration of the parameter.
2147     // FIXME: Should we build redeclaration chains for function parameters?
2148     const FunctionDecl *FirstFD =
2149       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2150     const ParmVarDecl *FirstVD =
2151       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2152     S.Diag(FirstVD->getLocation(),
2153            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2154   }
2155 
2156   if (!oldDecl->hasAttrs())
2157     return;
2158 
2159   bool foundAny = newDecl->hasAttrs();
2160 
2161   // Ensure that any moving of objects within the allocated map is
2162   // done before we process them.
2163   if (!foundAny) newDecl->setAttrs(AttrVec());
2164 
2165   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2166     if (!DeclHasAttr(newDecl, I)) {
2167       InheritableAttr *newAttr =
2168         cast<InheritableParamAttr>(I->clone(S.Context));
2169       newAttr->setInherited(true);
2170       newDecl->addAttr(newAttr);
2171       foundAny = true;
2172     }
2173   }
2174 
2175   if (!foundAny) newDecl->dropAttrs();
2176 }
2177 
2178 namespace {
2179 
2180 /// Used in MergeFunctionDecl to keep track of function parameters in
2181 /// C.
2182 struct GNUCompatibleParamWarning {
2183   ParmVarDecl *OldParm;
2184   ParmVarDecl *NewParm;
2185   QualType PromotedType;
2186 };
2187 
2188 }
2189 
2190 /// getSpecialMember - get the special member enum for a method.
2191 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2192   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2193     if (Ctor->isDefaultConstructor())
2194       return Sema::CXXDefaultConstructor;
2195 
2196     if (Ctor->isCopyConstructor())
2197       return Sema::CXXCopyConstructor;
2198 
2199     if (Ctor->isMoveConstructor())
2200       return Sema::CXXMoveConstructor;
2201   } else if (isa<CXXDestructorDecl>(MD)) {
2202     return Sema::CXXDestructor;
2203   } else if (MD->isCopyAssignmentOperator()) {
2204     return Sema::CXXCopyAssignment;
2205   } else if (MD->isMoveAssignmentOperator()) {
2206     return Sema::CXXMoveAssignment;
2207   }
2208 
2209   return Sema::CXXInvalid;
2210 }
2211 
2212 /// canRedefineFunction - checks if a function can be redefined. Currently,
2213 /// only extern inline functions can be redefined, and even then only in
2214 /// GNU89 mode.
2215 static bool canRedefineFunction(const FunctionDecl *FD,
2216                                 const LangOptions& LangOpts) {
2217   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2218           !LangOpts.CPlusPlus &&
2219           FD->isInlineSpecified() &&
2220           FD->getStorageClass() == SC_Extern);
2221 }
2222 
2223 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2224   const AttributedType *AT = T->getAs<AttributedType>();
2225   while (AT && !AT->isCallingConv())
2226     AT = AT->getModifiedType()->getAs<AttributedType>();
2227   return AT;
2228 }
2229 
2230 template <typename T>
2231 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2232   const DeclContext *DC = Old->getDeclContext();
2233   if (DC->isRecord())
2234     return false;
2235 
2236   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2237   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2238     return true;
2239   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2240     return true;
2241   return false;
2242 }
2243 
2244 /// MergeFunctionDecl - We just parsed a function 'New' from
2245 /// declarator D which has the same name and scope as a previous
2246 /// declaration 'Old'.  Figure out how to resolve this situation,
2247 /// merging decls or emitting diagnostics as appropriate.
2248 ///
2249 /// In C++, New and Old must be declarations that are not
2250 /// overloaded. Use IsOverload to determine whether New and Old are
2251 /// overloaded, and to select the Old declaration that New should be
2252 /// merged with.
2253 ///
2254 /// Returns true if there was an error, false otherwise.
2255 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2256                              Scope *S, bool MergeTypeWithOld) {
2257   // Verify the old decl was also a function.
2258   FunctionDecl *Old = OldD->getAsFunction();
2259   if (!Old) {
2260     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2261       if (New->getFriendObjectKind()) {
2262         Diag(New->getLocation(), diag::err_using_decl_friend);
2263         Diag(Shadow->getTargetDecl()->getLocation(),
2264              diag::note_using_decl_target);
2265         Diag(Shadow->getUsingDecl()->getLocation(),
2266              diag::note_using_decl) << 0;
2267         return true;
2268       }
2269 
2270       // C++11 [namespace.udecl]p14:
2271       //   If a function declaration in namespace scope or block scope has the
2272       //   same name and the same parameter-type-list as a function introduced
2273       //   by a using-declaration, and the declarations do not declare the same
2274       //   function, the program is ill-formed.
2275 
2276       // Check whether the two declarations might declare the same function.
2277       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2278       if (Old &&
2279           !Old->getDeclContext()->getRedeclContext()->Equals(
2280               New->getDeclContext()->getRedeclContext()) &&
2281           !(Old->isExternC() && New->isExternC()))
2282         Old = 0;
2283 
2284       if (!Old) {
2285         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2286         Diag(Shadow->getTargetDecl()->getLocation(),
2287              diag::note_using_decl_target);
2288         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2289         return true;
2290       }
2291       OldD = Old;
2292     } else {
2293       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2294         << New->getDeclName();
2295       Diag(OldD->getLocation(), diag::note_previous_definition);
2296       return true;
2297     }
2298   }
2299 
2300   // If the old declaration is invalid, just give up here.
2301   if (Old->isInvalidDecl())
2302     return true;
2303 
2304   // Determine whether the previous declaration was a definition,
2305   // implicit declaration, or a declaration.
2306   diag::kind PrevDiag;
2307   SourceLocation OldLocation = Old->getLocation();
2308   if (Old->isThisDeclarationADefinition())
2309     PrevDiag = diag::note_previous_definition;
2310   else if (Old->isImplicit()) {
2311     PrevDiag = diag::note_previous_implicit_declaration;
2312     if (OldLocation.isInvalid())
2313       OldLocation = New->getLocation();
2314   } else
2315     PrevDiag = diag::note_previous_declaration;
2316 
2317   // Don't complain about this if we're in GNU89 mode and the old function
2318   // is an extern inline function.
2319   // Don't complain about specializations. They are not supposed to have
2320   // storage classes.
2321   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2322       New->getStorageClass() == SC_Static &&
2323       Old->hasExternalFormalLinkage() &&
2324       !New->getTemplateSpecializationInfo() &&
2325       !canRedefineFunction(Old, getLangOpts())) {
2326     if (getLangOpts().MicrosoftExt) {
2327       Diag(New->getLocation(), diag::warn_static_non_static) << New;
2328       Diag(OldLocation, PrevDiag);
2329     } else {
2330       Diag(New->getLocation(), diag::err_static_non_static) << New;
2331       Diag(OldLocation, PrevDiag);
2332       return true;
2333     }
2334   }
2335 
2336 
2337   // If a function is first declared with a calling convention, but is later
2338   // declared or defined without one, all following decls assume the calling
2339   // convention of the first.
2340   //
2341   // It's OK if a function is first declared without a calling convention,
2342   // but is later declared or defined with the default calling convention.
2343   //
2344   // To test if either decl has an explicit calling convention, we look for
2345   // AttributedType sugar nodes on the type as written.  If they are missing or
2346   // were canonicalized away, we assume the calling convention was implicit.
2347   //
2348   // Note also that we DO NOT return at this point, because we still have
2349   // other tests to run.
2350   QualType OldQType = Context.getCanonicalType(Old->getType());
2351   QualType NewQType = Context.getCanonicalType(New->getType());
2352   const FunctionType *OldType = cast<FunctionType>(OldQType);
2353   const FunctionType *NewType = cast<FunctionType>(NewQType);
2354   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2355   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2356   bool RequiresAdjustment = false;
2357 
2358   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2359     FunctionDecl *First = Old->getFirstDecl();
2360     const FunctionType *FT =
2361         First->getType().getCanonicalType()->castAs<FunctionType>();
2362     FunctionType::ExtInfo FI = FT->getExtInfo();
2363     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2364     if (!NewCCExplicit) {
2365       // Inherit the CC from the previous declaration if it was specified
2366       // there but not here.
2367       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2368       RequiresAdjustment = true;
2369     } else {
2370       // Calling conventions aren't compatible, so complain.
2371       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2372       Diag(New->getLocation(), diag::err_cconv_change)
2373         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2374         << !FirstCCExplicit
2375         << (!FirstCCExplicit ? "" :
2376             FunctionType::getNameForCallConv(FI.getCC()));
2377 
2378       // Put the note on the first decl, since it is the one that matters.
2379       Diag(First->getLocation(), diag::note_previous_declaration);
2380       return true;
2381     }
2382   }
2383 
2384   // FIXME: diagnose the other way around?
2385   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2386     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2387     RequiresAdjustment = true;
2388   }
2389 
2390   // Merge regparm attribute.
2391   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2392       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2393     if (NewTypeInfo.getHasRegParm()) {
2394       Diag(New->getLocation(), diag::err_regparm_mismatch)
2395         << NewType->getRegParmType()
2396         << OldType->getRegParmType();
2397       Diag(OldLocation, diag::note_previous_declaration);
2398       return true;
2399     }
2400 
2401     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2402     RequiresAdjustment = true;
2403   }
2404 
2405   // Merge ns_returns_retained attribute.
2406   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2407     if (NewTypeInfo.getProducesResult()) {
2408       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2409       Diag(OldLocation, diag::note_previous_declaration);
2410       return true;
2411     }
2412 
2413     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2414     RequiresAdjustment = true;
2415   }
2416 
2417   if (RequiresAdjustment) {
2418     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2419     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2420     New->setType(QualType(AdjustedType, 0));
2421     NewQType = Context.getCanonicalType(New->getType());
2422     NewType = cast<FunctionType>(NewQType);
2423   }
2424 
2425   // If this redeclaration makes the function inline, we may need to add it to
2426   // UndefinedButUsed.
2427   if (!Old->isInlined() && New->isInlined() &&
2428       !New->hasAttr<GNUInlineAttr>() &&
2429       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2430       Old->isUsed(false) &&
2431       !Old->isDefined() && !New->isThisDeclarationADefinition())
2432     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2433                                            SourceLocation()));
2434 
2435   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2436   // about it.
2437   if (New->hasAttr<GNUInlineAttr>() &&
2438       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2439     UndefinedButUsed.erase(Old->getCanonicalDecl());
2440   }
2441 
2442   if (getLangOpts().CPlusPlus) {
2443     // (C++98 13.1p2):
2444     //   Certain function declarations cannot be overloaded:
2445     //     -- Function declarations that differ only in the return type
2446     //        cannot be overloaded.
2447 
2448     // Go back to the type source info to compare the declared return types,
2449     // per C++1y [dcl.type.auto]p13:
2450     //   Redeclarations or specializations of a function or function template
2451     //   with a declared return type that uses a placeholder type shall also
2452     //   use that placeholder, not a deduced type.
2453     QualType OldDeclaredReturnType =
2454         (Old->getTypeSourceInfo()
2455              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2456              : OldType)->getReturnType();
2457     QualType NewDeclaredReturnType =
2458         (New->getTypeSourceInfo()
2459              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2460              : NewType)->getReturnType();
2461     QualType ResQT;
2462     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2463         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2464           New->isLocalExternDecl())) {
2465       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2466           OldDeclaredReturnType->isObjCObjectPointerType())
2467         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2468       if (ResQT.isNull()) {
2469         if (New->isCXXClassMember() && New->isOutOfLine())
2470           Diag(New->getLocation(),
2471                diag::err_member_def_does_not_match_ret_type) << New;
2472         else
2473           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2474         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2475         return true;
2476       }
2477       else
2478         NewQType = ResQT;
2479     }
2480 
2481     QualType OldReturnType = OldType->getReturnType();
2482     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2483     if (OldReturnType != NewReturnType) {
2484       // If this function has a deduced return type and has already been
2485       // defined, copy the deduced value from the old declaration.
2486       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2487       if (OldAT && OldAT->isDeduced()) {
2488         New->setType(
2489             SubstAutoType(New->getType(),
2490                           OldAT->isDependentType() ? Context.DependentTy
2491                                                    : OldAT->getDeducedType()));
2492         NewQType = Context.getCanonicalType(
2493             SubstAutoType(NewQType,
2494                           OldAT->isDependentType() ? Context.DependentTy
2495                                                    : OldAT->getDeducedType()));
2496       }
2497     }
2498 
2499     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2500     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2501     if (OldMethod && NewMethod) {
2502       // Preserve triviality.
2503       NewMethod->setTrivial(OldMethod->isTrivial());
2504 
2505       // MSVC allows explicit template specialization at class scope:
2506       // 2 CXXMethodDecls referring to the same function will be injected.
2507       // We don't want a redeclaration error.
2508       bool IsClassScopeExplicitSpecialization =
2509                               OldMethod->isFunctionTemplateSpecialization() &&
2510                               NewMethod->isFunctionTemplateSpecialization();
2511       bool isFriend = NewMethod->getFriendObjectKind();
2512 
2513       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2514           !IsClassScopeExplicitSpecialization) {
2515         //    -- Member function declarations with the same name and the
2516         //       same parameter types cannot be overloaded if any of them
2517         //       is a static member function declaration.
2518         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2519           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2520           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2521           return true;
2522         }
2523 
2524         // C++ [class.mem]p1:
2525         //   [...] A member shall not be declared twice in the
2526         //   member-specification, except that a nested class or member
2527         //   class template can be declared and then later defined.
2528         if (ActiveTemplateInstantiations.empty()) {
2529           unsigned NewDiag;
2530           if (isa<CXXConstructorDecl>(OldMethod))
2531             NewDiag = diag::err_constructor_redeclared;
2532           else if (isa<CXXDestructorDecl>(NewMethod))
2533             NewDiag = diag::err_destructor_redeclared;
2534           else if (isa<CXXConversionDecl>(NewMethod))
2535             NewDiag = diag::err_conv_function_redeclared;
2536           else
2537             NewDiag = diag::err_member_redeclared;
2538 
2539           Diag(New->getLocation(), NewDiag);
2540         } else {
2541           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2542             << New << New->getType();
2543         }
2544         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2545 
2546       // Complain if this is an explicit declaration of a special
2547       // member that was initially declared implicitly.
2548       //
2549       // As an exception, it's okay to befriend such methods in order
2550       // to permit the implicit constructor/destructor/operator calls.
2551       } else if (OldMethod->isImplicit()) {
2552         if (isFriend) {
2553           NewMethod->setImplicit();
2554         } else {
2555           Diag(NewMethod->getLocation(),
2556                diag::err_definition_of_implicitly_declared_member)
2557             << New << getSpecialMember(OldMethod);
2558           return true;
2559         }
2560       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2561         Diag(NewMethod->getLocation(),
2562              diag::err_definition_of_explicitly_defaulted_member)
2563           << getSpecialMember(OldMethod);
2564         return true;
2565       }
2566     }
2567 
2568     // C++11 [dcl.attr.noreturn]p1:
2569     //   The first declaration of a function shall specify the noreturn
2570     //   attribute if any declaration of that function specifies the noreturn
2571     //   attribute.
2572     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2573     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2574       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2575       Diag(Old->getFirstDecl()->getLocation(),
2576            diag::note_noreturn_missing_first_decl);
2577     }
2578 
2579     // C++11 [dcl.attr.depend]p2:
2580     //   The first declaration of a function shall specify the
2581     //   carries_dependency attribute for its declarator-id if any declaration
2582     //   of the function specifies the carries_dependency attribute.
2583     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2584     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2585       Diag(CDA->getLocation(),
2586            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2587       Diag(Old->getFirstDecl()->getLocation(),
2588            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2589     }
2590 
2591     // (C++98 8.3.5p3):
2592     //   All declarations for a function shall agree exactly in both the
2593     //   return type and the parameter-type-list.
2594     // We also want to respect all the extended bits except noreturn.
2595 
2596     // noreturn should now match unless the old type info didn't have it.
2597     QualType OldQTypeForComparison = OldQType;
2598     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2599       assert(OldQType == QualType(OldType, 0));
2600       const FunctionType *OldTypeForComparison
2601         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2602       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2603       assert(OldQTypeForComparison.isCanonical());
2604     }
2605 
2606     if (haveIncompatibleLanguageLinkages(Old, New)) {
2607       // As a special case, retain the language linkage from previous
2608       // declarations of a friend function as an extension.
2609       //
2610       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2611       // and is useful because there's otherwise no way to specify language
2612       // linkage within class scope.
2613       //
2614       // Check cautiously as the friend object kind isn't yet complete.
2615       if (New->getFriendObjectKind() != Decl::FOK_None) {
2616         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2617         Diag(OldLocation, PrevDiag);
2618       } else {
2619         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2620         Diag(OldLocation, PrevDiag);
2621         return true;
2622       }
2623     }
2624 
2625     if (OldQTypeForComparison == NewQType)
2626       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2627 
2628     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2629         New->isLocalExternDecl()) {
2630       // It's OK if we couldn't merge types for a local function declaraton
2631       // if either the old or new type is dependent. We'll merge the types
2632       // when we instantiate the function.
2633       return false;
2634     }
2635 
2636     // Fall through for conflicting redeclarations and redefinitions.
2637   }
2638 
2639   // C: Function types need to be compatible, not identical. This handles
2640   // duplicate function decls like "void f(int); void f(enum X);" properly.
2641   if (!getLangOpts().CPlusPlus &&
2642       Context.typesAreCompatible(OldQType, NewQType)) {
2643     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2644     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2645     const FunctionProtoType *OldProto = 0;
2646     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2647         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2648       // The old declaration provided a function prototype, but the
2649       // new declaration does not. Merge in the prototype.
2650       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2651       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
2652       NewQType =
2653           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2654                                   OldProto->getExtProtoInfo());
2655       New->setType(NewQType);
2656       New->setHasInheritedPrototype();
2657 
2658       // Synthesize a parameter for each argument type.
2659       SmallVector<ParmVarDecl*, 16> Params;
2660       for (const auto &ParamType : OldProto->param_types()) {
2661         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
2662                                                  SourceLocation(), 0, ParamType,
2663                                                  /*TInfo=*/0, SC_None, 0);
2664         Param->setScopeInfo(0, Params.size());
2665         Param->setImplicit();
2666         Params.push_back(Param);
2667       }
2668 
2669       New->setParams(Params);
2670     }
2671 
2672     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2673   }
2674 
2675   // GNU C permits a K&R definition to follow a prototype declaration
2676   // if the declared types of the parameters in the K&R definition
2677   // match the types in the prototype declaration, even when the
2678   // promoted types of the parameters from the K&R definition differ
2679   // from the types in the prototype. GCC then keeps the types from
2680   // the prototype.
2681   //
2682   // If a variadic prototype is followed by a non-variadic K&R definition,
2683   // the K&R definition becomes variadic.  This is sort of an edge case, but
2684   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2685   // C99 6.9.1p8.
2686   if (!getLangOpts().CPlusPlus &&
2687       Old->hasPrototype() && !New->hasPrototype() &&
2688       New->getType()->getAs<FunctionProtoType>() &&
2689       Old->getNumParams() == New->getNumParams()) {
2690     SmallVector<QualType, 16> ArgTypes;
2691     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2692     const FunctionProtoType *OldProto
2693       = Old->getType()->getAs<FunctionProtoType>();
2694     const FunctionProtoType *NewProto
2695       = New->getType()->getAs<FunctionProtoType>();
2696 
2697     // Determine whether this is the GNU C extension.
2698     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2699                                                NewProto->getReturnType());
2700     bool LooseCompatible = !MergedReturn.isNull();
2701     for (unsigned Idx = 0, End = Old->getNumParams();
2702          LooseCompatible && Idx != End; ++Idx) {
2703       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2704       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2705       if (Context.typesAreCompatible(OldParm->getType(),
2706                                      NewProto->getParamType(Idx))) {
2707         ArgTypes.push_back(NewParm->getType());
2708       } else if (Context.typesAreCompatible(OldParm->getType(),
2709                                             NewParm->getType(),
2710                                             /*CompareUnqualified=*/true)) {
2711         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2712                                            NewProto->getParamType(Idx) };
2713         Warnings.push_back(Warn);
2714         ArgTypes.push_back(NewParm->getType());
2715       } else
2716         LooseCompatible = false;
2717     }
2718 
2719     if (LooseCompatible) {
2720       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2721         Diag(Warnings[Warn].NewParm->getLocation(),
2722              diag::ext_param_promoted_not_compatible_with_prototype)
2723           << Warnings[Warn].PromotedType
2724           << Warnings[Warn].OldParm->getType();
2725         if (Warnings[Warn].OldParm->getLocation().isValid())
2726           Diag(Warnings[Warn].OldParm->getLocation(),
2727                diag::note_previous_declaration);
2728       }
2729 
2730       if (MergeTypeWithOld)
2731         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2732                                              OldProto->getExtProtoInfo()));
2733       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2734     }
2735 
2736     // Fall through to diagnose conflicting types.
2737   }
2738 
2739   // A function that has already been declared has been redeclared or
2740   // defined with a different type; show an appropriate diagnostic.
2741 
2742   // If the previous declaration was an implicitly-generated builtin
2743   // declaration, then at the very least we should use a specialized note.
2744   unsigned BuiltinID;
2745   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2746     // If it's actually a library-defined builtin function like 'malloc'
2747     // or 'printf', just warn about the incompatible redeclaration.
2748     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2749       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2750       Diag(OldLocation, diag::note_previous_builtin_declaration)
2751         << Old << Old->getType();
2752 
2753       // If this is a global redeclaration, just forget hereafter
2754       // about the "builtin-ness" of the function.
2755       //
2756       // Doing this for local extern declarations is problematic.  If
2757       // the builtin declaration remains visible, a second invalid
2758       // local declaration will produce a hard error; if it doesn't
2759       // remain visible, a single bogus local redeclaration (which is
2760       // actually only a warning) could break all the downstream code.
2761       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2762         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2763 
2764       return false;
2765     }
2766 
2767     PrevDiag = diag::note_previous_builtin_declaration;
2768   }
2769 
2770   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2771   Diag(OldLocation, PrevDiag) << Old << Old->getType();
2772   return true;
2773 }
2774 
2775 /// \brief Completes the merge of two function declarations that are
2776 /// known to be compatible.
2777 ///
2778 /// This routine handles the merging of attributes and other
2779 /// properties of function declarations from the old declaration to
2780 /// the new declaration, once we know that New is in fact a
2781 /// redeclaration of Old.
2782 ///
2783 /// \returns false
2784 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2785                                         Scope *S, bool MergeTypeWithOld) {
2786   // Merge the attributes
2787   mergeDeclAttributes(New, Old);
2788 
2789   // Merge "pure" flag.
2790   if (Old->isPure())
2791     New->setPure();
2792 
2793   // Merge "used" flag.
2794   if (Old->getMostRecentDecl()->isUsed(false))
2795     New->setIsUsed();
2796 
2797   // Merge attributes from the parameters.  These can mismatch with K&R
2798   // declarations.
2799   if (New->getNumParams() == Old->getNumParams())
2800     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2801       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2802                                *this);
2803 
2804   if (getLangOpts().CPlusPlus)
2805     return MergeCXXFunctionDecl(New, Old, S);
2806 
2807   // Merge the function types so the we get the composite types for the return
2808   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2809   // was visible.
2810   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2811   if (!Merged.isNull() && MergeTypeWithOld)
2812     New->setType(Merged);
2813 
2814   return false;
2815 }
2816 
2817 
2818 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2819                                 ObjCMethodDecl *oldMethod) {
2820 
2821   // Merge the attributes, including deprecated/unavailable
2822   AvailabilityMergeKind MergeKind =
2823     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2824                                                    : AMK_Override;
2825   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
2826 
2827   // Merge attributes from the parameters.
2828   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2829                                        oe = oldMethod->param_end();
2830   for (ObjCMethodDecl::param_iterator
2831          ni = newMethod->param_begin(), ne = newMethod->param_end();
2832        ni != ne && oi != oe; ++ni, ++oi)
2833     mergeParamDeclAttributes(*ni, *oi, *this);
2834 
2835   CheckObjCMethodOverride(newMethod, oldMethod);
2836 }
2837 
2838 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2839 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2840 /// emitting diagnostics as appropriate.
2841 ///
2842 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2843 /// to here in AddInitializerToDecl. We can't check them before the initializer
2844 /// is attached.
2845 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2846                              bool MergeTypeWithOld) {
2847   if (New->isInvalidDecl() || Old->isInvalidDecl())
2848     return;
2849 
2850   QualType MergedT;
2851   if (getLangOpts().CPlusPlus) {
2852     if (New->getType()->isUndeducedType()) {
2853       // We don't know what the new type is until the initializer is attached.
2854       return;
2855     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2856       // These could still be something that needs exception specs checked.
2857       return MergeVarDeclExceptionSpecs(New, Old);
2858     }
2859     // C++ [basic.link]p10:
2860     //   [...] the types specified by all declarations referring to a given
2861     //   object or function shall be identical, except that declarations for an
2862     //   array object can specify array types that differ by the presence or
2863     //   absence of a major array bound (8.3.4).
2864     else if (Old->getType()->isIncompleteArrayType() &&
2865              New->getType()->isArrayType()) {
2866       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2867       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2868       if (Context.hasSameType(OldArray->getElementType(),
2869                               NewArray->getElementType()))
2870         MergedT = New->getType();
2871     } else if (Old->getType()->isArrayType() &&
2872                New->getType()->isIncompleteArrayType()) {
2873       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2874       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2875       if (Context.hasSameType(OldArray->getElementType(),
2876                               NewArray->getElementType()))
2877         MergedT = Old->getType();
2878     } else if (New->getType()->isObjCObjectPointerType() &&
2879                Old->getType()->isObjCObjectPointerType()) {
2880       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2881                                               Old->getType());
2882     }
2883   } else {
2884     // C 6.2.7p2:
2885     //   All declarations that refer to the same object or function shall have
2886     //   compatible type.
2887     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2888   }
2889   if (MergedT.isNull()) {
2890     // It's OK if we couldn't merge types if either type is dependent, for a
2891     // block-scope variable. In other cases (static data members of class
2892     // templates, variable templates, ...), we require the types to be
2893     // equivalent.
2894     // FIXME: The C++ standard doesn't say anything about this.
2895     if ((New->getType()->isDependentType() ||
2896          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2897       // If the old type was dependent, we can't merge with it, so the new type
2898       // becomes dependent for now. We'll reproduce the original type when we
2899       // instantiate the TypeSourceInfo for the variable.
2900       if (!New->getType()->isDependentType() && MergeTypeWithOld)
2901         New->setType(Context.DependentTy);
2902       return;
2903     }
2904 
2905     // FIXME: Even if this merging succeeds, some other non-visible declaration
2906     // of this variable might have an incompatible type. For instance:
2907     //
2908     //   extern int arr[];
2909     //   void f() { extern int arr[2]; }
2910     //   void g() { extern int arr[3]; }
2911     //
2912     // Neither C nor C++ requires a diagnostic for this, but we should still try
2913     // to diagnose it.
2914     Diag(New->getLocation(), diag::err_redefinition_different_type)
2915       << New->getDeclName() << New->getType() << Old->getType();
2916     Diag(Old->getLocation(), diag::note_previous_definition);
2917     return New->setInvalidDecl();
2918   }
2919 
2920   // Don't actually update the type on the new declaration if the old
2921   // declaration was an extern declaration in a different scope.
2922   if (MergeTypeWithOld)
2923     New->setType(MergedT);
2924 }
2925 
2926 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2927                                   LookupResult &Previous) {
2928   // C11 6.2.7p4:
2929   //   For an identifier with internal or external linkage declared
2930   //   in a scope in which a prior declaration of that identifier is
2931   //   visible, if the prior declaration specifies internal or
2932   //   external linkage, the type of the identifier at the later
2933   //   declaration becomes the composite type.
2934   //
2935   // If the variable isn't visible, we do not merge with its type.
2936   if (Previous.isShadowed())
2937     return false;
2938 
2939   if (S.getLangOpts().CPlusPlus) {
2940     // C++11 [dcl.array]p3:
2941     //   If there is a preceding declaration of the entity in the same
2942     //   scope in which the bound was specified, an omitted array bound
2943     //   is taken to be the same as in that earlier declaration.
2944     return NewVD->isPreviousDeclInSameBlockScope() ||
2945            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2946             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2947   } else {
2948     // If the old declaration was function-local, don't merge with its
2949     // type unless we're in the same function.
2950     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2951            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2952   }
2953 }
2954 
2955 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2956 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2957 /// situation, merging decls or emitting diagnostics as appropriate.
2958 ///
2959 /// Tentative definition rules (C99 6.9.2p2) are checked by
2960 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2961 /// definitions here, since the initializer hasn't been attached.
2962 ///
2963 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2964   // If the new decl is already invalid, don't do any other checking.
2965   if (New->isInvalidDecl())
2966     return;
2967 
2968   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2969 
2970   // Verify the old decl was also a variable or variable template.
2971   VarDecl *Old = 0;
2972   VarTemplateDecl *OldTemplate = 0;
2973   if (Previous.isSingleResult()) {
2974     if (NewTemplate) {
2975       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2976       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
2977     } else
2978       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
2979   }
2980   if (!Old) {
2981     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2982       << New->getDeclName();
2983     Diag(Previous.getRepresentativeDecl()->getLocation(),
2984          diag::note_previous_definition);
2985     return New->setInvalidDecl();
2986   }
2987 
2988   if (!shouldLinkPossiblyHiddenDecl(Old, New))
2989     return;
2990 
2991   // Ensure the template parameters are compatible.
2992   if (NewTemplate &&
2993       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
2994                                       OldTemplate->getTemplateParameters(),
2995                                       /*Complain=*/true, TPL_TemplateMatch))
2996     return;
2997 
2998   // C++ [class.mem]p1:
2999   //   A member shall not be declared twice in the member-specification [...]
3000   //
3001   // Here, we need only consider static data members.
3002   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3003     Diag(New->getLocation(), diag::err_duplicate_member)
3004       << New->getIdentifier();
3005     Diag(Old->getLocation(), diag::note_previous_declaration);
3006     New->setInvalidDecl();
3007   }
3008 
3009   mergeDeclAttributes(New, Old);
3010   // Warn if an already-declared variable is made a weak_import in a subsequent
3011   // declaration
3012   if (New->hasAttr<WeakImportAttr>() &&
3013       Old->getStorageClass() == SC_None &&
3014       !Old->hasAttr<WeakImportAttr>()) {
3015     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3016     Diag(Old->getLocation(), diag::note_previous_definition);
3017     // Remove weak_import attribute on new declaration.
3018     New->dropAttr<WeakImportAttr>();
3019   }
3020 
3021   // Merge the types.
3022   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3023 
3024   if (New->isInvalidDecl())
3025     return;
3026 
3027   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3028   if (New->getStorageClass() == SC_Static &&
3029       !New->isStaticDataMember() &&
3030       Old->hasExternalFormalLinkage()) {
3031     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
3032     Diag(Old->getLocation(), diag::note_previous_definition);
3033     return New->setInvalidDecl();
3034   }
3035   // C99 6.2.2p4:
3036   //   For an identifier declared with the storage-class specifier
3037   //   extern in a scope in which a prior declaration of that
3038   //   identifier is visible,23) if the prior declaration specifies
3039   //   internal or external linkage, the linkage of the identifier at
3040   //   the later declaration is the same as the linkage specified at
3041   //   the prior declaration. If no prior declaration is visible, or
3042   //   if the prior declaration specifies no linkage, then the
3043   //   identifier has external linkage.
3044   if (New->hasExternalStorage() && Old->hasLinkage())
3045     /* Okay */;
3046   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3047            !New->isStaticDataMember() &&
3048            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3049     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3050     Diag(Old->getLocation(), diag::note_previous_definition);
3051     return New->setInvalidDecl();
3052   }
3053 
3054   // Check if extern is followed by non-extern and vice-versa.
3055   if (New->hasExternalStorage() &&
3056       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3057     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3058     Diag(Old->getLocation(), diag::note_previous_definition);
3059     return New->setInvalidDecl();
3060   }
3061   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3062       !New->hasExternalStorage()) {
3063     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3064     Diag(Old->getLocation(), diag::note_previous_definition);
3065     return New->setInvalidDecl();
3066   }
3067 
3068   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3069 
3070   // FIXME: The test for external storage here seems wrong? We still
3071   // need to check for mismatches.
3072   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3073       // Don't complain about out-of-line definitions of static members.
3074       !(Old->getLexicalDeclContext()->isRecord() &&
3075         !New->getLexicalDeclContext()->isRecord())) {
3076     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3077     Diag(Old->getLocation(), diag::note_previous_definition);
3078     return New->setInvalidDecl();
3079   }
3080 
3081   if (New->getTLSKind() != Old->getTLSKind()) {
3082     if (!Old->getTLSKind()) {
3083       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3084       Diag(Old->getLocation(), diag::note_previous_declaration);
3085     } else if (!New->getTLSKind()) {
3086       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3087       Diag(Old->getLocation(), diag::note_previous_declaration);
3088     } else {
3089       // Do not allow redeclaration to change the variable between requiring
3090       // static and dynamic initialization.
3091       // FIXME: GCC allows this, but uses the TLS keyword on the first
3092       // declaration to determine the kind. Do we need to be compatible here?
3093       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3094         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3095       Diag(Old->getLocation(), diag::note_previous_declaration);
3096     }
3097   }
3098 
3099   // C++ doesn't have tentative definitions, so go right ahead and check here.
3100   const VarDecl *Def;
3101   if (getLangOpts().CPlusPlus &&
3102       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3103       (Def = Old->getDefinition())) {
3104     Diag(New->getLocation(), diag::err_redefinition) << New;
3105     Diag(Def->getLocation(), diag::note_previous_definition);
3106     New->setInvalidDecl();
3107     return;
3108   }
3109 
3110   if (haveIncompatibleLanguageLinkages(Old, New)) {
3111     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3112     Diag(Old->getLocation(), diag::note_previous_definition);
3113     New->setInvalidDecl();
3114     return;
3115   }
3116 
3117   // Merge "used" flag.
3118   if (Old->getMostRecentDecl()->isUsed(false))
3119     New->setIsUsed();
3120 
3121   // Keep a chain of previous declarations.
3122   New->setPreviousDecl(Old);
3123   if (NewTemplate)
3124     NewTemplate->setPreviousDecl(OldTemplate);
3125 
3126   // Inherit access appropriately.
3127   New->setAccess(Old->getAccess());
3128   if (NewTemplate)
3129     NewTemplate->setAccess(New->getAccess());
3130 }
3131 
3132 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3133 /// no declarator (e.g. "struct foo;") is parsed.
3134 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3135                                        DeclSpec &DS) {
3136   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3137 }
3138 
3139 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
3140   if (!S.Context.getLangOpts().CPlusPlus)
3141     return;
3142 
3143   if (isa<CXXRecordDecl>(Tag->getParent())) {
3144     // If this tag is the direct child of a class, number it if
3145     // it is anonymous.
3146     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3147       return;
3148     MangleNumberingContext &MCtx =
3149         S.Context.getManglingNumberContext(Tag->getParent());
3150     S.Context.setManglingNumber(
3151         Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3152     return;
3153   }
3154 
3155   // If this tag isn't a direct child of a class, number it if it is local.
3156   Decl *ManglingContextDecl;
3157   if (MangleNumberingContext *MCtx =
3158           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3159                                           ManglingContextDecl)) {
3160     S.Context.setManglingNumber(
3161         Tag,
3162         MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
3163   }
3164 }
3165 
3166 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3167 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3168 /// parameters to cope with template friend declarations.
3169 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3170                                        DeclSpec &DS,
3171                                        MultiTemplateParamsArg TemplateParams,
3172                                        bool IsExplicitInstantiation) {
3173   Decl *TagD = 0;
3174   TagDecl *Tag = 0;
3175   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3176       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3177       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3178       DS.getTypeSpecType() == DeclSpec::TST_union ||
3179       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3180     TagD = DS.getRepAsDecl();
3181 
3182     if (!TagD) // We probably had an error
3183       return 0;
3184 
3185     // Note that the above type specs guarantee that the
3186     // type rep is a Decl, whereas in many of the others
3187     // it's a Type.
3188     if (isa<TagDecl>(TagD))
3189       Tag = cast<TagDecl>(TagD);
3190     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3191       Tag = CTD->getTemplatedDecl();
3192   }
3193 
3194   if (Tag) {
3195     HandleTagNumbering(*this, Tag, S);
3196     Tag->setFreeStanding();
3197     if (Tag->isInvalidDecl())
3198       return Tag;
3199   }
3200 
3201   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3202     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3203     // or incomplete types shall not be restrict-qualified."
3204     if (TypeQuals & DeclSpec::TQ_restrict)
3205       Diag(DS.getRestrictSpecLoc(),
3206            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3207            << DS.getSourceRange();
3208   }
3209 
3210   if (DS.isConstexprSpecified()) {
3211     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3212     // and definitions of functions and variables.
3213     if (Tag)
3214       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3215         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3216             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3217             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3218             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3219     else
3220       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3221     // Don't emit warnings after this error.
3222     return TagD;
3223   }
3224 
3225   DiagnoseFunctionSpecifiers(DS);
3226 
3227   if (DS.isFriendSpecified()) {
3228     // If we're dealing with a decl but not a TagDecl, assume that
3229     // whatever routines created it handled the friendship aspect.
3230     if (TagD && !Tag)
3231       return 0;
3232     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3233   }
3234 
3235   CXXScopeSpec &SS = DS.getTypeSpecScope();
3236   bool IsExplicitSpecialization =
3237     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3238   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3239       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3240     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3241     // nested-name-specifier unless it is an explicit instantiation
3242     // or an explicit specialization.
3243     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3244     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3245       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3246           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3247           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3248           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3249       << SS.getRange();
3250     return 0;
3251   }
3252 
3253   // Track whether this decl-specifier declares anything.
3254   bool DeclaresAnything = true;
3255 
3256   // Handle anonymous struct definitions.
3257   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3258     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3259         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3260       if (getLangOpts().CPlusPlus ||
3261           Record->getDeclContext()->isRecord())
3262         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
3263 
3264       DeclaresAnything = false;
3265     }
3266   }
3267 
3268   // Check for Microsoft C extension: anonymous struct member.
3269   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3270       CurContext->isRecord() &&
3271       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3272     // Handle 2 kinds of anonymous struct:
3273     //   struct STRUCT;
3274     // and
3275     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3276     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3277     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3278         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3279          DS.getRepAsType().get()->isStructureType())) {
3280       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3281         << DS.getSourceRange();
3282       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3283     }
3284   }
3285 
3286   // Skip all the checks below if we have a type error.
3287   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3288       (TagD && TagD->isInvalidDecl()))
3289     return TagD;
3290 
3291   if (getLangOpts().CPlusPlus &&
3292       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3293     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3294       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3295           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3296         DeclaresAnything = false;
3297 
3298   if (!DS.isMissingDeclaratorOk()) {
3299     // Customize diagnostic for a typedef missing a name.
3300     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3301       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3302         << DS.getSourceRange();
3303     else
3304       DeclaresAnything = false;
3305   }
3306 
3307   if (DS.isModulePrivateSpecified() &&
3308       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3309     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3310       << Tag->getTagKind()
3311       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3312 
3313   ActOnDocumentableDecl(TagD);
3314 
3315   // C 6.7/2:
3316   //   A declaration [...] shall declare at least a declarator [...], a tag,
3317   //   or the members of an enumeration.
3318   // C++ [dcl.dcl]p3:
3319   //   [If there are no declarators], and except for the declaration of an
3320   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3321   //   names into the program, or shall redeclare a name introduced by a
3322   //   previous declaration.
3323   if (!DeclaresAnything) {
3324     // In C, we allow this as a (popular) extension / bug. Don't bother
3325     // producing further diagnostics for redundant qualifiers after this.
3326     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3327     return TagD;
3328   }
3329 
3330   // C++ [dcl.stc]p1:
3331   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3332   //   init-declarator-list of the declaration shall not be empty.
3333   // C++ [dcl.fct.spec]p1:
3334   //   If a cv-qualifier appears in a decl-specifier-seq, the
3335   //   init-declarator-list of the declaration shall not be empty.
3336   //
3337   // Spurious qualifiers here appear to be valid in C.
3338   unsigned DiagID = diag::warn_standalone_specifier;
3339   if (getLangOpts().CPlusPlus)
3340     DiagID = diag::ext_standalone_specifier;
3341 
3342   // Note that a linkage-specification sets a storage class, but
3343   // 'extern "C" struct foo;' is actually valid and not theoretically
3344   // useless.
3345   if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3346     if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3347       Diag(DS.getStorageClassSpecLoc(), DiagID)
3348         << DeclSpec::getSpecifierName(SCS);
3349 
3350   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3351     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3352       << DeclSpec::getSpecifierName(TSCS);
3353   if (DS.getTypeQualifiers()) {
3354     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3355       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3356     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3357       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3358     // Restrict is covered above.
3359     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3360       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3361   }
3362 
3363   // Warn about ignored type attributes, for example:
3364   // __attribute__((aligned)) struct A;
3365   // Attributes should be placed after tag to apply to type declaration.
3366   if (!DS.getAttributes().empty()) {
3367     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3368     if (TypeSpecType == DeclSpec::TST_class ||
3369         TypeSpecType == DeclSpec::TST_struct ||
3370         TypeSpecType == DeclSpec::TST_interface ||
3371         TypeSpecType == DeclSpec::TST_union ||
3372         TypeSpecType == DeclSpec::TST_enum) {
3373       AttributeList* attrs = DS.getAttributes().getList();
3374       while (attrs) {
3375         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3376         << attrs->getName()
3377         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3378             TypeSpecType == DeclSpec::TST_struct ? 1 :
3379             TypeSpecType == DeclSpec::TST_union ? 2 :
3380             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3381         attrs = attrs->getNext();
3382       }
3383     }
3384   }
3385 
3386   return TagD;
3387 }
3388 
3389 /// We are trying to inject an anonymous member into the given scope;
3390 /// check if there's an existing declaration that can't be overloaded.
3391 ///
3392 /// \return true if this is a forbidden redeclaration
3393 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3394                                          Scope *S,
3395                                          DeclContext *Owner,
3396                                          DeclarationName Name,
3397                                          SourceLocation NameLoc,
3398                                          unsigned diagnostic) {
3399   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3400                  Sema::ForRedeclaration);
3401   if (!SemaRef.LookupName(R, S)) return false;
3402 
3403   if (R.getAsSingle<TagDecl>())
3404     return false;
3405 
3406   // Pick a representative declaration.
3407   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3408   assert(PrevDecl && "Expected a non-null Decl");
3409 
3410   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3411     return false;
3412 
3413   SemaRef.Diag(NameLoc, diagnostic) << Name;
3414   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3415 
3416   return true;
3417 }
3418 
3419 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3420 /// anonymous struct or union AnonRecord into the owning context Owner
3421 /// and scope S. This routine will be invoked just after we realize
3422 /// that an unnamed union or struct is actually an anonymous union or
3423 /// struct, e.g.,
3424 ///
3425 /// @code
3426 /// union {
3427 ///   int i;
3428 ///   float f;
3429 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3430 ///    // f into the surrounding scope.x
3431 /// @endcode
3432 ///
3433 /// This routine is recursive, injecting the names of nested anonymous
3434 /// structs/unions into the owning context and scope as well.
3435 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3436                                          DeclContext *Owner,
3437                                          RecordDecl *AnonRecord,
3438                                          AccessSpecifier AS,
3439                                          SmallVectorImpl<NamedDecl *> &Chaining,
3440                                          bool MSAnonStruct) {
3441   unsigned diagKind
3442     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3443                             : diag::err_anonymous_struct_member_redecl;
3444 
3445   bool Invalid = false;
3446 
3447   // Look every FieldDecl and IndirectFieldDecl with a name.
3448   for (auto *D : AnonRecord->decls()) {
3449     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3450         cast<NamedDecl>(D)->getDeclName()) {
3451       ValueDecl *VD = cast<ValueDecl>(D);
3452       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3453                                        VD->getLocation(), diagKind)) {
3454         // C++ [class.union]p2:
3455         //   The names of the members of an anonymous union shall be
3456         //   distinct from the names of any other entity in the
3457         //   scope in which the anonymous union is declared.
3458         Invalid = true;
3459       } else {
3460         // C++ [class.union]p2:
3461         //   For the purpose of name lookup, after the anonymous union
3462         //   definition, the members of the anonymous union are
3463         //   considered to have been defined in the scope in which the
3464         //   anonymous union is declared.
3465         unsigned OldChainingSize = Chaining.size();
3466         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3467           for (auto *PI : IF->chain())
3468             Chaining.push_back(PI);
3469         else
3470           Chaining.push_back(VD);
3471 
3472         assert(Chaining.size() >= 2);
3473         NamedDecl **NamedChain =
3474           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3475         for (unsigned i = 0; i < Chaining.size(); i++)
3476           NamedChain[i] = Chaining[i];
3477 
3478         IndirectFieldDecl* IndirectField =
3479           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3480                                     VD->getIdentifier(), VD->getType(),
3481                                     NamedChain, Chaining.size());
3482 
3483         IndirectField->setAccess(AS);
3484         IndirectField->setImplicit();
3485         SemaRef.PushOnScopeChains(IndirectField, S);
3486 
3487         // That includes picking up the appropriate access specifier.
3488         if (AS != AS_none) IndirectField->setAccess(AS);
3489 
3490         Chaining.resize(OldChainingSize);
3491       }
3492     }
3493   }
3494 
3495   return Invalid;
3496 }
3497 
3498 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3499 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3500 /// illegal input values are mapped to SC_None.
3501 static StorageClass
3502 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3503   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3504   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3505          "Parser allowed 'typedef' as storage class VarDecl.");
3506   switch (StorageClassSpec) {
3507   case DeclSpec::SCS_unspecified:    return SC_None;
3508   case DeclSpec::SCS_extern:
3509     if (DS.isExternInLinkageSpec())
3510       return SC_None;
3511     return SC_Extern;
3512   case DeclSpec::SCS_static:         return SC_Static;
3513   case DeclSpec::SCS_auto:           return SC_Auto;
3514   case DeclSpec::SCS_register:       return SC_Register;
3515   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3516     // Illegal SCSs map to None: error reporting is up to the caller.
3517   case DeclSpec::SCS_mutable:        // Fall through.
3518   case DeclSpec::SCS_typedef:        return SC_None;
3519   }
3520   llvm_unreachable("unknown storage class specifier");
3521 }
3522 
3523 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3524   assert(Record->hasInClassInitializer());
3525 
3526   for (const auto *I : Record->decls()) {
3527     const auto *FD = dyn_cast<FieldDecl>(I);
3528     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
3529       FD = IFD->getAnonField();
3530     if (FD && FD->hasInClassInitializer())
3531       return FD->getLocation();
3532   }
3533 
3534   llvm_unreachable("couldn't find in-class initializer");
3535 }
3536 
3537 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3538                                       SourceLocation DefaultInitLoc) {
3539   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3540     return;
3541 
3542   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3543   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3544 }
3545 
3546 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3547                                       CXXRecordDecl *AnonUnion) {
3548   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3549     return;
3550 
3551   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3552 }
3553 
3554 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3555 /// anonymous structure or union. Anonymous unions are a C++ feature
3556 /// (C++ [class.union]) and a C11 feature; anonymous structures
3557 /// are a C11 feature and GNU C++ extension.
3558 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3559                                         AccessSpecifier AS,
3560                                         RecordDecl *Record,
3561                                         const PrintingPolicy &Policy) {
3562   DeclContext *Owner = Record->getDeclContext();
3563 
3564   // Diagnose whether this anonymous struct/union is an extension.
3565   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3566     Diag(Record->getLocation(), diag::ext_anonymous_union);
3567   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3568     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3569   else if (!Record->isUnion() && !getLangOpts().C11)
3570     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3571 
3572   // C and C++ require different kinds of checks for anonymous
3573   // structs/unions.
3574   bool Invalid = false;
3575   if (getLangOpts().CPlusPlus) {
3576     const char* PrevSpec = 0;
3577     unsigned DiagID;
3578     if (Record->isUnion()) {
3579       // C++ [class.union]p6:
3580       //   Anonymous unions declared in a named namespace or in the
3581       //   global namespace shall be declared static.
3582       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3583           (isa<TranslationUnitDecl>(Owner) ||
3584            (isa<NamespaceDecl>(Owner) &&
3585             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3586         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3587           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3588 
3589         // Recover by adding 'static'.
3590         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3591                                PrevSpec, DiagID, Policy);
3592       }
3593       // C++ [class.union]p6:
3594       //   A storage class is not allowed in a declaration of an
3595       //   anonymous union in a class scope.
3596       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3597                isa<RecordDecl>(Owner)) {
3598         Diag(DS.getStorageClassSpecLoc(),
3599              diag::err_anonymous_union_with_storage_spec)
3600           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3601 
3602         // Recover by removing the storage specifier.
3603         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3604                                SourceLocation(),
3605                                PrevSpec, DiagID, Context.getPrintingPolicy());
3606       }
3607     }
3608 
3609     // Ignore const/volatile/restrict qualifiers.
3610     if (DS.getTypeQualifiers()) {
3611       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3612         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3613           << Record->isUnion() << "const"
3614           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3615       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3616         Diag(DS.getVolatileSpecLoc(),
3617              diag::ext_anonymous_struct_union_qualified)
3618           << Record->isUnion() << "volatile"
3619           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3620       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3621         Diag(DS.getRestrictSpecLoc(),
3622              diag::ext_anonymous_struct_union_qualified)
3623           << Record->isUnion() << "restrict"
3624           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3625       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3626         Diag(DS.getAtomicSpecLoc(),
3627              diag::ext_anonymous_struct_union_qualified)
3628           << Record->isUnion() << "_Atomic"
3629           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3630 
3631       DS.ClearTypeQualifiers();
3632     }
3633 
3634     // C++ [class.union]p2:
3635     //   The member-specification of an anonymous union shall only
3636     //   define non-static data members. [Note: nested types and
3637     //   functions cannot be declared within an anonymous union. ]
3638     for (auto *Mem : Record->decls()) {
3639       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
3640         // C++ [class.union]p3:
3641         //   An anonymous union shall not have private or protected
3642         //   members (clause 11).
3643         assert(FD->getAccess() != AS_none);
3644         if (FD->getAccess() != AS_public) {
3645           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3646             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3647           Invalid = true;
3648         }
3649 
3650         // C++ [class.union]p1
3651         //   An object of a class with a non-trivial constructor, a non-trivial
3652         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3653         //   assignment operator cannot be a member of a union, nor can an
3654         //   array of such objects.
3655         if (CheckNontrivialField(FD))
3656           Invalid = true;
3657       } else if (Mem->isImplicit()) {
3658         // Any implicit members are fine.
3659       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
3660         // This is a type that showed up in an
3661         // elaborated-type-specifier inside the anonymous struct or
3662         // union, but which actually declares a type outside of the
3663         // anonymous struct or union. It's okay.
3664       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
3665         if (!MemRecord->isAnonymousStructOrUnion() &&
3666             MemRecord->getDeclName()) {
3667           // Visual C++ allows type definition in anonymous struct or union.
3668           if (getLangOpts().MicrosoftExt)
3669             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3670               << (int)Record->isUnion();
3671           else {
3672             // This is a nested type declaration.
3673             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3674               << (int)Record->isUnion();
3675             Invalid = true;
3676           }
3677         } else {
3678           // This is an anonymous type definition within another anonymous type.
3679           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3680           // not part of standard C++.
3681           Diag(MemRecord->getLocation(),
3682                diag::ext_anonymous_record_with_anonymous_type)
3683             << (int)Record->isUnion();
3684         }
3685       } else if (isa<AccessSpecDecl>(Mem)) {
3686         // Any access specifier is fine.
3687       } else {
3688         // We have something that isn't a non-static data
3689         // member. Complain about it.
3690         unsigned DK = diag::err_anonymous_record_bad_member;
3691         if (isa<TypeDecl>(Mem))
3692           DK = diag::err_anonymous_record_with_type;
3693         else if (isa<FunctionDecl>(Mem))
3694           DK = diag::err_anonymous_record_with_function;
3695         else if (isa<VarDecl>(Mem))
3696           DK = diag::err_anonymous_record_with_static;
3697 
3698         // Visual C++ allows type definition in anonymous struct or union.
3699         if (getLangOpts().MicrosoftExt &&
3700             DK == diag::err_anonymous_record_with_type)
3701           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
3702             << (int)Record->isUnion();
3703         else {
3704           Diag(Mem->getLocation(), DK)
3705               << (int)Record->isUnion();
3706           Invalid = true;
3707         }
3708       }
3709     }
3710 
3711     // C++11 [class.union]p8 (DR1460):
3712     //   At most one variant member of a union may have a
3713     //   brace-or-equal-initializer.
3714     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3715         Owner->isRecord())
3716       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3717                                 cast<CXXRecordDecl>(Record));
3718   }
3719 
3720   if (!Record->isUnion() && !Owner->isRecord()) {
3721     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3722       << (int)getLangOpts().CPlusPlus;
3723     Invalid = true;
3724   }
3725 
3726   // Mock up a declarator.
3727   Declarator Dc(DS, Declarator::MemberContext);
3728   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3729   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3730 
3731   // Create a declaration for this anonymous struct/union.
3732   NamedDecl *Anon = 0;
3733   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3734     Anon = FieldDecl::Create(Context, OwningClass,
3735                              DS.getLocStart(),
3736                              Record->getLocation(),
3737                              /*IdentifierInfo=*/0,
3738                              Context.getTypeDeclType(Record),
3739                              TInfo,
3740                              /*BitWidth=*/0, /*Mutable=*/false,
3741                              /*InitStyle=*/ICIS_NoInit);
3742     Anon->setAccess(AS);
3743     if (getLangOpts().CPlusPlus)
3744       FieldCollector->Add(cast<FieldDecl>(Anon));
3745   } else {
3746     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3747     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3748     if (SCSpec == DeclSpec::SCS_mutable) {
3749       // mutable can only appear on non-static class members, so it's always
3750       // an error here
3751       Diag(Record->getLocation(), diag::err_mutable_nonmember);
3752       Invalid = true;
3753       SC = SC_None;
3754     }
3755 
3756     Anon = VarDecl::Create(Context, Owner,
3757                            DS.getLocStart(),
3758                            Record->getLocation(), /*IdentifierInfo=*/0,
3759                            Context.getTypeDeclType(Record),
3760                            TInfo, SC);
3761 
3762     // Default-initialize the implicit variable. This initialization will be
3763     // trivial in almost all cases, except if a union member has an in-class
3764     // initializer:
3765     //   union { int n = 0; };
3766     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3767   }
3768   Anon->setImplicit();
3769 
3770   // Mark this as an anonymous struct/union type.
3771   Record->setAnonymousStructOrUnion(true);
3772 
3773   // Add the anonymous struct/union object to the current
3774   // context. We'll be referencing this object when we refer to one of
3775   // its members.
3776   Owner->addDecl(Anon);
3777 
3778   // Inject the members of the anonymous struct/union into the owning
3779   // context and into the identifier resolver chain for name lookup
3780   // purposes.
3781   SmallVector<NamedDecl*, 2> Chain;
3782   Chain.push_back(Anon);
3783 
3784   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3785                                           Chain, false))
3786     Invalid = true;
3787 
3788   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
3789     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
3790       Decl *ManglingContextDecl;
3791       if (MangleNumberingContext *MCtx =
3792               getCurrentMangleNumberContext(NewVD->getDeclContext(),
3793                                             ManglingContextDecl)) {
3794         Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
3795         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
3796       }
3797     }
3798   }
3799 
3800   if (Invalid)
3801     Anon->setInvalidDecl();
3802 
3803   return Anon;
3804 }
3805 
3806 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3807 /// Microsoft C anonymous structure.
3808 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3809 /// Example:
3810 ///
3811 /// struct A { int a; };
3812 /// struct B { struct A; int b; };
3813 ///
3814 /// void foo() {
3815 ///   B var;
3816 ///   var.a = 3;
3817 /// }
3818 ///
3819 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3820                                            RecordDecl *Record) {
3821 
3822   // If there is no Record, get the record via the typedef.
3823   if (!Record)
3824     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3825 
3826   // Mock up a declarator.
3827   Declarator Dc(DS, Declarator::TypeNameContext);
3828   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3829   assert(TInfo && "couldn't build declarator info for anonymous struct");
3830 
3831   // Create a declaration for this anonymous struct.
3832   NamedDecl* Anon = FieldDecl::Create(Context,
3833                              cast<RecordDecl>(CurContext),
3834                              DS.getLocStart(),
3835                              DS.getLocStart(),
3836                              /*IdentifierInfo=*/0,
3837                              Context.getTypeDeclType(Record),
3838                              TInfo,
3839                              /*BitWidth=*/0, /*Mutable=*/false,
3840                              /*InitStyle=*/ICIS_NoInit);
3841   Anon->setImplicit();
3842 
3843   // Add the anonymous struct object to the current context.
3844   CurContext->addDecl(Anon);
3845 
3846   // Inject the members of the anonymous struct into the current
3847   // context and into the identifier resolver chain for name lookup
3848   // purposes.
3849   SmallVector<NamedDecl*, 2> Chain;
3850   Chain.push_back(Anon);
3851 
3852   RecordDecl *RecordDef = Record->getDefinition();
3853   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3854                                                         RecordDef, AS_none,
3855                                                         Chain, true))
3856     Anon->setInvalidDecl();
3857 
3858   return Anon;
3859 }
3860 
3861 /// GetNameForDeclarator - Determine the full declaration name for the
3862 /// given Declarator.
3863 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3864   return GetNameFromUnqualifiedId(D.getName());
3865 }
3866 
3867 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3868 DeclarationNameInfo
3869 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3870   DeclarationNameInfo NameInfo;
3871   NameInfo.setLoc(Name.StartLocation);
3872 
3873   switch (Name.getKind()) {
3874 
3875   case UnqualifiedId::IK_ImplicitSelfParam:
3876   case UnqualifiedId::IK_Identifier:
3877     NameInfo.setName(Name.Identifier);
3878     NameInfo.setLoc(Name.StartLocation);
3879     return NameInfo;
3880 
3881   case UnqualifiedId::IK_OperatorFunctionId:
3882     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3883                                            Name.OperatorFunctionId.Operator));
3884     NameInfo.setLoc(Name.StartLocation);
3885     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3886       = Name.OperatorFunctionId.SymbolLocations[0];
3887     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3888       = Name.EndLocation.getRawEncoding();
3889     return NameInfo;
3890 
3891   case UnqualifiedId::IK_LiteralOperatorId:
3892     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3893                                                            Name.Identifier));
3894     NameInfo.setLoc(Name.StartLocation);
3895     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3896     return NameInfo;
3897 
3898   case UnqualifiedId::IK_ConversionFunctionId: {
3899     TypeSourceInfo *TInfo;
3900     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3901     if (Ty.isNull())
3902       return DeclarationNameInfo();
3903     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3904                                                Context.getCanonicalType(Ty)));
3905     NameInfo.setLoc(Name.StartLocation);
3906     NameInfo.setNamedTypeInfo(TInfo);
3907     return NameInfo;
3908   }
3909 
3910   case UnqualifiedId::IK_ConstructorName: {
3911     TypeSourceInfo *TInfo;
3912     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3913     if (Ty.isNull())
3914       return DeclarationNameInfo();
3915     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3916                                               Context.getCanonicalType(Ty)));
3917     NameInfo.setLoc(Name.StartLocation);
3918     NameInfo.setNamedTypeInfo(TInfo);
3919     return NameInfo;
3920   }
3921 
3922   case UnqualifiedId::IK_ConstructorTemplateId: {
3923     // In well-formed code, we can only have a constructor
3924     // template-id that refers to the current context, so go there
3925     // to find the actual type being constructed.
3926     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3927     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3928       return DeclarationNameInfo();
3929 
3930     // Determine the type of the class being constructed.
3931     QualType CurClassType = Context.getTypeDeclType(CurClass);
3932 
3933     // FIXME: Check two things: that the template-id names the same type as
3934     // CurClassType, and that the template-id does not occur when the name
3935     // was qualified.
3936 
3937     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3938                                     Context.getCanonicalType(CurClassType)));
3939     NameInfo.setLoc(Name.StartLocation);
3940     // FIXME: should we retrieve TypeSourceInfo?
3941     NameInfo.setNamedTypeInfo(0);
3942     return NameInfo;
3943   }
3944 
3945   case UnqualifiedId::IK_DestructorName: {
3946     TypeSourceInfo *TInfo;
3947     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3948     if (Ty.isNull())
3949       return DeclarationNameInfo();
3950     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3951                                               Context.getCanonicalType(Ty)));
3952     NameInfo.setLoc(Name.StartLocation);
3953     NameInfo.setNamedTypeInfo(TInfo);
3954     return NameInfo;
3955   }
3956 
3957   case UnqualifiedId::IK_TemplateId: {
3958     TemplateName TName = Name.TemplateId->Template.get();
3959     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3960     return Context.getNameForTemplate(TName, TNameLoc);
3961   }
3962 
3963   } // switch (Name.getKind())
3964 
3965   llvm_unreachable("Unknown name kind");
3966 }
3967 
3968 static QualType getCoreType(QualType Ty) {
3969   do {
3970     if (Ty->isPointerType() || Ty->isReferenceType())
3971       Ty = Ty->getPointeeType();
3972     else if (Ty->isArrayType())
3973       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3974     else
3975       return Ty.withoutLocalFastQualifiers();
3976   } while (true);
3977 }
3978 
3979 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3980 /// and Definition have "nearly" matching parameters. This heuristic is
3981 /// used to improve diagnostics in the case where an out-of-line function
3982 /// definition doesn't match any declaration within the class or namespace.
3983 /// Also sets Params to the list of indices to the parameters that differ
3984 /// between the declaration and the definition. If hasSimilarParameters
3985 /// returns true and Params is empty, then all of the parameters match.
3986 static bool hasSimilarParameters(ASTContext &Context,
3987                                      FunctionDecl *Declaration,
3988                                      FunctionDecl *Definition,
3989                                      SmallVectorImpl<unsigned> &Params) {
3990   Params.clear();
3991   if (Declaration->param_size() != Definition->param_size())
3992     return false;
3993   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3994     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3995     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3996 
3997     // The parameter types are identical
3998     if (Context.hasSameType(DefParamTy, DeclParamTy))
3999       continue;
4000 
4001     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4002     QualType DefParamBaseTy = getCoreType(DefParamTy);
4003     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4004     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4005 
4006     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4007         (DeclTyName && DeclTyName == DefTyName))
4008       Params.push_back(Idx);
4009     else  // The two parameters aren't even close
4010       return false;
4011   }
4012 
4013   return true;
4014 }
4015 
4016 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4017 /// declarator needs to be rebuilt in the current instantiation.
4018 /// Any bits of declarator which appear before the name are valid for
4019 /// consideration here.  That's specifically the type in the decl spec
4020 /// and the base type in any member-pointer chunks.
4021 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4022                                                     DeclarationName Name) {
4023   // The types we specifically need to rebuild are:
4024   //   - typenames, typeofs, and decltypes
4025   //   - types which will become injected class names
4026   // Of course, we also need to rebuild any type referencing such a
4027   // type.  It's safest to just say "dependent", but we call out a
4028   // few cases here.
4029 
4030   DeclSpec &DS = D.getMutableDeclSpec();
4031   switch (DS.getTypeSpecType()) {
4032   case DeclSpec::TST_typename:
4033   case DeclSpec::TST_typeofType:
4034   case DeclSpec::TST_underlyingType:
4035   case DeclSpec::TST_atomic: {
4036     // Grab the type from the parser.
4037     TypeSourceInfo *TSI = 0;
4038     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4039     if (T.isNull() || !T->isDependentType()) break;
4040 
4041     // Make sure there's a type source info.  This isn't really much
4042     // of a waste; most dependent types should have type source info
4043     // attached already.
4044     if (!TSI)
4045       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4046 
4047     // Rebuild the type in the current instantiation.
4048     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4049     if (!TSI) return true;
4050 
4051     // Store the new type back in the decl spec.
4052     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4053     DS.UpdateTypeRep(LocType);
4054     break;
4055   }
4056 
4057   case DeclSpec::TST_decltype:
4058   case DeclSpec::TST_typeofExpr: {
4059     Expr *E = DS.getRepAsExpr();
4060     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4061     if (Result.isInvalid()) return true;
4062     DS.UpdateExprRep(Result.get());
4063     break;
4064   }
4065 
4066   default:
4067     // Nothing to do for these decl specs.
4068     break;
4069   }
4070 
4071   // It doesn't matter what order we do this in.
4072   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4073     DeclaratorChunk &Chunk = D.getTypeObject(I);
4074 
4075     // The only type information in the declarator which can come
4076     // before the declaration name is the base type of a member
4077     // pointer.
4078     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4079       continue;
4080 
4081     // Rebuild the scope specifier in-place.
4082     CXXScopeSpec &SS = Chunk.Mem.Scope();
4083     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4084       return true;
4085   }
4086 
4087   return false;
4088 }
4089 
4090 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4091   D.setFunctionDefinitionKind(FDK_Declaration);
4092   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4093 
4094   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4095       Dcl && Dcl->getDeclContext()->isFileContext())
4096     Dcl->setTopLevelDeclInObjCContainer();
4097 
4098   return Dcl;
4099 }
4100 
4101 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4102 ///   If T is the name of a class, then each of the following shall have a
4103 ///   name different from T:
4104 ///     - every static data member of class T;
4105 ///     - every member function of class T
4106 ///     - every member of class T that is itself a type;
4107 /// \returns true if the declaration name violates these rules.
4108 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4109                                    DeclarationNameInfo NameInfo) {
4110   DeclarationName Name = NameInfo.getName();
4111 
4112   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4113     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4114       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4115       return true;
4116     }
4117 
4118   return false;
4119 }
4120 
4121 /// \brief Diagnose a declaration whose declarator-id has the given
4122 /// nested-name-specifier.
4123 ///
4124 /// \param SS The nested-name-specifier of the declarator-id.
4125 ///
4126 /// \param DC The declaration context to which the nested-name-specifier
4127 /// resolves.
4128 ///
4129 /// \param Name The name of the entity being declared.
4130 ///
4131 /// \param Loc The location of the name of the entity being declared.
4132 ///
4133 /// \returns true if we cannot safely recover from this error, false otherwise.
4134 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4135                                         DeclarationName Name,
4136                                         SourceLocation Loc) {
4137   DeclContext *Cur = CurContext;
4138   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4139     Cur = Cur->getParent();
4140 
4141   // If the user provided a superfluous scope specifier that refers back to the
4142   // class in which the entity is already declared, diagnose and ignore it.
4143   //
4144   // class X {
4145   //   void X::f();
4146   // };
4147   //
4148   // Note, it was once ill-formed to give redundant qualification in all
4149   // contexts, but that rule was removed by DR482.
4150   if (Cur->Equals(DC)) {
4151     if (Cur->isRecord()) {
4152       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4153                                       : diag::err_member_extra_qualification)
4154         << Name << FixItHint::CreateRemoval(SS.getRange());
4155       SS.clear();
4156     } else {
4157       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4158     }
4159     return false;
4160   }
4161 
4162   // Check whether the qualifying scope encloses the scope of the original
4163   // declaration.
4164   if (!Cur->Encloses(DC)) {
4165     if (Cur->isRecord())
4166       Diag(Loc, diag::err_member_qualification)
4167         << Name << SS.getRange();
4168     else if (isa<TranslationUnitDecl>(DC))
4169       Diag(Loc, diag::err_invalid_declarator_global_scope)
4170         << Name << SS.getRange();
4171     else if (isa<FunctionDecl>(Cur))
4172       Diag(Loc, diag::err_invalid_declarator_in_function)
4173         << Name << SS.getRange();
4174     else if (isa<BlockDecl>(Cur))
4175       Diag(Loc, diag::err_invalid_declarator_in_block)
4176         << Name << SS.getRange();
4177     else
4178       Diag(Loc, diag::err_invalid_declarator_scope)
4179       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4180 
4181     return true;
4182   }
4183 
4184   if (Cur->isRecord()) {
4185     // Cannot qualify members within a class.
4186     Diag(Loc, diag::err_member_qualification)
4187       << Name << SS.getRange();
4188     SS.clear();
4189 
4190     // C++ constructors and destructors with incorrect scopes can break
4191     // our AST invariants by having the wrong underlying types. If
4192     // that's the case, then drop this declaration entirely.
4193     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4194          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4195         !Context.hasSameType(Name.getCXXNameType(),
4196                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4197       return true;
4198 
4199     return false;
4200   }
4201 
4202   // C++11 [dcl.meaning]p1:
4203   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4204   //   not begin with a decltype-specifer"
4205   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4206   while (SpecLoc.getPrefix())
4207     SpecLoc = SpecLoc.getPrefix();
4208   if (dyn_cast_or_null<DecltypeType>(
4209         SpecLoc.getNestedNameSpecifier()->getAsType()))
4210     Diag(Loc, diag::err_decltype_in_declarator)
4211       << SpecLoc.getTypeLoc().getSourceRange();
4212 
4213   return false;
4214 }
4215 
4216 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4217                                   MultiTemplateParamsArg TemplateParamLists) {
4218   // TODO: consider using NameInfo for diagnostic.
4219   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4220   DeclarationName Name = NameInfo.getName();
4221 
4222   // All of these full declarators require an identifier.  If it doesn't have
4223   // one, the ParsedFreeStandingDeclSpec action should be used.
4224   if (!Name) {
4225     if (!D.isInvalidType())  // Reject this if we think it is valid.
4226       Diag(D.getDeclSpec().getLocStart(),
4227            diag::err_declarator_need_ident)
4228         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4229     return 0;
4230   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4231     return 0;
4232 
4233   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4234   // we find one that is.
4235   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4236          (S->getFlags() & Scope::TemplateParamScope) != 0)
4237     S = S->getParent();
4238 
4239   DeclContext *DC = CurContext;
4240   if (D.getCXXScopeSpec().isInvalid())
4241     D.setInvalidType();
4242   else if (D.getCXXScopeSpec().isSet()) {
4243     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4244                                         UPPC_DeclarationQualifier))
4245       return 0;
4246 
4247     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4248     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4249     if (!DC || isa<EnumDecl>(DC)) {
4250       // If we could not compute the declaration context, it's because the
4251       // declaration context is dependent but does not refer to a class,
4252       // class template, or class template partial specialization. Complain
4253       // and return early, to avoid the coming semantic disaster.
4254       Diag(D.getIdentifierLoc(),
4255            diag::err_template_qualified_declarator_no_match)
4256         << D.getCXXScopeSpec().getScopeRep()
4257         << D.getCXXScopeSpec().getRange();
4258       return 0;
4259     }
4260     bool IsDependentContext = DC->isDependentContext();
4261 
4262     if (!IsDependentContext &&
4263         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4264       return 0;
4265 
4266     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4267       Diag(D.getIdentifierLoc(),
4268            diag::err_member_def_undefined_record)
4269         << Name << DC << D.getCXXScopeSpec().getRange();
4270       D.setInvalidType();
4271     } else if (!D.getDeclSpec().isFriendSpecified()) {
4272       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4273                                       Name, D.getIdentifierLoc())) {
4274         if (DC->isRecord())
4275           return 0;
4276 
4277         D.setInvalidType();
4278       }
4279     }
4280 
4281     // Check whether we need to rebuild the type of the given
4282     // declaration in the current instantiation.
4283     if (EnteringContext && IsDependentContext &&
4284         TemplateParamLists.size() != 0) {
4285       ContextRAII SavedContext(*this, DC);
4286       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4287         D.setInvalidType();
4288     }
4289   }
4290 
4291   if (DiagnoseClassNameShadow(DC, NameInfo))
4292     // If this is a typedef, we'll end up spewing multiple diagnostics.
4293     // Just return early; it's safer.
4294     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4295       return 0;
4296 
4297   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4298   QualType R = TInfo->getType();
4299 
4300   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4301                                       UPPC_DeclarationType))
4302     D.setInvalidType();
4303 
4304   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4305                         ForRedeclaration);
4306 
4307   // See if this is a redefinition of a variable in the same scope.
4308   if (!D.getCXXScopeSpec().isSet()) {
4309     bool IsLinkageLookup = false;
4310     bool CreateBuiltins = false;
4311 
4312     // If the declaration we're planning to build will be a function
4313     // or object with linkage, then look for another declaration with
4314     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4315     //
4316     // If the declaration we're planning to build will be declared with
4317     // external linkage in the translation unit, create any builtin with
4318     // the same name.
4319     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4320       /* Do nothing*/;
4321     else if (CurContext->isFunctionOrMethod() &&
4322              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4323               R->isFunctionType())) {
4324       IsLinkageLookup = true;
4325       CreateBuiltins =
4326           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4327     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4328                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4329       CreateBuiltins = true;
4330 
4331     if (IsLinkageLookup)
4332       Previous.clear(LookupRedeclarationWithLinkage);
4333 
4334     LookupName(Previous, S, CreateBuiltins);
4335   } else { // Something like "int foo::x;"
4336     LookupQualifiedName(Previous, DC);
4337 
4338     // C++ [dcl.meaning]p1:
4339     //   When the declarator-id is qualified, the declaration shall refer to a
4340     //  previously declared member of the class or namespace to which the
4341     //  qualifier refers (or, in the case of a namespace, of an element of the
4342     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4343     //  thereof; [...]
4344     //
4345     // Note that we already checked the context above, and that we do not have
4346     // enough information to make sure that Previous contains the declaration
4347     // we want to match. For example, given:
4348     //
4349     //   class X {
4350     //     void f();
4351     //     void f(float);
4352     //   };
4353     //
4354     //   void X::f(int) { } // ill-formed
4355     //
4356     // In this case, Previous will point to the overload set
4357     // containing the two f's declared in X, but neither of them
4358     // matches.
4359 
4360     // C++ [dcl.meaning]p1:
4361     //   [...] the member shall not merely have been introduced by a
4362     //   using-declaration in the scope of the class or namespace nominated by
4363     //   the nested-name-specifier of the declarator-id.
4364     RemoveUsingDecls(Previous);
4365   }
4366 
4367   if (Previous.isSingleResult() &&
4368       Previous.getFoundDecl()->isTemplateParameter()) {
4369     // Maybe we will complain about the shadowed template parameter.
4370     if (!D.isInvalidType())
4371       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4372                                       Previous.getFoundDecl());
4373 
4374     // Just pretend that we didn't see the previous declaration.
4375     Previous.clear();
4376   }
4377 
4378   // In C++, the previous declaration we find might be a tag type
4379   // (class or enum). In this case, the new declaration will hide the
4380   // tag type. Note that this does does not apply if we're declaring a
4381   // typedef (C++ [dcl.typedef]p4).
4382   if (Previous.isSingleTagDecl() &&
4383       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4384     Previous.clear();
4385 
4386   // Check that there are no default arguments other than in the parameters
4387   // of a function declaration (C++ only).
4388   if (getLangOpts().CPlusPlus)
4389     CheckExtraCXXDefaultArguments(D);
4390 
4391   NamedDecl *New;
4392 
4393   bool AddToScope = true;
4394   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4395     if (TemplateParamLists.size()) {
4396       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4397       return 0;
4398     }
4399 
4400     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4401   } else if (R->isFunctionType()) {
4402     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4403                                   TemplateParamLists,
4404                                   AddToScope);
4405   } else {
4406     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4407                                   AddToScope);
4408   }
4409 
4410   if (New == 0)
4411     return 0;
4412 
4413   // If this has an identifier and is not an invalid redeclaration or
4414   // function template specialization, add it to the scope stack.
4415   if (New->getDeclName() && AddToScope &&
4416        !(D.isRedeclaration() && New->isInvalidDecl())) {
4417     // Only make a locally-scoped extern declaration visible if it is the first
4418     // declaration of this entity. Qualified lookup for such an entity should
4419     // only find this declaration if there is no visible declaration of it.
4420     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4421     PushOnScopeChains(New, S, AddToContext);
4422     if (!AddToContext)
4423       CurContext->addHiddenDecl(New);
4424   }
4425 
4426   return New;
4427 }
4428 
4429 /// Helper method to turn variable array types into constant array
4430 /// types in certain situations which would otherwise be errors (for
4431 /// GCC compatibility).
4432 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4433                                                     ASTContext &Context,
4434                                                     bool &SizeIsNegative,
4435                                                     llvm::APSInt &Oversized) {
4436   // This method tries to turn a variable array into a constant
4437   // array even when the size isn't an ICE.  This is necessary
4438   // for compatibility with code that depends on gcc's buggy
4439   // constant expression folding, like struct {char x[(int)(char*)2];}
4440   SizeIsNegative = false;
4441   Oversized = 0;
4442 
4443   if (T->isDependentType())
4444     return QualType();
4445 
4446   QualifierCollector Qs;
4447   const Type *Ty = Qs.strip(T);
4448 
4449   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4450     QualType Pointee = PTy->getPointeeType();
4451     QualType FixedType =
4452         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4453                                             Oversized);
4454     if (FixedType.isNull()) return FixedType;
4455     FixedType = Context.getPointerType(FixedType);
4456     return Qs.apply(Context, FixedType);
4457   }
4458   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4459     QualType Inner = PTy->getInnerType();
4460     QualType FixedType =
4461         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4462                                             Oversized);
4463     if (FixedType.isNull()) return FixedType;
4464     FixedType = Context.getParenType(FixedType);
4465     return Qs.apply(Context, FixedType);
4466   }
4467 
4468   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4469   if (!VLATy)
4470     return QualType();
4471   // FIXME: We should probably handle this case
4472   if (VLATy->getElementType()->isVariablyModifiedType())
4473     return QualType();
4474 
4475   llvm::APSInt Res;
4476   if (!VLATy->getSizeExpr() ||
4477       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4478     return QualType();
4479 
4480   // Check whether the array size is negative.
4481   if (Res.isSigned() && Res.isNegative()) {
4482     SizeIsNegative = true;
4483     return QualType();
4484   }
4485 
4486   // Check whether the array is too large to be addressed.
4487   unsigned ActiveSizeBits
4488     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4489                                               Res);
4490   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4491     Oversized = Res;
4492     return QualType();
4493   }
4494 
4495   return Context.getConstantArrayType(VLATy->getElementType(),
4496                                       Res, ArrayType::Normal, 0);
4497 }
4498 
4499 static void
4500 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4501   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4502     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4503     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4504                                       DstPTL.getPointeeLoc());
4505     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4506     return;
4507   }
4508   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4509     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4510     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4511                                       DstPTL.getInnerLoc());
4512     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4513     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4514     return;
4515   }
4516   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4517   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4518   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4519   TypeLoc DstElemTL = DstATL.getElementLoc();
4520   DstElemTL.initializeFullCopy(SrcElemTL);
4521   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4522   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4523   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4524 }
4525 
4526 /// Helper method to turn variable array types into constant array
4527 /// types in certain situations which would otherwise be errors (for
4528 /// GCC compatibility).
4529 static TypeSourceInfo*
4530 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4531                                               ASTContext &Context,
4532                                               bool &SizeIsNegative,
4533                                               llvm::APSInt &Oversized) {
4534   QualType FixedTy
4535     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4536                                           SizeIsNegative, Oversized);
4537   if (FixedTy.isNull())
4538     return 0;
4539   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4540   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4541                                     FixedTInfo->getTypeLoc());
4542   return FixedTInfo;
4543 }
4544 
4545 /// \brief Register the given locally-scoped extern "C" declaration so
4546 /// that it can be found later for redeclarations. We include any extern "C"
4547 /// declaration that is not visible in the translation unit here, not just
4548 /// function-scope declarations.
4549 void
4550 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4551   if (!getLangOpts().CPlusPlus &&
4552       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4553     // Don't need to track declarations in the TU in C.
4554     return;
4555 
4556   // Note that we have a locally-scoped external with this name.
4557   // FIXME: There can be multiple such declarations if they are functions marked
4558   // __attribute__((overloadable)) declared in function scope in C.
4559   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4560 }
4561 
4562 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4563   if (ExternalSource) {
4564     // Load locally-scoped external decls from the external source.
4565     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4566     SmallVector<NamedDecl *, 4> Decls;
4567     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4568     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4569       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4570         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4571       if (Pos == LocallyScopedExternCDecls.end())
4572         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4573     }
4574   }
4575 
4576   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4577   return D ? D->getMostRecentDecl() : 0;
4578 }
4579 
4580 /// \brief Diagnose function specifiers on a declaration of an identifier that
4581 /// does not identify a function.
4582 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4583   // FIXME: We should probably indicate the identifier in question to avoid
4584   // confusion for constructs like "inline int a(), b;"
4585   if (DS.isInlineSpecified())
4586     Diag(DS.getInlineSpecLoc(),
4587          diag::err_inline_non_function);
4588 
4589   if (DS.isVirtualSpecified())
4590     Diag(DS.getVirtualSpecLoc(),
4591          diag::err_virtual_non_function);
4592 
4593   if (DS.isExplicitSpecified())
4594     Diag(DS.getExplicitSpecLoc(),
4595          diag::err_explicit_non_function);
4596 
4597   if (DS.isNoreturnSpecified())
4598     Diag(DS.getNoreturnSpecLoc(),
4599          diag::err_noreturn_non_function);
4600 }
4601 
4602 NamedDecl*
4603 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4604                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4605   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4606   if (D.getCXXScopeSpec().isSet()) {
4607     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4608       << D.getCXXScopeSpec().getRange();
4609     D.setInvalidType();
4610     // Pretend we didn't see the scope specifier.
4611     DC = CurContext;
4612     Previous.clear();
4613   }
4614 
4615   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4616 
4617   if (D.getDeclSpec().isConstexprSpecified())
4618     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4619       << 1;
4620 
4621   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4622     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4623       << D.getName().getSourceRange();
4624     return 0;
4625   }
4626 
4627   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4628   if (!NewTD) return 0;
4629 
4630   // Handle attributes prior to checking for duplicates in MergeVarDecl
4631   ProcessDeclAttributes(S, NewTD, D);
4632 
4633   CheckTypedefForVariablyModifiedType(S, NewTD);
4634 
4635   bool Redeclaration = D.isRedeclaration();
4636   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4637   D.setRedeclaration(Redeclaration);
4638   return ND;
4639 }
4640 
4641 void
4642 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4643   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4644   // then it shall have block scope.
4645   // Note that variably modified types must be fixed before merging the decl so
4646   // that redeclarations will match.
4647   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4648   QualType T = TInfo->getType();
4649   if (T->isVariablyModifiedType()) {
4650     getCurFunction()->setHasBranchProtectedScope();
4651 
4652     if (S->getFnParent() == 0) {
4653       bool SizeIsNegative;
4654       llvm::APSInt Oversized;
4655       TypeSourceInfo *FixedTInfo =
4656         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4657                                                       SizeIsNegative,
4658                                                       Oversized);
4659       if (FixedTInfo) {
4660         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4661         NewTD->setTypeSourceInfo(FixedTInfo);
4662       } else {
4663         if (SizeIsNegative)
4664           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4665         else if (T->isVariableArrayType())
4666           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4667         else if (Oversized.getBoolValue())
4668           Diag(NewTD->getLocation(), diag::err_array_too_large)
4669             << Oversized.toString(10);
4670         else
4671           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4672         NewTD->setInvalidDecl();
4673       }
4674     }
4675   }
4676 }
4677 
4678 
4679 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4680 /// declares a typedef-name, either using the 'typedef' type specifier or via
4681 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4682 NamedDecl*
4683 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4684                            LookupResult &Previous, bool &Redeclaration) {
4685   // Merge the decl with the existing one if appropriate. If the decl is
4686   // in an outer scope, it isn't the same thing.
4687   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4688                        /*AllowInlineNamespace*/false);
4689   filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4690   if (!Previous.empty()) {
4691     Redeclaration = true;
4692     MergeTypedefNameDecl(NewTD, Previous);
4693   }
4694 
4695   // If this is the C FILE type, notify the AST context.
4696   if (IdentifierInfo *II = NewTD->getIdentifier())
4697     if (!NewTD->isInvalidDecl() &&
4698         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4699       if (II->isStr("FILE"))
4700         Context.setFILEDecl(NewTD);
4701       else if (II->isStr("jmp_buf"))
4702         Context.setjmp_bufDecl(NewTD);
4703       else if (II->isStr("sigjmp_buf"))
4704         Context.setsigjmp_bufDecl(NewTD);
4705       else if (II->isStr("ucontext_t"))
4706         Context.setucontext_tDecl(NewTD);
4707     }
4708 
4709   return NewTD;
4710 }
4711 
4712 /// \brief Determines whether the given declaration is an out-of-scope
4713 /// previous declaration.
4714 ///
4715 /// This routine should be invoked when name lookup has found a
4716 /// previous declaration (PrevDecl) that is not in the scope where a
4717 /// new declaration by the same name is being introduced. If the new
4718 /// declaration occurs in a local scope, previous declarations with
4719 /// linkage may still be considered previous declarations (C99
4720 /// 6.2.2p4-5, C++ [basic.link]p6).
4721 ///
4722 /// \param PrevDecl the previous declaration found by name
4723 /// lookup
4724 ///
4725 /// \param DC the context in which the new declaration is being
4726 /// declared.
4727 ///
4728 /// \returns true if PrevDecl is an out-of-scope previous declaration
4729 /// for a new delcaration with the same name.
4730 static bool
4731 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4732                                 ASTContext &Context) {
4733   if (!PrevDecl)
4734     return false;
4735 
4736   if (!PrevDecl->hasLinkage())
4737     return false;
4738 
4739   if (Context.getLangOpts().CPlusPlus) {
4740     // C++ [basic.link]p6:
4741     //   If there is a visible declaration of an entity with linkage
4742     //   having the same name and type, ignoring entities declared
4743     //   outside the innermost enclosing namespace scope, the block
4744     //   scope declaration declares that same entity and receives the
4745     //   linkage of the previous declaration.
4746     DeclContext *OuterContext = DC->getRedeclContext();
4747     if (!OuterContext->isFunctionOrMethod())
4748       // This rule only applies to block-scope declarations.
4749       return false;
4750 
4751     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4752     if (PrevOuterContext->isRecord())
4753       // We found a member function: ignore it.
4754       return false;
4755 
4756     // Find the innermost enclosing namespace for the new and
4757     // previous declarations.
4758     OuterContext = OuterContext->getEnclosingNamespaceContext();
4759     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4760 
4761     // The previous declaration is in a different namespace, so it
4762     // isn't the same function.
4763     if (!OuterContext->Equals(PrevOuterContext))
4764       return false;
4765   }
4766 
4767   return true;
4768 }
4769 
4770 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4771   CXXScopeSpec &SS = D.getCXXScopeSpec();
4772   if (!SS.isSet()) return;
4773   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4774 }
4775 
4776 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4777   QualType type = decl->getType();
4778   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4779   if (lifetime == Qualifiers::OCL_Autoreleasing) {
4780     // Various kinds of declaration aren't allowed to be __autoreleasing.
4781     unsigned kind = -1U;
4782     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4783       if (var->hasAttr<BlocksAttr>())
4784         kind = 0; // __block
4785       else if (!var->hasLocalStorage())
4786         kind = 1; // global
4787     } else if (isa<ObjCIvarDecl>(decl)) {
4788       kind = 3; // ivar
4789     } else if (isa<FieldDecl>(decl)) {
4790       kind = 2; // field
4791     }
4792 
4793     if (kind != -1U) {
4794       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4795         << kind;
4796     }
4797   } else if (lifetime == Qualifiers::OCL_None) {
4798     // Try to infer lifetime.
4799     if (!type->isObjCLifetimeType())
4800       return false;
4801 
4802     lifetime = type->getObjCARCImplicitLifetime();
4803     type = Context.getLifetimeQualifiedType(type, lifetime);
4804     decl->setType(type);
4805   }
4806 
4807   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4808     // Thread-local variables cannot have lifetime.
4809     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4810         var->getTLSKind()) {
4811       Diag(var->getLocation(), diag::err_arc_thread_ownership)
4812         << var->getType();
4813       return true;
4814     }
4815   }
4816 
4817   return false;
4818 }
4819 
4820 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4821   // Ensure that an auto decl is deduced otherwise the checks below might cache
4822   // the wrong linkage.
4823   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4824 
4825   // 'weak' only applies to declarations with external linkage.
4826   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4827     if (!ND.isExternallyVisible()) {
4828       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4829       ND.dropAttr<WeakAttr>();
4830     }
4831   }
4832   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4833     if (ND.isExternallyVisible()) {
4834       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4835       ND.dropAttr<WeakRefAttr>();
4836     }
4837   }
4838 
4839   // 'selectany' only applies to externally visible varable declarations.
4840   // It does not apply to functions.
4841   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4842     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4843       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4844       ND.dropAttr<SelectAnyAttr>();
4845     }
4846   }
4847 
4848   // dll attributes require external linkage.
4849   if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) {
4850     if (!ND.isExternallyVisible()) {
4851       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4852         << &ND << Attr;
4853       ND.setInvalidDecl();
4854     }
4855   }
4856   if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) {
4857     if (!ND.isExternallyVisible()) {
4858       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
4859         << &ND << Attr;
4860       ND.setInvalidDecl();
4861     }
4862   }
4863 }
4864 
4865 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
4866                                            NamedDecl *NewDecl,
4867                                            bool IsSpecialization) {
4868   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
4869     OldDecl = OldTD->getTemplatedDecl();
4870   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
4871     NewDecl = NewTD->getTemplatedDecl();
4872 
4873   if (!OldDecl || !NewDecl)
4874       return;
4875 
4876   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
4877   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
4878   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
4879   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
4880 
4881   // dllimport and dllexport are inheritable attributes so we have to exclude
4882   // inherited attribute instances.
4883   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
4884                     (NewExportAttr && !NewExportAttr->isInherited());
4885 
4886   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
4887   // the only exception being explicit specializations.
4888   // Implicitly generated declarations are also excluded for now because there
4889   // is no other way to switch these to use dllimport or dllexport.
4890   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
4891   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
4892     S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration)
4893       << NewDecl
4894       << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
4895     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4896     NewDecl->setInvalidDecl();
4897     return;
4898   }
4899 
4900   // A redeclaration is not allowed to drop a dllimport attribute, the only
4901   // exception being inline function definitions.
4902   // FIXME: Handle inline functions.
4903   // NB: MSVC converts such a declaration to dllexport.
4904   if (OldImportAttr && !HasNewAttr) {
4905     S.Diag(NewDecl->getLocation(),
4906            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4907       << NewDecl << OldImportAttr;
4908     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
4909     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
4910     OldDecl->dropAttr<DLLImportAttr>();
4911     NewDecl->dropAttr<DLLImportAttr>();
4912   }
4913 }
4914 
4915 /// Given that we are within the definition of the given function,
4916 /// will that definition behave like C99's 'inline', where the
4917 /// definition is discarded except for optimization purposes?
4918 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4919   // Try to avoid calling GetGVALinkageForFunction.
4920 
4921   // All cases of this require the 'inline' keyword.
4922   if (!FD->isInlined()) return false;
4923 
4924   // This is only possible in C++ with the gnu_inline attribute.
4925   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4926     return false;
4927 
4928   // Okay, go ahead and call the relatively-more-expensive function.
4929 
4930 #ifndef NDEBUG
4931   // AST quite reasonably asserts that it's working on a function
4932   // definition.  We don't really have a way to tell it that we're
4933   // currently defining the function, so just lie to it in +Asserts
4934   // builds.  This is an awful hack.
4935   FD->setLazyBody(1);
4936 #endif
4937 
4938   bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4939 
4940 #ifndef NDEBUG
4941   FD->setLazyBody(0);
4942 #endif
4943 
4944   return isC99Inline;
4945 }
4946 
4947 /// Determine whether a variable is extern "C" prior to attaching
4948 /// an initializer. We can't just call isExternC() here, because that
4949 /// will also compute and cache whether the declaration is externally
4950 /// visible, which might change when we attach the initializer.
4951 ///
4952 /// This can only be used if the declaration is known to not be a
4953 /// redeclaration of an internal linkage declaration.
4954 ///
4955 /// For instance:
4956 ///
4957 ///   auto x = []{};
4958 ///
4959 /// Attaching the initializer here makes this declaration not externally
4960 /// visible, because its type has internal linkage.
4961 ///
4962 /// FIXME: This is a hack.
4963 template<typename T>
4964 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4965   if (S.getLangOpts().CPlusPlus) {
4966     // In C++, the overloadable attribute negates the effects of extern "C".
4967     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4968       return false;
4969   }
4970   return D->isExternC();
4971 }
4972 
4973 static bool shouldConsiderLinkage(const VarDecl *VD) {
4974   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4975   if (DC->isFunctionOrMethod())
4976     return VD->hasExternalStorage();
4977   if (DC->isFileContext())
4978     return true;
4979   if (DC->isRecord())
4980     return false;
4981   llvm_unreachable("Unexpected context");
4982 }
4983 
4984 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4985   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4986   if (DC->isFileContext() || DC->isFunctionOrMethod())
4987     return true;
4988   if (DC->isRecord())
4989     return false;
4990   llvm_unreachable("Unexpected context");
4991 }
4992 
4993 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
4994                           AttributeList::Kind Kind) {
4995   for (const AttributeList *L = AttrList; L; L = L->getNext())
4996     if (L->getKind() == Kind)
4997       return true;
4998   return false;
4999 }
5000 
5001 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5002                           AttributeList::Kind Kind) {
5003   // Check decl attributes on the DeclSpec.
5004   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5005     return true;
5006 
5007   // Walk the declarator structure, checking decl attributes that were in a type
5008   // position to the decl itself.
5009   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5010     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5011       return true;
5012   }
5013 
5014   // Finally, check attributes on the decl itself.
5015   return hasParsedAttr(S, PD.getAttributes(), Kind);
5016 }
5017 
5018 /// Adjust the \c DeclContext for a function or variable that might be a
5019 /// function-local external declaration.
5020 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5021   if (!DC->isFunctionOrMethod())
5022     return false;
5023 
5024   // If this is a local extern function or variable declared within a function
5025   // template, don't add it into the enclosing namespace scope until it is
5026   // instantiated; it might have a dependent type right now.
5027   if (DC->isDependentContext())
5028     return true;
5029 
5030   // C++11 [basic.link]p7:
5031   //   When a block scope declaration of an entity with linkage is not found to
5032   //   refer to some other declaration, then that entity is a member of the
5033   //   innermost enclosing namespace.
5034   //
5035   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5036   // semantically-enclosing namespace, not a lexically-enclosing one.
5037   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5038     DC = DC->getParent();
5039   return true;
5040 }
5041 
5042 NamedDecl *
5043 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5044                               TypeSourceInfo *TInfo, LookupResult &Previous,
5045                               MultiTemplateParamsArg TemplateParamLists,
5046                               bool &AddToScope) {
5047   QualType R = TInfo->getType();
5048   DeclarationName Name = GetNameForDeclarator(D).getName();
5049 
5050   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5051   VarDecl::StorageClass SC =
5052     StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5053 
5054   // dllimport globals without explicit storage class are treated as extern. We
5055   // have to change the storage class this early to get the right DeclContext.
5056   if (SC == SC_None && !DC->isRecord() &&
5057       hasParsedAttr(S, D, AttributeList::AT_DLLImport))
5058     SC = SC_Extern;
5059 
5060   DeclContext *OriginalDC = DC;
5061   bool IsLocalExternDecl = SC == SC_Extern &&
5062                            adjustContextForLocalExternDecl(DC);
5063 
5064   if (getLangOpts().OpenCL) {
5065     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5066     QualType NR = R;
5067     while (NR->isPointerType()) {
5068       if (NR->isFunctionPointerType()) {
5069         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5070         D.setInvalidType();
5071         break;
5072       }
5073       NR = NR->getPointeeType();
5074     }
5075 
5076     if (!getOpenCLOptions().cl_khr_fp16) {
5077       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5078       // half array type (unless the cl_khr_fp16 extension is enabled).
5079       if (Context.getBaseElementType(R)->isHalfType()) {
5080         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5081         D.setInvalidType();
5082       }
5083     }
5084   }
5085 
5086   if (SCSpec == DeclSpec::SCS_mutable) {
5087     // mutable can only appear on non-static class members, so it's always
5088     // an error here
5089     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5090     D.setInvalidType();
5091     SC = SC_None;
5092   }
5093 
5094   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5095       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5096                               D.getDeclSpec().getStorageClassSpecLoc())) {
5097     // In C++11, the 'register' storage class specifier is deprecated.
5098     // Suppress the warning in system macros, it's used in macros in some
5099     // popular C system headers, such as in glibc's htonl() macro.
5100     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5101          diag::warn_deprecated_register)
5102       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5103   }
5104 
5105   IdentifierInfo *II = Name.getAsIdentifierInfo();
5106   if (!II) {
5107     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5108       << Name;
5109     return 0;
5110   }
5111 
5112   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5113 
5114   if (!DC->isRecord() && S->getFnParent() == 0) {
5115     // C99 6.9p2: The storage-class specifiers auto and register shall not
5116     // appear in the declaration specifiers in an external declaration.
5117     if (SC == SC_Auto || SC == SC_Register) {
5118       // If this is a register variable with an asm label specified, then this
5119       // is a GNU extension.
5120       if (SC == SC_Register && D.getAsmLabel())
5121         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5122       else
5123         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5124       D.setInvalidType();
5125     }
5126   }
5127 
5128   if (getLangOpts().OpenCL) {
5129     // Set up the special work-group-local storage class for variables in the
5130     // OpenCL __local address space.
5131     if (R.getAddressSpace() == LangAS::opencl_local) {
5132       SC = SC_OpenCLWorkGroupLocal;
5133     }
5134 
5135     // OpenCL v1.2 s6.9.b p4:
5136     // The sampler type cannot be used with the __local and __global address
5137     // space qualifiers.
5138     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5139       R.getAddressSpace() == LangAS::opencl_global)) {
5140       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5141     }
5142 
5143     // OpenCL 1.2 spec, p6.9 r:
5144     // The event type cannot be used to declare a program scope variable.
5145     // The event type cannot be used with the __local, __constant and __global
5146     // address space qualifiers.
5147     if (R->isEventT()) {
5148       if (S->getParent() == 0) {
5149         Diag(D.getLocStart(), diag::err_event_t_global_var);
5150         D.setInvalidType();
5151       }
5152 
5153       if (R.getAddressSpace()) {
5154         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5155         D.setInvalidType();
5156       }
5157     }
5158   }
5159 
5160   bool IsExplicitSpecialization = false;
5161   bool IsVariableTemplateSpecialization = false;
5162   bool IsPartialSpecialization = false;
5163   bool IsVariableTemplate = false;
5164   VarDecl *NewVD = 0;
5165   VarTemplateDecl *NewTemplate = 0;
5166   TemplateParameterList *TemplateParams = 0;
5167   if (!getLangOpts().CPlusPlus) {
5168     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5169                             D.getIdentifierLoc(), II,
5170                             R, TInfo, SC);
5171 
5172     if (D.isInvalidType())
5173       NewVD->setInvalidDecl();
5174   } else {
5175     bool Invalid = false;
5176 
5177     if (DC->isRecord() && !CurContext->isRecord()) {
5178       // This is an out-of-line definition of a static data member.
5179       switch (SC) {
5180       case SC_None:
5181         break;
5182       case SC_Static:
5183         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5184              diag::err_static_out_of_line)
5185           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5186         break;
5187       case SC_Auto:
5188       case SC_Register:
5189       case SC_Extern:
5190         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5191         // to names of variables declared in a block or to function parameters.
5192         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5193         // of class members
5194 
5195         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5196              diag::err_storage_class_for_static_member)
5197           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5198         break;
5199       case SC_PrivateExtern:
5200         llvm_unreachable("C storage class in c++!");
5201       case SC_OpenCLWorkGroupLocal:
5202         llvm_unreachable("OpenCL storage class in c++!");
5203       }
5204     }
5205 
5206     if (SC == SC_Static && CurContext->isRecord()) {
5207       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5208         if (RD->isLocalClass())
5209           Diag(D.getIdentifierLoc(),
5210                diag::err_static_data_member_not_allowed_in_local_class)
5211             << Name << RD->getDeclName();
5212 
5213         // C++98 [class.union]p1: If a union contains a static data member,
5214         // the program is ill-formed. C++11 drops this restriction.
5215         if (RD->isUnion())
5216           Diag(D.getIdentifierLoc(),
5217                getLangOpts().CPlusPlus11
5218                  ? diag::warn_cxx98_compat_static_data_member_in_union
5219                  : diag::ext_static_data_member_in_union) << Name;
5220         // We conservatively disallow static data members in anonymous structs.
5221         else if (!RD->getDeclName())
5222           Diag(D.getIdentifierLoc(),
5223                diag::err_static_data_member_not_allowed_in_anon_struct)
5224             << Name << RD->isUnion();
5225       }
5226     }
5227 
5228     // Match up the template parameter lists with the scope specifier, then
5229     // determine whether we have a template or a template specialization.
5230     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5231         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5232         D.getCXXScopeSpec(), TemplateParamLists,
5233         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5234 
5235     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
5236         !TemplateParams) {
5237       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5238 
5239       // We have encountered something that the user meant to be a
5240       // specialization (because it has explicitly-specified template
5241       // arguments) but that was not introduced with a "template<>" (or had
5242       // too few of them).
5243       // FIXME: Differentiate between attempts for explicit instantiations
5244       // (starting with "template") and the rest.
5245       Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5246           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5247           << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5248                                         "template<> ");
5249       IsExplicitSpecialization = true;
5250       TemplateParams = TemplateParameterList::Create(Context, SourceLocation(),
5251                                                      SourceLocation(), 0, 0,
5252                                                      SourceLocation());
5253     }
5254 
5255     if (TemplateParams) {
5256       if (!TemplateParams->size() &&
5257           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5258         // There is an extraneous 'template<>' for this variable. Complain
5259         // about it, but allow the declaration of the variable.
5260         Diag(TemplateParams->getTemplateLoc(),
5261              diag::err_template_variable_noparams)
5262           << II
5263           << SourceRange(TemplateParams->getTemplateLoc(),
5264                          TemplateParams->getRAngleLoc());
5265         TemplateParams = 0;
5266       } else {
5267         // Only C++1y supports variable templates (N3651).
5268         Diag(D.getIdentifierLoc(),
5269              getLangOpts().CPlusPlus1y
5270                  ? diag::warn_cxx11_compat_variable_template
5271                  : diag::ext_variable_template);
5272 
5273         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5274           // This is an explicit specialization or a partial specialization.
5275           // FIXME: Check that we can declare a specialization here.
5276           IsVariableTemplateSpecialization = true;
5277           IsPartialSpecialization = TemplateParams->size() > 0;
5278         } else { // if (TemplateParams->size() > 0)
5279           // This is a template declaration.
5280           IsVariableTemplate = true;
5281 
5282           // Check that we can declare a template here.
5283           if (CheckTemplateDeclScope(S, TemplateParams))
5284             return 0;
5285         }
5286       }
5287     }
5288 
5289     if (IsVariableTemplateSpecialization) {
5290       SourceLocation TemplateKWLoc =
5291           TemplateParamLists.size() > 0
5292               ? TemplateParamLists[0]->getTemplateLoc()
5293               : SourceLocation();
5294       DeclResult Res = ActOnVarTemplateSpecialization(
5295           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5296           IsPartialSpecialization);
5297       if (Res.isInvalid())
5298         return 0;
5299       NewVD = cast<VarDecl>(Res.get());
5300       AddToScope = false;
5301     } else
5302       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5303                               D.getIdentifierLoc(), II, R, TInfo, SC);
5304 
5305     // If this is supposed to be a variable template, create it as such.
5306     if (IsVariableTemplate) {
5307       NewTemplate =
5308           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5309                                   TemplateParams, NewVD);
5310       NewVD->setDescribedVarTemplate(NewTemplate);
5311     }
5312 
5313     // If this decl has an auto type in need of deduction, make a note of the
5314     // Decl so we can diagnose uses of it in its own initializer.
5315     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5316       ParsingInitForAutoVars.insert(NewVD);
5317 
5318     if (D.isInvalidType() || Invalid) {
5319       NewVD->setInvalidDecl();
5320       if (NewTemplate)
5321         NewTemplate->setInvalidDecl();
5322     }
5323 
5324     SetNestedNameSpecifier(NewVD, D);
5325 
5326     // If we have any template parameter lists that don't directly belong to
5327     // the variable (matching the scope specifier), store them.
5328     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5329     if (TemplateParamLists.size() > VDTemplateParamLists)
5330       NewVD->setTemplateParameterListsInfo(
5331           Context, TemplateParamLists.size() - VDTemplateParamLists,
5332           TemplateParamLists.data());
5333 
5334     if (D.getDeclSpec().isConstexprSpecified())
5335       NewVD->setConstexpr(true);
5336   }
5337 
5338   // Set the lexical context. If the declarator has a C++ scope specifier, the
5339   // lexical context will be different from the semantic context.
5340   NewVD->setLexicalDeclContext(CurContext);
5341   if (NewTemplate)
5342     NewTemplate->setLexicalDeclContext(CurContext);
5343 
5344   if (IsLocalExternDecl)
5345     NewVD->setLocalExternDecl();
5346 
5347   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5348     if (NewVD->hasLocalStorage()) {
5349       // C++11 [dcl.stc]p4:
5350       //   When thread_local is applied to a variable of block scope the
5351       //   storage-class-specifier static is implied if it does not appear
5352       //   explicitly.
5353       // Core issue: 'static' is not implied if the variable is declared
5354       //   'extern'.
5355       if (SCSpec == DeclSpec::SCS_unspecified &&
5356           TSCS == DeclSpec::TSCS_thread_local &&
5357           DC->isFunctionOrMethod())
5358         NewVD->setTSCSpec(TSCS);
5359       else
5360         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5361              diag::err_thread_non_global)
5362           << DeclSpec::getSpecifierName(TSCS);
5363     } else if (!Context.getTargetInfo().isTLSSupported())
5364       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5365            diag::err_thread_unsupported);
5366     else
5367       NewVD->setTSCSpec(TSCS);
5368   }
5369 
5370   // C99 6.7.4p3
5371   //   An inline definition of a function with external linkage shall
5372   //   not contain a definition of a modifiable object with static or
5373   //   thread storage duration...
5374   // We only apply this when the function is required to be defined
5375   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5376   // that a local variable with thread storage duration still has to
5377   // be marked 'static'.  Also note that it's possible to get these
5378   // semantics in C++ using __attribute__((gnu_inline)).
5379   if (SC == SC_Static && S->getFnParent() != 0 &&
5380       !NewVD->getType().isConstQualified()) {
5381     FunctionDecl *CurFD = getCurFunctionDecl();
5382     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5383       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5384            diag::warn_static_local_in_extern_inline);
5385       MaybeSuggestAddingStaticToDecl(CurFD);
5386     }
5387   }
5388 
5389   if (D.getDeclSpec().isModulePrivateSpecified()) {
5390     if (IsVariableTemplateSpecialization)
5391       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5392           << (IsPartialSpecialization ? 1 : 0)
5393           << FixItHint::CreateRemoval(
5394                  D.getDeclSpec().getModulePrivateSpecLoc());
5395     else if (IsExplicitSpecialization)
5396       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5397         << 2
5398         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5399     else if (NewVD->hasLocalStorage())
5400       Diag(NewVD->getLocation(), diag::err_module_private_local)
5401         << 0 << NewVD->getDeclName()
5402         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5403         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5404     else {
5405       NewVD->setModulePrivate();
5406       if (NewTemplate)
5407         NewTemplate->setModulePrivate();
5408     }
5409   }
5410 
5411   // Handle attributes prior to checking for duplicates in MergeVarDecl
5412   ProcessDeclAttributes(S, NewVD, D);
5413 
5414   if (getLangOpts().CUDA) {
5415     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5416     // storage [duration]."
5417     if (SC == SC_None && S->getFnParent() != 0 &&
5418         (NewVD->hasAttr<CUDASharedAttr>() ||
5419          NewVD->hasAttr<CUDAConstantAttr>())) {
5420       NewVD->setStorageClass(SC_Static);
5421     }
5422   }
5423 
5424   // Ensure that dllimport globals without explicit storage class are treated as
5425   // extern. The storage class is set above using parsed attributes. Now we can
5426   // check the VarDecl itself.
5427   assert(!NewVD->hasAttr<DLLImportAttr>() ||
5428          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
5429          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
5430 
5431   // In auto-retain/release, infer strong retension for variables of
5432   // retainable type.
5433   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5434     NewVD->setInvalidDecl();
5435 
5436   // Handle GNU asm-label extension (encoded as an attribute).
5437   if (Expr *E = (Expr*)D.getAsmLabel()) {
5438     // The parser guarantees this is a string.
5439     StringLiteral *SE = cast<StringLiteral>(E);
5440     StringRef Label = SE->getString();
5441     if (S->getFnParent() != 0) {
5442       switch (SC) {
5443       case SC_None:
5444       case SC_Auto:
5445         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5446         break;
5447       case SC_Register:
5448         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5449           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5450         break;
5451       case SC_Static:
5452       case SC_Extern:
5453       case SC_PrivateExtern:
5454       case SC_OpenCLWorkGroupLocal:
5455         break;
5456       }
5457     }
5458 
5459     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5460                                                 Context, Label, 0));
5461   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5462     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5463       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5464     if (I != ExtnameUndeclaredIdentifiers.end()) {
5465       NewVD->addAttr(I->second);
5466       ExtnameUndeclaredIdentifiers.erase(I);
5467     }
5468   }
5469 
5470   // Diagnose shadowed variables before filtering for scope.
5471   if (D.getCXXScopeSpec().isEmpty())
5472     CheckShadow(S, NewVD, Previous);
5473 
5474   // Don't consider existing declarations that are in a different
5475   // scope and are out-of-semantic-context declarations (if the new
5476   // declaration has linkage).
5477   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5478                        D.getCXXScopeSpec().isNotEmpty() ||
5479                        IsExplicitSpecialization ||
5480                        IsVariableTemplateSpecialization);
5481 
5482   // Check whether the previous declaration is in the same block scope. This
5483   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5484   if (getLangOpts().CPlusPlus &&
5485       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5486     NewVD->setPreviousDeclInSameBlockScope(
5487         Previous.isSingleResult() && !Previous.isShadowed() &&
5488         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5489 
5490   if (!getLangOpts().CPlusPlus) {
5491     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5492   } else {
5493     // If this is an explicit specialization of a static data member, check it.
5494     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5495         CheckMemberSpecialization(NewVD, Previous))
5496       NewVD->setInvalidDecl();
5497 
5498     // Merge the decl with the existing one if appropriate.
5499     if (!Previous.empty()) {
5500       if (Previous.isSingleResult() &&
5501           isa<FieldDecl>(Previous.getFoundDecl()) &&
5502           D.getCXXScopeSpec().isSet()) {
5503         // The user tried to define a non-static data member
5504         // out-of-line (C++ [dcl.meaning]p1).
5505         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5506           << D.getCXXScopeSpec().getRange();
5507         Previous.clear();
5508         NewVD->setInvalidDecl();
5509       }
5510     } else if (D.getCXXScopeSpec().isSet()) {
5511       // No previous declaration in the qualifying scope.
5512       Diag(D.getIdentifierLoc(), diag::err_no_member)
5513         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5514         << D.getCXXScopeSpec().getRange();
5515       NewVD->setInvalidDecl();
5516     }
5517 
5518     if (!IsVariableTemplateSpecialization)
5519       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5520 
5521     if (NewTemplate) {
5522       VarTemplateDecl *PrevVarTemplate =
5523           NewVD->getPreviousDecl()
5524               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5525               : 0;
5526 
5527       // Check the template parameter list of this declaration, possibly
5528       // merging in the template parameter list from the previous variable
5529       // template declaration.
5530       if (CheckTemplateParameterList(
5531               TemplateParams,
5532               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5533                               : 0,
5534               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5535                DC->isDependentContext())
5536                   ? TPC_ClassTemplateMember
5537                   : TPC_VarTemplate))
5538         NewVD->setInvalidDecl();
5539 
5540       // If we are providing an explicit specialization of a static variable
5541       // template, make a note of that.
5542       if (PrevVarTemplate &&
5543           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5544         PrevVarTemplate->setMemberSpecialization();
5545     }
5546   }
5547 
5548   ProcessPragmaWeak(S, NewVD);
5549 
5550   // If this is the first declaration of an extern C variable, update
5551   // the map of such variables.
5552   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5553       isIncompleteDeclExternC(*this, NewVD))
5554     RegisterLocallyScopedExternCDecl(NewVD, S);
5555 
5556   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5557     Decl *ManglingContextDecl;
5558     if (MangleNumberingContext *MCtx =
5559             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5560                                           ManglingContextDecl)) {
5561       Context.setManglingNumber(
5562           NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
5563       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5564     }
5565   }
5566 
5567   if (D.isRedeclaration() && !Previous.empty()) {
5568     checkDLLAttributeRedeclaration(
5569         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
5570         IsExplicitSpecialization);
5571   }
5572 
5573   if (NewTemplate) {
5574     if (NewVD->isInvalidDecl())
5575       NewTemplate->setInvalidDecl();
5576     ActOnDocumentableDecl(NewTemplate);
5577     return NewTemplate;
5578   }
5579 
5580   return NewVD;
5581 }
5582 
5583 /// \brief Diagnose variable or built-in function shadowing.  Implements
5584 /// -Wshadow.
5585 ///
5586 /// This method is called whenever a VarDecl is added to a "useful"
5587 /// scope.
5588 ///
5589 /// \param S the scope in which the shadowing name is being declared
5590 /// \param R the lookup of the name
5591 ///
5592 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5593   // Return if warning is ignored.
5594   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
5595         DiagnosticsEngine::Ignored)
5596     return;
5597 
5598   // Don't diagnose declarations at file scope.
5599   if (D->hasGlobalStorage())
5600     return;
5601 
5602   DeclContext *NewDC = D->getDeclContext();
5603 
5604   // Only diagnose if we're shadowing an unambiguous field or variable.
5605   if (R.getResultKind() != LookupResult::Found)
5606     return;
5607 
5608   NamedDecl* ShadowedDecl = R.getFoundDecl();
5609   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5610     return;
5611 
5612   // Fields are not shadowed by variables in C++ static methods.
5613   if (isa<FieldDecl>(ShadowedDecl))
5614     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5615       if (MD->isStatic())
5616         return;
5617 
5618   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5619     if (shadowedVar->isExternC()) {
5620       // For shadowing external vars, make sure that we point to the global
5621       // declaration, not a locally scoped extern declaration.
5622       for (auto I : shadowedVar->redecls())
5623         if (I->isFileVarDecl()) {
5624           ShadowedDecl = I;
5625           break;
5626         }
5627     }
5628 
5629   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5630 
5631   // Only warn about certain kinds of shadowing for class members.
5632   if (NewDC && NewDC->isRecord()) {
5633     // In particular, don't warn about shadowing non-class members.
5634     if (!OldDC->isRecord())
5635       return;
5636 
5637     // TODO: should we warn about static data members shadowing
5638     // static data members from base classes?
5639 
5640     // TODO: don't diagnose for inaccessible shadowed members.
5641     // This is hard to do perfectly because we might friend the
5642     // shadowing context, but that's just a false negative.
5643   }
5644 
5645   // Determine what kind of declaration we're shadowing.
5646   unsigned Kind;
5647   if (isa<RecordDecl>(OldDC)) {
5648     if (isa<FieldDecl>(ShadowedDecl))
5649       Kind = 3; // field
5650     else
5651       Kind = 2; // static data member
5652   } else if (OldDC->isFileContext())
5653     Kind = 1; // global
5654   else
5655     Kind = 0; // local
5656 
5657   DeclarationName Name = R.getLookupName();
5658 
5659   // Emit warning and note.
5660   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5661     return;
5662   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5663   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5664 }
5665 
5666 /// \brief Check -Wshadow without the advantage of a previous lookup.
5667 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5668   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
5669         DiagnosticsEngine::Ignored)
5670     return;
5671 
5672   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5673                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5674   LookupName(R, S);
5675   CheckShadow(S, D, R);
5676 }
5677 
5678 /// Check for conflict between this global or extern "C" declaration and
5679 /// previous global or extern "C" declarations. This is only used in C++.
5680 template<typename T>
5681 static bool checkGlobalOrExternCConflict(
5682     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5683   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5684   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5685 
5686   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5687     // The common case: this global doesn't conflict with any extern "C"
5688     // declaration.
5689     return false;
5690   }
5691 
5692   if (Prev) {
5693     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5694       // Both the old and new declarations have C language linkage. This is a
5695       // redeclaration.
5696       Previous.clear();
5697       Previous.addDecl(Prev);
5698       return true;
5699     }
5700 
5701     // This is a global, non-extern "C" declaration, and there is a previous
5702     // non-global extern "C" declaration. Diagnose if this is a variable
5703     // declaration.
5704     if (!isa<VarDecl>(ND))
5705       return false;
5706   } else {
5707     // The declaration is extern "C". Check for any declaration in the
5708     // translation unit which might conflict.
5709     if (IsGlobal) {
5710       // We have already performed the lookup into the translation unit.
5711       IsGlobal = false;
5712       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5713            I != E; ++I) {
5714         if (isa<VarDecl>(*I)) {
5715           Prev = *I;
5716           break;
5717         }
5718       }
5719     } else {
5720       DeclContext::lookup_result R =
5721           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5722       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5723            I != E; ++I) {
5724         if (isa<VarDecl>(*I)) {
5725           Prev = *I;
5726           break;
5727         }
5728         // FIXME: If we have any other entity with this name in global scope,
5729         // the declaration is ill-formed, but that is a defect: it breaks the
5730         // 'stat' hack, for instance. Only variables can have mangled name
5731         // clashes with extern "C" declarations, so only they deserve a
5732         // diagnostic.
5733       }
5734     }
5735 
5736     if (!Prev)
5737       return false;
5738   }
5739 
5740   // Use the first declaration's location to ensure we point at something which
5741   // is lexically inside an extern "C" linkage-spec.
5742   assert(Prev && "should have found a previous declaration to diagnose");
5743   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5744     Prev = FD->getFirstDecl();
5745   else
5746     Prev = cast<VarDecl>(Prev)->getFirstDecl();
5747 
5748   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5749     << IsGlobal << ND;
5750   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5751     << IsGlobal;
5752   return false;
5753 }
5754 
5755 /// Apply special rules for handling extern "C" declarations. Returns \c true
5756 /// if we have found that this is a redeclaration of some prior entity.
5757 ///
5758 /// Per C++ [dcl.link]p6:
5759 ///   Two declarations [for a function or variable] with C language linkage
5760 ///   with the same name that appear in different scopes refer to the same
5761 ///   [entity]. An entity with C language linkage shall not be declared with
5762 ///   the same name as an entity in global scope.
5763 template<typename T>
5764 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5765                                                   LookupResult &Previous) {
5766   if (!S.getLangOpts().CPlusPlus) {
5767     // In C, when declaring a global variable, look for a corresponding 'extern'
5768     // variable declared in function scope. We don't need this in C++, because
5769     // we find local extern decls in the surrounding file-scope DeclContext.
5770     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5771       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5772         Previous.clear();
5773         Previous.addDecl(Prev);
5774         return true;
5775       }
5776     }
5777     return false;
5778   }
5779 
5780   // A declaration in the translation unit can conflict with an extern "C"
5781   // declaration.
5782   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5783     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5784 
5785   // An extern "C" declaration can conflict with a declaration in the
5786   // translation unit or can be a redeclaration of an extern "C" declaration
5787   // in another scope.
5788   if (isIncompleteDeclExternC(S,ND))
5789     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5790 
5791   // Neither global nor extern "C": nothing to do.
5792   return false;
5793 }
5794 
5795 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
5796   // If the decl is already known invalid, don't check it.
5797   if (NewVD->isInvalidDecl())
5798     return;
5799 
5800   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5801   QualType T = TInfo->getType();
5802 
5803   // Defer checking an 'auto' type until its initializer is attached.
5804   if (T->isUndeducedType())
5805     return;
5806 
5807   if (NewVD->hasAttrs())
5808     CheckAlignasUnderalignment(NewVD);
5809 
5810   if (T->isObjCObjectType()) {
5811     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5812       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5813     T = Context.getObjCObjectPointerType(T);
5814     NewVD->setType(T);
5815   }
5816 
5817   // Emit an error if an address space was applied to decl with local storage.
5818   // This includes arrays of objects with address space qualifiers, but not
5819   // automatic variables that point to other address spaces.
5820   // ISO/IEC TR 18037 S5.1.2
5821   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5822     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5823     NewVD->setInvalidDecl();
5824     return;
5825   }
5826 
5827   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5828   // __constant address space.
5829   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5830       && T.getAddressSpace() != LangAS::opencl_constant
5831       && !T->isSamplerT()){
5832     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5833     NewVD->setInvalidDecl();
5834     return;
5835   }
5836 
5837   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5838   // scope.
5839   if ((getLangOpts().OpenCLVersion >= 120)
5840       && NewVD->isStaticLocal()) {
5841     Diag(NewVD->getLocation(), diag::err_static_function_scope);
5842     NewVD->setInvalidDecl();
5843     return;
5844   }
5845 
5846   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5847       && !NewVD->hasAttr<BlocksAttr>()) {
5848     if (getLangOpts().getGC() != LangOptions::NonGC)
5849       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5850     else {
5851       assert(!getLangOpts().ObjCAutoRefCount);
5852       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5853     }
5854   }
5855 
5856   bool isVM = T->isVariablyModifiedType();
5857   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5858       NewVD->hasAttr<BlocksAttr>())
5859     getCurFunction()->setHasBranchProtectedScope();
5860 
5861   if ((isVM && NewVD->hasLinkage()) ||
5862       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5863     bool SizeIsNegative;
5864     llvm::APSInt Oversized;
5865     TypeSourceInfo *FixedTInfo =
5866       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5867                                                     SizeIsNegative, Oversized);
5868     if (FixedTInfo == 0 && T->isVariableArrayType()) {
5869       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5870       // FIXME: This won't give the correct result for
5871       // int a[10][n];
5872       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5873 
5874       if (NewVD->isFileVarDecl())
5875         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5876         << SizeRange;
5877       else if (NewVD->isStaticLocal())
5878         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5879         << SizeRange;
5880       else
5881         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5882         << SizeRange;
5883       NewVD->setInvalidDecl();
5884       return;
5885     }
5886 
5887     if (FixedTInfo == 0) {
5888       if (NewVD->isFileVarDecl())
5889         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5890       else
5891         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5892       NewVD->setInvalidDecl();
5893       return;
5894     }
5895 
5896     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5897     NewVD->setType(FixedTInfo->getType());
5898     NewVD->setTypeSourceInfo(FixedTInfo);
5899   }
5900 
5901   if (T->isVoidType()) {
5902     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5903     //                    of objects and functions.
5904     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5905       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5906         << T;
5907       NewVD->setInvalidDecl();
5908       return;
5909     }
5910   }
5911 
5912   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5913     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5914     NewVD->setInvalidDecl();
5915     return;
5916   }
5917 
5918   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5919     Diag(NewVD->getLocation(), diag::err_block_on_vm);
5920     NewVD->setInvalidDecl();
5921     return;
5922   }
5923 
5924   if (NewVD->isConstexpr() && !T->isDependentType() &&
5925       RequireLiteralType(NewVD->getLocation(), T,
5926                          diag::err_constexpr_var_non_literal)) {
5927     NewVD->setInvalidDecl();
5928     return;
5929   }
5930 }
5931 
5932 /// \brief Perform semantic checking on a newly-created variable
5933 /// declaration.
5934 ///
5935 /// This routine performs all of the type-checking required for a
5936 /// variable declaration once it has been built. It is used both to
5937 /// check variables after they have been parsed and their declarators
5938 /// have been translated into a declaration, and to check variables
5939 /// that have been instantiated from a template.
5940 ///
5941 /// Sets NewVD->isInvalidDecl() if an error was encountered.
5942 ///
5943 /// Returns true if the variable declaration is a redeclaration.
5944 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
5945   CheckVariableDeclarationType(NewVD);
5946 
5947   // If the decl is already known invalid, don't check it.
5948   if (NewVD->isInvalidDecl())
5949     return false;
5950 
5951   // If we did not find anything by this name, look for a non-visible
5952   // extern "C" declaration with the same name.
5953   if (Previous.empty() &&
5954       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
5955     Previous.setShadowed();
5956 
5957   // Filter out any non-conflicting previous declarations.
5958   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5959 
5960   if (!Previous.empty()) {
5961     MergeVarDecl(NewVD, Previous);
5962     return true;
5963   }
5964   return false;
5965 }
5966 
5967 /// \brief Data used with FindOverriddenMethod
5968 struct FindOverriddenMethodData {
5969   Sema *S;
5970   CXXMethodDecl *Method;
5971 };
5972 
5973 /// \brief Member lookup function that determines whether a given C++
5974 /// method overrides a method in a base class, to be used with
5975 /// CXXRecordDecl::lookupInBases().
5976 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
5977                                  CXXBasePath &Path,
5978                                  void *UserData) {
5979   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5980 
5981   FindOverriddenMethodData *Data
5982     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
5983 
5984   DeclarationName Name = Data->Method->getDeclName();
5985 
5986   // FIXME: Do we care about other names here too?
5987   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5988     // We really want to find the base class destructor here.
5989     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5990     CanQualType CT = Data->S->Context.getCanonicalType(T);
5991 
5992     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
5993   }
5994 
5995   for (Path.Decls = BaseRecord->lookup(Name);
5996        !Path.Decls.empty();
5997        Path.Decls = Path.Decls.slice(1)) {
5998     NamedDecl *D = Path.Decls.front();
5999     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6000       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
6001         return true;
6002     }
6003   }
6004 
6005   return false;
6006 }
6007 
6008 namespace {
6009   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6010 }
6011 /// \brief Report an error regarding overriding, along with any relevant
6012 /// overriden methods.
6013 ///
6014 /// \param DiagID the primary error to report.
6015 /// \param MD the overriding method.
6016 /// \param OEK which overrides to include as notes.
6017 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6018                             OverrideErrorKind OEK = OEK_All) {
6019   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6020   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6021                                       E = MD->end_overridden_methods();
6022        I != E; ++I) {
6023     // This check (& the OEK parameter) could be replaced by a predicate, but
6024     // without lambdas that would be overkill. This is still nicer than writing
6025     // out the diag loop 3 times.
6026     if ((OEK == OEK_All) ||
6027         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6028         (OEK == OEK_Deleted && (*I)->isDeleted()))
6029       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6030   }
6031 }
6032 
6033 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6034 /// and if so, check that it's a valid override and remember it.
6035 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6036   // Look for virtual methods in base classes that this method might override.
6037   CXXBasePaths Paths;
6038   FindOverriddenMethodData Data;
6039   Data.Method = MD;
6040   Data.S = this;
6041   bool hasDeletedOverridenMethods = false;
6042   bool hasNonDeletedOverridenMethods = false;
6043   bool AddedAny = false;
6044   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
6045     for (auto *I : Paths.found_decls()) {
6046       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6047         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6048         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6049             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6050             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6051             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6052           hasDeletedOverridenMethods |= OldMD->isDeleted();
6053           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6054           AddedAny = true;
6055         }
6056       }
6057     }
6058   }
6059 
6060   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6061     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6062   }
6063   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6064     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6065   }
6066 
6067   return AddedAny;
6068 }
6069 
6070 namespace {
6071   // Struct for holding all of the extra arguments needed by
6072   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6073   struct ActOnFDArgs {
6074     Scope *S;
6075     Declarator &D;
6076     MultiTemplateParamsArg TemplateParamLists;
6077     bool AddToScope;
6078   };
6079 }
6080 
6081 namespace {
6082 
6083 // Callback to only accept typo corrections that have a non-zero edit distance.
6084 // Also only accept corrections that have the same parent decl.
6085 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6086  public:
6087   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6088                             CXXRecordDecl *Parent)
6089       : Context(Context), OriginalFD(TypoFD),
6090         ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
6091 
6092   bool ValidateCandidate(const TypoCorrection &candidate) override {
6093     if (candidate.getEditDistance() == 0)
6094       return false;
6095 
6096     SmallVector<unsigned, 1> MismatchedParams;
6097     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6098                                           CDeclEnd = candidate.end();
6099          CDecl != CDeclEnd; ++CDecl) {
6100       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6101 
6102       if (FD && !FD->hasBody() &&
6103           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6104         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6105           CXXRecordDecl *Parent = MD->getParent();
6106           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6107             return true;
6108         } else if (!ExpectedParent) {
6109           return true;
6110         }
6111       }
6112     }
6113 
6114     return false;
6115   }
6116 
6117  private:
6118   ASTContext &Context;
6119   FunctionDecl *OriginalFD;
6120   CXXRecordDecl *ExpectedParent;
6121 };
6122 
6123 }
6124 
6125 /// \brief Generate diagnostics for an invalid function redeclaration.
6126 ///
6127 /// This routine handles generating the diagnostic messages for an invalid
6128 /// function redeclaration, including finding possible similar declarations
6129 /// or performing typo correction if there are no previous declarations with
6130 /// the same name.
6131 ///
6132 /// Returns a NamedDecl iff typo correction was performed and substituting in
6133 /// the new declaration name does not cause new errors.
6134 static NamedDecl *DiagnoseInvalidRedeclaration(
6135     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6136     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6137   DeclarationName Name = NewFD->getDeclName();
6138   DeclContext *NewDC = NewFD->getDeclContext();
6139   SmallVector<unsigned, 1> MismatchedParams;
6140   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6141   TypoCorrection Correction;
6142   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6143   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6144                                    : diag::err_member_decl_does_not_match;
6145   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6146                     IsLocalFriend ? Sema::LookupLocalFriendName
6147                                   : Sema::LookupOrdinaryName,
6148                     Sema::ForRedeclaration);
6149 
6150   NewFD->setInvalidDecl();
6151   if (IsLocalFriend)
6152     SemaRef.LookupName(Prev, S);
6153   else
6154     SemaRef.LookupQualifiedName(Prev, NewDC);
6155   assert(!Prev.isAmbiguous() &&
6156          "Cannot have an ambiguity in previous-declaration lookup");
6157   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6158   DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6159                                       MD ? MD->getParent() : 0);
6160   if (!Prev.empty()) {
6161     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6162          Func != FuncEnd; ++Func) {
6163       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6164       if (FD &&
6165           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6166         // Add 1 to the index so that 0 can mean the mismatch didn't
6167         // involve a parameter
6168         unsigned ParamNum =
6169             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6170         NearMatches.push_back(std::make_pair(FD, ParamNum));
6171       }
6172     }
6173   // If the qualified name lookup yielded nothing, try typo correction
6174   } else if ((Correction = SemaRef.CorrectTypo(
6175                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6176                  &ExtraArgs.D.getCXXScopeSpec(), Validator,
6177                  IsLocalFriend ? 0 : NewDC))) {
6178     // Set up everything for the call to ActOnFunctionDeclarator
6179     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6180                               ExtraArgs.D.getIdentifierLoc());
6181     Previous.clear();
6182     Previous.setLookupName(Correction.getCorrection());
6183     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6184                                     CDeclEnd = Correction.end();
6185          CDecl != CDeclEnd; ++CDecl) {
6186       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6187       if (FD && !FD->hasBody() &&
6188           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6189         Previous.addDecl(FD);
6190       }
6191     }
6192     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6193 
6194     NamedDecl *Result;
6195     // Retry building the function declaration with the new previous
6196     // declarations, and with errors suppressed.
6197     {
6198       // Trap errors.
6199       Sema::SFINAETrap Trap(SemaRef);
6200 
6201       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6202       // pieces need to verify the typo-corrected C++ declaration and hopefully
6203       // eliminate the need for the parameter pack ExtraArgs.
6204       Result = SemaRef.ActOnFunctionDeclarator(
6205           ExtraArgs.S, ExtraArgs.D,
6206           Correction.getCorrectionDecl()->getDeclContext(),
6207           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6208           ExtraArgs.AddToScope);
6209 
6210       if (Trap.hasErrorOccurred())
6211         Result = 0;
6212     }
6213 
6214     if (Result) {
6215       // Determine which correction we picked.
6216       Decl *Canonical = Result->getCanonicalDecl();
6217       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6218            I != E; ++I)
6219         if ((*I)->getCanonicalDecl() == Canonical)
6220           Correction.setCorrectionDecl(*I);
6221 
6222       SemaRef.diagnoseTypo(
6223           Correction,
6224           SemaRef.PDiag(IsLocalFriend
6225                           ? diag::err_no_matching_local_friend_suggest
6226                           : diag::err_member_decl_does_not_match_suggest)
6227             << Name << NewDC << IsDefinition);
6228       return Result;
6229     }
6230 
6231     // Pretend the typo correction never occurred
6232     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6233                               ExtraArgs.D.getIdentifierLoc());
6234     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6235     Previous.clear();
6236     Previous.setLookupName(Name);
6237   }
6238 
6239   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6240       << Name << NewDC << IsDefinition << NewFD->getLocation();
6241 
6242   bool NewFDisConst = false;
6243   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6244     NewFDisConst = NewMD->isConst();
6245 
6246   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6247        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6248        NearMatch != NearMatchEnd; ++NearMatch) {
6249     FunctionDecl *FD = NearMatch->first;
6250     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6251     bool FDisConst = MD && MD->isConst();
6252     bool IsMember = MD || !IsLocalFriend;
6253 
6254     // FIXME: These notes are poorly worded for the local friend case.
6255     if (unsigned Idx = NearMatch->second) {
6256       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6257       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6258       if (Loc.isInvalid()) Loc = FD->getLocation();
6259       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6260                                  : diag::note_local_decl_close_param_match)
6261         << Idx << FDParam->getType()
6262         << NewFD->getParamDecl(Idx - 1)->getType();
6263     } else if (FDisConst != NewFDisConst) {
6264       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6265           << NewFDisConst << FD->getSourceRange().getEnd();
6266     } else
6267       SemaRef.Diag(FD->getLocation(),
6268                    IsMember ? diag::note_member_def_close_match
6269                             : diag::note_local_decl_close_match);
6270   }
6271   return 0;
6272 }
6273 
6274 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6275                                                           Declarator &D) {
6276   switch (D.getDeclSpec().getStorageClassSpec()) {
6277   default: llvm_unreachable("Unknown storage class!");
6278   case DeclSpec::SCS_auto:
6279   case DeclSpec::SCS_register:
6280   case DeclSpec::SCS_mutable:
6281     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6282                  diag::err_typecheck_sclass_func);
6283     D.setInvalidType();
6284     break;
6285   case DeclSpec::SCS_unspecified: break;
6286   case DeclSpec::SCS_extern:
6287     if (D.getDeclSpec().isExternInLinkageSpec())
6288       return SC_None;
6289     return SC_Extern;
6290   case DeclSpec::SCS_static: {
6291     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6292       // C99 6.7.1p5:
6293       //   The declaration of an identifier for a function that has
6294       //   block scope shall have no explicit storage-class specifier
6295       //   other than extern
6296       // See also (C++ [dcl.stc]p4).
6297       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6298                    diag::err_static_block_func);
6299       break;
6300     } else
6301       return SC_Static;
6302   }
6303   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6304   }
6305 
6306   // No explicit storage class has already been returned
6307   return SC_None;
6308 }
6309 
6310 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6311                                            DeclContext *DC, QualType &R,
6312                                            TypeSourceInfo *TInfo,
6313                                            FunctionDecl::StorageClass SC,
6314                                            bool &IsVirtualOkay) {
6315   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6316   DeclarationName Name = NameInfo.getName();
6317 
6318   FunctionDecl *NewFD = 0;
6319   bool isInline = D.getDeclSpec().isInlineSpecified();
6320 
6321   if (!SemaRef.getLangOpts().CPlusPlus) {
6322     // Determine whether the function was written with a
6323     // prototype. This true when:
6324     //   - there is a prototype in the declarator, or
6325     //   - the type R of the function is some kind of typedef or other reference
6326     //     to a type name (which eventually refers to a function type).
6327     bool HasPrototype =
6328       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6329       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6330 
6331     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6332                                  D.getLocStart(), NameInfo, R,
6333                                  TInfo, SC, isInline,
6334                                  HasPrototype, false);
6335     if (D.isInvalidType())
6336       NewFD->setInvalidDecl();
6337 
6338     // Set the lexical context.
6339     NewFD->setLexicalDeclContext(SemaRef.CurContext);
6340 
6341     return NewFD;
6342   }
6343 
6344   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6345   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6346 
6347   // Check that the return type is not an abstract class type.
6348   // For record types, this is done by the AbstractClassUsageDiagnoser once
6349   // the class has been completely parsed.
6350   if (!DC->isRecord() &&
6351       SemaRef.RequireNonAbstractType(
6352           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6353           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6354     D.setInvalidType();
6355 
6356   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6357     // This is a C++ constructor declaration.
6358     assert(DC->isRecord() &&
6359            "Constructors can only be declared in a member context");
6360 
6361     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6362     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6363                                       D.getLocStart(), NameInfo,
6364                                       R, TInfo, isExplicit, isInline,
6365                                       /*isImplicitlyDeclared=*/false,
6366                                       isConstexpr);
6367 
6368   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6369     // This is a C++ destructor declaration.
6370     if (DC->isRecord()) {
6371       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6372       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6373       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6374                                         SemaRef.Context, Record,
6375                                         D.getLocStart(),
6376                                         NameInfo, R, TInfo, isInline,
6377                                         /*isImplicitlyDeclared=*/false);
6378 
6379       // If the class is complete, then we now create the implicit exception
6380       // specification. If the class is incomplete or dependent, we can't do
6381       // it yet.
6382       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6383           Record->getDefinition() && !Record->isBeingDefined() &&
6384           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6385         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6386       }
6387 
6388       IsVirtualOkay = true;
6389       return NewDD;
6390 
6391     } else {
6392       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6393       D.setInvalidType();
6394 
6395       // Create a FunctionDecl to satisfy the function definition parsing
6396       // code path.
6397       return FunctionDecl::Create(SemaRef.Context, DC,
6398                                   D.getLocStart(),
6399                                   D.getIdentifierLoc(), Name, R, TInfo,
6400                                   SC, isInline,
6401                                   /*hasPrototype=*/true, isConstexpr);
6402     }
6403 
6404   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6405     if (!DC->isRecord()) {
6406       SemaRef.Diag(D.getIdentifierLoc(),
6407            diag::err_conv_function_not_member);
6408       return 0;
6409     }
6410 
6411     SemaRef.CheckConversionDeclarator(D, R, SC);
6412     IsVirtualOkay = true;
6413     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6414                                      D.getLocStart(), NameInfo,
6415                                      R, TInfo, isInline, isExplicit,
6416                                      isConstexpr, SourceLocation());
6417 
6418   } else if (DC->isRecord()) {
6419     // If the name of the function is the same as the name of the record,
6420     // then this must be an invalid constructor that has a return type.
6421     // (The parser checks for a return type and makes the declarator a
6422     // constructor if it has no return type).
6423     if (Name.getAsIdentifierInfo() &&
6424         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6425       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6426         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6427         << SourceRange(D.getIdentifierLoc());
6428       return 0;
6429     }
6430 
6431     // This is a C++ method declaration.
6432     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6433                                                cast<CXXRecordDecl>(DC),
6434                                                D.getLocStart(), NameInfo, R,
6435                                                TInfo, SC, isInline,
6436                                                isConstexpr, SourceLocation());
6437     IsVirtualOkay = !Ret->isStatic();
6438     return Ret;
6439   } else {
6440     // Determine whether the function was written with a
6441     // prototype. This true when:
6442     //   - we're in C++ (where every function has a prototype),
6443     return FunctionDecl::Create(SemaRef.Context, DC,
6444                                 D.getLocStart(),
6445                                 NameInfo, R, TInfo, SC, isInline,
6446                                 true/*HasPrototype*/, isConstexpr);
6447   }
6448 }
6449 
6450 enum OpenCLParamType {
6451   ValidKernelParam,
6452   PtrPtrKernelParam,
6453   PtrKernelParam,
6454   PrivatePtrKernelParam,
6455   InvalidKernelParam,
6456   RecordKernelParam
6457 };
6458 
6459 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6460   if (PT->isPointerType()) {
6461     QualType PointeeType = PT->getPointeeType();
6462     if (PointeeType->isPointerType())
6463       return PtrPtrKernelParam;
6464     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
6465                                               : PtrKernelParam;
6466   }
6467 
6468   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6469   // be used as builtin types.
6470 
6471   if (PT->isImageType())
6472     return PtrKernelParam;
6473 
6474   if (PT->isBooleanType())
6475     return InvalidKernelParam;
6476 
6477   if (PT->isEventT())
6478     return InvalidKernelParam;
6479 
6480   if (PT->isHalfType())
6481     return InvalidKernelParam;
6482 
6483   if (PT->isRecordType())
6484     return RecordKernelParam;
6485 
6486   return ValidKernelParam;
6487 }
6488 
6489 static void checkIsValidOpenCLKernelParameter(
6490   Sema &S,
6491   Declarator &D,
6492   ParmVarDecl *Param,
6493   llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6494   QualType PT = Param->getType();
6495 
6496   // Cache the valid types we encounter to avoid rechecking structs that are
6497   // used again
6498   if (ValidTypes.count(PT.getTypePtr()))
6499     return;
6500 
6501   switch (getOpenCLKernelParameterType(PT)) {
6502   case PtrPtrKernelParam:
6503     // OpenCL v1.2 s6.9.a:
6504     // A kernel function argument cannot be declared as a
6505     // pointer to a pointer type.
6506     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6507     D.setInvalidType();
6508     return;
6509 
6510   case PrivatePtrKernelParam:
6511     // OpenCL v1.2 s6.9.a:
6512     // A kernel function argument cannot be declared as a
6513     // pointer to the private address space.
6514     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
6515     D.setInvalidType();
6516     return;
6517 
6518     // OpenCL v1.2 s6.9.k:
6519     // Arguments to kernel functions in a program cannot be declared with the
6520     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6521     // uintptr_t or a struct and/or union that contain fields declared to be
6522     // one of these built-in scalar types.
6523 
6524   case InvalidKernelParam:
6525     // OpenCL v1.2 s6.8 n:
6526     // A kernel function argument cannot be declared
6527     // of event_t type.
6528     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6529     D.setInvalidType();
6530     return;
6531 
6532   case PtrKernelParam:
6533   case ValidKernelParam:
6534     ValidTypes.insert(PT.getTypePtr());
6535     return;
6536 
6537   case RecordKernelParam:
6538     break;
6539   }
6540 
6541   // Track nested structs we will inspect
6542   SmallVector<const Decl *, 4> VisitStack;
6543 
6544   // Track where we are in the nested structs. Items will migrate from
6545   // VisitStack to HistoryStack as we do the DFS for bad field.
6546   SmallVector<const FieldDecl *, 4> HistoryStack;
6547   HistoryStack.push_back((const FieldDecl *) 0);
6548 
6549   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6550   VisitStack.push_back(PD);
6551 
6552   assert(VisitStack.back() && "First decl null?");
6553 
6554   do {
6555     const Decl *Next = VisitStack.pop_back_val();
6556     if (!Next) {
6557       assert(!HistoryStack.empty());
6558       // Found a marker, we have gone up a level
6559       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6560         ValidTypes.insert(Hist->getType().getTypePtr());
6561 
6562       continue;
6563     }
6564 
6565     // Adds everything except the original parameter declaration (which is not a
6566     // field itself) to the history stack.
6567     const RecordDecl *RD;
6568     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6569       HistoryStack.push_back(Field);
6570       RD = Field->getType()->castAs<RecordType>()->getDecl();
6571     } else {
6572       RD = cast<RecordDecl>(Next);
6573     }
6574 
6575     // Add a null marker so we know when we've gone back up a level
6576     VisitStack.push_back((const Decl *) 0);
6577 
6578     for (const auto *FD : RD->fields()) {
6579       QualType QT = FD->getType();
6580 
6581       if (ValidTypes.count(QT.getTypePtr()))
6582         continue;
6583 
6584       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6585       if (ParamType == ValidKernelParam)
6586         continue;
6587 
6588       if (ParamType == RecordKernelParam) {
6589         VisitStack.push_back(FD);
6590         continue;
6591       }
6592 
6593       // OpenCL v1.2 s6.9.p:
6594       // Arguments to kernel functions that are declared to be a struct or union
6595       // do not allow OpenCL objects to be passed as elements of the struct or
6596       // union.
6597       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
6598           ParamType == PrivatePtrKernelParam) {
6599         S.Diag(Param->getLocation(),
6600                diag::err_record_with_pointers_kernel_param)
6601           << PT->isUnionType()
6602           << PT;
6603       } else {
6604         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6605       }
6606 
6607       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6608         << PD->getDeclName();
6609 
6610       // We have an error, now let's go back up through history and show where
6611       // the offending field came from
6612       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6613              E = HistoryStack.end(); I != E; ++I) {
6614         const FieldDecl *OuterField = *I;
6615         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6616           << OuterField->getType();
6617       }
6618 
6619       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6620         << QT->isPointerType()
6621         << QT;
6622       D.setInvalidType();
6623       return;
6624     }
6625   } while (!VisitStack.empty());
6626 }
6627 
6628 NamedDecl*
6629 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6630                               TypeSourceInfo *TInfo, LookupResult &Previous,
6631                               MultiTemplateParamsArg TemplateParamLists,
6632                               bool &AddToScope) {
6633   QualType R = TInfo->getType();
6634 
6635   assert(R.getTypePtr()->isFunctionType());
6636 
6637   // TODO: consider using NameInfo for diagnostic.
6638   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6639   DeclarationName Name = NameInfo.getName();
6640   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6641 
6642   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6643     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6644          diag::err_invalid_thread)
6645       << DeclSpec::getSpecifierName(TSCS);
6646 
6647   if (D.isFirstDeclarationOfMember())
6648     adjustMemberFunctionCC(R, D.isStaticMember());
6649 
6650   bool isFriend = false;
6651   FunctionTemplateDecl *FunctionTemplate = 0;
6652   bool isExplicitSpecialization = false;
6653   bool isFunctionTemplateSpecialization = false;
6654 
6655   bool isDependentClassScopeExplicitSpecialization = false;
6656   bool HasExplicitTemplateArgs = false;
6657   TemplateArgumentListInfo TemplateArgs;
6658 
6659   bool isVirtualOkay = false;
6660 
6661   DeclContext *OriginalDC = DC;
6662   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6663 
6664   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6665                                               isVirtualOkay);
6666   if (!NewFD) return 0;
6667 
6668   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6669     NewFD->setTopLevelDeclInObjCContainer();
6670 
6671   // Set the lexical context. If this is a function-scope declaration, or has a
6672   // C++ scope specifier, or is the object of a friend declaration, the lexical
6673   // context will be different from the semantic context.
6674   NewFD->setLexicalDeclContext(CurContext);
6675 
6676   if (IsLocalExternDecl)
6677     NewFD->setLocalExternDecl();
6678 
6679   if (getLangOpts().CPlusPlus) {
6680     bool isInline = D.getDeclSpec().isInlineSpecified();
6681     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6682     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6683     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6684     isFriend = D.getDeclSpec().isFriendSpecified();
6685     if (isFriend && !isInline && D.isFunctionDefinition()) {
6686       // C++ [class.friend]p5
6687       //   A function can be defined in a friend declaration of a
6688       //   class . . . . Such a function is implicitly inline.
6689       NewFD->setImplicitlyInline();
6690     }
6691 
6692     // If this is a method defined in an __interface, and is not a constructor
6693     // or an overloaded operator, then set the pure flag (isVirtual will already
6694     // return true).
6695     if (const CXXRecordDecl *Parent =
6696           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6697       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6698         NewFD->setPure(true);
6699     }
6700 
6701     SetNestedNameSpecifier(NewFD, D);
6702     isExplicitSpecialization = false;
6703     isFunctionTemplateSpecialization = false;
6704     if (D.isInvalidType())
6705       NewFD->setInvalidDecl();
6706 
6707     // Match up the template parameter lists with the scope specifier, then
6708     // determine whether we have a template or a template specialization.
6709     bool Invalid = false;
6710     if (TemplateParameterList *TemplateParams =
6711             MatchTemplateParametersToScopeSpecifier(
6712                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6713                 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6714                 isExplicitSpecialization, Invalid)) {
6715       if (TemplateParams->size() > 0) {
6716         // This is a function template
6717 
6718         // Check that we can declare a template here.
6719         if (CheckTemplateDeclScope(S, TemplateParams))
6720           return 0;
6721 
6722         // A destructor cannot be a template.
6723         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6724           Diag(NewFD->getLocation(), diag::err_destructor_template);
6725           return 0;
6726         }
6727 
6728         // If we're adding a template to a dependent context, we may need to
6729         // rebuilding some of the types used within the template parameter list,
6730         // now that we know what the current instantiation is.
6731         if (DC->isDependentContext()) {
6732           ContextRAII SavedContext(*this, DC);
6733           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6734             Invalid = true;
6735         }
6736 
6737 
6738         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6739                                                         NewFD->getLocation(),
6740                                                         Name, TemplateParams,
6741                                                         NewFD);
6742         FunctionTemplate->setLexicalDeclContext(CurContext);
6743         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6744 
6745         // For source fidelity, store the other template param lists.
6746         if (TemplateParamLists.size() > 1) {
6747           NewFD->setTemplateParameterListsInfo(Context,
6748                                                TemplateParamLists.size() - 1,
6749                                                TemplateParamLists.data());
6750         }
6751       } else {
6752         // This is a function template specialization.
6753         isFunctionTemplateSpecialization = true;
6754         // For source fidelity, store all the template param lists.
6755         NewFD->setTemplateParameterListsInfo(Context,
6756                                              TemplateParamLists.size(),
6757                                              TemplateParamLists.data());
6758 
6759         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6760         if (isFriend) {
6761           // We want to remove the "template<>", found here.
6762           SourceRange RemoveRange = TemplateParams->getSourceRange();
6763 
6764           // If we remove the template<> and the name is not a
6765           // template-id, we're actually silently creating a problem:
6766           // the friend declaration will refer to an untemplated decl,
6767           // and clearly the user wants a template specialization.  So
6768           // we need to insert '<>' after the name.
6769           SourceLocation InsertLoc;
6770           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6771             InsertLoc = D.getName().getSourceRange().getEnd();
6772             InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6773           }
6774 
6775           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6776             << Name << RemoveRange
6777             << FixItHint::CreateRemoval(RemoveRange)
6778             << FixItHint::CreateInsertion(InsertLoc, "<>");
6779         }
6780       }
6781     }
6782     else {
6783       // All template param lists were matched against the scope specifier:
6784       // this is NOT (an explicit specialization of) a template.
6785       if (TemplateParamLists.size() > 0)
6786         // For source fidelity, store all the template param lists.
6787         NewFD->setTemplateParameterListsInfo(Context,
6788                                              TemplateParamLists.size(),
6789                                              TemplateParamLists.data());
6790     }
6791 
6792     if (Invalid) {
6793       NewFD->setInvalidDecl();
6794       if (FunctionTemplate)
6795         FunctionTemplate->setInvalidDecl();
6796     }
6797 
6798     // C++ [dcl.fct.spec]p5:
6799     //   The virtual specifier shall only be used in declarations of
6800     //   nonstatic class member functions that appear within a
6801     //   member-specification of a class declaration; see 10.3.
6802     //
6803     if (isVirtual && !NewFD->isInvalidDecl()) {
6804       if (!isVirtualOkay) {
6805         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6806              diag::err_virtual_non_function);
6807       } else if (!CurContext->isRecord()) {
6808         // 'virtual' was specified outside of the class.
6809         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6810              diag::err_virtual_out_of_class)
6811           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6812       } else if (NewFD->getDescribedFunctionTemplate()) {
6813         // C++ [temp.mem]p3:
6814         //  A member function template shall not be virtual.
6815         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6816              diag::err_virtual_member_function_template)
6817           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6818       } else {
6819         // Okay: Add virtual to the method.
6820         NewFD->setVirtualAsWritten(true);
6821       }
6822 
6823       if (getLangOpts().CPlusPlus1y &&
6824           NewFD->getReturnType()->isUndeducedType())
6825         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
6826     }
6827 
6828     if (getLangOpts().CPlusPlus1y &&
6829         (NewFD->isDependentContext() ||
6830          (isFriend && CurContext->isDependentContext())) &&
6831         NewFD->getReturnType()->isUndeducedType()) {
6832       // If the function template is referenced directly (for instance, as a
6833       // member of the current instantiation), pretend it has a dependent type.
6834       // This is not really justified by the standard, but is the only sane
6835       // thing to do.
6836       // FIXME: For a friend function, we have not marked the function as being
6837       // a friend yet, so 'isDependentContext' on the FD doesn't work.
6838       const FunctionProtoType *FPT =
6839           NewFD->getType()->castAs<FunctionProtoType>();
6840       QualType Result =
6841           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
6842       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
6843                                              FPT->getExtProtoInfo()));
6844     }
6845 
6846     // C++ [dcl.fct.spec]p3:
6847     //  The inline specifier shall not appear on a block scope function
6848     //  declaration.
6849     if (isInline && !NewFD->isInvalidDecl()) {
6850       if (CurContext->isFunctionOrMethod()) {
6851         // 'inline' is not allowed on block scope function declaration.
6852         Diag(D.getDeclSpec().getInlineSpecLoc(),
6853              diag::err_inline_declaration_block_scope) << Name
6854           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6855       }
6856     }
6857 
6858     // C++ [dcl.fct.spec]p6:
6859     //  The explicit specifier shall be used only in the declaration of a
6860     //  constructor or conversion function within its class definition;
6861     //  see 12.3.1 and 12.3.2.
6862     if (isExplicit && !NewFD->isInvalidDecl()) {
6863       if (!CurContext->isRecord()) {
6864         // 'explicit' was specified outside of the class.
6865         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6866              diag::err_explicit_out_of_class)
6867           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6868       } else if (!isa<CXXConstructorDecl>(NewFD) &&
6869                  !isa<CXXConversionDecl>(NewFD)) {
6870         // 'explicit' was specified on a function that wasn't a constructor
6871         // or conversion function.
6872         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6873              diag::err_explicit_non_ctor_or_conv_function)
6874           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6875       }
6876     }
6877 
6878     if (isConstexpr) {
6879       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6880       // are implicitly inline.
6881       NewFD->setImplicitlyInline();
6882 
6883       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6884       // be either constructors or to return a literal type. Therefore,
6885       // destructors cannot be declared constexpr.
6886       if (isa<CXXDestructorDecl>(NewFD))
6887         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6888     }
6889 
6890     // If __module_private__ was specified, mark the function accordingly.
6891     if (D.getDeclSpec().isModulePrivateSpecified()) {
6892       if (isFunctionTemplateSpecialization) {
6893         SourceLocation ModulePrivateLoc
6894           = D.getDeclSpec().getModulePrivateSpecLoc();
6895         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6896           << 0
6897           << FixItHint::CreateRemoval(ModulePrivateLoc);
6898       } else {
6899         NewFD->setModulePrivate();
6900         if (FunctionTemplate)
6901           FunctionTemplate->setModulePrivate();
6902       }
6903     }
6904 
6905     if (isFriend) {
6906       if (FunctionTemplate) {
6907         FunctionTemplate->setObjectOfFriendDecl();
6908         FunctionTemplate->setAccess(AS_public);
6909       }
6910       NewFD->setObjectOfFriendDecl();
6911       NewFD->setAccess(AS_public);
6912     }
6913 
6914     // If a function is defined as defaulted or deleted, mark it as such now.
6915     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6916     // definition kind to FDK_Definition.
6917     switch (D.getFunctionDefinitionKind()) {
6918       case FDK_Declaration:
6919       case FDK_Definition:
6920         break;
6921 
6922       case FDK_Defaulted:
6923         NewFD->setDefaulted();
6924         break;
6925 
6926       case FDK_Deleted:
6927         NewFD->setDeletedAsWritten();
6928         break;
6929     }
6930 
6931     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6932         D.isFunctionDefinition()) {
6933       // C++ [class.mfct]p2:
6934       //   A member function may be defined (8.4) in its class definition, in
6935       //   which case it is an inline member function (7.1.2)
6936       NewFD->setImplicitlyInline();
6937     }
6938 
6939     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6940         !CurContext->isRecord()) {
6941       // C++ [class.static]p1:
6942       //   A data or function member of a class may be declared static
6943       //   in a class definition, in which case it is a static member of
6944       //   the class.
6945 
6946       // Complain about the 'static' specifier if it's on an out-of-line
6947       // member function definition.
6948       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6949            diag::err_static_out_of_line)
6950         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6951     }
6952 
6953     // C++11 [except.spec]p15:
6954     //   A deallocation function with no exception-specification is treated
6955     //   as if it were specified with noexcept(true).
6956     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6957     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6958          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
6959         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
6960       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6961       EPI.ExceptionSpecType = EST_BasicNoexcept;
6962       NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
6963                                              FPT->getParamTypes(), EPI));
6964     }
6965   }
6966 
6967   // Filter out previous declarations that don't match the scope.
6968   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
6969                        D.getCXXScopeSpec().isNotEmpty() ||
6970                        isExplicitSpecialization ||
6971                        isFunctionTemplateSpecialization);
6972 
6973   // Handle GNU asm-label extension (encoded as an attribute).
6974   if (Expr *E = (Expr*) D.getAsmLabel()) {
6975     // The parser guarantees this is a string.
6976     StringLiteral *SE = cast<StringLiteral>(E);
6977     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6978                                                 SE->getString(), 0));
6979   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6980     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6981       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6982     if (I != ExtnameUndeclaredIdentifiers.end()) {
6983       NewFD->addAttr(I->second);
6984       ExtnameUndeclaredIdentifiers.erase(I);
6985     }
6986   }
6987 
6988   // Copy the parameter declarations from the declarator D to the function
6989   // declaration NewFD, if they are available.  First scavenge them into Params.
6990   SmallVector<ParmVarDecl*, 16> Params;
6991   if (D.isFunctionDeclarator()) {
6992     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6993 
6994     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6995     // function that takes no arguments, not a function that takes a
6996     // single void argument.
6997     // We let through "const void" here because Sema::GetTypeForDeclarator
6998     // already checks for that case.
6999     if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
7000         FTI.Params[0].Param &&
7001         cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) {
7002       // Empty arg list, don't push any params.
7003     } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) {
7004       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7005         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7006         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7007         Param->setDeclContext(NewFD);
7008         Params.push_back(Param);
7009 
7010         if (Param->isInvalidDecl())
7011           NewFD->setInvalidDecl();
7012       }
7013     }
7014 
7015   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7016     // When we're declaring a function with a typedef, typeof, etc as in the
7017     // following example, we'll need to synthesize (unnamed)
7018     // parameters for use in the declaration.
7019     //
7020     // @code
7021     // typedef void fn(int);
7022     // fn f;
7023     // @endcode
7024 
7025     // Synthesize a parameter for each argument type.
7026     for (const auto &AI : FT->param_types()) {
7027       ParmVarDecl *Param =
7028           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7029       Param->setScopeInfo(0, Params.size());
7030       Params.push_back(Param);
7031     }
7032   } else {
7033     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7034            "Should not need args for typedef of non-prototype fn");
7035   }
7036 
7037   // Finally, we know we have the right number of parameters, install them.
7038   NewFD->setParams(Params);
7039 
7040   // Find all anonymous symbols defined during the declaration of this function
7041   // and add to NewFD. This lets us track decls such 'enum Y' in:
7042   //
7043   //   void f(enum Y {AA} x) {}
7044   //
7045   // which would otherwise incorrectly end up in the translation unit scope.
7046   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7047   DeclsInPrototypeScope.clear();
7048 
7049   if (D.getDeclSpec().isNoreturnSpecified())
7050     NewFD->addAttr(
7051         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7052                                        Context, 0));
7053 
7054   // Functions returning a variably modified type violate C99 6.7.5.2p2
7055   // because all functions have linkage.
7056   if (!NewFD->isInvalidDecl() &&
7057       NewFD->getReturnType()->isVariablyModifiedType()) {
7058     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7059     NewFD->setInvalidDecl();
7060   }
7061 
7062   // Handle attributes.
7063   ProcessDeclAttributes(S, NewFD, D);
7064 
7065   QualType RetType = NewFD->getReturnType();
7066   const CXXRecordDecl *Ret = RetType->isRecordType() ?
7067       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
7068   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
7069       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
7070     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7071     // Attach WarnUnusedResult to functions returning types with that attribute.
7072     // Don't apply the attribute to that type's own non-static member functions
7073     // (to avoid warning on things like assignment operators)
7074     if (!MD || MD->getParent() != Ret)
7075       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
7076   }
7077 
7078   if (getLangOpts().OpenCL) {
7079     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7080     // type declaration will generate a compilation error.
7081     unsigned AddressSpace = RetType.getAddressSpace();
7082     if (AddressSpace == LangAS::opencl_local ||
7083         AddressSpace == LangAS::opencl_global ||
7084         AddressSpace == LangAS::opencl_constant) {
7085       Diag(NewFD->getLocation(),
7086            diag::err_opencl_return_value_with_address_space);
7087       NewFD->setInvalidDecl();
7088     }
7089   }
7090 
7091   if (!getLangOpts().CPlusPlus) {
7092     // Perform semantic checking on the function declaration.
7093     bool isExplicitSpecialization=false;
7094     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7095       CheckMain(NewFD, D.getDeclSpec());
7096 
7097     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7098       CheckMSVCRTEntryPoint(NewFD);
7099 
7100     if (!NewFD->isInvalidDecl())
7101       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7102                                                   isExplicitSpecialization));
7103     else if (!Previous.empty())
7104       // Make graceful recovery from an invalid redeclaration.
7105       D.setRedeclaration(true);
7106     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7107             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7108            "previous declaration set still overloaded");
7109   } else {
7110     // C++11 [replacement.functions]p3:
7111     //  The program's definitions shall not be specified as inline.
7112     //
7113     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7114     //
7115     // Suppress the diagnostic if the function is __attribute__((used)), since
7116     // that forces an external definition to be emitted.
7117     if (D.getDeclSpec().isInlineSpecified() &&
7118         NewFD->isReplaceableGlobalAllocationFunction() &&
7119         !NewFD->hasAttr<UsedAttr>())
7120       Diag(D.getDeclSpec().getInlineSpecLoc(),
7121            diag::ext_operator_new_delete_declared_inline)
7122         << NewFD->getDeclName();
7123 
7124     // If the declarator is a template-id, translate the parser's template
7125     // argument list into our AST format.
7126     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7127       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7128       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7129       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7130       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7131                                          TemplateId->NumArgs);
7132       translateTemplateArguments(TemplateArgsPtr,
7133                                  TemplateArgs);
7134 
7135       HasExplicitTemplateArgs = true;
7136 
7137       if (NewFD->isInvalidDecl()) {
7138         HasExplicitTemplateArgs = false;
7139       } else if (FunctionTemplate) {
7140         // Function template with explicit template arguments.
7141         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7142           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7143 
7144         HasExplicitTemplateArgs = false;
7145       } else if (!isFunctionTemplateSpecialization &&
7146                  !D.getDeclSpec().isFriendSpecified()) {
7147         // We have encountered something that the user meant to be a
7148         // specialization (because it has explicitly-specified template
7149         // arguments) but that was not introduced with a "template<>" (or had
7150         // too few of them).
7151         // FIXME: Differentiate between attempts for explicit instantiations
7152         // (starting with "template") and the rest.
7153         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7154           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7155           << FixItHint::CreateInsertion(
7156                                     D.getDeclSpec().getLocStart(),
7157                                         "template<> ");
7158         isFunctionTemplateSpecialization = true;
7159       } else {
7160         // "friend void foo<>(int);" is an implicit specialization decl.
7161         isFunctionTemplateSpecialization = true;
7162       }
7163     } else if (isFriend && isFunctionTemplateSpecialization) {
7164       // This combination is only possible in a recovery case;  the user
7165       // wrote something like:
7166       //   template <> friend void foo(int);
7167       // which we're recovering from as if the user had written:
7168       //   friend void foo<>(int);
7169       // Go ahead and fake up a template id.
7170       HasExplicitTemplateArgs = true;
7171         TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7172       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7173     }
7174 
7175     // If it's a friend (and only if it's a friend), it's possible
7176     // that either the specialized function type or the specialized
7177     // template is dependent, and therefore matching will fail.  In
7178     // this case, don't check the specialization yet.
7179     bool InstantiationDependent = false;
7180     if (isFunctionTemplateSpecialization && isFriend &&
7181         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7182          TemplateSpecializationType::anyDependentTemplateArguments(
7183             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7184             InstantiationDependent))) {
7185       assert(HasExplicitTemplateArgs &&
7186              "friend function specialization without template args");
7187       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7188                                                        Previous))
7189         NewFD->setInvalidDecl();
7190     } else if (isFunctionTemplateSpecialization) {
7191       if (CurContext->isDependentContext() && CurContext->isRecord()
7192           && !isFriend) {
7193         isDependentClassScopeExplicitSpecialization = true;
7194         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7195           diag::ext_function_specialization_in_class :
7196           diag::err_function_specialization_in_class)
7197           << NewFD->getDeclName();
7198       } else if (CheckFunctionTemplateSpecialization(NewFD,
7199                                   (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7200                                                      Previous))
7201         NewFD->setInvalidDecl();
7202 
7203       // C++ [dcl.stc]p1:
7204       //   A storage-class-specifier shall not be specified in an explicit
7205       //   specialization (14.7.3)
7206       FunctionTemplateSpecializationInfo *Info =
7207           NewFD->getTemplateSpecializationInfo();
7208       if (Info && SC != SC_None) {
7209         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7210           Diag(NewFD->getLocation(),
7211                diag::err_explicit_specialization_inconsistent_storage_class)
7212             << SC
7213             << FixItHint::CreateRemoval(
7214                                       D.getDeclSpec().getStorageClassSpecLoc());
7215 
7216         else
7217           Diag(NewFD->getLocation(),
7218                diag::ext_explicit_specialization_storage_class)
7219             << FixItHint::CreateRemoval(
7220                                       D.getDeclSpec().getStorageClassSpecLoc());
7221       }
7222 
7223     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7224       if (CheckMemberSpecialization(NewFD, Previous))
7225           NewFD->setInvalidDecl();
7226     }
7227 
7228     // Perform semantic checking on the function declaration.
7229     if (!isDependentClassScopeExplicitSpecialization) {
7230       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7231         CheckMain(NewFD, D.getDeclSpec());
7232 
7233       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7234         CheckMSVCRTEntryPoint(NewFD);
7235 
7236       if (!NewFD->isInvalidDecl())
7237         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7238                                                     isExplicitSpecialization));
7239     }
7240 
7241     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7242             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7243            "previous declaration set still overloaded");
7244 
7245     NamedDecl *PrincipalDecl = (FunctionTemplate
7246                                 ? cast<NamedDecl>(FunctionTemplate)
7247                                 : NewFD);
7248 
7249     if (isFriend && D.isRedeclaration()) {
7250       AccessSpecifier Access = AS_public;
7251       if (!NewFD->isInvalidDecl())
7252         Access = NewFD->getPreviousDecl()->getAccess();
7253 
7254       NewFD->setAccess(Access);
7255       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7256     }
7257 
7258     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7259         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7260       PrincipalDecl->setNonMemberOperator();
7261 
7262     // If we have a function template, check the template parameter
7263     // list. This will check and merge default template arguments.
7264     if (FunctionTemplate) {
7265       FunctionTemplateDecl *PrevTemplate =
7266                                      FunctionTemplate->getPreviousDecl();
7267       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7268                        PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
7269                             D.getDeclSpec().isFriendSpecified()
7270                               ? (D.isFunctionDefinition()
7271                                    ? TPC_FriendFunctionTemplateDefinition
7272                                    : TPC_FriendFunctionTemplate)
7273                               : (D.getCXXScopeSpec().isSet() &&
7274                                  DC && DC->isRecord() &&
7275                                  DC->isDependentContext())
7276                                   ? TPC_ClassTemplateMember
7277                                   : TPC_FunctionTemplate);
7278     }
7279 
7280     if (NewFD->isInvalidDecl()) {
7281       // Ignore all the rest of this.
7282     } else if (!D.isRedeclaration()) {
7283       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7284                                        AddToScope };
7285       // Fake up an access specifier if it's supposed to be a class member.
7286       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7287         NewFD->setAccess(AS_public);
7288 
7289       // Qualified decls generally require a previous declaration.
7290       if (D.getCXXScopeSpec().isSet()) {
7291         // ...with the major exception of templated-scope or
7292         // dependent-scope friend declarations.
7293 
7294         // TODO: we currently also suppress this check in dependent
7295         // contexts because (1) the parameter depth will be off when
7296         // matching friend templates and (2) we might actually be
7297         // selecting a friend based on a dependent factor.  But there
7298         // are situations where these conditions don't apply and we
7299         // can actually do this check immediately.
7300         if (isFriend &&
7301             (TemplateParamLists.size() ||
7302              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7303              CurContext->isDependentContext())) {
7304           // ignore these
7305         } else {
7306           // The user tried to provide an out-of-line definition for a
7307           // function that is a member of a class or namespace, but there
7308           // was no such member function declared (C++ [class.mfct]p2,
7309           // C++ [namespace.memdef]p2). For example:
7310           //
7311           // class X {
7312           //   void f() const;
7313           // };
7314           //
7315           // void X::f() { } // ill-formed
7316           //
7317           // Complain about this problem, and attempt to suggest close
7318           // matches (e.g., those that differ only in cv-qualifiers and
7319           // whether the parameter types are references).
7320 
7321           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7322                   *this, Previous, NewFD, ExtraArgs, false, 0)) {
7323             AddToScope = ExtraArgs.AddToScope;
7324             return Result;
7325           }
7326         }
7327 
7328         // Unqualified local friend declarations are required to resolve
7329         // to something.
7330       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7331         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7332                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7333           AddToScope = ExtraArgs.AddToScope;
7334           return Result;
7335         }
7336       }
7337 
7338     } else if (!D.isFunctionDefinition() &&
7339                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7340                !isFriend && !isFunctionTemplateSpecialization &&
7341                !isExplicitSpecialization) {
7342       // An out-of-line member function declaration must also be a
7343       // definition (C++ [class.mfct]p2).
7344       // Note that this is not the case for explicit specializations of
7345       // function templates or member functions of class templates, per
7346       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7347       // extension for compatibility with old SWIG code which likes to
7348       // generate them.
7349       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7350         << D.getCXXScopeSpec().getRange();
7351     }
7352   }
7353 
7354   ProcessPragmaWeak(S, NewFD);
7355   checkAttributesAfterMerging(*this, *NewFD);
7356 
7357   AddKnownFunctionAttributes(NewFD);
7358 
7359   if (NewFD->hasAttr<OverloadableAttr>() &&
7360       !NewFD->getType()->getAs<FunctionProtoType>()) {
7361     Diag(NewFD->getLocation(),
7362          diag::err_attribute_overloadable_no_prototype)
7363       << NewFD;
7364 
7365     // Turn this into a variadic function with no parameters.
7366     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7367     FunctionProtoType::ExtProtoInfo EPI(
7368         Context.getDefaultCallingConvention(true, false));
7369     EPI.Variadic = true;
7370     EPI.ExtInfo = FT->getExtInfo();
7371 
7372     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7373     NewFD->setType(R);
7374   }
7375 
7376   // If there's a #pragma GCC visibility in scope, and this isn't a class
7377   // member, set the visibility of this function.
7378   if (!DC->isRecord() && NewFD->isExternallyVisible())
7379     AddPushedVisibilityAttribute(NewFD);
7380 
7381   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7382   // marking the function.
7383   AddCFAuditedAttribute(NewFD);
7384 
7385   // If this is the first declaration of an extern C variable, update
7386   // the map of such variables.
7387   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7388       isIncompleteDeclExternC(*this, NewFD))
7389     RegisterLocallyScopedExternCDecl(NewFD, S);
7390 
7391   // Set this FunctionDecl's range up to the right paren.
7392   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7393 
7394   if (D.isRedeclaration() && !Previous.empty()) {
7395     checkDLLAttributeRedeclaration(
7396         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
7397         isExplicitSpecialization || isFunctionTemplateSpecialization);
7398   }
7399 
7400   if (getLangOpts().CPlusPlus) {
7401     if (FunctionTemplate) {
7402       if (NewFD->isInvalidDecl())
7403         FunctionTemplate->setInvalidDecl();
7404       return FunctionTemplate;
7405     }
7406   }
7407 
7408   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7409     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7410     if ((getLangOpts().OpenCLVersion >= 120)
7411         && (SC == SC_Static)) {
7412       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7413       D.setInvalidType();
7414     }
7415 
7416     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7417     if (!NewFD->getReturnType()->isVoidType()) {
7418       Diag(D.getIdentifierLoc(),
7419            diag::err_expected_kernel_void_return_type);
7420       D.setInvalidType();
7421     }
7422 
7423     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7424     for (auto Param : NewFD->params())
7425       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7426   }
7427 
7428   MarkUnusedFileScopedDecl(NewFD);
7429 
7430   if (getLangOpts().CUDA)
7431     if (IdentifierInfo *II = NewFD->getIdentifier())
7432       if (!NewFD->isInvalidDecl() &&
7433           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7434         if (II->isStr("cudaConfigureCall")) {
7435           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7436             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7437 
7438           Context.setcudaConfigureCallDecl(NewFD);
7439         }
7440       }
7441 
7442   // Here we have an function template explicit specialization at class scope.
7443   // The actually specialization will be postponed to template instatiation
7444   // time via the ClassScopeFunctionSpecializationDecl node.
7445   if (isDependentClassScopeExplicitSpecialization) {
7446     ClassScopeFunctionSpecializationDecl *NewSpec =
7447                          ClassScopeFunctionSpecializationDecl::Create(
7448                                 Context, CurContext, SourceLocation(),
7449                                 cast<CXXMethodDecl>(NewFD),
7450                                 HasExplicitTemplateArgs, TemplateArgs);
7451     CurContext->addDecl(NewSpec);
7452     AddToScope = false;
7453   }
7454 
7455   return NewFD;
7456 }
7457 
7458 /// \brief Perform semantic checking of a new function declaration.
7459 ///
7460 /// Performs semantic analysis of the new function declaration
7461 /// NewFD. This routine performs all semantic checking that does not
7462 /// require the actual declarator involved in the declaration, and is
7463 /// used both for the declaration of functions as they are parsed
7464 /// (called via ActOnDeclarator) and for the declaration of functions
7465 /// that have been instantiated via C++ template instantiation (called
7466 /// via InstantiateDecl).
7467 ///
7468 /// \param IsExplicitSpecialization whether this new function declaration is
7469 /// an explicit specialization of the previous declaration.
7470 ///
7471 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7472 ///
7473 /// \returns true if the function declaration is a redeclaration.
7474 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7475                                     LookupResult &Previous,
7476                                     bool IsExplicitSpecialization) {
7477   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7478          "Variably modified return types are not handled here");
7479 
7480   // Determine whether the type of this function should be merged with
7481   // a previous visible declaration. This never happens for functions in C++,
7482   // and always happens in C if the previous declaration was visible.
7483   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7484                                !Previous.isShadowed();
7485 
7486   // Filter out any non-conflicting previous declarations.
7487   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7488 
7489   bool Redeclaration = false;
7490   NamedDecl *OldDecl = 0;
7491 
7492   // Merge or overload the declaration with an existing declaration of
7493   // the same name, if appropriate.
7494   if (!Previous.empty()) {
7495     // Determine whether NewFD is an overload of PrevDecl or
7496     // a declaration that requires merging. If it's an overload,
7497     // there's no more work to do here; we'll just add the new
7498     // function to the scope.
7499     if (!AllowOverloadingOfFunction(Previous, Context)) {
7500       NamedDecl *Candidate = Previous.getFoundDecl();
7501       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7502         Redeclaration = true;
7503         OldDecl = Candidate;
7504       }
7505     } else {
7506       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7507                             /*NewIsUsingDecl*/ false)) {
7508       case Ovl_Match:
7509         Redeclaration = true;
7510         break;
7511 
7512       case Ovl_NonFunction:
7513         Redeclaration = true;
7514         break;
7515 
7516       case Ovl_Overload:
7517         Redeclaration = false;
7518         break;
7519       }
7520 
7521       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7522         // If a function name is overloadable in C, then every function
7523         // with that name must be marked "overloadable".
7524         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7525           << Redeclaration << NewFD;
7526         NamedDecl *OverloadedDecl = 0;
7527         if (Redeclaration)
7528           OverloadedDecl = OldDecl;
7529         else if (!Previous.empty())
7530           OverloadedDecl = Previous.getRepresentativeDecl();
7531         if (OverloadedDecl)
7532           Diag(OverloadedDecl->getLocation(),
7533                diag::note_attribute_overloadable_prev_overload);
7534         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7535       }
7536     }
7537   }
7538 
7539   // Check for a previous extern "C" declaration with this name.
7540   if (!Redeclaration &&
7541       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7542     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7543     if (!Previous.empty()) {
7544       // This is an extern "C" declaration with the same name as a previous
7545       // declaration, and thus redeclares that entity...
7546       Redeclaration = true;
7547       OldDecl = Previous.getFoundDecl();
7548       MergeTypeWithPrevious = false;
7549 
7550       // ... except in the presence of __attribute__((overloadable)).
7551       if (OldDecl->hasAttr<OverloadableAttr>()) {
7552         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7553           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7554             << Redeclaration << NewFD;
7555           Diag(Previous.getFoundDecl()->getLocation(),
7556                diag::note_attribute_overloadable_prev_overload);
7557           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7558         }
7559         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7560           Redeclaration = false;
7561           OldDecl = 0;
7562         }
7563       }
7564     }
7565   }
7566 
7567   // C++11 [dcl.constexpr]p8:
7568   //   A constexpr specifier for a non-static member function that is not
7569   //   a constructor declares that member function to be const.
7570   //
7571   // This needs to be delayed until we know whether this is an out-of-line
7572   // definition of a static member function.
7573   //
7574   // This rule is not present in C++1y, so we produce a backwards
7575   // compatibility warning whenever it happens in C++11.
7576   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7577   if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7578       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7579       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7580     CXXMethodDecl *OldMD = 0;
7581     if (OldDecl)
7582       OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
7583     if (!OldMD || !OldMD->isStatic()) {
7584       const FunctionProtoType *FPT =
7585         MD->getType()->castAs<FunctionProtoType>();
7586       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7587       EPI.TypeQuals |= Qualifiers::Const;
7588       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7589                                           FPT->getParamTypes(), EPI));
7590 
7591       // Warn that we did this, if we're not performing template instantiation.
7592       // In that case, we'll have warned already when the template was defined.
7593       if (ActiveTemplateInstantiations.empty()) {
7594         SourceLocation AddConstLoc;
7595         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7596                 .IgnoreParens().getAs<FunctionTypeLoc>())
7597           AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7598 
7599         Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7600           << FixItHint::CreateInsertion(AddConstLoc, " const");
7601       }
7602     }
7603   }
7604 
7605   if (Redeclaration) {
7606     // NewFD and OldDecl represent declarations that need to be
7607     // merged.
7608     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7609       NewFD->setInvalidDecl();
7610       return Redeclaration;
7611     }
7612 
7613     Previous.clear();
7614     Previous.addDecl(OldDecl);
7615 
7616     if (FunctionTemplateDecl *OldTemplateDecl
7617                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7618       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7619       FunctionTemplateDecl *NewTemplateDecl
7620         = NewFD->getDescribedFunctionTemplate();
7621       assert(NewTemplateDecl && "Template/non-template mismatch");
7622       if (CXXMethodDecl *Method
7623             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7624         Method->setAccess(OldTemplateDecl->getAccess());
7625         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7626       }
7627 
7628       // If this is an explicit specialization of a member that is a function
7629       // template, mark it as a member specialization.
7630       if (IsExplicitSpecialization &&
7631           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7632         NewTemplateDecl->setMemberSpecialization();
7633         assert(OldTemplateDecl->isMemberSpecialization());
7634       }
7635 
7636     } else {
7637       // This needs to happen first so that 'inline' propagates.
7638       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7639 
7640       if (isa<CXXMethodDecl>(NewFD)) {
7641         // A valid redeclaration of a C++ method must be out-of-line,
7642         // but (unfortunately) it's not necessarily a definition
7643         // because of templates, which means that the previous
7644         // declaration is not necessarily from the class definition.
7645 
7646         // For just setting the access, that doesn't matter.
7647         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7648         NewFD->setAccess(oldMethod->getAccess());
7649 
7650         // Update the key-function state if necessary for this ABI.
7651         if (NewFD->isInlined() &&
7652             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7653           // setNonKeyFunction needs to work with the original
7654           // declaration from the class definition, and isVirtual() is
7655           // just faster in that case, so map back to that now.
7656           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7657           if (oldMethod->isVirtual()) {
7658             Context.setNonKeyFunction(oldMethod);
7659           }
7660         }
7661       }
7662     }
7663   }
7664 
7665   // Semantic checking for this function declaration (in isolation).
7666   if (getLangOpts().CPlusPlus) {
7667     // C++-specific checks.
7668     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7669       CheckConstructor(Constructor);
7670     } else if (CXXDestructorDecl *Destructor =
7671                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7672       CXXRecordDecl *Record = Destructor->getParent();
7673       QualType ClassType = Context.getTypeDeclType(Record);
7674 
7675       // FIXME: Shouldn't we be able to perform this check even when the class
7676       // type is dependent? Both gcc and edg can handle that.
7677       if (!ClassType->isDependentType()) {
7678         DeclarationName Name
7679           = Context.DeclarationNames.getCXXDestructorName(
7680                                         Context.getCanonicalType(ClassType));
7681         if (NewFD->getDeclName() != Name) {
7682           Diag(NewFD->getLocation(), diag::err_destructor_name);
7683           NewFD->setInvalidDecl();
7684           return Redeclaration;
7685         }
7686       }
7687     } else if (CXXConversionDecl *Conversion
7688                = dyn_cast<CXXConversionDecl>(NewFD)) {
7689       ActOnConversionDeclarator(Conversion);
7690     }
7691 
7692     // Find any virtual functions that this function overrides.
7693     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7694       if (!Method->isFunctionTemplateSpecialization() &&
7695           !Method->getDescribedFunctionTemplate() &&
7696           Method->isCanonicalDecl()) {
7697         if (AddOverriddenMethods(Method->getParent(), Method)) {
7698           // If the function was marked as "static", we have a problem.
7699           if (NewFD->getStorageClass() == SC_Static) {
7700             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7701           }
7702         }
7703       }
7704 
7705       if (Method->isStatic())
7706         checkThisInStaticMemberFunctionType(Method);
7707     }
7708 
7709     // Extra checking for C++ overloaded operators (C++ [over.oper]).
7710     if (NewFD->isOverloadedOperator() &&
7711         CheckOverloadedOperatorDeclaration(NewFD)) {
7712       NewFD->setInvalidDecl();
7713       return Redeclaration;
7714     }
7715 
7716     // Extra checking for C++0x literal operators (C++0x [over.literal]).
7717     if (NewFD->getLiteralIdentifier() &&
7718         CheckLiteralOperatorDeclaration(NewFD)) {
7719       NewFD->setInvalidDecl();
7720       return Redeclaration;
7721     }
7722 
7723     // In C++, check default arguments now that we have merged decls. Unless
7724     // the lexical context is the class, because in this case this is done
7725     // during delayed parsing anyway.
7726     if (!CurContext->isRecord())
7727       CheckCXXDefaultArguments(NewFD);
7728 
7729     // If this function declares a builtin function, check the type of this
7730     // declaration against the expected type for the builtin.
7731     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7732       ASTContext::GetBuiltinTypeError Error;
7733       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
7734       QualType T = Context.GetBuiltinType(BuiltinID, Error);
7735       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7736         // The type of this function differs from the type of the builtin,
7737         // so forget about the builtin entirely.
7738         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7739       }
7740     }
7741 
7742     // If this function is declared as being extern "C", then check to see if
7743     // the function returns a UDT (class, struct, or union type) that is not C
7744     // compatible, and if it does, warn the user.
7745     // But, issue any diagnostic on the first declaration only.
7746     if (NewFD->isExternC() && Previous.empty()) {
7747       QualType R = NewFD->getReturnType();
7748       if (R->isIncompleteType() && !R->isVoidType())
7749         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7750             << NewFD << R;
7751       else if (!R.isPODType(Context) && !R->isVoidType() &&
7752                !R->isObjCObjectPointerType())
7753         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
7754     }
7755   }
7756   return Redeclaration;
7757 }
7758 
7759 static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7760   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7761   if (!TSI)
7762     return SourceRange();
7763 
7764   TypeLoc TL = TSI->getTypeLoc();
7765   FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
7766   if (!FunctionTL)
7767     return SourceRange();
7768 
7769   TypeLoc ResultTL = FunctionTL.getReturnLoc();
7770   if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
7771     return ResultTL.getSourceRange();
7772 
7773   return SourceRange();
7774 }
7775 
7776 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
7777   // C++11 [basic.start.main]p3:
7778   //   A program that [...] declares main to be inline, static or
7779   //   constexpr is ill-formed.
7780   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
7781   //   appear in a declaration of main.
7782   // static main is not an error under C99, but we should warn about it.
7783   // We accept _Noreturn main as an extension.
7784   if (FD->getStorageClass() == SC_Static)
7785     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
7786          ? diag::err_static_main : diag::warn_static_main)
7787       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7788   if (FD->isInlineSpecified())
7789     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7790       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
7791   if (DS.isNoreturnSpecified()) {
7792     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7793     SourceRange NoreturnRange(NoreturnLoc,
7794                               PP.getLocForEndOfToken(NoreturnLoc));
7795     Diag(NoreturnLoc, diag::ext_noreturn_main);
7796     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7797       << FixItHint::CreateRemoval(NoreturnRange);
7798   }
7799   if (FD->isConstexpr()) {
7800     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7801       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7802     FD->setConstexpr(false);
7803   }
7804 
7805   if (getLangOpts().OpenCL) {
7806     Diag(FD->getLocation(), diag::err_opencl_no_main)
7807         << FD->hasAttr<OpenCLKernelAttr>();
7808     FD->setInvalidDecl();
7809     return;
7810   }
7811 
7812   QualType T = FD->getType();
7813   assert(T->isFunctionType() && "function decl is not of function type");
7814   const FunctionType* FT = T->castAs<FunctionType>();
7815 
7816   // All the standards say that main() should should return 'int'.
7817   if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
7818     // In C and C++, main magically returns 0 if you fall off the end;
7819     // set the flag which tells us that.
7820     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7821     FD->setHasImplicitReturnZero(true);
7822 
7823   // In C with GNU extensions we allow main() to have non-integer return
7824   // type, but we should warn about the extension, and we disable the
7825   // implicit-return-zero rule.
7826   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
7827     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7828 
7829     SourceRange ResultRange = getResultSourceRange(FD);
7830     if (ResultRange.isValid())
7831       Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7832           << FixItHint::CreateReplacement(ResultRange, "int");
7833 
7834   // Otherwise, this is just a flat-out error.
7835   } else {
7836     SourceRange ResultRange = getResultSourceRange(FD);
7837     if (ResultRange.isValid())
7838       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7839           << FixItHint::CreateReplacement(ResultRange, "int");
7840     else
7841       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7842 
7843     FD->setInvalidDecl(true);
7844   }
7845 
7846   // Treat protoless main() as nullary.
7847   if (isa<FunctionNoProtoType>(FT)) return;
7848 
7849   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7850   unsigned nparams = FTP->getNumParams();
7851   assert(FD->getNumParams() == nparams);
7852 
7853   bool HasExtraParameters = (nparams > 3);
7854 
7855   // Darwin passes an undocumented fourth argument of type char**.  If
7856   // other platforms start sprouting these, the logic below will start
7857   // getting shifty.
7858   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
7859     HasExtraParameters = false;
7860 
7861   if (HasExtraParameters) {
7862     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7863     FD->setInvalidDecl(true);
7864     nparams = 3;
7865   }
7866 
7867   // FIXME: a lot of the following diagnostics would be improved
7868   // if we had some location information about types.
7869 
7870   QualType CharPP =
7871     Context.getPointerType(Context.getPointerType(Context.CharTy));
7872   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
7873 
7874   for (unsigned i = 0; i < nparams; ++i) {
7875     QualType AT = FTP->getParamType(i);
7876 
7877     bool mismatch = true;
7878 
7879     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7880       mismatch = false;
7881     else if (Expected[i] == CharPP) {
7882       // As an extension, the following forms are okay:
7883       //   char const **
7884       //   char const * const *
7885       //   char * const *
7886 
7887       QualifierCollector qs;
7888       const PointerType* PT;
7889       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7890           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
7891           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7892                               Context.CharTy)) {
7893         qs.removeConst();
7894         mismatch = !qs.empty();
7895       }
7896     }
7897 
7898     if (mismatch) {
7899       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7900       // TODO: suggest replacing given type with expected type
7901       FD->setInvalidDecl(true);
7902     }
7903   }
7904 
7905   if (nparams == 1 && !FD->isInvalidDecl()) {
7906     Diag(FD->getLocation(), diag::warn_main_one_arg);
7907   }
7908 
7909   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7910     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
7911     FD->setInvalidDecl();
7912   }
7913 }
7914 
7915 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7916   QualType T = FD->getType();
7917   assert(T->isFunctionType() && "function decl is not of function type");
7918   const FunctionType *FT = T->castAs<FunctionType>();
7919 
7920   // Set an implicit return of 'zero' if the function can return some integral,
7921   // enumeration, pointer or nullptr type.
7922   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7923       FT->getReturnType()->isAnyPointerType() ||
7924       FT->getReturnType()->isNullPtrType())
7925     // DllMain is exempt because a return value of zero means it failed.
7926     if (FD->getName() != "DllMain")
7927       FD->setHasImplicitReturnZero(true);
7928 
7929   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7930     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
7931     FD->setInvalidDecl();
7932   }
7933 }
7934 
7935 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
7936   // FIXME: Need strict checking.  In C89, we need to check for
7937   // any assignment, increment, decrement, function-calls, or
7938   // commas outside of a sizeof.  In C99, it's the same list,
7939   // except that the aforementioned are allowed in unevaluated
7940   // expressions.  Everything else falls under the
7941   // "may accept other forms of constant expressions" exception.
7942   // (We never end up here for C++, so the constant expression
7943   // rules there don't matter.)
7944   if (Init->isConstantInitializer(Context, false))
7945     return false;
7946   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7947     << Init->getSourceRange();
7948   return true;
7949 }
7950 
7951 namespace {
7952   // Visits an initialization expression to see if OrigDecl is evaluated in
7953   // its own initialization and throws a warning if it does.
7954   class SelfReferenceChecker
7955       : public EvaluatedExprVisitor<SelfReferenceChecker> {
7956     Sema &S;
7957     Decl *OrigDecl;
7958     bool isRecordType;
7959     bool isPODType;
7960     bool isReferenceType;
7961 
7962   public:
7963     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7964 
7965     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
7966                                                     S(S), OrigDecl(OrigDecl) {
7967       isPODType = false;
7968       isRecordType = false;
7969       isReferenceType = false;
7970       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7971         isPODType = VD->getType().isPODType(S.Context);
7972         isRecordType = VD->getType()->isRecordType();
7973         isReferenceType = VD->getType()->isReferenceType();
7974       }
7975     }
7976 
7977     // For most expressions, the cast is directly above the DeclRefExpr.
7978     // For conditional operators, the cast can be outside the conditional
7979     // operator if both expressions are DeclRefExpr's.
7980     void HandleValue(Expr *E) {
7981       if (isReferenceType)
7982         return;
7983       E = E->IgnoreParenImpCasts();
7984       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7985         HandleDeclRefExpr(DRE);
7986         return;
7987       }
7988 
7989       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7990         HandleValue(CO->getTrueExpr());
7991         HandleValue(CO->getFalseExpr());
7992         return;
7993       }
7994 
7995       if (isa<MemberExpr>(E)) {
7996         Expr *Base = E->IgnoreParenImpCasts();
7997         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7998           // Check for static member variables and don't warn on them.
7999           if (!isa<FieldDecl>(ME->getMemberDecl()))
8000             return;
8001           Base = ME->getBase()->IgnoreParenImpCasts();
8002         }
8003         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8004           HandleDeclRefExpr(DRE);
8005         return;
8006       }
8007     }
8008 
8009     // Reference types are handled here since all uses of references are
8010     // bad, not just r-value uses.
8011     void VisitDeclRefExpr(DeclRefExpr *E) {
8012       if (isReferenceType)
8013         HandleDeclRefExpr(E);
8014     }
8015 
8016     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8017       if (E->getCastKind() == CK_LValueToRValue ||
8018           (isRecordType && E->getCastKind() == CK_NoOp))
8019         HandleValue(E->getSubExpr());
8020 
8021       Inherited::VisitImplicitCastExpr(E);
8022     }
8023 
8024     void VisitMemberExpr(MemberExpr *E) {
8025       // Don't warn on arrays since they can be treated as pointers.
8026       if (E->getType()->canDecayToPointerType()) return;
8027 
8028       // Warn when a non-static method call is followed by non-static member
8029       // field accesses, which is followed by a DeclRefExpr.
8030       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8031       bool Warn = (MD && !MD->isStatic());
8032       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8033       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8034         if (!isa<FieldDecl>(ME->getMemberDecl()))
8035           Warn = false;
8036         Base = ME->getBase()->IgnoreParenImpCasts();
8037       }
8038 
8039       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8040         if (Warn)
8041           HandleDeclRefExpr(DRE);
8042         return;
8043       }
8044 
8045       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8046       // Visit that expression.
8047       Visit(Base);
8048     }
8049 
8050     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8051       if (E->getNumArgs() > 0)
8052         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
8053           HandleDeclRefExpr(DRE);
8054 
8055       Inherited::VisitCXXOperatorCallExpr(E);
8056     }
8057 
8058     void VisitUnaryOperator(UnaryOperator *E) {
8059       // For POD record types, addresses of its own members are well-defined.
8060       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8061           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8062         if (!isPODType)
8063           HandleValue(E->getSubExpr());
8064         return;
8065       }
8066       Inherited::VisitUnaryOperator(E);
8067     }
8068 
8069     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8070 
8071     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8072       Decl* ReferenceDecl = DRE->getDecl();
8073       if (OrigDecl != ReferenceDecl) return;
8074       unsigned diag;
8075       if (isReferenceType) {
8076         diag = diag::warn_uninit_self_reference_in_reference_init;
8077       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
8078         diag = diag::warn_static_self_reference_in_init;
8079       } else {
8080         diag = diag::warn_uninit_self_reference_in_init;
8081       }
8082 
8083       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8084                             S.PDiag(diag)
8085                               << DRE->getNameInfo().getName()
8086                               << OrigDecl->getLocation()
8087                               << DRE->getSourceRange());
8088     }
8089   };
8090 
8091   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8092   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8093                                  bool DirectInit) {
8094     // Parameters arguments are occassionially constructed with itself,
8095     // for instance, in recursive functions.  Skip them.
8096     if (isa<ParmVarDecl>(OrigDecl))
8097       return;
8098 
8099     E = E->IgnoreParens();
8100 
8101     // Skip checking T a = a where T is not a record or reference type.
8102     // Doing so is a way to silence uninitialized warnings.
8103     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8104       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8105         if (ICE->getCastKind() == CK_LValueToRValue)
8106           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8107             if (DRE->getDecl() == OrigDecl)
8108               return;
8109 
8110     SelfReferenceChecker(S, OrigDecl).Visit(E);
8111   }
8112 }
8113 
8114 /// AddInitializerToDecl - Adds the initializer Init to the
8115 /// declaration dcl. If DirectInit is true, this is C++ direct
8116 /// initialization rather than copy initialization.
8117 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8118                                 bool DirectInit, bool TypeMayContainAuto) {
8119   // If there is no declaration, there was an error parsing it.  Just ignore
8120   // the initializer.
8121   if (RealDecl == 0 || RealDecl->isInvalidDecl())
8122     return;
8123 
8124   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8125     // With declarators parsed the way they are, the parser cannot
8126     // distinguish between a normal initializer and a pure-specifier.
8127     // Thus this grotesque test.
8128     IntegerLiteral *IL;
8129     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8130         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8131       CheckPureMethod(Method, Init->getSourceRange());
8132     else {
8133       Diag(Method->getLocation(), diag::err_member_function_initialization)
8134         << Method->getDeclName() << Init->getSourceRange();
8135       Method->setInvalidDecl();
8136     }
8137     return;
8138   }
8139 
8140   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8141   if (!VDecl) {
8142     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8143     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8144     RealDecl->setInvalidDecl();
8145     return;
8146   }
8147   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8148 
8149   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8150   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8151     Expr *DeduceInit = Init;
8152     // Initializer could be a C++ direct-initializer. Deduction only works if it
8153     // contains exactly one expression.
8154     if (CXXDirectInit) {
8155       if (CXXDirectInit->getNumExprs() == 0) {
8156         // It isn't possible to write this directly, but it is possible to
8157         // end up in this situation with "auto x(some_pack...);"
8158         Diag(CXXDirectInit->getLocStart(),
8159              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8160                                     : diag::err_auto_var_init_no_expression)
8161           << VDecl->getDeclName() << VDecl->getType()
8162           << VDecl->getSourceRange();
8163         RealDecl->setInvalidDecl();
8164         return;
8165       } else if (CXXDirectInit->getNumExprs() > 1) {
8166         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8167              VDecl->isInitCapture()
8168                  ? diag::err_init_capture_multiple_expressions
8169                  : diag::err_auto_var_init_multiple_expressions)
8170           << VDecl->getDeclName() << VDecl->getType()
8171           << VDecl->getSourceRange();
8172         RealDecl->setInvalidDecl();
8173         return;
8174       } else {
8175         DeduceInit = CXXDirectInit->getExpr(0);
8176         if (isa<InitListExpr>(DeduceInit))
8177           Diag(CXXDirectInit->getLocStart(),
8178                diag::err_auto_var_init_paren_braces)
8179             << VDecl->getDeclName() << VDecl->getType()
8180             << VDecl->getSourceRange();
8181       }
8182     }
8183 
8184     // Expressions default to 'id' when we're in a debugger.
8185     bool DefaultedToAuto = false;
8186     if (getLangOpts().DebuggerCastResultToId &&
8187         Init->getType() == Context.UnknownAnyTy) {
8188       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8189       if (Result.isInvalid()) {
8190         VDecl->setInvalidDecl();
8191         return;
8192       }
8193       Init = Result.take();
8194       DefaultedToAuto = true;
8195     }
8196 
8197     QualType DeducedType;
8198     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8199             DAR_Failed)
8200       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8201     if (DeducedType.isNull()) {
8202       RealDecl->setInvalidDecl();
8203       return;
8204     }
8205     VDecl->setType(DeducedType);
8206     assert(VDecl->isLinkageValid());
8207 
8208     // In ARC, infer lifetime.
8209     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8210       VDecl->setInvalidDecl();
8211 
8212     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8213     // 'id' instead of a specific object type prevents most of our usual checks.
8214     // We only want to warn outside of template instantiations, though:
8215     // inside a template, the 'id' could have come from a parameter.
8216     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8217         DeducedType->isObjCIdType()) {
8218       SourceLocation Loc =
8219           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8220       Diag(Loc, diag::warn_auto_var_is_id)
8221         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8222     }
8223 
8224     // If this is a redeclaration, check that the type we just deduced matches
8225     // the previously declared type.
8226     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8227       // We never need to merge the type, because we cannot form an incomplete
8228       // array of auto, nor deduce such a type.
8229       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8230     }
8231 
8232     // Check the deduced type is valid for a variable declaration.
8233     CheckVariableDeclarationType(VDecl);
8234     if (VDecl->isInvalidDecl())
8235       return;
8236   }
8237 
8238   // dllimport cannot be used on variable definitions.
8239   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8240     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8241     VDecl->setInvalidDecl();
8242     return;
8243   }
8244 
8245   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8246     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8247     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8248     VDecl->setInvalidDecl();
8249     return;
8250   }
8251 
8252   if (!VDecl->getType()->isDependentType()) {
8253     // A definition must end up with a complete type, which means it must be
8254     // complete with the restriction that an array type might be completed by
8255     // the initializer; note that later code assumes this restriction.
8256     QualType BaseDeclType = VDecl->getType();
8257     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8258       BaseDeclType = Array->getElementType();
8259     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8260                             diag::err_typecheck_decl_incomplete_type)) {
8261       RealDecl->setInvalidDecl();
8262       return;
8263     }
8264 
8265     // The variable can not have an abstract class type.
8266     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8267                                diag::err_abstract_type_in_decl,
8268                                AbstractVariableType))
8269       VDecl->setInvalidDecl();
8270   }
8271 
8272   const VarDecl *Def;
8273   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8274     Diag(VDecl->getLocation(), diag::err_redefinition)
8275       << VDecl->getDeclName();
8276     Diag(Def->getLocation(), diag::note_previous_definition);
8277     VDecl->setInvalidDecl();
8278     return;
8279   }
8280 
8281   const VarDecl* PrevInit = 0;
8282   if (getLangOpts().CPlusPlus) {
8283     // C++ [class.static.data]p4
8284     //   If a static data member is of const integral or const
8285     //   enumeration type, its declaration in the class definition can
8286     //   specify a constant-initializer which shall be an integral
8287     //   constant expression (5.19). In that case, the member can appear
8288     //   in integral constant expressions. The member shall still be
8289     //   defined in a namespace scope if it is used in the program and the
8290     //   namespace scope definition shall not contain an initializer.
8291     //
8292     // We already performed a redefinition check above, but for static
8293     // data members we also need to check whether there was an in-class
8294     // declaration with an initializer.
8295     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8296       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8297           << VDecl->getDeclName();
8298       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8299       return;
8300     }
8301 
8302     if (VDecl->hasLocalStorage())
8303       getCurFunction()->setHasBranchProtectedScope();
8304 
8305     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8306       VDecl->setInvalidDecl();
8307       return;
8308     }
8309   }
8310 
8311   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8312   // a kernel function cannot be initialized."
8313   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8314     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8315     VDecl->setInvalidDecl();
8316     return;
8317   }
8318 
8319   // Get the decls type and save a reference for later, since
8320   // CheckInitializerTypes may change it.
8321   QualType DclT = VDecl->getType(), SavT = DclT;
8322 
8323   // Expressions default to 'id' when we're in a debugger
8324   // and we are assigning it to a variable of Objective-C pointer type.
8325   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8326       Init->getType() == Context.UnknownAnyTy) {
8327     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8328     if (Result.isInvalid()) {
8329       VDecl->setInvalidDecl();
8330       return;
8331     }
8332     Init = Result.take();
8333   }
8334 
8335   // Perform the initialization.
8336   if (!VDecl->isInvalidDecl()) {
8337     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8338     InitializationKind Kind
8339       = DirectInit ?
8340           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8341                                                            Init->getLocStart(),
8342                                                            Init->getLocEnd())
8343                         : InitializationKind::CreateDirectList(
8344                                                           VDecl->getLocation())
8345                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8346                                                     Init->getLocStart());
8347 
8348     MultiExprArg Args = Init;
8349     if (CXXDirectInit)
8350       Args = MultiExprArg(CXXDirectInit->getExprs(),
8351                           CXXDirectInit->getNumExprs());
8352 
8353     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8354     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8355     if (Result.isInvalid()) {
8356       VDecl->setInvalidDecl();
8357       return;
8358     }
8359 
8360     Init = Result.takeAs<Expr>();
8361   }
8362 
8363   // Check for self-references within variable initializers.
8364   // Variables declared within a function/method body (except for references)
8365   // are handled by a dataflow analysis.
8366   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8367       VDecl->getType()->isReferenceType()) {
8368     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8369   }
8370 
8371   // If the type changed, it means we had an incomplete type that was
8372   // completed by the initializer. For example:
8373   //   int ary[] = { 1, 3, 5 };
8374   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8375   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8376     VDecl->setType(DclT);
8377 
8378   if (!VDecl->isInvalidDecl()) {
8379     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8380 
8381     if (VDecl->hasAttr<BlocksAttr>())
8382       checkRetainCycles(VDecl, Init);
8383 
8384     // It is safe to assign a weak reference into a strong variable.
8385     // Although this code can still have problems:
8386     //   id x = self.weakProp;
8387     //   id y = self.weakProp;
8388     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8389     // paths through the function. This should be revisited if
8390     // -Wrepeated-use-of-weak is made flow-sensitive.
8391     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
8392       DiagnosticsEngine::Level Level =
8393         Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8394                                  Init->getLocStart());
8395       if (Level != DiagnosticsEngine::Ignored)
8396         getCurFunction()->markSafeWeakUse(Init);
8397     }
8398   }
8399 
8400   // The initialization is usually a full-expression.
8401   //
8402   // FIXME: If this is a braced initialization of an aggregate, it is not
8403   // an expression, and each individual field initializer is a separate
8404   // full-expression. For instance, in:
8405   //
8406   //   struct Temp { ~Temp(); };
8407   //   struct S { S(Temp); };
8408   //   struct T { S a, b; } t = { Temp(), Temp() }
8409   //
8410   // we should destroy the first Temp before constructing the second.
8411   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8412                                           false,
8413                                           VDecl->isConstexpr());
8414   if (Result.isInvalid()) {
8415     VDecl->setInvalidDecl();
8416     return;
8417   }
8418   Init = Result.take();
8419 
8420   // Attach the initializer to the decl.
8421   VDecl->setInit(Init);
8422 
8423   if (VDecl->isLocalVarDecl()) {
8424     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8425     // static storage duration shall be constant expressions or string literals.
8426     // C++ does not have this restriction.
8427     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8428       if (VDecl->getStorageClass() == SC_Static)
8429         CheckForConstantInitializer(Init, DclT);
8430       // C89 is stricter than C99 for non-static aggregate types.
8431       // C89 6.5.7p3: All the expressions [...] in an initializer list
8432       // for an object that has aggregate or union type shall be
8433       // constant expressions.
8434       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8435                isa<InitListExpr>(Init) &&
8436                !Init->isConstantInitializer(Context, false))
8437         Diag(Init->getExprLoc(),
8438              diag::ext_aggregate_init_not_constant)
8439           << Init->getSourceRange();
8440     }
8441   } else if (VDecl->isStaticDataMember() &&
8442              VDecl->getLexicalDeclContext()->isRecord()) {
8443     // This is an in-class initialization for a static data member, e.g.,
8444     //
8445     // struct S {
8446     //   static const int value = 17;
8447     // };
8448 
8449     // C++ [class.mem]p4:
8450     //   A member-declarator can contain a constant-initializer only
8451     //   if it declares a static member (9.4) of const integral or
8452     //   const enumeration type, see 9.4.2.
8453     //
8454     // C++11 [class.static.data]p3:
8455     //   If a non-volatile const static data member is of integral or
8456     //   enumeration type, its declaration in the class definition can
8457     //   specify a brace-or-equal-initializer in which every initalizer-clause
8458     //   that is an assignment-expression is a constant expression. A static
8459     //   data member of literal type can be declared in the class definition
8460     //   with the constexpr specifier; if so, its declaration shall specify a
8461     //   brace-or-equal-initializer in which every initializer-clause that is
8462     //   an assignment-expression is a constant expression.
8463 
8464     // Do nothing on dependent types.
8465     if (DclT->isDependentType()) {
8466 
8467     // Allow any 'static constexpr' members, whether or not they are of literal
8468     // type. We separately check that every constexpr variable is of literal
8469     // type.
8470     } else if (VDecl->isConstexpr()) {
8471 
8472     // Require constness.
8473     } else if (!DclT.isConstQualified()) {
8474       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8475         << Init->getSourceRange();
8476       VDecl->setInvalidDecl();
8477 
8478     // We allow integer constant expressions in all cases.
8479     } else if (DclT->isIntegralOrEnumerationType()) {
8480       // Check whether the expression is a constant expression.
8481       SourceLocation Loc;
8482       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8483         // In C++11, a non-constexpr const static data member with an
8484         // in-class initializer cannot be volatile.
8485         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8486       else if (Init->isValueDependent())
8487         ; // Nothing to check.
8488       else if (Init->isIntegerConstantExpr(Context, &Loc))
8489         ; // Ok, it's an ICE!
8490       else if (Init->isEvaluatable(Context)) {
8491         // If we can constant fold the initializer through heroics, accept it,
8492         // but report this as a use of an extension for -pedantic.
8493         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8494           << Init->getSourceRange();
8495       } else {
8496         // Otherwise, this is some crazy unknown case.  Report the issue at the
8497         // location provided by the isIntegerConstantExpr failed check.
8498         Diag(Loc, diag::err_in_class_initializer_non_constant)
8499           << Init->getSourceRange();
8500         VDecl->setInvalidDecl();
8501       }
8502 
8503     // We allow foldable floating-point constants as an extension.
8504     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8505       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8506       // it anyway and provide a fixit to add the 'constexpr'.
8507       if (getLangOpts().CPlusPlus11) {
8508         Diag(VDecl->getLocation(),
8509              diag::ext_in_class_initializer_float_type_cxx11)
8510             << DclT << Init->getSourceRange();
8511         Diag(VDecl->getLocStart(),
8512              diag::note_in_class_initializer_float_type_cxx11)
8513             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8514       } else {
8515         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8516           << DclT << Init->getSourceRange();
8517 
8518         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8519           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8520             << Init->getSourceRange();
8521           VDecl->setInvalidDecl();
8522         }
8523       }
8524 
8525     // Suggest adding 'constexpr' in C++11 for literal types.
8526     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8527       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8528         << DclT << Init->getSourceRange()
8529         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8530       VDecl->setConstexpr(true);
8531 
8532     } else {
8533       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8534         << DclT << Init->getSourceRange();
8535       VDecl->setInvalidDecl();
8536     }
8537   } else if (VDecl->isFileVarDecl()) {
8538     if (VDecl->getStorageClass() == SC_Extern &&
8539         (!getLangOpts().CPlusPlus ||
8540          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8541            VDecl->isExternC())) &&
8542         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
8543       Diag(VDecl->getLocation(), diag::warn_extern_init);
8544 
8545     // C99 6.7.8p4. All file scoped initializers need to be constant.
8546     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8547       CheckForConstantInitializer(Init, DclT);
8548     else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8549              !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8550              !Init->isValueDependent() && !VDecl->isConstexpr() &&
8551              !Init->isConstantInitializer(
8552                  Context, VDecl->getType()->isReferenceType())) {
8553       // GNU C++98 edits for __thread, [basic.start.init]p4:
8554       //   An object of thread storage duration shall not require dynamic
8555       //   initialization.
8556       // FIXME: Need strict checking here.
8557       Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8558       if (getLangOpts().CPlusPlus11)
8559         Diag(VDecl->getLocation(), diag::note_use_thread_local);
8560     }
8561   }
8562 
8563   // We will represent direct-initialization similarly to copy-initialization:
8564   //    int x(1);  -as-> int x = 1;
8565   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8566   //
8567   // Clients that want to distinguish between the two forms, can check for
8568   // direct initializer using VarDecl::getInitStyle().
8569   // A major benefit is that clients that don't particularly care about which
8570   // exactly form was it (like the CodeGen) can handle both cases without
8571   // special case code.
8572 
8573   // C++ 8.5p11:
8574   // The form of initialization (using parentheses or '=') is generally
8575   // insignificant, but does matter when the entity being initialized has a
8576   // class type.
8577   if (CXXDirectInit) {
8578     assert(DirectInit && "Call-style initializer must be direct init.");
8579     VDecl->setInitStyle(VarDecl::CallInit);
8580   } else if (DirectInit) {
8581     // This must be list-initialization. No other way is direct-initialization.
8582     VDecl->setInitStyle(VarDecl::ListInit);
8583   }
8584 
8585   CheckCompleteVariableDeclaration(VDecl);
8586 }
8587 
8588 /// ActOnInitializerError - Given that there was an error parsing an
8589 /// initializer for the given declaration, try to return to some form
8590 /// of sanity.
8591 void Sema::ActOnInitializerError(Decl *D) {
8592   // Our main concern here is re-establishing invariants like "a
8593   // variable's type is either dependent or complete".
8594   if (!D || D->isInvalidDecl()) return;
8595 
8596   VarDecl *VD = dyn_cast<VarDecl>(D);
8597   if (!VD) return;
8598 
8599   // Auto types are meaningless if we can't make sense of the initializer.
8600   if (ParsingInitForAutoVars.count(D)) {
8601     D->setInvalidDecl();
8602     return;
8603   }
8604 
8605   QualType Ty = VD->getType();
8606   if (Ty->isDependentType()) return;
8607 
8608   // Require a complete type.
8609   if (RequireCompleteType(VD->getLocation(),
8610                           Context.getBaseElementType(Ty),
8611                           diag::err_typecheck_decl_incomplete_type)) {
8612     VD->setInvalidDecl();
8613     return;
8614   }
8615 
8616   // Require an abstract type.
8617   if (RequireNonAbstractType(VD->getLocation(), Ty,
8618                              diag::err_abstract_type_in_decl,
8619                              AbstractVariableType)) {
8620     VD->setInvalidDecl();
8621     return;
8622   }
8623 
8624   // Don't bother complaining about constructors or destructors,
8625   // though.
8626 }
8627 
8628 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
8629                                   bool TypeMayContainAuto) {
8630   // If there is no declaration, there was an error parsing it. Just ignore it.
8631   if (RealDecl == 0)
8632     return;
8633 
8634   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8635     QualType Type = Var->getType();
8636 
8637     // C++11 [dcl.spec.auto]p3
8638     if (TypeMayContainAuto && Type->getContainedAutoType()) {
8639       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8640         << Var->getDeclName() << Type;
8641       Var->setInvalidDecl();
8642       return;
8643     }
8644 
8645     // C++11 [class.static.data]p3: A static data member can be declared with
8646     // the constexpr specifier; if so, its declaration shall specify
8647     // a brace-or-equal-initializer.
8648     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8649     // the definition of a variable [...] or the declaration of a static data
8650     // member.
8651     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8652       if (Var->isStaticDataMember())
8653         Diag(Var->getLocation(),
8654              diag::err_constexpr_static_mem_var_requires_init)
8655           << Var->getDeclName();
8656       else
8657         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8658       Var->setInvalidDecl();
8659       return;
8660     }
8661 
8662     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8663     // be initialized.
8664     if (!Var->isInvalidDecl() &&
8665         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
8666         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
8667       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8668       Var->setInvalidDecl();
8669       return;
8670     }
8671 
8672     switch (Var->isThisDeclarationADefinition()) {
8673     case VarDecl::Definition:
8674       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8675         break;
8676 
8677       // We have an out-of-line definition of a static data member
8678       // that has an in-class initializer, so we type-check this like
8679       // a declaration.
8680       //
8681       // Fall through
8682 
8683     case VarDecl::DeclarationOnly:
8684       // It's only a declaration.
8685 
8686       // Block scope. C99 6.7p7: If an identifier for an object is
8687       // declared with no linkage (C99 6.2.2p6), the type for the
8688       // object shall be complete.
8689       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
8690           !Var->hasLinkage() && !Var->isInvalidDecl() &&
8691           RequireCompleteType(Var->getLocation(), Type,
8692                               diag::err_typecheck_decl_incomplete_type))
8693         Var->setInvalidDecl();
8694 
8695       // Make sure that the type is not abstract.
8696       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8697           RequireNonAbstractType(Var->getLocation(), Type,
8698                                  diag::err_abstract_type_in_decl,
8699                                  AbstractVariableType))
8700         Var->setInvalidDecl();
8701       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8702           Var->getStorageClass() == SC_PrivateExtern) {
8703         Diag(Var->getLocation(), diag::warn_private_extern);
8704         Diag(Var->getLocation(), diag::note_private_extern);
8705       }
8706 
8707       return;
8708 
8709     case VarDecl::TentativeDefinition:
8710       // File scope. C99 6.9.2p2: A declaration of an identifier for an
8711       // object that has file scope without an initializer, and without a
8712       // storage-class specifier or with the storage-class specifier "static",
8713       // constitutes a tentative definition. Note: A tentative definition with
8714       // external linkage is valid (C99 6.2.2p5).
8715       if (!Var->isInvalidDecl()) {
8716         if (const IncompleteArrayType *ArrayT
8717                                     = Context.getAsIncompleteArrayType(Type)) {
8718           if (RequireCompleteType(Var->getLocation(),
8719                                   ArrayT->getElementType(),
8720                                   diag::err_illegal_decl_array_incomplete_type))
8721             Var->setInvalidDecl();
8722         } else if (Var->getStorageClass() == SC_Static) {
8723           // C99 6.9.2p3: If the declaration of an identifier for an object is
8724           // a tentative definition and has internal linkage (C99 6.2.2p3), the
8725           // declared type shall not be an incomplete type.
8726           // NOTE: code such as the following
8727           //     static struct s;
8728           //     struct s { int a; };
8729           // is accepted by gcc. Hence here we issue a warning instead of
8730           // an error and we do not invalidate the static declaration.
8731           // NOTE: to avoid multiple warnings, only check the first declaration.
8732           if (Var->isFirstDecl())
8733             RequireCompleteType(Var->getLocation(), Type,
8734                                 diag::ext_typecheck_decl_incomplete_type);
8735         }
8736       }
8737 
8738       // Record the tentative definition; we're done.
8739       if (!Var->isInvalidDecl())
8740         TentativeDefinitions.push_back(Var);
8741       return;
8742     }
8743 
8744     // Provide a specific diagnostic for uninitialized variable
8745     // definitions with incomplete array type.
8746     if (Type->isIncompleteArrayType()) {
8747       Diag(Var->getLocation(),
8748            diag::err_typecheck_incomplete_array_needs_initializer);
8749       Var->setInvalidDecl();
8750       return;
8751     }
8752 
8753     // Provide a specific diagnostic for uninitialized variable
8754     // definitions with reference type.
8755     if (Type->isReferenceType()) {
8756       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8757         << Var->getDeclName()
8758         << SourceRange(Var->getLocation(), Var->getLocation());
8759       Var->setInvalidDecl();
8760       return;
8761     }
8762 
8763     // Do not attempt to type-check the default initializer for a
8764     // variable with dependent type.
8765     if (Type->isDependentType())
8766       return;
8767 
8768     if (Var->isInvalidDecl())
8769       return;
8770 
8771     if (RequireCompleteType(Var->getLocation(),
8772                             Context.getBaseElementType(Type),
8773                             diag::err_typecheck_decl_incomplete_type)) {
8774       Var->setInvalidDecl();
8775       return;
8776     }
8777 
8778     // The variable can not have an abstract class type.
8779     if (RequireNonAbstractType(Var->getLocation(), Type,
8780                                diag::err_abstract_type_in_decl,
8781                                AbstractVariableType)) {
8782       Var->setInvalidDecl();
8783       return;
8784     }
8785 
8786     // Check for jumps past the implicit initializer.  C++0x
8787     // clarifies that this applies to a "variable with automatic
8788     // storage duration", not a "local variable".
8789     // C++11 [stmt.dcl]p3
8790     //   A program that jumps from a point where a variable with automatic
8791     //   storage duration is not in scope to a point where it is in scope is
8792     //   ill-formed unless the variable has scalar type, class type with a
8793     //   trivial default constructor and a trivial destructor, a cv-qualified
8794     //   version of one of these types, or an array of one of the preceding
8795     //   types and is declared without an initializer.
8796     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
8797       if (const RecordType *Record
8798             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
8799         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
8800         // Mark the function for further checking even if the looser rules of
8801         // C++11 do not require such checks, so that we can diagnose
8802         // incompatibilities with C++98.
8803         if (!CXXRecord->isPOD())
8804           getCurFunction()->setHasBranchProtectedScope();
8805       }
8806     }
8807 
8808     // C++03 [dcl.init]p9:
8809     //   If no initializer is specified for an object, and the
8810     //   object is of (possibly cv-qualified) non-POD class type (or
8811     //   array thereof), the object shall be default-initialized; if
8812     //   the object is of const-qualified type, the underlying class
8813     //   type shall have a user-declared default
8814     //   constructor. Otherwise, if no initializer is specified for
8815     //   a non- static object, the object and its subobjects, if
8816     //   any, have an indeterminate initial value); if the object
8817     //   or any of its subobjects are of const-qualified type, the
8818     //   program is ill-formed.
8819     // C++0x [dcl.init]p11:
8820     //   If no initializer is specified for an object, the object is
8821     //   default-initialized; [...].
8822     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8823     InitializationKind Kind
8824       = InitializationKind::CreateDefault(Var->getLocation());
8825 
8826     InitializationSequence InitSeq(*this, Entity, Kind, None);
8827     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
8828     if (Init.isInvalid())
8829       Var->setInvalidDecl();
8830     else if (Init.get()) {
8831       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
8832       // This is important for template substitution.
8833       Var->setInitStyle(VarDecl::CallInit);
8834     }
8835 
8836     CheckCompleteVariableDeclaration(Var);
8837   }
8838 }
8839 
8840 void Sema::ActOnCXXForRangeDecl(Decl *D) {
8841   VarDecl *VD = dyn_cast<VarDecl>(D);
8842   if (!VD) {
8843     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8844     D->setInvalidDecl();
8845     return;
8846   }
8847 
8848   VD->setCXXForRangeDecl(true);
8849 
8850   // for-range-declaration cannot be given a storage class specifier.
8851   int Error = -1;
8852   switch (VD->getStorageClass()) {
8853   case SC_None:
8854     break;
8855   case SC_Extern:
8856     Error = 0;
8857     break;
8858   case SC_Static:
8859     Error = 1;
8860     break;
8861   case SC_PrivateExtern:
8862     Error = 2;
8863     break;
8864   case SC_Auto:
8865     Error = 3;
8866     break;
8867   case SC_Register:
8868     Error = 4;
8869     break;
8870   case SC_OpenCLWorkGroupLocal:
8871     llvm_unreachable("Unexpected storage class");
8872   }
8873   if (VD->isConstexpr())
8874     Error = 5;
8875   if (Error != -1) {
8876     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8877       << VD->getDeclName() << Error;
8878     D->setInvalidDecl();
8879   }
8880 }
8881 
8882 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8883   if (var->isInvalidDecl()) return;
8884 
8885   // In ARC, don't allow jumps past the implicit initialization of a
8886   // local retaining variable.
8887   if (getLangOpts().ObjCAutoRefCount &&
8888       var->hasLocalStorage()) {
8889     switch (var->getType().getObjCLifetime()) {
8890     case Qualifiers::OCL_None:
8891     case Qualifiers::OCL_ExplicitNone:
8892     case Qualifiers::OCL_Autoreleasing:
8893       break;
8894 
8895     case Qualifiers::OCL_Weak:
8896     case Qualifiers::OCL_Strong:
8897       getCurFunction()->setHasBranchProtectedScope();
8898       break;
8899     }
8900   }
8901 
8902   // Warn about externally-visible variables being defined without a
8903   // prior declaration.  We only want to do this for global
8904   // declarations, but we also specifically need to avoid doing it for
8905   // class members because the linkage of an anonymous class can
8906   // change if it's later given a typedef name.
8907   if (var->isThisDeclarationADefinition() &&
8908       var->getDeclContext()->getRedeclContext()->isFileContext() &&
8909       var->isExternallyVisible() && var->hasLinkage() &&
8910       getDiagnostics().getDiagnosticLevel(
8911                        diag::warn_missing_variable_declarations,
8912                        var->getLocation())) {
8913     // Find a previous declaration that's not a definition.
8914     VarDecl *prev = var->getPreviousDecl();
8915     while (prev && prev->isThisDeclarationADefinition())
8916       prev = prev->getPreviousDecl();
8917 
8918     if (!prev)
8919       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8920   }
8921 
8922   if (var->getTLSKind() == VarDecl::TLS_Static &&
8923       var->getType().isDestructedType()) {
8924     // GNU C++98 edits for __thread, [basic.start.term]p3:
8925     //   The type of an object with thread storage duration shall not
8926     //   have a non-trivial destructor.
8927     Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8928     if (getLangOpts().CPlusPlus11)
8929       Diag(var->getLocation(), diag::note_use_thread_local);
8930   }
8931 
8932   // All the following checks are C++ only.
8933   if (!getLangOpts().CPlusPlus) return;
8934 
8935   QualType type = var->getType();
8936   if (type->isDependentType()) return;
8937 
8938   // __block variables might require us to capture a copy-initializer.
8939   if (var->hasAttr<BlocksAttr>()) {
8940     // It's currently invalid to ever have a __block variable with an
8941     // array type; should we diagnose that here?
8942 
8943     // Regardless, we don't want to ignore array nesting when
8944     // constructing this copy.
8945     if (type->isStructureOrClassType()) {
8946       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
8947       SourceLocation poi = var->getLocation();
8948       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
8949       ExprResult result
8950         = PerformMoveOrCopyInitialization(
8951             InitializedEntity::InitializeBlock(poi, type, false),
8952             var, var->getType(), varRef, /*AllowNRVO=*/true);
8953       if (!result.isInvalid()) {
8954         result = MaybeCreateExprWithCleanups(result);
8955         Expr *init = result.takeAs<Expr>();
8956         Context.setBlockVarCopyInits(var, init);
8957       }
8958     }
8959   }
8960 
8961   Expr *Init = var->getInit();
8962   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
8963   QualType baseType = Context.getBaseElementType(type);
8964 
8965   if (!var->getDeclContext()->isDependentContext() &&
8966       Init && !Init->isValueDependent()) {
8967     if (IsGlobal && !var->isConstexpr() &&
8968         getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8969                                             var->getLocation())
8970           != DiagnosticsEngine::Ignored) {
8971       // Warn about globals which don't have a constant initializer.  Don't
8972       // warn about globals with a non-trivial destructor because we already
8973       // warned about them.
8974       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8975       if (!(RD && !RD->hasTrivialDestructor()) &&
8976           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8977         Diag(var->getLocation(), diag::warn_global_constructor)
8978           << Init->getSourceRange();
8979     }
8980 
8981     if (var->isConstexpr()) {
8982       SmallVector<PartialDiagnosticAt, 8> Notes;
8983       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8984         SourceLocation DiagLoc = var->getLocation();
8985         // If the note doesn't add any useful information other than a source
8986         // location, fold it into the primary diagnostic.
8987         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8988               diag::note_invalid_subexpr_in_const_expr) {
8989           DiagLoc = Notes[0].first;
8990           Notes.clear();
8991         }
8992         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8993           << var << Init->getSourceRange();
8994         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8995           Diag(Notes[I].first, Notes[I].second);
8996       }
8997     } else if (var->isUsableInConstantExpressions(Context)) {
8998       // Check whether the initializer of a const variable of integral or
8999       // enumeration type is an ICE now, since we can't tell whether it was
9000       // initialized by a constant expression if we check later.
9001       var->checkInitIsICE();
9002     }
9003   }
9004 
9005   // Require the destructor.
9006   if (const RecordType *recordType = baseType->getAs<RecordType>())
9007     FinalizeVarWithDestructor(var, recordType);
9008 }
9009 
9010 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
9011 /// any semantic actions necessary after any initializer has been attached.
9012 void
9013 Sema::FinalizeDeclaration(Decl *ThisDecl) {
9014   // Note that we are no longer parsing the initializer for this declaration.
9015   ParsingInitForAutoVars.erase(ThisDecl);
9016 
9017   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
9018   if (!VD)
9019     return;
9020 
9021   checkAttributesAfterMerging(*this, *VD);
9022 
9023   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
9024     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
9025       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
9026       VD->dropAttr<UsedAttr>();
9027     }
9028   }
9029 
9030   if (!VD->isInvalidDecl() &&
9031       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
9032     if (const VarDecl *Def = VD->getDefinition()) {
9033       if (Def->hasAttr<AliasAttr>()) {
9034         Diag(VD->getLocation(), diag::err_tentative_after_alias)
9035             << VD->getDeclName();
9036         Diag(Def->getLocation(), diag::note_previous_definition);
9037         VD->setInvalidDecl();
9038       }
9039     }
9040   }
9041 
9042   const DeclContext *DC = VD->getDeclContext();
9043   // If there's a #pragma GCC visibility in scope, and this isn't a class
9044   // member, set the visibility of this variable.
9045   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
9046     AddPushedVisibilityAttribute(VD);
9047 
9048   // FIXME: Warn on unused templates.
9049   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate())
9050     MarkUnusedFileScopedDecl(VD);
9051 
9052   // Now we have parsed the initializer and can update the table of magic
9053   // tag values.
9054   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
9055       !VD->getType()->isIntegralOrEnumerationType())
9056     return;
9057 
9058   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
9059     const Expr *MagicValueExpr = VD->getInit();
9060     if (!MagicValueExpr) {
9061       continue;
9062     }
9063     llvm::APSInt MagicValueInt;
9064     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
9065       Diag(I->getRange().getBegin(),
9066            diag::err_type_tag_for_datatype_not_ice)
9067         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9068       continue;
9069     }
9070     if (MagicValueInt.getActiveBits() > 64) {
9071       Diag(I->getRange().getBegin(),
9072            diag::err_type_tag_for_datatype_too_large)
9073         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
9074       continue;
9075     }
9076     uint64_t MagicValue = MagicValueInt.getZExtValue();
9077     RegisterTypeTagForDatatype(I->getArgumentKind(),
9078                                MagicValue,
9079                                I->getMatchingCType(),
9080                                I->getLayoutCompatible(),
9081                                I->getMustBeNull());
9082   }
9083 }
9084 
9085 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
9086                                                    ArrayRef<Decl *> Group) {
9087   SmallVector<Decl*, 8> Decls;
9088 
9089   if (DS.isTypeSpecOwned())
9090     Decls.push_back(DS.getRepAsDecl());
9091 
9092   DeclaratorDecl *FirstDeclaratorInGroup = 0;
9093   for (unsigned i = 0, e = Group.size(); i != e; ++i)
9094     if (Decl *D = Group[i]) {
9095       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
9096         if (!FirstDeclaratorInGroup)
9097           FirstDeclaratorInGroup = DD;
9098       Decls.push_back(D);
9099     }
9100 
9101   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9102     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9103       HandleTagNumbering(*this, Tag, S);
9104       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9105         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9106     }
9107   }
9108 
9109   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9110 }
9111 
9112 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9113 /// group, performing any necessary semantic checking.
9114 Sema::DeclGroupPtrTy
9115 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
9116                            bool TypeMayContainAuto) {
9117   // C++0x [dcl.spec.auto]p7:
9118   //   If the type deduced for the template parameter U is not the same in each
9119   //   deduction, the program is ill-formed.
9120   // FIXME: When initializer-list support is added, a distinction is needed
9121   // between the deduced type U and the deduced type which 'auto' stands for.
9122   //   auto a = 0, b = { 1, 2, 3 };
9123   // is legal because the deduced type U is 'int' in both cases.
9124   if (TypeMayContainAuto && Group.size() > 1) {
9125     QualType Deduced;
9126     CanQualType DeducedCanon;
9127     VarDecl *DeducedDecl = 0;
9128     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9129       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9130         AutoType *AT = D->getType()->getContainedAutoType();
9131         // Don't reissue diagnostics when instantiating a template.
9132         if (AT && D->isInvalidDecl())
9133           break;
9134         QualType U = AT ? AT->getDeducedType() : QualType();
9135         if (!U.isNull()) {
9136           CanQualType UCanon = Context.getCanonicalType(U);
9137           if (Deduced.isNull()) {
9138             Deduced = U;
9139             DeducedCanon = UCanon;
9140             DeducedDecl = D;
9141           } else if (DeducedCanon != UCanon) {
9142             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9143                  diag::err_auto_different_deductions)
9144               << (AT->isDecltypeAuto() ? 1 : 0)
9145               << Deduced << DeducedDecl->getDeclName()
9146               << U << D->getDeclName()
9147               << DeducedDecl->getInit()->getSourceRange()
9148               << D->getInit()->getSourceRange();
9149             D->setInvalidDecl();
9150             break;
9151           }
9152         }
9153       }
9154     }
9155   }
9156 
9157   ActOnDocumentableDecls(Group);
9158 
9159   return DeclGroupPtrTy::make(
9160       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9161 }
9162 
9163 void Sema::ActOnDocumentableDecl(Decl *D) {
9164   ActOnDocumentableDecls(D);
9165 }
9166 
9167 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9168   // Don't parse the comment if Doxygen diagnostics are ignored.
9169   if (Group.empty() || !Group[0])
9170    return;
9171 
9172   if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9173                                Group[0]->getLocation())
9174         == DiagnosticsEngine::Ignored)
9175     return;
9176 
9177   if (Group.size() >= 2) {
9178     // This is a decl group.  Normally it will contain only declarations
9179     // produced from declarator list.  But in case we have any definitions or
9180     // additional declaration references:
9181     //   'typedef struct S {} S;'
9182     //   'typedef struct S *S;'
9183     //   'struct S *pS;'
9184     // FinalizeDeclaratorGroup adds these as separate declarations.
9185     Decl *MaybeTagDecl = Group[0];
9186     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9187       Group = Group.slice(1);
9188     }
9189   }
9190 
9191   // See if there are any new comments that are not attached to a decl.
9192   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9193   if (!Comments.empty() &&
9194       !Comments.back()->isAttached()) {
9195     // There is at least one comment that not attached to a decl.
9196     // Maybe it should be attached to one of these decls?
9197     //
9198     // Note that this way we pick up not only comments that precede the
9199     // declaration, but also comments that *follow* the declaration -- thanks to
9200     // the lookahead in the lexer: we've consumed the semicolon and looked
9201     // ahead through comments.
9202     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9203       Context.getCommentForDecl(Group[i], &PP);
9204   }
9205 }
9206 
9207 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9208 /// to introduce parameters into function prototype scope.
9209 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9210   const DeclSpec &DS = D.getDeclSpec();
9211 
9212   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9213 
9214   // C++03 [dcl.stc]p2 also permits 'auto'.
9215   VarDecl::StorageClass StorageClass = SC_None;
9216   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9217     StorageClass = SC_Register;
9218   } else if (getLangOpts().CPlusPlus &&
9219              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9220     StorageClass = SC_Auto;
9221   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9222     Diag(DS.getStorageClassSpecLoc(),
9223          diag::err_invalid_storage_class_in_func_decl);
9224     D.getMutableDeclSpec().ClearStorageClassSpecs();
9225   }
9226 
9227   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9228     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9229       << DeclSpec::getSpecifierName(TSCS);
9230   if (DS.isConstexprSpecified())
9231     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9232       << 0;
9233 
9234   DiagnoseFunctionSpecifiers(DS);
9235 
9236   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9237   QualType parmDeclType = TInfo->getType();
9238 
9239   if (getLangOpts().CPlusPlus) {
9240     // Check that there are no default arguments inside the type of this
9241     // parameter.
9242     CheckExtraCXXDefaultArguments(D);
9243 
9244     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9245     if (D.getCXXScopeSpec().isSet()) {
9246       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9247         << D.getCXXScopeSpec().getRange();
9248       D.getCXXScopeSpec().clear();
9249     }
9250   }
9251 
9252   // Ensure we have a valid name
9253   IdentifierInfo *II = 0;
9254   if (D.hasName()) {
9255     II = D.getIdentifier();
9256     if (!II) {
9257       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9258         << GetNameForDeclarator(D).getName();
9259       D.setInvalidType(true);
9260     }
9261   }
9262 
9263   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9264   if (II) {
9265     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9266                    ForRedeclaration);
9267     LookupName(R, S);
9268     if (R.isSingleResult()) {
9269       NamedDecl *PrevDecl = R.getFoundDecl();
9270       if (PrevDecl->isTemplateParameter()) {
9271         // Maybe we will complain about the shadowed template parameter.
9272         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9273         // Just pretend that we didn't see the previous declaration.
9274         PrevDecl = 0;
9275       } else if (S->isDeclScope(PrevDecl)) {
9276         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9277         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9278 
9279         // Recover by removing the name
9280         II = 0;
9281         D.SetIdentifier(0, D.getIdentifierLoc());
9282         D.setInvalidType(true);
9283       }
9284     }
9285   }
9286 
9287   // Temporarily put parameter variables in the translation unit, not
9288   // the enclosing context.  This prevents them from accidentally
9289   // looking like class members in C++.
9290   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9291                                     D.getLocStart(),
9292                                     D.getIdentifierLoc(), II,
9293                                     parmDeclType, TInfo,
9294                                     StorageClass);
9295 
9296   if (D.isInvalidType())
9297     New->setInvalidDecl();
9298 
9299   assert(S->isFunctionPrototypeScope());
9300   assert(S->getFunctionPrototypeDepth() >= 1);
9301   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9302                     S->getNextFunctionPrototypeIndex());
9303 
9304   // Add the parameter declaration into this scope.
9305   S->AddDecl(New);
9306   if (II)
9307     IdResolver.AddDecl(New);
9308 
9309   ProcessDeclAttributes(S, New, D);
9310 
9311   if (D.getDeclSpec().isModulePrivateSpecified())
9312     Diag(New->getLocation(), diag::err_module_private_local)
9313       << 1 << New->getDeclName()
9314       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9315       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9316 
9317   if (New->hasAttr<BlocksAttr>()) {
9318     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9319   }
9320   return New;
9321 }
9322 
9323 /// \brief Synthesizes a variable for a parameter arising from a
9324 /// typedef.
9325 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9326                                               SourceLocation Loc,
9327                                               QualType T) {
9328   /* FIXME: setting StartLoc == Loc.
9329      Would it be worth to modify callers so as to provide proper source
9330      location for the unnamed parameters, embedding the parameter's type? */
9331   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
9332                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9333                                            SC_None, 0);
9334   Param->setImplicit();
9335   return Param;
9336 }
9337 
9338 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9339                                     ParmVarDecl * const *ParamEnd) {
9340   // Don't diagnose unused-parameter errors in template instantiations; we
9341   // will already have done so in the template itself.
9342   if (!ActiveTemplateInstantiations.empty())
9343     return;
9344 
9345   for (; Param != ParamEnd; ++Param) {
9346     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9347         !(*Param)->hasAttr<UnusedAttr>()) {
9348       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9349         << (*Param)->getDeclName();
9350     }
9351   }
9352 }
9353 
9354 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9355                                                   ParmVarDecl * const *ParamEnd,
9356                                                   QualType ReturnTy,
9357                                                   NamedDecl *D) {
9358   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9359     return;
9360 
9361   // Warn if the return value is pass-by-value and larger than the specified
9362   // threshold.
9363   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9364     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9365     if (Size > LangOpts.NumLargeByValueCopy)
9366       Diag(D->getLocation(), diag::warn_return_value_size)
9367           << D->getDeclName() << Size;
9368   }
9369 
9370   // Warn if any parameter is pass-by-value and larger than the specified
9371   // threshold.
9372   for (; Param != ParamEnd; ++Param) {
9373     QualType T = (*Param)->getType();
9374     if (T->isDependentType() || !T.isPODType(Context))
9375       continue;
9376     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9377     if (Size > LangOpts.NumLargeByValueCopy)
9378       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9379           << (*Param)->getDeclName() << Size;
9380   }
9381 }
9382 
9383 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9384                                   SourceLocation NameLoc, IdentifierInfo *Name,
9385                                   QualType T, TypeSourceInfo *TSInfo,
9386                                   VarDecl::StorageClass StorageClass) {
9387   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9388   if (getLangOpts().ObjCAutoRefCount &&
9389       T.getObjCLifetime() == Qualifiers::OCL_None &&
9390       T->isObjCLifetimeType()) {
9391 
9392     Qualifiers::ObjCLifetime lifetime;
9393 
9394     // Special cases for arrays:
9395     //   - if it's const, use __unsafe_unretained
9396     //   - otherwise, it's an error
9397     if (T->isArrayType()) {
9398       if (!T.isConstQualified()) {
9399         DelayedDiagnostics.add(
9400             sema::DelayedDiagnostic::makeForbiddenType(
9401             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9402       }
9403       lifetime = Qualifiers::OCL_ExplicitNone;
9404     } else {
9405       lifetime = T->getObjCARCImplicitLifetime();
9406     }
9407     T = Context.getLifetimeQualifiedType(T, lifetime);
9408   }
9409 
9410   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9411                                          Context.getAdjustedParameterType(T),
9412                                          TSInfo,
9413                                          StorageClass, 0);
9414 
9415   // Parameters can not be abstract class types.
9416   // For record types, this is done by the AbstractClassUsageDiagnoser once
9417   // the class has been completely parsed.
9418   if (!CurContext->isRecord() &&
9419       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9420                              AbstractParamType))
9421     New->setInvalidDecl();
9422 
9423   // Parameter declarators cannot be interface types. All ObjC objects are
9424   // passed by reference.
9425   if (T->isObjCObjectType()) {
9426     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9427     Diag(NameLoc,
9428          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9429       << FixItHint::CreateInsertion(TypeEndLoc, "*");
9430     T = Context.getObjCObjectPointerType(T);
9431     New->setType(T);
9432   }
9433 
9434   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9435   // duration shall not be qualified by an address-space qualifier."
9436   // Since all parameters have automatic store duration, they can not have
9437   // an address space.
9438   if (T.getAddressSpace() != 0) {
9439     Diag(NameLoc, diag::err_arg_with_address_space);
9440     New->setInvalidDecl();
9441   }
9442 
9443   return New;
9444 }
9445 
9446 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9447                                            SourceLocation LocAfterDecls) {
9448   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9449 
9450   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9451   // for a K&R function.
9452   if (!FTI.hasPrototype) {
9453     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
9454       --i;
9455       if (FTI.Params[i].Param == 0) {
9456         SmallString<256> Code;
9457         llvm::raw_svector_ostream(Code)
9458             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
9459         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9460             << FTI.Params[i].Ident
9461             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9462 
9463         // Implicitly declare the argument as type 'int' for lack of a better
9464         // type.
9465         AttributeFactory attrs;
9466         DeclSpec DS(attrs);
9467         const char* PrevSpec; // unused
9468         unsigned DiagID; // unused
9469         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9470                            DiagID, Context.getPrintingPolicy());
9471         // Use the identifier location for the type source range.
9472         DS.SetRangeStart(FTI.Params[i].IdentLoc);
9473         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
9474         Declarator ParamD(DS, Declarator::KNRTypeListContext);
9475         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9476         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
9477       }
9478     }
9479   }
9480 }
9481 
9482 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9483   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
9484   assert(D.isFunctionDeclarator() && "Not a function declarator!");
9485   Scope *ParentScope = FnBodyScope->getParent();
9486 
9487   D.setFunctionDefinitionKind(FDK_Definition);
9488   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9489   return ActOnStartOfFunctionDef(FnBodyScope, DP);
9490 }
9491 
9492 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9493                              const FunctionDecl*& PossibleZeroParamPrototype) {
9494   // Don't warn about invalid declarations.
9495   if (FD->isInvalidDecl())
9496     return false;
9497 
9498   // Or declarations that aren't global.
9499   if (!FD->isGlobal())
9500     return false;
9501 
9502   // Don't warn about C++ member functions.
9503   if (isa<CXXMethodDecl>(FD))
9504     return false;
9505 
9506   // Don't warn about 'main'.
9507   if (FD->isMain())
9508     return false;
9509 
9510   // Don't warn about inline functions.
9511   if (FD->isInlined())
9512     return false;
9513 
9514   // Don't warn about function templates.
9515   if (FD->getDescribedFunctionTemplate())
9516     return false;
9517 
9518   // Don't warn about function template specializations.
9519   if (FD->isFunctionTemplateSpecialization())
9520     return false;
9521 
9522   // Don't warn for OpenCL kernels.
9523   if (FD->hasAttr<OpenCLKernelAttr>())
9524     return false;
9525 
9526   bool MissingPrototype = true;
9527   for (const FunctionDecl *Prev = FD->getPreviousDecl();
9528        Prev; Prev = Prev->getPreviousDecl()) {
9529     // Ignore any declarations that occur in function or method
9530     // scope, because they aren't visible from the header.
9531     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9532       continue;
9533 
9534     MissingPrototype = !Prev->getType()->isFunctionProtoType();
9535     if (FD->getNumParams() == 0)
9536       PossibleZeroParamPrototype = Prev;
9537     break;
9538   }
9539 
9540   return MissingPrototype;
9541 }
9542 
9543 void
9544 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9545                                    const FunctionDecl *EffectiveDefinition) {
9546   // Don't complain if we're in GNU89 mode and the previous definition
9547   // was an extern inline function.
9548   const FunctionDecl *Definition = EffectiveDefinition;
9549   if (!Definition)
9550     if (!FD->isDefined(Definition))
9551       return;
9552 
9553   if (canRedefineFunction(Definition, getLangOpts()))
9554     return;
9555 
9556   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9557       Definition->getStorageClass() == SC_Extern)
9558     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9559         << FD->getDeclName() << getLangOpts().CPlusPlus;
9560   else
9561     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9562 
9563   Diag(Definition->getLocation(), diag::note_previous_definition);
9564   FD->setInvalidDecl();
9565 }
9566 
9567 
9568 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9569                                    Sema &S) {
9570   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9571 
9572   LambdaScopeInfo *LSI = S.PushLambdaScope();
9573   LSI->CallOperator = CallOperator;
9574   LSI->Lambda = LambdaClass;
9575   LSI->ReturnType = CallOperator->getReturnType();
9576   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9577 
9578   if (LCD == LCD_None)
9579     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9580   else if (LCD == LCD_ByCopy)
9581     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9582   else if (LCD == LCD_ByRef)
9583     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9584   DeclarationNameInfo DNI = CallOperator->getNameInfo();
9585 
9586   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9587   LSI->Mutable = !CallOperator->isConst();
9588 
9589   // Add the captures to the LSI so they can be noted as already
9590   // captured within tryCaptureVar.
9591   for (const auto &C : LambdaClass->captures()) {
9592     if (C.capturesVariable()) {
9593       VarDecl *VD = C.getCapturedVar();
9594       if (VD->isInitCapture())
9595         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9596       QualType CaptureType = VD->getType();
9597       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
9598       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9599           /*RefersToEnclosingLocal*/true, C.getLocation(),
9600           /*EllipsisLoc*/C.isPackExpansion()
9601                          ? C.getEllipsisLoc() : SourceLocation(),
9602           CaptureType, /*Expr*/ 0);
9603 
9604     } else if (C.capturesThis()) {
9605       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
9606                               S.getCurrentThisType(), /*Expr*/ 0);
9607     }
9608   }
9609 }
9610 
9611 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
9612   // Clear the last template instantiation error context.
9613   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9614 
9615   if (!D)
9616     return D;
9617   FunctionDecl *FD = 0;
9618 
9619   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
9620     FD = FunTmpl->getTemplatedDecl();
9621   else
9622     FD = cast<FunctionDecl>(D);
9623   // If we are instantiating a generic lambda call operator, push
9624   // a LambdaScopeInfo onto the function stack.  But use the information
9625   // that's already been calculated (ActOnLambdaExpr) to prime the current
9626   // LambdaScopeInfo.
9627   // When the template operator is being specialized, the LambdaScopeInfo,
9628   // has to be properly restored so that tryCaptureVariable doesn't try
9629   // and capture any new variables. In addition when calculating potential
9630   // captures during transformation of nested lambdas, it is necessary to
9631   // have the LSI properly restored.
9632   if (isGenericLambdaCallOperatorSpecialization(FD)) {
9633     assert(ActiveTemplateInstantiations.size() &&
9634       "There should be an active template instantiation on the stack "
9635       "when instantiating a generic lambda!");
9636     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
9637   }
9638   else
9639     // Enter a new function scope
9640     PushFunctionScope();
9641 
9642   // See if this is a redefinition.
9643   if (!FD->isLateTemplateParsed())
9644     CheckForFunctionRedefinition(FD);
9645 
9646   // Builtin functions cannot be defined.
9647   if (unsigned BuiltinID = FD->getBuiltinID()) {
9648     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9649         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
9650       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
9651       FD->setInvalidDecl();
9652     }
9653   }
9654 
9655   // The return type of a function definition must be complete
9656   // (C99 6.9.1p3, C++ [dcl.fct]p6).
9657   QualType ResultType = FD->getReturnType();
9658   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
9659       !FD->isInvalidDecl() &&
9660       RequireCompleteType(FD->getLocation(), ResultType,
9661                           diag::err_func_def_incomplete_result))
9662     FD->setInvalidDecl();
9663 
9664   // GNU warning -Wmissing-prototypes:
9665   //   Warn if a global function is defined without a previous
9666   //   prototype declaration. This warning is issued even if the
9667   //   definition itself provides a prototype. The aim is to detect
9668   //   global functions that fail to be declared in header files.
9669   const FunctionDecl *PossibleZeroParamPrototype = 0;
9670   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
9671     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
9672 
9673     if (PossibleZeroParamPrototype) {
9674       // We found a declaration that is not a prototype,
9675       // but that could be a zero-parameter prototype
9676       if (TypeSourceInfo *TI =
9677               PossibleZeroParamPrototype->getTypeSourceInfo()) {
9678         TypeLoc TL = TI->getTypeLoc();
9679         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9680           Diag(PossibleZeroParamPrototype->getLocation(),
9681                diag::note_declaration_not_a_prototype)
9682             << PossibleZeroParamPrototype
9683             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9684       }
9685     }
9686   }
9687 
9688   if (FnBodyScope)
9689     PushDeclContext(FnBodyScope, FD);
9690 
9691   // Check the validity of our function parameters
9692   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9693                            /*CheckParameterNames=*/true);
9694 
9695   // Introduce our parameters into the function scope
9696   for (auto Param : FD->params()) {
9697     Param->setOwningFunction(FD);
9698 
9699     // If this has an identifier, add it to the scope stack.
9700     if (Param->getIdentifier() && FnBodyScope) {
9701       CheckShadow(FnBodyScope, Param);
9702 
9703       PushOnScopeChains(Param, FnBodyScope);
9704     }
9705   }
9706 
9707   // If we had any tags defined in the function prototype,
9708   // introduce them into the function scope.
9709   if (FnBodyScope) {
9710     for (ArrayRef<NamedDecl *>::iterator
9711              I = FD->getDeclsInPrototypeScope().begin(),
9712              E = FD->getDeclsInPrototypeScope().end();
9713          I != E; ++I) {
9714       NamedDecl *D = *I;
9715 
9716       // Some of these decls (like enums) may have been pinned to the translation unit
9717       // for lack of a real context earlier. If so, remove from the translation unit
9718       // and reattach to the current context.
9719       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9720         // Is the decl actually in the context?
9721         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
9722           if (DI == D) {
9723             Context.getTranslationUnitDecl()->removeDecl(D);
9724             break;
9725           }
9726         }
9727         // Either way, reassign the lexical decl context to our FunctionDecl.
9728         D->setLexicalDeclContext(CurContext);
9729       }
9730 
9731       // If the decl has a non-null name, make accessible in the current scope.
9732       if (!D->getName().empty())
9733         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9734 
9735       // Similarly, dive into enums and fish their constants out, making them
9736       // accessible in this scope.
9737       if (auto *ED = dyn_cast<EnumDecl>(D)) {
9738         for (auto *EI : ED->enumerators())
9739           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
9740       }
9741     }
9742   }
9743 
9744   // Ensure that the function's exception specification is instantiated.
9745   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9746     ResolveExceptionSpec(D->getLocation(), FPT);
9747 
9748   // Checking attributes of current function definition
9749   // dllimport attribute.
9750   DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9751   if (DA && (!FD->hasAttr<DLLExportAttr>())) {
9752     // dllimport attribute cannot be directly applied to definition.
9753     // Microsoft accepts dllimport for functions defined within class scope.
9754     if (!DA->isInherited() &&
9755         !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
9756       Diag(FD->getLocation(),
9757            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9758         << DA;
9759       FD->setInvalidDecl();
9760       return D;
9761     }
9762   }
9763   // We want to attach documentation to original Decl (which might be
9764   // a function template).
9765   ActOnDocumentableDecl(D);
9766   return D;
9767 }
9768 
9769 /// \brief Given the set of return statements within a function body,
9770 /// compute the variables that are subject to the named return value
9771 /// optimization.
9772 ///
9773 /// Each of the variables that is subject to the named return value
9774 /// optimization will be marked as NRVO variables in the AST, and any
9775 /// return statement that has a marked NRVO variable as its NRVO candidate can
9776 /// use the named return value optimization.
9777 ///
9778 /// This function applies a very simplistic algorithm for NRVO: if every return
9779 /// statement in the function has the same NRVO candidate, that candidate is
9780 /// the NRVO variable.
9781 ///
9782 /// FIXME: Employ a smarter algorithm that accounts for multiple return
9783 /// statements and the lifetimes of the NRVO candidates. We should be able to
9784 /// find a maximal set of NRVO variables.
9785 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
9786   ReturnStmt **Returns = Scope->Returns.data();
9787 
9788   const VarDecl *NRVOCandidate = 0;
9789   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
9790     if (!Returns[I]->getNRVOCandidate())
9791       return;
9792 
9793     if (!NRVOCandidate)
9794       NRVOCandidate = Returns[I]->getNRVOCandidate();
9795     else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9796       return;
9797   }
9798 
9799   if (NRVOCandidate)
9800     const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9801 }
9802 
9803 bool Sema::canDelayFunctionBody(const Declarator &D) {
9804   // We can't delay parsing the body of a constexpr function template (yet).
9805   if (D.getDeclSpec().isConstexprSpecified())
9806     return false;
9807 
9808   // We can't delay parsing the body of a function template with a deduced
9809   // return type (yet).
9810   if (D.getDeclSpec().containsPlaceholderType()) {
9811     // If the placeholder introduces a non-deduced trailing return type,
9812     // we can still delay parsing it.
9813     if (D.getNumTypeObjects()) {
9814       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
9815       if (Outer.Kind == DeclaratorChunk::Function &&
9816           Outer.Fun.hasTrailingReturnType()) {
9817         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
9818         return Ty.isNull() || !Ty->isUndeducedType();
9819       }
9820     }
9821     return false;
9822   }
9823 
9824   return true;
9825 }
9826 
9827 bool Sema::canSkipFunctionBody(Decl *D) {
9828   // We cannot skip the body of a function (or function template) which is
9829   // constexpr, since we may need to evaluate its body in order to parse the
9830   // rest of the file.
9831   // We cannot skip the body of a function with an undeduced return type,
9832   // because any callers of that function need to know the type.
9833   if (const FunctionDecl *FD = D->getAsFunction())
9834     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
9835       return false;
9836   return Consumer.shouldSkipFunctionBody(D);
9837 }
9838 
9839 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
9840   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
9841     FD->setHasSkippedBody();
9842   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
9843     MD->setHasSkippedBody();
9844   return ActOnFinishFunctionBody(Decl, 0);
9845 }
9846 
9847 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
9848   return ActOnFinishFunctionBody(D, BodyArg, false);
9849 }
9850 
9851 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9852                                     bool IsInstantiation) {
9853   FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
9854 
9855   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
9856   sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
9857 
9858   if (FD) {
9859     FD->setBody(Body);
9860 
9861     if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9862         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
9863       // If the function has a deduced result type but contains no 'return'
9864       // statements, the result type as written must be exactly 'auto', and
9865       // the deduced result type is 'void'.
9866       if (!FD->getReturnType()->getAs<AutoType>()) {
9867         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9868             << FD->getReturnType();
9869         FD->setInvalidDecl();
9870       } else {
9871         // Substitute 'void' for the 'auto' in the type.
9872         TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9873             IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
9874         Context.adjustDeducedFunctionResultType(
9875             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
9876       }
9877     }
9878 
9879     // The only way to be included in UndefinedButUsed is if there is an
9880     // ODR use before the definition. Avoid the expensive map lookup if this
9881     // is the first declaration.
9882     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
9883       if (!FD->isExternallyVisible())
9884         UndefinedButUsed.erase(FD);
9885       else if (FD->isInlined() &&
9886                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9887                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9888         UndefinedButUsed.erase(FD);
9889     }
9890 
9891     // If the function implicitly returns zero (like 'main') or is naked,
9892     // don't complain about missing return statements.
9893     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
9894       WP.disableCheckFallThrough();
9895 
9896     // MSVC permits the use of pure specifier (=0) on function definition,
9897     // defined at class scope, warn about this non-standard construct.
9898     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
9899       Diag(FD->getLocation(), diag::warn_pure_function_definition);
9900 
9901     if (!FD->isInvalidDecl()) {
9902       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
9903       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9904                                              FD->getReturnType(), FD);
9905 
9906       // If this is a constructor, we need a vtable.
9907       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9908         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
9909 
9910       // Try to apply the named return value optimization. We have to check
9911       // if we can do this here because lambdas keep return statements around
9912       // to deduce an implicit return type.
9913       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
9914           !FD->isDependentContext())
9915         computeNRVO(Body, getCurFunction());
9916     }
9917 
9918     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9919            "Function parsing confused");
9920   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
9921     assert(MD == getCurMethodDecl() && "Method parsing confused");
9922     MD->setBody(Body);
9923     if (!MD->isInvalidDecl()) {
9924       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
9925       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9926                                              MD->getReturnType(), MD);
9927 
9928       if (Body)
9929         computeNRVO(Body, getCurFunction());
9930     }
9931     if (getCurFunction()->ObjCShouldCallSuper) {
9932       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9933         << MD->getSelector().getAsString();
9934       getCurFunction()->ObjCShouldCallSuper = false;
9935     }
9936     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9937       const ObjCMethodDecl *InitMethod = 0;
9938       bool isDesignated =
9939           MD->isDesignatedInitializerForTheInterface(&InitMethod);
9940       assert(isDesignated && InitMethod);
9941       (void)isDesignated;
9942       // Don't issue this warning for unavaialable inits.
9943       if (!MD->isUnavailable()) {
9944         Diag(MD->getLocation(),
9945              diag::warn_objc_designated_init_missing_super_call);
9946         Diag(InitMethod->getLocation(),
9947              diag::note_objc_designated_init_marked_here);
9948       }
9949       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9950     }
9951     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9952       // Don't issue this warning for unavaialable inits.
9953       if (!MD->isUnavailable())
9954         Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9955       getCurFunction()->ObjCWarnForNoInitDelegation = false;
9956     }
9957   } else {
9958     return 0;
9959   }
9960 
9961   assert(!getCurFunction()->ObjCShouldCallSuper &&
9962          "This should only be set for ObjC methods, which should have been "
9963          "handled in the block above.");
9964 
9965   // Verify and clean out per-function state.
9966   if (Body) {
9967     // C++ constructors that have function-try-blocks can't have return
9968     // statements in the handlers of that block. (C++ [except.handle]p14)
9969     // Verify this.
9970     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9971       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9972 
9973     // Verify that gotos and switch cases don't jump into scopes illegally.
9974     if (getCurFunction()->NeedsScopeChecking() &&
9975         !dcl->isInvalidDecl() &&
9976         !hasAnyUnrecoverableErrorsInThisFunction() &&
9977         !PP.isCodeCompletionEnabled())
9978       DiagnoseInvalidJumps(Body);
9979 
9980     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9981       if (!Destructor->getParent()->isDependentType())
9982         CheckDestructor(Destructor);
9983 
9984       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9985                                              Destructor->getParent());
9986     }
9987 
9988     // If any errors have occurred, clear out any temporaries that may have
9989     // been leftover. This ensures that these temporaries won't be picked up for
9990     // deletion in some later function.
9991     if (PP.getDiagnostics().hasErrorOccurred() ||
9992         PP.getDiagnostics().getSuppressAllDiagnostics()) {
9993       DiscardCleanupsInEvaluationContext();
9994     }
9995     if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9996         !isa<FunctionTemplateDecl>(dcl)) {
9997       // Since the body is valid, issue any analysis-based warnings that are
9998       // enabled.
9999       ActivePolicy = &WP;
10000     }
10001 
10002     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
10003         (!CheckConstexprFunctionDecl(FD) ||
10004          !CheckConstexprFunctionBody(FD, Body)))
10005       FD->setInvalidDecl();
10006 
10007     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
10008     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
10009     assert(MaybeODRUseExprs.empty() &&
10010            "Leftover expressions for odr-use checking");
10011   }
10012 
10013   if (!IsInstantiation)
10014     PopDeclContext();
10015 
10016   PopFunctionScopeInfo(ActivePolicy, dcl);
10017   // If any errors have occurred, clear out any temporaries that may have
10018   // been leftover. This ensures that these temporaries won't be picked up for
10019   // deletion in some later function.
10020   if (getDiagnostics().hasErrorOccurred()) {
10021     DiscardCleanupsInEvaluationContext();
10022   }
10023 
10024   return dcl;
10025 }
10026 
10027 
10028 /// When we finish delayed parsing of an attribute, we must attach it to the
10029 /// relevant Decl.
10030 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
10031                                        ParsedAttributes &Attrs) {
10032   // Always attach attributes to the underlying decl.
10033   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
10034     D = TD->getTemplatedDecl();
10035   ProcessDeclAttributeList(S, D, Attrs.getList());
10036 
10037   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
10038     if (Method->isStatic())
10039       checkThisInStaticMemberFunctionAttributes(Method);
10040 }
10041 
10042 
10043 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
10044 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
10045 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
10046                                           IdentifierInfo &II, Scope *S) {
10047   // Before we produce a declaration for an implicitly defined
10048   // function, see whether there was a locally-scoped declaration of
10049   // this name as a function or variable. If so, use that
10050   // (non-visible) declaration, and complain about it.
10051   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
10052     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
10053     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
10054     return ExternCPrev;
10055   }
10056 
10057   // Extension in C99.  Legal in C90, but warn about it.
10058   unsigned diag_id;
10059   if (II.getName().startswith("__builtin_"))
10060     diag_id = diag::warn_builtin_unknown;
10061   else if (getLangOpts().C99)
10062     diag_id = diag::ext_implicit_function_decl;
10063   else
10064     diag_id = diag::warn_implicit_function_decl;
10065   Diag(Loc, diag_id) << &II;
10066 
10067   // Because typo correction is expensive, only do it if the implicit
10068   // function declaration is going to be treated as an error.
10069   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
10070     TypoCorrection Corrected;
10071     DeclFilterCCC<FunctionDecl> Validator;
10072     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
10073                                       LookupOrdinaryName, S, 0, Validator)))
10074       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
10075                    /*ErrorRecovery*/false);
10076   }
10077 
10078   // Set a Declarator for the implicit definition: int foo();
10079   const char *Dummy;
10080   AttributeFactory attrFactory;
10081   DeclSpec DS(attrFactory);
10082   unsigned DiagID;
10083   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
10084                                   Context.getPrintingPolicy());
10085   (void)Error; // Silence warning.
10086   assert(!Error && "Error setting up implicit decl!");
10087   SourceLocation NoLoc;
10088   Declarator D(DS, Declarator::BlockContext);
10089   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
10090                                              /*IsAmbiguous=*/false,
10091                                              /*LParenLoc=*/NoLoc,
10092                                              /*Params=*/0,
10093                                              /*NumParams=*/0,
10094                                              /*EllipsisLoc=*/NoLoc,
10095                                              /*RParenLoc=*/NoLoc,
10096                                              /*TypeQuals=*/0,
10097                                              /*RefQualifierIsLvalueRef=*/true,
10098                                              /*RefQualifierLoc=*/NoLoc,
10099                                              /*ConstQualifierLoc=*/NoLoc,
10100                                              /*VolatileQualifierLoc=*/NoLoc,
10101                                              /*MutableLoc=*/NoLoc,
10102                                              EST_None,
10103                                              /*ESpecLoc=*/NoLoc,
10104                                              /*Exceptions=*/0,
10105                                              /*ExceptionRanges=*/0,
10106                                              /*NumExceptions=*/0,
10107                                              /*NoexceptExpr=*/0,
10108                                              Loc, Loc, D),
10109                 DS.getAttributes(),
10110                 SourceLocation());
10111   D.SetIdentifier(&II, Loc);
10112 
10113   // Insert this function into translation-unit scope.
10114 
10115   DeclContext *PrevDC = CurContext;
10116   CurContext = Context.getTranslationUnitDecl();
10117 
10118   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10119   FD->setImplicit();
10120 
10121   CurContext = PrevDC;
10122 
10123   AddKnownFunctionAttributes(FD);
10124 
10125   return FD;
10126 }
10127 
10128 /// \brief Adds any function attributes that we know a priori based on
10129 /// the declaration of this function.
10130 ///
10131 /// These attributes can apply both to implicitly-declared builtins
10132 /// (like __builtin___printf_chk) or to library-declared functions
10133 /// like NSLog or printf.
10134 ///
10135 /// We need to check for duplicate attributes both here and where user-written
10136 /// attributes are applied to declarations.
10137 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10138   if (FD->isInvalidDecl())
10139     return;
10140 
10141   // If this is a built-in function, map its builtin attributes to
10142   // actual attributes.
10143   if (unsigned BuiltinID = FD->getBuiltinID()) {
10144     // Handle printf-formatting attributes.
10145     unsigned FormatIdx;
10146     bool HasVAListArg;
10147     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10148       if (!FD->hasAttr<FormatAttr>()) {
10149         const char *fmt = "printf";
10150         unsigned int NumParams = FD->getNumParams();
10151         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10152             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10153           fmt = "NSString";
10154         FD->addAttr(FormatAttr::CreateImplicit(Context,
10155                                                &Context.Idents.get(fmt),
10156                                                FormatIdx+1,
10157                                                HasVAListArg ? 0 : FormatIdx+2,
10158                                                FD->getLocation()));
10159       }
10160     }
10161     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10162                                              HasVAListArg)) {
10163      if (!FD->hasAttr<FormatAttr>())
10164        FD->addAttr(FormatAttr::CreateImplicit(Context,
10165                                               &Context.Idents.get("scanf"),
10166                                               FormatIdx+1,
10167                                               HasVAListArg ? 0 : FormatIdx+2,
10168                                               FD->getLocation()));
10169     }
10170 
10171     // Mark const if we don't care about errno and that is the only
10172     // thing preventing the function from being const. This allows
10173     // IRgen to use LLVM intrinsics for such functions.
10174     if (!getLangOpts().MathErrno &&
10175         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10176       if (!FD->hasAttr<ConstAttr>())
10177         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10178     }
10179 
10180     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10181         !FD->hasAttr<ReturnsTwiceAttr>())
10182       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10183                                          FD->getLocation()));
10184     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10185       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10186     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10187       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10188   }
10189 
10190   IdentifierInfo *Name = FD->getIdentifier();
10191   if (!Name)
10192     return;
10193   if ((!getLangOpts().CPlusPlus &&
10194        FD->getDeclContext()->isTranslationUnit()) ||
10195       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10196        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10197        LinkageSpecDecl::lang_c)) {
10198     // Okay: this could be a libc/libm/Objective-C function we know
10199     // about.
10200   } else
10201     return;
10202 
10203   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10204     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10205     // target-specific builtins, perhaps?
10206     if (!FD->hasAttr<FormatAttr>())
10207       FD->addAttr(FormatAttr::CreateImplicit(Context,
10208                                              &Context.Idents.get("printf"), 2,
10209                                              Name->isStr("vasprintf") ? 0 : 3,
10210                                              FD->getLocation()));
10211   }
10212 
10213   if (Name->isStr("__CFStringMakeConstantString")) {
10214     // We already have a __builtin___CFStringMakeConstantString,
10215     // but builds that use -fno-constant-cfstrings don't go through that.
10216     if (!FD->hasAttr<FormatArgAttr>())
10217       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10218                                                 FD->getLocation()));
10219   }
10220 }
10221 
10222 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10223                                     TypeSourceInfo *TInfo) {
10224   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10225   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10226 
10227   if (!TInfo) {
10228     assert(D.isInvalidType() && "no declarator info for valid type");
10229     TInfo = Context.getTrivialTypeSourceInfo(T);
10230   }
10231 
10232   // Scope manipulation handled by caller.
10233   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10234                                            D.getLocStart(),
10235                                            D.getIdentifierLoc(),
10236                                            D.getIdentifier(),
10237                                            TInfo);
10238 
10239   // Bail out immediately if we have an invalid declaration.
10240   if (D.isInvalidType()) {
10241     NewTD->setInvalidDecl();
10242     return NewTD;
10243   }
10244 
10245   if (D.getDeclSpec().isModulePrivateSpecified()) {
10246     if (CurContext->isFunctionOrMethod())
10247       Diag(NewTD->getLocation(), diag::err_module_private_local)
10248         << 2 << NewTD->getDeclName()
10249         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10250         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10251     else
10252       NewTD->setModulePrivate();
10253   }
10254 
10255   // C++ [dcl.typedef]p8:
10256   //   If the typedef declaration defines an unnamed class (or
10257   //   enum), the first typedef-name declared by the declaration
10258   //   to be that class type (or enum type) is used to denote the
10259   //   class type (or enum type) for linkage purposes only.
10260   // We need to check whether the type was declared in the declaration.
10261   switch (D.getDeclSpec().getTypeSpecType()) {
10262   case TST_enum:
10263   case TST_struct:
10264   case TST_interface:
10265   case TST_union:
10266   case TST_class: {
10267     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10268 
10269     // Do nothing if the tag is not anonymous or already has an
10270     // associated typedef (from an earlier typedef in this decl group).
10271     if (tagFromDeclSpec->getIdentifier()) break;
10272     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10273 
10274     // A well-formed anonymous tag must always be a TUK_Definition.
10275     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10276 
10277     // The type must match the tag exactly;  no qualifiers allowed.
10278     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10279       break;
10280 
10281     // If we've already computed linkage for the anonymous tag, then
10282     // adding a typedef name for the anonymous decl can change that
10283     // linkage, which might be a serious problem.  Diagnose this as
10284     // unsupported and ignore the typedef name.  TODO: we should
10285     // pursue this as a language defect and establish a formal rule
10286     // for how to handle it.
10287     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10288       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10289 
10290       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10291       tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(),
10292                                           getLangOpts());
10293 
10294       llvm::SmallString<40> textToInsert;
10295       textToInsert += ' ';
10296       textToInsert += D.getIdentifier()->getName();
10297       Diag(tagLoc, diag::note_typedef_changes_linkage)
10298         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10299       break;
10300     }
10301 
10302     // Otherwise, set this is the anon-decl typedef for the tag.
10303     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10304     break;
10305   }
10306 
10307   default:
10308     break;
10309   }
10310 
10311   return NewTD;
10312 }
10313 
10314 
10315 /// \brief Check that this is a valid underlying type for an enum declaration.
10316 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10317   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10318   QualType T = TI->getType();
10319 
10320   if (T->isDependentType())
10321     return false;
10322 
10323   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10324     if (BT->isInteger())
10325       return false;
10326 
10327   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10328   return true;
10329 }
10330 
10331 /// Check whether this is a valid redeclaration of a previous enumeration.
10332 /// \return true if the redeclaration was invalid.
10333 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10334                                   QualType EnumUnderlyingTy,
10335                                   const EnumDecl *Prev) {
10336   bool IsFixed = !EnumUnderlyingTy.isNull();
10337 
10338   if (IsScoped != Prev->isScoped()) {
10339     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10340       << Prev->isScoped();
10341     Diag(Prev->getLocation(), diag::note_previous_declaration);
10342     return true;
10343   }
10344 
10345   if (IsFixed && Prev->isFixed()) {
10346     if (!EnumUnderlyingTy->isDependentType() &&
10347         !Prev->getIntegerType()->isDependentType() &&
10348         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10349                                         Prev->getIntegerType())) {
10350       // TODO: Highlight the underlying type of the redeclaration.
10351       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10352         << EnumUnderlyingTy << Prev->getIntegerType();
10353       Diag(Prev->getLocation(), diag::note_previous_declaration)
10354           << Prev->getIntegerTypeRange();
10355       return true;
10356     }
10357   } else if (IsFixed != Prev->isFixed()) {
10358     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10359       << Prev->isFixed();
10360     Diag(Prev->getLocation(), diag::note_previous_declaration);
10361     return true;
10362   }
10363 
10364   return false;
10365 }
10366 
10367 /// \brief Get diagnostic %select index for tag kind for
10368 /// redeclaration diagnostic message.
10369 /// WARNING: Indexes apply to particular diagnostics only!
10370 ///
10371 /// \returns diagnostic %select index.
10372 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10373   switch (Tag) {
10374   case TTK_Struct: return 0;
10375   case TTK_Interface: return 1;
10376   case TTK_Class:  return 2;
10377   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10378   }
10379 }
10380 
10381 /// \brief Determine if tag kind is a class-key compatible with
10382 /// class for redeclaration (class, struct, or __interface).
10383 ///
10384 /// \returns true iff the tag kind is compatible.
10385 static bool isClassCompatTagKind(TagTypeKind Tag)
10386 {
10387   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10388 }
10389 
10390 /// \brief Determine whether a tag with a given kind is acceptable
10391 /// as a redeclaration of the given tag declaration.
10392 ///
10393 /// \returns true if the new tag kind is acceptable, false otherwise.
10394 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10395                                         TagTypeKind NewTag, bool isDefinition,
10396                                         SourceLocation NewTagLoc,
10397                                         const IdentifierInfo &Name) {
10398   // C++ [dcl.type.elab]p3:
10399   //   The class-key or enum keyword present in the
10400   //   elaborated-type-specifier shall agree in kind with the
10401   //   declaration to which the name in the elaborated-type-specifier
10402   //   refers. This rule also applies to the form of
10403   //   elaborated-type-specifier that declares a class-name or
10404   //   friend class since it can be construed as referring to the
10405   //   definition of the class. Thus, in any
10406   //   elaborated-type-specifier, the enum keyword shall be used to
10407   //   refer to an enumeration (7.2), the union class-key shall be
10408   //   used to refer to a union (clause 9), and either the class or
10409   //   struct class-key shall be used to refer to a class (clause 9)
10410   //   declared using the class or struct class-key.
10411   TagTypeKind OldTag = Previous->getTagKind();
10412   if (!isDefinition || !isClassCompatTagKind(NewTag))
10413     if (OldTag == NewTag)
10414       return true;
10415 
10416   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10417     // Warn about the struct/class tag mismatch.
10418     bool isTemplate = false;
10419     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10420       isTemplate = Record->getDescribedClassTemplate();
10421 
10422     if (!ActiveTemplateInstantiations.empty()) {
10423       // In a template instantiation, do not offer fix-its for tag mismatches
10424       // since they usually mess up the template instead of fixing the problem.
10425       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10426         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10427         << getRedeclDiagFromTagKind(OldTag);
10428       return true;
10429     }
10430 
10431     if (isDefinition) {
10432       // On definitions, check previous tags and issue a fix-it for each
10433       // one that doesn't match the current tag.
10434       if (Previous->getDefinition()) {
10435         // Don't suggest fix-its for redefinitions.
10436         return true;
10437       }
10438 
10439       bool previousMismatch = false;
10440       for (auto I : Previous->redecls()) {
10441         if (I->getTagKind() != NewTag) {
10442           if (!previousMismatch) {
10443             previousMismatch = true;
10444             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10445               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10446               << getRedeclDiagFromTagKind(I->getTagKind());
10447           }
10448           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10449             << getRedeclDiagFromTagKind(NewTag)
10450             << FixItHint::CreateReplacement(I->getInnerLocStart(),
10451                  TypeWithKeyword::getTagTypeKindName(NewTag));
10452         }
10453       }
10454       return true;
10455     }
10456 
10457     // Check for a previous definition.  If current tag and definition
10458     // are same type, do nothing.  If no definition, but disagree with
10459     // with previous tag type, give a warning, but no fix-it.
10460     const TagDecl *Redecl = Previous->getDefinition() ?
10461                             Previous->getDefinition() : Previous;
10462     if (Redecl->getTagKind() == NewTag) {
10463       return true;
10464     }
10465 
10466     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10467       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10468       << getRedeclDiagFromTagKind(OldTag);
10469     Diag(Redecl->getLocation(), diag::note_previous_use);
10470 
10471     // If there is a previous definition, suggest a fix-it.
10472     if (Previous->getDefinition()) {
10473         Diag(NewTagLoc, diag::note_struct_class_suggestion)
10474           << getRedeclDiagFromTagKind(Redecl->getTagKind())
10475           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10476                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10477     }
10478 
10479     return true;
10480   }
10481   return false;
10482 }
10483 
10484 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10485 /// former case, Name will be non-null.  In the later case, Name will be null.
10486 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10487 /// reference/declaration/definition of a tag.
10488 ///
10489 /// IsTypeSpecifier is true if this is a type-specifier (or
10490 /// trailing-type-specifier) other than one in an alias-declaration.
10491 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10492                      SourceLocation KWLoc, CXXScopeSpec &SS,
10493                      IdentifierInfo *Name, SourceLocation NameLoc,
10494                      AttributeList *Attr, AccessSpecifier AS,
10495                      SourceLocation ModulePrivateLoc,
10496                      MultiTemplateParamsArg TemplateParameterLists,
10497                      bool &OwnedDecl, bool &IsDependent,
10498                      SourceLocation ScopedEnumKWLoc,
10499                      bool ScopedEnumUsesClassTag,
10500                      TypeResult UnderlyingType,
10501                      bool IsTypeSpecifier) {
10502   // If this is not a definition, it must have a name.
10503   IdentifierInfo *OrigName = Name;
10504   assert((Name != 0 || TUK == TUK_Definition) &&
10505          "Nameless record must be a definition!");
10506   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10507 
10508   OwnedDecl = false;
10509   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10510   bool ScopedEnum = ScopedEnumKWLoc.isValid();
10511 
10512   // FIXME: Check explicit specializations more carefully.
10513   bool isExplicitSpecialization = false;
10514   bool Invalid = false;
10515 
10516   // We only need to do this matching if we have template parameters
10517   // or a scope specifier, which also conveniently avoids this work
10518   // for non-C++ cases.
10519   if (TemplateParameterLists.size() > 0 ||
10520       (SS.isNotEmpty() && TUK != TUK_Reference)) {
10521     if (TemplateParameterList *TemplateParams =
10522             MatchTemplateParametersToScopeSpecifier(
10523                 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10524                 isExplicitSpecialization, Invalid)) {
10525       if (Kind == TTK_Enum) {
10526         Diag(KWLoc, diag::err_enum_template);
10527         return 0;
10528       }
10529 
10530       if (TemplateParams->size() > 0) {
10531         // This is a declaration or definition of a class template (which may
10532         // be a member of another template).
10533 
10534         if (Invalid)
10535           return 0;
10536 
10537         OwnedDecl = false;
10538         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
10539                                                SS, Name, NameLoc, Attr,
10540                                                TemplateParams, AS,
10541                                                ModulePrivateLoc,
10542                                                TemplateParameterLists.size()-1,
10543                                                TemplateParameterLists.data());
10544         return Result.get();
10545       } else {
10546         // The "template<>" header is extraneous.
10547         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10548           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10549         isExplicitSpecialization = true;
10550       }
10551     }
10552   }
10553 
10554   // Figure out the underlying type if this a enum declaration. We need to do
10555   // this early, because it's needed to detect if this is an incompatible
10556   // redeclaration.
10557   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10558 
10559   if (Kind == TTK_Enum) {
10560     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10561       // No underlying type explicitly specified, or we failed to parse the
10562       // type, default to int.
10563       EnumUnderlying = Context.IntTy.getTypePtr();
10564     else if (UnderlyingType.get()) {
10565       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10566       // integral type; any cv-qualification is ignored.
10567       TypeSourceInfo *TI = 0;
10568       GetTypeFromParser(UnderlyingType.get(), &TI);
10569       EnumUnderlying = TI;
10570 
10571       if (CheckEnumUnderlyingType(TI))
10572         // Recover by falling back to int.
10573         EnumUnderlying = Context.IntTy.getTypePtr();
10574 
10575       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
10576                                           UPPC_FixedUnderlyingType))
10577         EnumUnderlying = Context.IntTy.getTypePtr();
10578 
10579     } else if (getLangOpts().MSVCCompat)
10580       // Microsoft enums are always of int type.
10581       EnumUnderlying = Context.IntTy.getTypePtr();
10582   }
10583 
10584   DeclContext *SearchDC = CurContext;
10585   DeclContext *DC = CurContext;
10586   bool isStdBadAlloc = false;
10587 
10588   RedeclarationKind Redecl = ForRedeclaration;
10589   if (TUK == TUK_Friend || TUK == TUK_Reference)
10590     Redecl = NotForRedeclaration;
10591 
10592   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
10593   bool FriendSawTagOutsideEnclosingNamespace = false;
10594   if (Name && SS.isNotEmpty()) {
10595     // We have a nested-name tag ('struct foo::bar').
10596 
10597     // Check for invalid 'foo::'.
10598     if (SS.isInvalid()) {
10599       Name = 0;
10600       goto CreateNewDecl;
10601     }
10602 
10603     // If this is a friend or a reference to a class in a dependent
10604     // context, don't try to make a decl for it.
10605     if (TUK == TUK_Friend || TUK == TUK_Reference) {
10606       DC = computeDeclContext(SS, false);
10607       if (!DC) {
10608         IsDependent = true;
10609         return 0;
10610       }
10611     } else {
10612       DC = computeDeclContext(SS, true);
10613       if (!DC) {
10614         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10615           << SS.getRange();
10616         return 0;
10617       }
10618     }
10619 
10620     if (RequireCompleteDeclContext(SS, DC))
10621       return 0;
10622 
10623     SearchDC = DC;
10624     // Look-up name inside 'foo::'.
10625     LookupQualifiedName(Previous, DC);
10626 
10627     if (Previous.isAmbiguous())
10628       return 0;
10629 
10630     if (Previous.empty()) {
10631       // Name lookup did not find anything. However, if the
10632       // nested-name-specifier refers to the current instantiation,
10633       // and that current instantiation has any dependent base
10634       // classes, we might find something at instantiation time: treat
10635       // this as a dependent elaborated-type-specifier.
10636       // But this only makes any sense for reference-like lookups.
10637       if (Previous.wasNotFoundInCurrentInstantiation() &&
10638           (TUK == TUK_Reference || TUK == TUK_Friend)) {
10639         IsDependent = true;
10640         return 0;
10641       }
10642 
10643       // A tag 'foo::bar' must already exist.
10644       Diag(NameLoc, diag::err_not_tag_in_scope)
10645         << Kind << Name << DC << SS.getRange();
10646       Name = 0;
10647       Invalid = true;
10648       goto CreateNewDecl;
10649     }
10650   } else if (Name) {
10651     // If this is a named struct, check to see if there was a previous forward
10652     // declaration or definition.
10653     // FIXME: We're looking into outer scopes here, even when we
10654     // shouldn't be. Doing so can result in ambiguities that we
10655     // shouldn't be diagnosing.
10656     LookupName(Previous, S);
10657 
10658     // When declaring or defining a tag, ignore ambiguities introduced
10659     // by types using'ed into this scope.
10660     if (Previous.isAmbiguous() &&
10661         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
10662       LookupResult::Filter F = Previous.makeFilter();
10663       while (F.hasNext()) {
10664         NamedDecl *ND = F.next();
10665         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10666           F.erase();
10667       }
10668       F.done();
10669     }
10670 
10671     // C++11 [namespace.memdef]p3:
10672     //   If the name in a friend declaration is neither qualified nor
10673     //   a template-id and the declaration is a function or an
10674     //   elaborated-type-specifier, the lookup to determine whether
10675     //   the entity has been previously declared shall not consider
10676     //   any scopes outside the innermost enclosing namespace.
10677     //
10678     // Does it matter that this should be by scope instead of by
10679     // semantic context?
10680     if (!Previous.empty() && TUK == TUK_Friend) {
10681       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10682       LookupResult::Filter F = Previous.makeFilter();
10683       while (F.hasNext()) {
10684         NamedDecl *ND = F.next();
10685         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10686         if (DC->isFileContext() &&
10687             !EnclosingNS->Encloses(ND->getDeclContext())) {
10688           F.erase();
10689           FriendSawTagOutsideEnclosingNamespace = true;
10690         }
10691       }
10692       F.done();
10693     }
10694 
10695     // Note:  there used to be some attempt at recovery here.
10696     if (Previous.isAmbiguous())
10697       return 0;
10698 
10699     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
10700       // FIXME: This makes sure that we ignore the contexts associated
10701       // with C structs, unions, and enums when looking for a matching
10702       // tag declaration or definition. See the similar lookup tweak
10703       // in Sema::LookupName; is there a better way to deal with this?
10704       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10705         SearchDC = SearchDC->getParent();
10706     }
10707   } else if (S->isFunctionPrototypeScope()) {
10708     // If this is an enum declaration in function prototype scope, set its
10709     // initial context to the translation unit.
10710     // FIXME: [citation needed]
10711     SearchDC = Context.getTranslationUnitDecl();
10712   }
10713 
10714   if (Previous.isSingleResult() &&
10715       Previous.getFoundDecl()->isTemplateParameter()) {
10716     // Maybe we will complain about the shadowed template parameter.
10717     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
10718     // Just pretend that we didn't see the previous declaration.
10719     Previous.clear();
10720   }
10721 
10722   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
10723       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
10724     // This is a declaration of or a reference to "std::bad_alloc".
10725     isStdBadAlloc = true;
10726 
10727     if (Previous.empty() && StdBadAlloc) {
10728       // std::bad_alloc has been implicitly declared (but made invisible to
10729       // name lookup). Fill in this implicit declaration as the previous
10730       // declaration, so that the declarations get chained appropriately.
10731       Previous.addDecl(getStdBadAlloc());
10732     }
10733   }
10734 
10735   // If we didn't find a previous declaration, and this is a reference
10736   // (or friend reference), move to the correct scope.  In C++, we
10737   // also need to do a redeclaration lookup there, just in case
10738   // there's a shadow friend decl.
10739   if (Name && Previous.empty() &&
10740       (TUK == TUK_Reference || TUK == TUK_Friend)) {
10741     if (Invalid) goto CreateNewDecl;
10742     assert(SS.isEmpty());
10743 
10744     if (TUK == TUK_Reference) {
10745       // C++ [basic.scope.pdecl]p5:
10746       //   -- for an elaborated-type-specifier of the form
10747       //
10748       //          class-key identifier
10749       //
10750       //      if the elaborated-type-specifier is used in the
10751       //      decl-specifier-seq or parameter-declaration-clause of a
10752       //      function defined in namespace scope, the identifier is
10753       //      declared as a class-name in the namespace that contains
10754       //      the declaration; otherwise, except as a friend
10755       //      declaration, the identifier is declared in the smallest
10756       //      non-class, non-function-prototype scope that contains the
10757       //      declaration.
10758       //
10759       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10760       // C structs and unions.
10761       //
10762       // It is an error in C++ to declare (rather than define) an enum
10763       // type, including via an elaborated type specifier.  We'll
10764       // diagnose that later; for now, declare the enum in the same
10765       // scope as we would have picked for any other tag type.
10766       //
10767       // GNU C also supports this behavior as part of its incomplete
10768       // enum types extension, while GNU C++ does not.
10769       //
10770       // Find the context where we'll be declaring the tag.
10771       // FIXME: We would like to maintain the current DeclContext as the
10772       // lexical context,
10773       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
10774         SearchDC = SearchDC->getParent();
10775 
10776       // Find the scope where we'll be declaring the tag.
10777       while (S->isClassScope() ||
10778              (getLangOpts().CPlusPlus &&
10779               S->isFunctionPrototypeScope()) ||
10780              ((S->getFlags() & Scope::DeclScope) == 0) ||
10781              (S->getEntity() && S->getEntity()->isTransparentContext()))
10782         S = S->getParent();
10783     } else {
10784       assert(TUK == TUK_Friend);
10785       // C++ [namespace.memdef]p3:
10786       //   If a friend declaration in a non-local class first declares a
10787       //   class or function, the friend class or function is a member of
10788       //   the innermost enclosing namespace.
10789       SearchDC = SearchDC->getEnclosingNamespaceContext();
10790     }
10791 
10792     // In C++, we need to do a redeclaration lookup to properly
10793     // diagnose some problems.
10794     if (getLangOpts().CPlusPlus) {
10795       Previous.setRedeclarationKind(ForRedeclaration);
10796       LookupQualifiedName(Previous, SearchDC);
10797     }
10798   }
10799 
10800   if (!Previous.empty()) {
10801     NamedDecl *PrevDecl = Previous.getFoundDecl();
10802     NamedDecl *DirectPrevDecl =
10803         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
10804 
10805     // It's okay to have a tag decl in the same scope as a typedef
10806     // which hides a tag decl in the same scope.  Finding this
10807     // insanity with a redeclaration lookup can only actually happen
10808     // in C++.
10809     //
10810     // This is also okay for elaborated-type-specifiers, which is
10811     // technically forbidden by the current standard but which is
10812     // okay according to the likely resolution of an open issue;
10813     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
10814     if (getLangOpts().CPlusPlus) {
10815       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10816         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10817           TagDecl *Tag = TT->getDecl();
10818           if (Tag->getDeclName() == Name &&
10819               Tag->getDeclContext()->getRedeclContext()
10820                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
10821             PrevDecl = Tag;
10822             Previous.clear();
10823             Previous.addDecl(Tag);
10824             Previous.resolveKind();
10825           }
10826         }
10827       }
10828     }
10829 
10830     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
10831       // If this is a use of a previous tag, or if the tag is already declared
10832       // in the same scope (so that the definition/declaration completes or
10833       // rementions the tag), reuse the decl.
10834       if (TUK == TUK_Reference || TUK == TUK_Friend ||
10835           isDeclInScope(DirectPrevDecl, SearchDC, S,
10836                         SS.isNotEmpty() || isExplicitSpecialization)) {
10837         // Make sure that this wasn't declared as an enum and now used as a
10838         // struct or something similar.
10839         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10840                                           TUK == TUK_Definition, KWLoc,
10841                                           *Name)) {
10842           bool SafeToContinue
10843             = (PrevTagDecl->getTagKind() != TTK_Enum &&
10844                Kind != TTK_Enum);
10845           if (SafeToContinue)
10846             Diag(KWLoc, diag::err_use_with_wrong_tag)
10847               << Name
10848               << FixItHint::CreateReplacement(SourceRange(KWLoc),
10849                                               PrevTagDecl->getKindName());
10850           else
10851             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
10852           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
10853 
10854           if (SafeToContinue)
10855             Kind = PrevTagDecl->getTagKind();
10856           else {
10857             // Recover by making this an anonymous redefinition.
10858             Name = 0;
10859             Previous.clear();
10860             Invalid = true;
10861           }
10862         }
10863 
10864         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10865           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10866 
10867           // If this is an elaborated-type-specifier for a scoped enumeration,
10868           // the 'class' keyword is not necessary and not permitted.
10869           if (TUK == TUK_Reference || TUK == TUK_Friend) {
10870             if (ScopedEnum)
10871               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10872                 << PrevEnum->isScoped()
10873                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10874             return PrevTagDecl;
10875           }
10876 
10877           QualType EnumUnderlyingTy;
10878           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10879             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
10880           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10881             EnumUnderlyingTy = QualType(T, 0);
10882 
10883           // All conflicts with previous declarations are recovered by
10884           // returning the previous declaration, unless this is a definition,
10885           // in which case we want the caller to bail out.
10886           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10887                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
10888             return TUK == TUK_Declaration ? PrevTagDecl : 0;
10889         }
10890 
10891         // C++11 [class.mem]p1:
10892         //   A member shall not be declared twice in the member-specification,
10893         //   except that a nested class or member class template can be declared
10894         //   and then later defined.
10895         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10896             S->isDeclScope(PrevDecl)) {
10897           Diag(NameLoc, diag::ext_member_redeclared);
10898           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10899         }
10900 
10901         if (!Invalid) {
10902           // If this is a use, just return the declaration we found.
10903 
10904           // FIXME: In the future, return a variant or some other clue
10905           // for the consumer of this Decl to know it doesn't own it.
10906           // For our current ASTs this shouldn't be a problem, but will
10907           // need to be changed with DeclGroups.
10908           if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
10909                getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
10910             return PrevTagDecl;
10911 
10912           // Diagnose attempts to redefine a tag.
10913           if (TUK == TUK_Definition) {
10914             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
10915               // If we're defining a specialization and the previous definition
10916               // is from an implicit instantiation, don't emit an error
10917               // here; we'll catch this in the general case below.
10918               bool IsExplicitSpecializationAfterInstantiation = false;
10919               if (isExplicitSpecialization) {
10920                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10921                   IsExplicitSpecializationAfterInstantiation =
10922                     RD->getTemplateSpecializationKind() !=
10923                     TSK_ExplicitSpecialization;
10924                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10925                   IsExplicitSpecializationAfterInstantiation =
10926                     ED->getTemplateSpecializationKind() !=
10927                     TSK_ExplicitSpecialization;
10928               }
10929 
10930               if (!IsExplicitSpecializationAfterInstantiation) {
10931                 // A redeclaration in function prototype scope in C isn't
10932                 // visible elsewhere, so merely issue a warning.
10933                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
10934                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10935                 else
10936                   Diag(NameLoc, diag::err_redefinition) << Name;
10937                 Diag(Def->getLocation(), diag::note_previous_definition);
10938                 // If this is a redefinition, recover by making this
10939                 // struct be anonymous, which will make any later
10940                 // references get the previous definition.
10941                 Name = 0;
10942                 Previous.clear();
10943                 Invalid = true;
10944               }
10945             } else {
10946               // If the type is currently being defined, complain
10947               // about a nested redefinition.
10948               const TagType *Tag
10949                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
10950               if (Tag->isBeingDefined()) {
10951                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
10952                 Diag(PrevTagDecl->getLocation(),
10953                      diag::note_previous_definition);
10954                 Name = 0;
10955                 Previous.clear();
10956                 Invalid = true;
10957               }
10958             }
10959 
10960             // Okay, this is definition of a previously declared or referenced
10961             // tag PrevDecl. We're going to create a new Decl for it.
10962           }
10963         }
10964         // If we get here we have (another) forward declaration or we
10965         // have a definition.  Just create a new decl.
10966 
10967       } else {
10968         // If we get here, this is a definition of a new tag type in a nested
10969         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
10970         // new decl/type.  We set PrevDecl to NULL so that the entities
10971         // have distinct types.
10972         Previous.clear();
10973       }
10974       // If we get here, we're going to create a new Decl. If PrevDecl
10975       // is non-NULL, it's a definition of the tag declared by
10976       // PrevDecl. If it's NULL, we have a new definition.
10977 
10978 
10979     // Otherwise, PrevDecl is not a tag, but was found with tag
10980     // lookup.  This is only actually possible in C++, where a few
10981     // things like templates still live in the tag namespace.
10982     } else {
10983       // Use a better diagnostic if an elaborated-type-specifier
10984       // found the wrong kind of type on the first
10985       // (non-redeclaration) lookup.
10986       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10987           !Previous.isForRedeclaration()) {
10988         unsigned Kind = 0;
10989         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10990         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10991         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10992         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10993         Diag(PrevDecl->getLocation(), diag::note_declared_at);
10994         Invalid = true;
10995 
10996       // Otherwise, only diagnose if the declaration is in scope.
10997       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10998                                 SS.isNotEmpty() || isExplicitSpecialization)) {
10999         // do nothing
11000 
11001       // Diagnose implicit declarations introduced by elaborated types.
11002       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
11003         unsigned Kind = 0;
11004         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
11005         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
11006         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
11007         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
11008         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11009         Invalid = true;
11010 
11011       // Otherwise it's a declaration.  Call out a particularly common
11012       // case here.
11013       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
11014         unsigned Kind = 0;
11015         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
11016         Diag(NameLoc, diag::err_tag_definition_of_typedef)
11017           << Name << Kind << TND->getUnderlyingType();
11018         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
11019         Invalid = true;
11020 
11021       // Otherwise, diagnose.
11022       } else {
11023         // The tag name clashes with something else in the target scope,
11024         // issue an error and recover by making this tag be anonymous.
11025         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
11026         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11027         Name = 0;
11028         Invalid = true;
11029       }
11030 
11031       // The existing declaration isn't relevant to us; we're in a
11032       // new scope, so clear out the previous declaration.
11033       Previous.clear();
11034     }
11035   }
11036 
11037 CreateNewDecl:
11038 
11039   TagDecl *PrevDecl = 0;
11040   if (Previous.isSingleResult())
11041     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
11042 
11043   // If there is an identifier, use the location of the identifier as the
11044   // location of the decl, otherwise use the location of the struct/union
11045   // keyword.
11046   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
11047 
11048   // Otherwise, create a new declaration. If there is a previous
11049   // declaration of the same entity, the two will be linked via
11050   // PrevDecl.
11051   TagDecl *New;
11052 
11053   bool IsForwardReference = false;
11054   if (Kind == TTK_Enum) {
11055     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11056     // enum X { A, B, C } D;    D should chain to X.
11057     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
11058                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
11059                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
11060     // If this is an undefined enum, warn.
11061     if (TUK != TUK_Definition && !Invalid) {
11062       TagDecl *Def;
11063       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
11064           cast<EnumDecl>(New)->isFixed()) {
11065         // C++0x: 7.2p2: opaque-enum-declaration.
11066         // Conflicts are diagnosed above. Do nothing.
11067       }
11068       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
11069         Diag(Loc, diag::ext_forward_ref_enum_def)
11070           << New;
11071         Diag(Def->getLocation(), diag::note_previous_definition);
11072       } else {
11073         unsigned DiagID = diag::ext_forward_ref_enum;
11074         if (getLangOpts().MSVCCompat)
11075           DiagID = diag::ext_ms_forward_ref_enum;
11076         else if (getLangOpts().CPlusPlus)
11077           DiagID = diag::err_forward_ref_enum;
11078         Diag(Loc, DiagID);
11079 
11080         // If this is a forward-declared reference to an enumeration, make a
11081         // note of it; we won't actually be introducing the declaration into
11082         // the declaration context.
11083         if (TUK == TUK_Reference)
11084           IsForwardReference = true;
11085       }
11086     }
11087 
11088     if (EnumUnderlying) {
11089       EnumDecl *ED = cast<EnumDecl>(New);
11090       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
11091         ED->setIntegerTypeSourceInfo(TI);
11092       else
11093         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
11094       ED->setPromotionType(ED->getIntegerType());
11095     }
11096 
11097   } else {
11098     // struct/union/class
11099 
11100     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
11101     // struct X { int A; } D;    D should chain to X.
11102     if (getLangOpts().CPlusPlus) {
11103       // FIXME: Look for a way to use RecordDecl for simple structs.
11104       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11105                                   cast_or_null<CXXRecordDecl>(PrevDecl));
11106 
11107       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
11108         StdBadAlloc = cast<CXXRecordDecl>(New);
11109     } else
11110       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
11111                                cast_or_null<RecordDecl>(PrevDecl));
11112   }
11113 
11114   // C++11 [dcl.type]p3:
11115   //   A type-specifier-seq shall not define a class or enumeration [...].
11116   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11117     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11118       << Context.getTagDeclType(New);
11119     Invalid = true;
11120   }
11121 
11122   // Maybe add qualifier info.
11123   if (SS.isNotEmpty()) {
11124     if (SS.isSet()) {
11125       // If this is either a declaration or a definition, check the
11126       // nested-name-specifier against the current context. We don't do this
11127       // for explicit specializations, because they have similar checking
11128       // (with more specific diagnostics) in the call to
11129       // CheckMemberSpecialization, below.
11130       if (!isExplicitSpecialization &&
11131           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11132           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11133         Invalid = true;
11134 
11135       New->setQualifierInfo(SS.getWithLocInContext(Context));
11136       if (TemplateParameterLists.size() > 0) {
11137         New->setTemplateParameterListsInfo(Context,
11138                                            TemplateParameterLists.size(),
11139                                            TemplateParameterLists.data());
11140       }
11141     }
11142     else
11143       Invalid = true;
11144   }
11145 
11146   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11147     // Add alignment attributes if necessary; these attributes are checked when
11148     // the ASTContext lays out the structure.
11149     //
11150     // It is important for implementing the correct semantics that this
11151     // happen here (in act on tag decl). The #pragma pack stack is
11152     // maintained as a result of parser callbacks which can occur at
11153     // many points during the parsing of a struct declaration (because
11154     // the #pragma tokens are effectively skipped over during the
11155     // parsing of the struct).
11156     if (TUK == TUK_Definition) {
11157       AddAlignmentAttributesForRecord(RD);
11158       AddMsStructLayoutForRecord(RD);
11159     }
11160   }
11161 
11162   if (ModulePrivateLoc.isValid()) {
11163     if (isExplicitSpecialization)
11164       Diag(New->getLocation(), diag::err_module_private_specialization)
11165         << 2
11166         << FixItHint::CreateRemoval(ModulePrivateLoc);
11167     // __module_private__ does not apply to local classes. However, we only
11168     // diagnose this as an error when the declaration specifiers are
11169     // freestanding. Here, we just ignore the __module_private__.
11170     else if (!SearchDC->isFunctionOrMethod())
11171       New->setModulePrivate();
11172   }
11173 
11174   // If this is a specialization of a member class (of a class template),
11175   // check the specialization.
11176   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11177     Invalid = true;
11178 
11179   if (Invalid)
11180     New->setInvalidDecl();
11181 
11182   if (Attr)
11183     ProcessDeclAttributeList(S, New, Attr);
11184 
11185   // If we're declaring or defining a tag in function prototype scope in C,
11186   // note that this type can only be used within the function and add it to
11187   // the list of decls to inject into the function definition scope.
11188   if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
11189       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11190     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11191     DeclsInPrototypeScope.push_back(New);
11192   }
11193 
11194   // Set the lexical context. If the tag has a C++ scope specifier, the
11195   // lexical context will be different from the semantic context.
11196   New->setLexicalDeclContext(CurContext);
11197 
11198   // Mark this as a friend decl if applicable.
11199   // In Microsoft mode, a friend declaration also acts as a forward
11200   // declaration so we always pass true to setObjectOfFriendDecl to make
11201   // the tag name visible.
11202   if (TUK == TUK_Friend)
11203     New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11204                                getLangOpts().MicrosoftExt);
11205 
11206   // Set the access specifier.
11207   if (!Invalid && SearchDC->isRecord())
11208     SetMemberAccessSpecifier(New, PrevDecl, AS);
11209 
11210   if (TUK == TUK_Definition)
11211     New->startDefinition();
11212 
11213   // If this has an identifier, add it to the scope stack.
11214   if (TUK == TUK_Friend) {
11215     // We might be replacing an existing declaration in the lookup tables;
11216     // if so, borrow its access specifier.
11217     if (PrevDecl)
11218       New->setAccess(PrevDecl->getAccess());
11219 
11220     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11221     DC->makeDeclVisibleInContext(New);
11222     if (Name) // can be null along some error paths
11223       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11224         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11225   } else if (Name) {
11226     S = getNonFieldDeclScope(S);
11227     PushOnScopeChains(New, S, !IsForwardReference);
11228     if (IsForwardReference)
11229       SearchDC->makeDeclVisibleInContext(New);
11230 
11231   } else {
11232     CurContext->addDecl(New);
11233   }
11234 
11235   // If this is the C FILE type, notify the AST context.
11236   if (IdentifierInfo *II = New->getIdentifier())
11237     if (!New->isInvalidDecl() &&
11238         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11239         II->isStr("FILE"))
11240       Context.setFILEDecl(New);
11241 
11242   if (PrevDecl)
11243     mergeDeclAttributes(New, PrevDecl);
11244 
11245   // If there's a #pragma GCC visibility in scope, set the visibility of this
11246   // record.
11247   AddPushedVisibilityAttribute(New);
11248 
11249   OwnedDecl = true;
11250   // In C++, don't return an invalid declaration. We can't recover well from
11251   // the cases where we make the type anonymous.
11252   return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
11253 }
11254 
11255 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11256   AdjustDeclIfTemplate(TagD);
11257   TagDecl *Tag = cast<TagDecl>(TagD);
11258 
11259   // Enter the tag context.
11260   PushDeclContext(S, Tag);
11261 
11262   ActOnDocumentableDecl(TagD);
11263 
11264   // If there's a #pragma GCC visibility in scope, set the visibility of this
11265   // record.
11266   AddPushedVisibilityAttribute(Tag);
11267 }
11268 
11269 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11270   assert(isa<ObjCContainerDecl>(IDecl) &&
11271          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11272   DeclContext *OCD = cast<DeclContext>(IDecl);
11273   assert(getContainingDC(OCD) == CurContext &&
11274       "The next DeclContext should be lexically contained in the current one.");
11275   CurContext = OCD;
11276   return IDecl;
11277 }
11278 
11279 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11280                                            SourceLocation FinalLoc,
11281                                            bool IsFinalSpelledSealed,
11282                                            SourceLocation LBraceLoc) {
11283   AdjustDeclIfTemplate(TagD);
11284   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11285 
11286   FieldCollector->StartClass();
11287 
11288   if (!Record->getIdentifier())
11289     return;
11290 
11291   if (FinalLoc.isValid())
11292     Record->addAttr(new (Context)
11293                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11294 
11295   // C++ [class]p2:
11296   //   [...] The class-name is also inserted into the scope of the
11297   //   class itself; this is known as the injected-class-name. For
11298   //   purposes of access checking, the injected-class-name is treated
11299   //   as if it were a public member name.
11300   CXXRecordDecl *InjectedClassName
11301     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11302                             Record->getLocStart(), Record->getLocation(),
11303                             Record->getIdentifier(),
11304                             /*PrevDecl=*/0,
11305                             /*DelayTypeCreation=*/true);
11306   Context.getTypeDeclType(InjectedClassName, Record);
11307   InjectedClassName->setImplicit();
11308   InjectedClassName->setAccess(AS_public);
11309   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11310       InjectedClassName->setDescribedClassTemplate(Template);
11311   PushOnScopeChains(InjectedClassName, S);
11312   assert(InjectedClassName->isInjectedClassName() &&
11313          "Broken injected-class-name");
11314 }
11315 
11316 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11317                                     SourceLocation RBraceLoc) {
11318   AdjustDeclIfTemplate(TagD);
11319   TagDecl *Tag = cast<TagDecl>(TagD);
11320   Tag->setRBraceLoc(RBraceLoc);
11321 
11322   // Make sure we "complete" the definition even it is invalid.
11323   if (Tag->isBeingDefined()) {
11324     assert(Tag->isInvalidDecl() && "We should already have completed it");
11325     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11326       RD->completeDefinition();
11327   }
11328 
11329   if (isa<CXXRecordDecl>(Tag))
11330     FieldCollector->FinishClass();
11331 
11332   // Exit this scope of this tag's definition.
11333   PopDeclContext();
11334 
11335   if (getCurLexicalContext()->isObjCContainer() &&
11336       Tag->getDeclContext()->isFileContext())
11337     Tag->setTopLevelDeclInObjCContainer();
11338 
11339   // Notify the consumer that we've defined a tag.
11340   if (!Tag->isInvalidDecl())
11341     Consumer.HandleTagDeclDefinition(Tag);
11342 }
11343 
11344 void Sema::ActOnObjCContainerFinishDefinition() {
11345   // Exit this scope of this interface definition.
11346   PopDeclContext();
11347 }
11348 
11349 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
11350   assert(DC == CurContext && "Mismatch of container contexts");
11351   OriginalLexicalContext = DC;
11352   ActOnObjCContainerFinishDefinition();
11353 }
11354 
11355 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11356   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
11357   OriginalLexicalContext = 0;
11358 }
11359 
11360 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11361   AdjustDeclIfTemplate(TagD);
11362   TagDecl *Tag = cast<TagDecl>(TagD);
11363   Tag->setInvalidDecl();
11364 
11365   // Make sure we "complete" the definition even it is invalid.
11366   if (Tag->isBeingDefined()) {
11367     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11368       RD->completeDefinition();
11369   }
11370 
11371   // We're undoing ActOnTagStartDefinition here, not
11372   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11373   // the FieldCollector.
11374 
11375   PopDeclContext();
11376 }
11377 
11378 // Note that FieldName may be null for anonymous bitfields.
11379 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11380                                 IdentifierInfo *FieldName,
11381                                 QualType FieldTy, bool IsMsStruct,
11382                                 Expr *BitWidth, bool *ZeroWidth) {
11383   // Default to true; that shouldn't confuse checks for emptiness
11384   if (ZeroWidth)
11385     *ZeroWidth = true;
11386 
11387   // C99 6.7.2.1p4 - verify the field type.
11388   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11389   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11390     // Handle incomplete types with specific error.
11391     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11392       return ExprError();
11393     if (FieldName)
11394       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11395         << FieldName << FieldTy << BitWidth->getSourceRange();
11396     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11397       << FieldTy << BitWidth->getSourceRange();
11398   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11399                                              UPPC_BitFieldWidth))
11400     return ExprError();
11401 
11402   // If the bit-width is type- or value-dependent, don't try to check
11403   // it now.
11404   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11405     return Owned(BitWidth);
11406 
11407   llvm::APSInt Value;
11408   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11409   if (ICE.isInvalid())
11410     return ICE;
11411   BitWidth = ICE.take();
11412 
11413   if (Value != 0 && ZeroWidth)
11414     *ZeroWidth = false;
11415 
11416   // Zero-width bitfield is ok for anonymous field.
11417   if (Value == 0 && FieldName)
11418     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11419 
11420   if (Value.isSigned() && Value.isNegative()) {
11421     if (FieldName)
11422       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11423                << FieldName << Value.toString(10);
11424     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11425       << Value.toString(10);
11426   }
11427 
11428   if (!FieldTy->isDependentType()) {
11429     uint64_t TypeSize = Context.getTypeSize(FieldTy);
11430     if (Value.getZExtValue() > TypeSize) {
11431       if (!getLangOpts().CPlusPlus || IsMsStruct ||
11432           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11433         if (FieldName)
11434           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11435             << FieldName << (unsigned)Value.getZExtValue()
11436             << (unsigned)TypeSize;
11437 
11438         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11439           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11440       }
11441 
11442       if (FieldName)
11443         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11444           << FieldName << (unsigned)Value.getZExtValue()
11445           << (unsigned)TypeSize;
11446       else
11447         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11448           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11449     }
11450   }
11451 
11452   return Owned(BitWidth);
11453 }
11454 
11455 /// ActOnField - Each field of a C struct/union is passed into this in order
11456 /// to create a FieldDecl object for it.
11457 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11458                        Declarator &D, Expr *BitfieldWidth) {
11459   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11460                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11461                                /*InitStyle=*/ICIS_NoInit, AS_public);
11462   return Res;
11463 }
11464 
11465 /// HandleField - Analyze a field of a C struct or a C++ data member.
11466 ///
11467 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11468                              SourceLocation DeclStart,
11469                              Declarator &D, Expr *BitWidth,
11470                              InClassInitStyle InitStyle,
11471                              AccessSpecifier AS) {
11472   IdentifierInfo *II = D.getIdentifier();
11473   SourceLocation Loc = DeclStart;
11474   if (II) Loc = D.getIdentifierLoc();
11475 
11476   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11477   QualType T = TInfo->getType();
11478   if (getLangOpts().CPlusPlus) {
11479     CheckExtraCXXDefaultArguments(D);
11480 
11481     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11482                                         UPPC_DataMemberType)) {
11483       D.setInvalidType();
11484       T = Context.IntTy;
11485       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11486     }
11487   }
11488 
11489   // TR 18037 does not allow fields to be declared with address spaces.
11490   if (T.getQualifiers().hasAddressSpace()) {
11491     Diag(Loc, diag::err_field_with_address_space);
11492     D.setInvalidType();
11493   }
11494 
11495   // OpenCL 1.2 spec, s6.9 r:
11496   // The event type cannot be used to declare a structure or union field.
11497   if (LangOpts.OpenCL && T->isEventT()) {
11498     Diag(Loc, diag::err_event_t_struct_field);
11499     D.setInvalidType();
11500   }
11501 
11502   DiagnoseFunctionSpecifiers(D.getDeclSpec());
11503 
11504   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11505     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11506          diag::err_invalid_thread)
11507       << DeclSpec::getSpecifierName(TSCS);
11508 
11509   // Check to see if this name was declared as a member previously
11510   NamedDecl *PrevDecl = 0;
11511   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11512   LookupName(Previous, S);
11513   switch (Previous.getResultKind()) {
11514     case LookupResult::Found:
11515     case LookupResult::FoundUnresolvedValue:
11516       PrevDecl = Previous.getAsSingle<NamedDecl>();
11517       break;
11518 
11519     case LookupResult::FoundOverloaded:
11520       PrevDecl = Previous.getRepresentativeDecl();
11521       break;
11522 
11523     case LookupResult::NotFound:
11524     case LookupResult::NotFoundInCurrentInstantiation:
11525     case LookupResult::Ambiguous:
11526       break;
11527   }
11528   Previous.suppressDiagnostics();
11529 
11530   if (PrevDecl && PrevDecl->isTemplateParameter()) {
11531     // Maybe we will complain about the shadowed template parameter.
11532     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11533     // Just pretend that we didn't see the previous declaration.
11534     PrevDecl = 0;
11535   }
11536 
11537   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11538     PrevDecl = 0;
11539 
11540   bool Mutable
11541     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
11542   SourceLocation TSSL = D.getLocStart();
11543   FieldDecl *NewFD
11544     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
11545                      TSSL, AS, PrevDecl, &D);
11546 
11547   if (NewFD->isInvalidDecl())
11548     Record->setInvalidDecl();
11549 
11550   if (D.getDeclSpec().isModulePrivateSpecified())
11551     NewFD->setModulePrivate();
11552 
11553   if (NewFD->isInvalidDecl() && PrevDecl) {
11554     // Don't introduce NewFD into scope; there's already something
11555     // with the same name in the same scope.
11556   } else if (II) {
11557     PushOnScopeChains(NewFD, S);
11558   } else
11559     Record->addDecl(NewFD);
11560 
11561   return NewFD;
11562 }
11563 
11564 /// \brief Build a new FieldDecl and check its well-formedness.
11565 ///
11566 /// This routine builds a new FieldDecl given the fields name, type,
11567 /// record, etc. \p PrevDecl should refer to any previous declaration
11568 /// with the same name and in the same scope as the field to be
11569 /// created.
11570 ///
11571 /// \returns a new FieldDecl.
11572 ///
11573 /// \todo The Declarator argument is a hack. It will be removed once
11574 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
11575                                 TypeSourceInfo *TInfo,
11576                                 RecordDecl *Record, SourceLocation Loc,
11577                                 bool Mutable, Expr *BitWidth,
11578                                 InClassInitStyle InitStyle,
11579                                 SourceLocation TSSL,
11580                                 AccessSpecifier AS, NamedDecl *PrevDecl,
11581                                 Declarator *D) {
11582   IdentifierInfo *II = Name.getAsIdentifierInfo();
11583   bool InvalidDecl = false;
11584   if (D) InvalidDecl = D->isInvalidType();
11585 
11586   // If we receive a broken type, recover by assuming 'int' and
11587   // marking this declaration as invalid.
11588   if (T.isNull()) {
11589     InvalidDecl = true;
11590     T = Context.IntTy;
11591   }
11592 
11593   QualType EltTy = Context.getBaseElementType(T);
11594   if (!EltTy->isDependentType()) {
11595     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11596       // Fields of incomplete type force their record to be invalid.
11597       Record->setInvalidDecl();
11598       InvalidDecl = true;
11599     } else {
11600       NamedDecl *Def;
11601       EltTy->isIncompleteType(&Def);
11602       if (Def && Def->isInvalidDecl()) {
11603         Record->setInvalidDecl();
11604         InvalidDecl = true;
11605       }
11606     }
11607   }
11608 
11609   // OpenCL v1.2 s6.9.c: bitfields are not supported.
11610   if (BitWidth && getLangOpts().OpenCL) {
11611     Diag(Loc, diag::err_opencl_bitfields);
11612     InvalidDecl = true;
11613   }
11614 
11615   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11616   // than a variably modified type.
11617   if (!InvalidDecl && T->isVariablyModifiedType()) {
11618     bool SizeIsNegative;
11619     llvm::APSInt Oversized;
11620 
11621     TypeSourceInfo *FixedTInfo =
11622       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11623                                                     SizeIsNegative,
11624                                                     Oversized);
11625     if (FixedTInfo) {
11626       Diag(Loc, diag::warn_illegal_constant_array_size);
11627       TInfo = FixedTInfo;
11628       T = FixedTInfo->getType();
11629     } else {
11630       if (SizeIsNegative)
11631         Diag(Loc, diag::err_typecheck_negative_array_size);
11632       else if (Oversized.getBoolValue())
11633         Diag(Loc, diag::err_array_too_large)
11634           << Oversized.toString(10);
11635       else
11636         Diag(Loc, diag::err_typecheck_field_variable_size);
11637       InvalidDecl = true;
11638     }
11639   }
11640 
11641   // Fields can not have abstract class types
11642   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11643                                              diag::err_abstract_type_in_decl,
11644                                              AbstractFieldType))
11645     InvalidDecl = true;
11646 
11647   bool ZeroWidth = false;
11648   // If this is declared as a bit-field, check the bit-field.
11649   if (!InvalidDecl && BitWidth) {
11650     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11651                               &ZeroWidth).take();
11652     if (!BitWidth) {
11653       InvalidDecl = true;
11654       BitWidth = 0;
11655       ZeroWidth = false;
11656     }
11657   }
11658 
11659   // Check that 'mutable' is consistent with the type of the declaration.
11660   if (!InvalidDecl && Mutable) {
11661     unsigned DiagID = 0;
11662     if (T->isReferenceType())
11663       DiagID = diag::err_mutable_reference;
11664     else if (T.isConstQualified())
11665       DiagID = diag::err_mutable_const;
11666 
11667     if (DiagID) {
11668       SourceLocation ErrLoc = Loc;
11669       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11670         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11671       Diag(ErrLoc, DiagID);
11672       Mutable = false;
11673       InvalidDecl = true;
11674     }
11675   }
11676 
11677   // C++11 [class.union]p8 (DR1460):
11678   //   At most one variant member of a union may have a
11679   //   brace-or-equal-initializer.
11680   if (InitStyle != ICIS_NoInit)
11681     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11682 
11683   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
11684                                        BitWidth, Mutable, InitStyle);
11685   if (InvalidDecl)
11686     NewFD->setInvalidDecl();
11687 
11688   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11689     Diag(Loc, diag::err_duplicate_member) << II;
11690     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11691     NewFD->setInvalidDecl();
11692   }
11693 
11694   if (!InvalidDecl && getLangOpts().CPlusPlus) {
11695     if (Record->isUnion()) {
11696       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11697         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11698         if (RDecl->getDefinition()) {
11699           // C++ [class.union]p1: An object of a class with a non-trivial
11700           // constructor, a non-trivial copy constructor, a non-trivial
11701           // destructor, or a non-trivial copy assignment operator
11702           // cannot be a member of a union, nor can an array of such
11703           // objects.
11704           if (CheckNontrivialField(NewFD))
11705             NewFD->setInvalidDecl();
11706         }
11707       }
11708 
11709       // C++ [class.union]p1: If a union contains a member of reference type,
11710       // the program is ill-formed, except when compiling with MSVC extensions
11711       // enabled.
11712       if (EltTy->isReferenceType()) {
11713         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11714                                     diag::ext_union_member_of_reference_type :
11715                                     diag::err_union_member_of_reference_type)
11716           << NewFD->getDeclName() << EltTy;
11717         if (!getLangOpts().MicrosoftExt)
11718           NewFD->setInvalidDecl();
11719       }
11720     }
11721   }
11722 
11723   // FIXME: We need to pass in the attributes given an AST
11724   // representation, not a parser representation.
11725   if (D) {
11726     // FIXME: The current scope is almost... but not entirely... correct here.
11727     ProcessDeclAttributes(getCurScope(), NewFD, *D);
11728 
11729     if (NewFD->hasAttrs())
11730       CheckAlignasUnderalignment(NewFD);
11731   }
11732 
11733   // In auto-retain/release, infer strong retension for fields of
11734   // retainable type.
11735   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
11736     NewFD->setInvalidDecl();
11737 
11738   if (T.isObjCGCWeak())
11739     Diag(Loc, diag::warn_attribute_weak_on_field);
11740 
11741   NewFD->setAccess(AS);
11742   return NewFD;
11743 }
11744 
11745 bool Sema::CheckNontrivialField(FieldDecl *FD) {
11746   assert(FD);
11747   assert(getLangOpts().CPlusPlus && "valid check only for C++");
11748 
11749   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11750     return false;
11751 
11752   QualType EltTy = Context.getBaseElementType(FD->getType());
11753   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11754     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
11755     if (RDecl->getDefinition()) {
11756       // We check for copy constructors before constructors
11757       // because otherwise we'll never get complaints about
11758       // copy constructors.
11759 
11760       CXXSpecialMember member = CXXInvalid;
11761       // We're required to check for any non-trivial constructors. Since the
11762       // implicit default constructor is suppressed if there are any
11763       // user-declared constructors, we just need to check that there is a
11764       // trivial default constructor and a trivial copy constructor. (We don't
11765       // worry about move constructors here, since this is a C++98 check.)
11766       if (RDecl->hasNonTrivialCopyConstructor())
11767         member = CXXCopyConstructor;
11768       else if (!RDecl->hasTrivialDefaultConstructor())
11769         member = CXXDefaultConstructor;
11770       else if (RDecl->hasNonTrivialCopyAssignment())
11771         member = CXXCopyAssignment;
11772       else if (RDecl->hasNonTrivialDestructor())
11773         member = CXXDestructor;
11774 
11775       if (member != CXXInvalid) {
11776         if (!getLangOpts().CPlusPlus11 &&
11777             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
11778           // Objective-C++ ARC: it is an error to have a non-trivial field of
11779           // a union. However, system headers in Objective-C programs
11780           // occasionally have Objective-C lifetime objects within unions,
11781           // and rather than cause the program to fail, we make those
11782           // members unavailable.
11783           SourceLocation Loc = FD->getLocation();
11784           if (getSourceManager().isInSystemHeader(Loc)) {
11785             if (!FD->hasAttr<UnavailableAttr>())
11786               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11787                                   "this system field has retaining ownership",
11788                                   Loc));
11789             return false;
11790           }
11791         }
11792 
11793         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
11794                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11795                diag::err_illegal_union_or_anon_struct_member)
11796           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
11797         DiagnoseNontrivial(RDecl, member);
11798         return !getLangOpts().CPlusPlus11;
11799       }
11800     }
11801   }
11802 
11803   return false;
11804 }
11805 
11806 /// TranslateIvarVisibility - Translate visibility from a token ID to an
11807 ///  AST enum value.
11808 static ObjCIvarDecl::AccessControl
11809 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
11810   switch (ivarVisibility) {
11811   default: llvm_unreachable("Unknown visitibility kind");
11812   case tok::objc_private: return ObjCIvarDecl::Private;
11813   case tok::objc_public: return ObjCIvarDecl::Public;
11814   case tok::objc_protected: return ObjCIvarDecl::Protected;
11815   case tok::objc_package: return ObjCIvarDecl::Package;
11816   }
11817 }
11818 
11819 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
11820 /// in order to create an IvarDecl object for it.
11821 Decl *Sema::ActOnIvar(Scope *S,
11822                                 SourceLocation DeclStart,
11823                                 Declarator &D, Expr *BitfieldWidth,
11824                                 tok::ObjCKeywordKind Visibility) {
11825 
11826   IdentifierInfo *II = D.getIdentifier();
11827   Expr *BitWidth = (Expr*)BitfieldWidth;
11828   SourceLocation Loc = DeclStart;
11829   if (II) Loc = D.getIdentifierLoc();
11830 
11831   // FIXME: Unnamed fields can be handled in various different ways, for
11832   // example, unnamed unions inject all members into the struct namespace!
11833 
11834   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11835   QualType T = TInfo->getType();
11836 
11837   if (BitWidth) {
11838     // 6.7.2.1p3, 6.7.2.1p4
11839     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
11840     if (!BitWidth)
11841       D.setInvalidType();
11842   } else {
11843     // Not a bitfield.
11844 
11845     // validate II.
11846 
11847   }
11848   if (T->isReferenceType()) {
11849     Diag(Loc, diag::err_ivar_reference_type);
11850     D.setInvalidType();
11851   }
11852   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11853   // than a variably modified type.
11854   else if (T->isVariablyModifiedType()) {
11855     Diag(Loc, diag::err_typecheck_ivar_variable_size);
11856     D.setInvalidType();
11857   }
11858 
11859   // Get the visibility (access control) for this ivar.
11860   ObjCIvarDecl::AccessControl ac =
11861     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11862                                         : ObjCIvarDecl::None;
11863   // Must set ivar's DeclContext to its enclosing interface.
11864   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
11865   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11866     return 0;
11867   ObjCContainerDecl *EnclosingContext;
11868   if (ObjCImplementationDecl *IMPDecl =
11869       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11870     if (LangOpts.ObjCRuntime.isFragile()) {
11871     // Case of ivar declared in an implementation. Context is that of its class.
11872       EnclosingContext = IMPDecl->getClassInterface();
11873       assert(EnclosingContext && "Implementation has no class interface!");
11874     }
11875     else
11876       EnclosingContext = EnclosingDecl;
11877   } else {
11878     if (ObjCCategoryDecl *CDecl =
11879         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11880       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
11881         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
11882         return 0;
11883       }
11884     }
11885     EnclosingContext = EnclosingDecl;
11886   }
11887 
11888   // Construct the decl.
11889   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11890                                              DeclStart, Loc, II, T,
11891                                              TInfo, ac, (Expr *)BitfieldWidth);
11892 
11893   if (II) {
11894     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
11895                                            ForRedeclaration);
11896     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
11897         && !isa<TagDecl>(PrevDecl)) {
11898       Diag(Loc, diag::err_duplicate_member) << II;
11899       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11900       NewID->setInvalidDecl();
11901     }
11902   }
11903 
11904   // Process attributes attached to the ivar.
11905   ProcessDeclAttributes(S, NewID, D);
11906 
11907   if (D.isInvalidType())
11908     NewID->setInvalidDecl();
11909 
11910   // In ARC, infer 'retaining' for ivars of retainable type.
11911   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
11912     NewID->setInvalidDecl();
11913 
11914   if (D.getDeclSpec().isModulePrivateSpecified())
11915     NewID->setModulePrivate();
11916 
11917   if (II) {
11918     // FIXME: When interfaces are DeclContexts, we'll need to add
11919     // these to the interface.
11920     S->AddDecl(NewID);
11921     IdResolver.AddDecl(NewID);
11922   }
11923 
11924   if (LangOpts.ObjCRuntime.isNonFragile() &&
11925       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
11926     Diag(Loc, diag::warn_ivars_in_interface);
11927 
11928   return NewID;
11929 }
11930 
11931 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
11932 /// class and class extensions. For every class \@interface and class
11933 /// extension \@interface, if the last ivar is a bitfield of any type,
11934 /// then add an implicit `char :0` ivar to the end of that interface.
11935 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
11936                              SmallVectorImpl<Decl *> &AllIvarDecls) {
11937   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
11938     return;
11939 
11940   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11941   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11942 
11943   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
11944     return;
11945   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
11946   if (!ID) {
11947     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
11948       if (!CD->IsClassExtension())
11949         return;
11950     }
11951     // No need to add this to end of @implementation.
11952     else
11953       return;
11954   }
11955   // All conditions are met. Add a new bitfield to the tail end of ivars.
11956   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11957   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
11958 
11959   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
11960                               DeclLoc, DeclLoc, 0,
11961                               Context.CharTy,
11962                               Context.getTrivialTypeSourceInfo(Context.CharTy,
11963                                                                DeclLoc),
11964                               ObjCIvarDecl::Private, BW,
11965                               true);
11966   AllIvarDecls.push_back(Ivar);
11967 }
11968 
11969 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11970                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
11971                        SourceLocation RBrac, AttributeList *Attr) {
11972   assert(EnclosingDecl && "missing record or interface decl");
11973 
11974   // If this is an Objective-C @implementation or category and we have
11975   // new fields here we should reset the layout of the interface since
11976   // it will now change.
11977   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11978     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11979     switch (DC->getKind()) {
11980     default: break;
11981     case Decl::ObjCCategory:
11982       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11983       break;
11984     case Decl::ObjCImplementation:
11985       Context.
11986         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11987       break;
11988     }
11989   }
11990 
11991   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11992 
11993   // Start counting up the number of named members; make sure to include
11994   // members of anonymous structs and unions in the total.
11995   unsigned NumNamedMembers = 0;
11996   if (Record) {
11997     for (const auto *I : Record->decls()) {
11998       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
11999         if (IFD->getDeclName())
12000           ++NumNamedMembers;
12001     }
12002   }
12003 
12004   // Verify that all the fields are okay.
12005   SmallVector<FieldDecl*, 32> RecFields;
12006 
12007   bool ARCErrReported = false;
12008   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
12009        i != end; ++i) {
12010     FieldDecl *FD = cast<FieldDecl>(*i);
12011 
12012     // Get the type for the field.
12013     const Type *FDTy = FD->getType().getTypePtr();
12014 
12015     if (!FD->isAnonymousStructOrUnion()) {
12016       // Remember all fields written by the user.
12017       RecFields.push_back(FD);
12018     }
12019 
12020     // If the field is already invalid for some reason, don't emit more
12021     // diagnostics about it.
12022     if (FD->isInvalidDecl()) {
12023       EnclosingDecl->setInvalidDecl();
12024       continue;
12025     }
12026 
12027     // C99 6.7.2.1p2:
12028     //   A structure or union shall not contain a member with
12029     //   incomplete or function type (hence, a structure shall not
12030     //   contain an instance of itself, but may contain a pointer to
12031     //   an instance of itself), except that the last member of a
12032     //   structure with more than one named member may have incomplete
12033     //   array type; such a structure (and any union containing,
12034     //   possibly recursively, a member that is such a structure)
12035     //   shall not be a member of a structure or an element of an
12036     //   array.
12037     if (FDTy->isFunctionType()) {
12038       // Field declared as a function.
12039       Diag(FD->getLocation(), diag::err_field_declared_as_function)
12040         << FD->getDeclName();
12041       FD->setInvalidDecl();
12042       EnclosingDecl->setInvalidDecl();
12043       continue;
12044     } else if (FDTy->isIncompleteArrayType() && Record &&
12045                ((i + 1 == Fields.end() && !Record->isUnion()) ||
12046                 ((getLangOpts().MicrosoftExt ||
12047                   getLangOpts().CPlusPlus) &&
12048                  (i + 1 == Fields.end() || Record->isUnion())))) {
12049       // Flexible array member.
12050       // Microsoft and g++ is more permissive regarding flexible array.
12051       // It will accept flexible array in union and also
12052       // as the sole element of a struct/class.
12053       unsigned DiagID = 0;
12054       if (Record->isUnion())
12055         DiagID = getLangOpts().MicrosoftExt
12056                      ? diag::ext_flexible_array_union_ms
12057                      : getLangOpts().CPlusPlus
12058                            ? diag::ext_flexible_array_union_gnu
12059                            : diag::err_flexible_array_union;
12060       else if (Fields.size() == 1)
12061         DiagID = getLangOpts().MicrosoftExt
12062                      ? diag::ext_flexible_array_empty_aggregate_ms
12063                      : getLangOpts().CPlusPlus
12064                            ? diag::ext_flexible_array_empty_aggregate_gnu
12065                            : NumNamedMembers < 1
12066                                  ? diag::err_flexible_array_empty_aggregate
12067                                  : 0;
12068 
12069       if (DiagID)
12070         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
12071                                         << Record->getTagKind();
12072       // While the layout of types that contain virtual bases is not specified
12073       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
12074       // virtual bases after the derived members.  This would make a flexible
12075       // array member declared at the end of an object not adjacent to the end
12076       // of the type.
12077       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
12078         if (RD->getNumVBases() != 0)
12079           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
12080             << FD->getDeclName() << Record->getTagKind();
12081       if (!getLangOpts().C99)
12082         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
12083           << FD->getDeclName() << Record->getTagKind();
12084 
12085       // If the element type has a non-trivial destructor, we would not
12086       // implicitly destroy the elements, so disallow it for now.
12087       //
12088       // FIXME: GCC allows this. We should probably either implicitly delete
12089       // the destructor of the containing class, or just allow this.
12090       QualType BaseElem = Context.getBaseElementType(FD->getType());
12091       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
12092         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
12093           << FD->getDeclName() << FD->getType();
12094         FD->setInvalidDecl();
12095         EnclosingDecl->setInvalidDecl();
12096         continue;
12097       }
12098       // Okay, we have a legal flexible array member at the end of the struct.
12099       if (Record)
12100         Record->setHasFlexibleArrayMember(true);
12101     } else if (!FDTy->isDependentType() &&
12102                RequireCompleteType(FD->getLocation(), FD->getType(),
12103                                    diag::err_field_incomplete)) {
12104       // Incomplete type
12105       FD->setInvalidDecl();
12106       EnclosingDecl->setInvalidDecl();
12107       continue;
12108     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
12109       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
12110         // If this is a member of a union, then entire union becomes "flexible".
12111         if (Record && Record->isUnion()) {
12112           Record->setHasFlexibleArrayMember(true);
12113         } else {
12114           // If this is a struct/class and this is not the last element, reject
12115           // it.  Note that GCC supports variable sized arrays in the middle of
12116           // structures.
12117           if (i + 1 != Fields.end())
12118             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12119               << FD->getDeclName() << FD->getType();
12120           else {
12121             // We support flexible arrays at the end of structs in
12122             // other structs as an extension.
12123             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12124               << FD->getDeclName();
12125             if (Record)
12126               Record->setHasFlexibleArrayMember(true);
12127           }
12128         }
12129       }
12130       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12131           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12132                                  diag::err_abstract_type_in_decl,
12133                                  AbstractIvarType)) {
12134         // Ivars can not have abstract class types
12135         FD->setInvalidDecl();
12136       }
12137       if (Record && FDTTy->getDecl()->hasObjectMember())
12138         Record->setHasObjectMember(true);
12139       if (Record && FDTTy->getDecl()->hasVolatileMember())
12140         Record->setHasVolatileMember(true);
12141     } else if (FDTy->isObjCObjectType()) {
12142       /// A field cannot be an Objective-c object
12143       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12144         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12145       QualType T = Context.getObjCObjectPointerType(FD->getType());
12146       FD->setType(T);
12147     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12148                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12149       // It's an error in ARC if a field has lifetime.
12150       // We don't want to report this in a system header, though,
12151       // so we just make the field unavailable.
12152       // FIXME: that's really not sufficient; we need to make the type
12153       // itself invalid to, say, initialize or copy.
12154       QualType T = FD->getType();
12155       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12156       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12157         SourceLocation loc = FD->getLocation();
12158         if (getSourceManager().isInSystemHeader(loc)) {
12159           if (!FD->hasAttr<UnavailableAttr>()) {
12160             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12161                               "this system field has retaining ownership",
12162                               loc));
12163           }
12164         } else {
12165           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12166             << T->isBlockPointerType() << Record->getTagKind();
12167         }
12168         ARCErrReported = true;
12169       }
12170     } else if (getLangOpts().ObjC1 &&
12171                getLangOpts().getGC() != LangOptions::NonGC &&
12172                Record && !Record->hasObjectMember()) {
12173       if (FD->getType()->isObjCObjectPointerType() ||
12174           FD->getType().isObjCGCStrong())
12175         Record->setHasObjectMember(true);
12176       else if (Context.getAsArrayType(FD->getType())) {
12177         QualType BaseType = Context.getBaseElementType(FD->getType());
12178         if (BaseType->isRecordType() &&
12179             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12180           Record->setHasObjectMember(true);
12181         else if (BaseType->isObjCObjectPointerType() ||
12182                  BaseType.isObjCGCStrong())
12183                Record->setHasObjectMember(true);
12184       }
12185     }
12186     if (Record && FD->getType().isVolatileQualified())
12187       Record->setHasVolatileMember(true);
12188     // Keep track of the number of named members.
12189     if (FD->getIdentifier())
12190       ++NumNamedMembers;
12191   }
12192 
12193   // Okay, we successfully defined 'Record'.
12194   if (Record) {
12195     bool Completed = false;
12196     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12197       if (!CXXRecord->isInvalidDecl()) {
12198         // Set access bits correctly on the directly-declared conversions.
12199         for (CXXRecordDecl::conversion_iterator
12200                I = CXXRecord->conversion_begin(),
12201                E = CXXRecord->conversion_end(); I != E; ++I)
12202           I.setAccess((*I)->getAccess());
12203 
12204         if (!CXXRecord->isDependentType()) {
12205           if (CXXRecord->hasUserDeclaredDestructor()) {
12206             // Adjust user-defined destructor exception spec.
12207             if (getLangOpts().CPlusPlus11)
12208               AdjustDestructorExceptionSpec(CXXRecord,
12209                                             CXXRecord->getDestructor());
12210           }
12211 
12212           // Add any implicitly-declared members to this class.
12213           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12214 
12215           // If we have virtual base classes, we may end up finding multiple
12216           // final overriders for a given virtual function. Check for this
12217           // problem now.
12218           if (CXXRecord->getNumVBases()) {
12219             CXXFinalOverriderMap FinalOverriders;
12220             CXXRecord->getFinalOverriders(FinalOverriders);
12221 
12222             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12223                                              MEnd = FinalOverriders.end();
12224                  M != MEnd; ++M) {
12225               for (OverridingMethods::iterator SO = M->second.begin(),
12226                                             SOEnd = M->second.end();
12227                    SO != SOEnd; ++SO) {
12228                 assert(SO->second.size() > 0 &&
12229                        "Virtual function without overridding functions?");
12230                 if (SO->second.size() == 1)
12231                   continue;
12232 
12233                 // C++ [class.virtual]p2:
12234                 //   In a derived class, if a virtual member function of a base
12235                 //   class subobject has more than one final overrider the
12236                 //   program is ill-formed.
12237                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12238                   << (const NamedDecl *)M->first << Record;
12239                 Diag(M->first->getLocation(),
12240                      diag::note_overridden_virtual_function);
12241                 for (OverridingMethods::overriding_iterator
12242                           OM = SO->second.begin(),
12243                        OMEnd = SO->second.end();
12244                      OM != OMEnd; ++OM)
12245                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12246                     << (const NamedDecl *)M->first << OM->Method->getParent();
12247 
12248                 Record->setInvalidDecl();
12249               }
12250             }
12251             CXXRecord->completeDefinition(&FinalOverriders);
12252             Completed = true;
12253           }
12254         }
12255       }
12256     }
12257 
12258     if (!Completed)
12259       Record->completeDefinition();
12260 
12261     if (Record->hasAttrs()) {
12262       CheckAlignasUnderalignment(Record);
12263 
12264       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12265         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12266                                            IA->getRange(), IA->getBestCase(),
12267                                            IA->getSemanticSpelling());
12268     }
12269 
12270     // Check if the structure/union declaration is a type that can have zero
12271     // size in C. For C this is a language extension, for C++ it may cause
12272     // compatibility problems.
12273     bool CheckForZeroSize;
12274     if (!getLangOpts().CPlusPlus) {
12275       CheckForZeroSize = true;
12276     } else {
12277       // For C++ filter out types that cannot be referenced in C code.
12278       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12279       CheckForZeroSize =
12280           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12281           !CXXRecord->isDependentType() &&
12282           CXXRecord->isCLike();
12283     }
12284     if (CheckForZeroSize) {
12285       bool ZeroSize = true;
12286       bool IsEmpty = true;
12287       unsigned NonBitFields = 0;
12288       for (RecordDecl::field_iterator I = Record->field_begin(),
12289                                       E = Record->field_end();
12290            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12291         IsEmpty = false;
12292         if (I->isUnnamedBitfield()) {
12293           if (I->getBitWidthValue(Context) > 0)
12294             ZeroSize = false;
12295         } else {
12296           ++NonBitFields;
12297           QualType FieldType = I->getType();
12298           if (FieldType->isIncompleteType() ||
12299               !Context.getTypeSizeInChars(FieldType).isZero())
12300             ZeroSize = false;
12301         }
12302       }
12303 
12304       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12305       // allowed in C++, but warn if its declaration is inside
12306       // extern "C" block.
12307       if (ZeroSize) {
12308         Diag(RecLoc, getLangOpts().CPlusPlus ?
12309                          diag::warn_zero_size_struct_union_in_extern_c :
12310                          diag::warn_zero_size_struct_union_compat)
12311           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12312       }
12313 
12314       // Structs without named members are extension in C (C99 6.7.2.1p7),
12315       // but are accepted by GCC.
12316       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12317         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12318                                diag::ext_no_named_members_in_struct_union)
12319           << Record->isUnion();
12320       }
12321     }
12322   } else {
12323     ObjCIvarDecl **ClsFields =
12324       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12325     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12326       ID->setEndOfDefinitionLoc(RBrac);
12327       // Add ivar's to class's DeclContext.
12328       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12329         ClsFields[i]->setLexicalDeclContext(ID);
12330         ID->addDecl(ClsFields[i]);
12331       }
12332       // Must enforce the rule that ivars in the base classes may not be
12333       // duplicates.
12334       if (ID->getSuperClass())
12335         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12336     } else if (ObjCImplementationDecl *IMPDecl =
12337                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12338       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12339       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12340         // Ivar declared in @implementation never belongs to the implementation.
12341         // Only it is in implementation's lexical context.
12342         ClsFields[I]->setLexicalDeclContext(IMPDecl);
12343       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12344       IMPDecl->setIvarLBraceLoc(LBrac);
12345       IMPDecl->setIvarRBraceLoc(RBrac);
12346     } else if (ObjCCategoryDecl *CDecl =
12347                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12348       // case of ivars in class extension; all other cases have been
12349       // reported as errors elsewhere.
12350       // FIXME. Class extension does not have a LocEnd field.
12351       // CDecl->setLocEnd(RBrac);
12352       // Add ivar's to class extension's DeclContext.
12353       // Diagnose redeclaration of private ivars.
12354       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
12355       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12356         if (IDecl) {
12357           if (const ObjCIvarDecl *ClsIvar =
12358               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12359             Diag(ClsFields[i]->getLocation(),
12360                  diag::err_duplicate_ivar_declaration);
12361             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12362             continue;
12363           }
12364           for (const auto *Ext : IDecl->known_extensions()) {
12365             if (const ObjCIvarDecl *ClsExtIvar
12366                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
12367               Diag(ClsFields[i]->getLocation(),
12368                    diag::err_duplicate_ivar_declaration);
12369               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12370               continue;
12371             }
12372           }
12373         }
12374         ClsFields[i]->setLexicalDeclContext(CDecl);
12375         CDecl->addDecl(ClsFields[i]);
12376       }
12377       CDecl->setIvarLBraceLoc(LBrac);
12378       CDecl->setIvarRBraceLoc(RBrac);
12379     }
12380   }
12381 
12382   if (Attr)
12383     ProcessDeclAttributeList(S, Record, Attr);
12384 }
12385 
12386 /// \brief Determine whether the given integral value is representable within
12387 /// the given type T.
12388 static bool isRepresentableIntegerValue(ASTContext &Context,
12389                                         llvm::APSInt &Value,
12390                                         QualType T) {
12391   assert(T->isIntegralType(Context) && "Integral type required!");
12392   unsigned BitWidth = Context.getIntWidth(T);
12393 
12394   if (Value.isUnsigned() || Value.isNonNegative()) {
12395     if (T->isSignedIntegerOrEnumerationType())
12396       --BitWidth;
12397     return Value.getActiveBits() <= BitWidth;
12398   }
12399   return Value.getMinSignedBits() <= BitWidth;
12400 }
12401 
12402 // \brief Given an integral type, return the next larger integral type
12403 // (or a NULL type of no such type exists).
12404 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12405   // FIXME: Int128/UInt128 support, which also needs to be introduced into
12406   // enum checking below.
12407   assert(T->isIntegralType(Context) && "Integral type required!");
12408   const unsigned NumTypes = 4;
12409   QualType SignedIntegralTypes[NumTypes] = {
12410     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12411   };
12412   QualType UnsignedIntegralTypes[NumTypes] = {
12413     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12414     Context.UnsignedLongLongTy
12415   };
12416 
12417   unsigned BitWidth = Context.getTypeSize(T);
12418   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12419                                                         : UnsignedIntegralTypes;
12420   for (unsigned I = 0; I != NumTypes; ++I)
12421     if (Context.getTypeSize(Types[I]) > BitWidth)
12422       return Types[I];
12423 
12424   return QualType();
12425 }
12426 
12427 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12428                                           EnumConstantDecl *LastEnumConst,
12429                                           SourceLocation IdLoc,
12430                                           IdentifierInfo *Id,
12431                                           Expr *Val) {
12432   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12433   llvm::APSInt EnumVal(IntWidth);
12434   QualType EltTy;
12435 
12436   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12437     Val = 0;
12438 
12439   if (Val)
12440     Val = DefaultLvalueConversion(Val).take();
12441 
12442   if (Val) {
12443     if (Enum->isDependentType() || Val->isTypeDependent())
12444       EltTy = Context.DependentTy;
12445     else {
12446       SourceLocation ExpLoc;
12447       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12448           !getLangOpts().MSVCCompat) {
12449         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12450         // constant-expression in the enumerator-definition shall be a converted
12451         // constant expression of the underlying type.
12452         EltTy = Enum->getIntegerType();
12453         ExprResult Converted =
12454           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12455                                            CCEK_Enumerator);
12456         if (Converted.isInvalid())
12457           Val = 0;
12458         else
12459           Val = Converted.take();
12460       } else if (!Val->isValueDependent() &&
12461                  !(Val = VerifyIntegerConstantExpression(Val,
12462                                                          &EnumVal).take())) {
12463         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12464       } else {
12465         if (Enum->isFixed()) {
12466           EltTy = Enum->getIntegerType();
12467 
12468           // In Obj-C and Microsoft mode, require the enumeration value to be
12469           // representable in the underlying type of the enumeration. In C++11,
12470           // we perform a non-narrowing conversion as part of converted constant
12471           // expression checking.
12472           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12473             if (getLangOpts().MSVCCompat) {
12474               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12475               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12476             } else
12477               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12478           } else
12479             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12480         } else if (getLangOpts().CPlusPlus) {
12481           // C++11 [dcl.enum]p5:
12482           //   If the underlying type is not fixed, the type of each enumerator
12483           //   is the type of its initializing value:
12484           //     - If an initializer is specified for an enumerator, the
12485           //       initializing value has the same type as the expression.
12486           EltTy = Val->getType();
12487         } else {
12488           // C99 6.7.2.2p2:
12489           //   The expression that defines the value of an enumeration constant
12490           //   shall be an integer constant expression that has a value
12491           //   representable as an int.
12492 
12493           // Complain if the value is not representable in an int.
12494           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12495             Diag(IdLoc, diag::ext_enum_value_not_int)
12496               << EnumVal.toString(10) << Val->getSourceRange()
12497               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12498           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12499             // Force the type of the expression to 'int'.
12500             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12501           }
12502           EltTy = Val->getType();
12503         }
12504       }
12505     }
12506   }
12507 
12508   if (!Val) {
12509     if (Enum->isDependentType())
12510       EltTy = Context.DependentTy;
12511     else if (!LastEnumConst) {
12512       // C++0x [dcl.enum]p5:
12513       //   If the underlying type is not fixed, the type of each enumerator
12514       //   is the type of its initializing value:
12515       //     - If no initializer is specified for the first enumerator, the
12516       //       initializing value has an unspecified integral type.
12517       //
12518       // GCC uses 'int' for its unspecified integral type, as does
12519       // C99 6.7.2.2p3.
12520       if (Enum->isFixed()) {
12521         EltTy = Enum->getIntegerType();
12522       }
12523       else {
12524         EltTy = Context.IntTy;
12525       }
12526     } else {
12527       // Assign the last value + 1.
12528       EnumVal = LastEnumConst->getInitVal();
12529       ++EnumVal;
12530       EltTy = LastEnumConst->getType();
12531 
12532       // Check for overflow on increment.
12533       if (EnumVal < LastEnumConst->getInitVal()) {
12534         // C++0x [dcl.enum]p5:
12535         //   If the underlying type is not fixed, the type of each enumerator
12536         //   is the type of its initializing value:
12537         //
12538         //     - Otherwise the type of the initializing value is the same as
12539         //       the type of the initializing value of the preceding enumerator
12540         //       unless the incremented value is not representable in that type,
12541         //       in which case the type is an unspecified integral type
12542         //       sufficient to contain the incremented value. If no such type
12543         //       exists, the program is ill-formed.
12544         QualType T = getNextLargerIntegralType(Context, EltTy);
12545         if (T.isNull() || Enum->isFixed()) {
12546           // There is no integral type larger enough to represent this
12547           // value. Complain, then allow the value to wrap around.
12548           EnumVal = LastEnumConst->getInitVal();
12549           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
12550           ++EnumVal;
12551           if (Enum->isFixed())
12552             // When the underlying type is fixed, this is ill-formed.
12553             Diag(IdLoc, diag::err_enumerator_wrapped)
12554               << EnumVal.toString(10)
12555               << EltTy;
12556           else
12557             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
12558               << EnumVal.toString(10);
12559         } else {
12560           EltTy = T;
12561         }
12562 
12563         // Retrieve the last enumerator's value, extent that type to the
12564         // type that is supposed to be large enough to represent the incremented
12565         // value, then increment.
12566         EnumVal = LastEnumConst->getInitVal();
12567         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12568         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
12569         ++EnumVal;
12570 
12571         // If we're not in C++, diagnose the overflow of enumerator values,
12572         // which in C99 means that the enumerator value is not representable in
12573         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12574         // permits enumerator values that are representable in some larger
12575         // integral type.
12576         if (!getLangOpts().CPlusPlus && !T.isNull())
12577           Diag(IdLoc, diag::warn_enum_value_overflow);
12578       } else if (!getLangOpts().CPlusPlus &&
12579                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12580         // Enforce C99 6.7.2.2p2 even when we compute the next value.
12581         Diag(IdLoc, diag::ext_enum_value_not_int)
12582           << EnumVal.toString(10) << 1;
12583       }
12584     }
12585   }
12586 
12587   if (!EltTy->isDependentType()) {
12588     // Make the enumerator value match the signedness and size of the
12589     // enumerator's type.
12590     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
12591     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12592   }
12593 
12594   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
12595                                   Val, EnumVal);
12596 }
12597 
12598 
12599 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12600                               SourceLocation IdLoc, IdentifierInfo *Id,
12601                               AttributeList *Attr,
12602                               SourceLocation EqualLoc, Expr *Val) {
12603   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
12604   EnumConstantDecl *LastEnumConst =
12605     cast_or_null<EnumConstantDecl>(lastEnumConst);
12606 
12607   // The scope passed in may not be a decl scope.  Zip up the scope tree until
12608   // we find one that is.
12609   S = getNonFieldDeclScope(S);
12610 
12611   // Verify that there isn't already something declared with this name in this
12612   // scope.
12613   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
12614                                          ForRedeclaration);
12615   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12616     // Maybe we will complain about the shadowed template parameter.
12617     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12618     // Just pretend that we didn't see the previous declaration.
12619     PrevDecl = 0;
12620   }
12621 
12622   if (PrevDecl) {
12623     // When in C++, we may get a TagDecl with the same name; in this case the
12624     // enum constant will 'hide' the tag.
12625     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
12626            "Received TagDecl when not in C++!");
12627     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
12628       if (isa<EnumConstantDecl>(PrevDecl))
12629         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
12630       else
12631         Diag(IdLoc, diag::err_redefinition) << Id;
12632       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12633       return 0;
12634     }
12635   }
12636 
12637   // C++ [class.mem]p15:
12638   // If T is the name of a class, then each of the following shall have a name
12639   // different from T:
12640   // - every enumerator of every member of class T that is an unscoped
12641   // enumerated type
12642   if (CXXRecordDecl *Record
12643                       = dyn_cast<CXXRecordDecl>(
12644                              TheEnumDecl->getDeclContext()->getRedeclContext()))
12645     if (!TheEnumDecl->isScoped() &&
12646         Record->getIdentifier() && Record->getIdentifier() == Id)
12647       Diag(IdLoc, diag::err_member_name_of_class) << Id;
12648 
12649   EnumConstantDecl *New =
12650     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
12651 
12652   if (New) {
12653     // Process attributes.
12654     if (Attr) ProcessDeclAttributeList(S, New, Attr);
12655 
12656     // Register this decl in the current scope stack.
12657     New->setAccess(TheEnumDecl->getAccess());
12658     PushOnScopeChains(New, S);
12659   }
12660 
12661   ActOnDocumentableDecl(New);
12662 
12663   return New;
12664 }
12665 
12666 // Returns true when the enum initial expression does not trigger the
12667 // duplicate enum warning.  A few common cases are exempted as follows:
12668 // Element2 = Element1
12669 // Element2 = Element1 + 1
12670 // Element2 = Element1 - 1
12671 // Where Element2 and Element1 are from the same enum.
12672 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12673   Expr *InitExpr = ECD->getInitExpr();
12674   if (!InitExpr)
12675     return true;
12676   InitExpr = InitExpr->IgnoreImpCasts();
12677 
12678   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12679     if (!BO->isAdditiveOp())
12680       return true;
12681     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12682     if (!IL)
12683       return true;
12684     if (IL->getValue() != 1)
12685       return true;
12686 
12687     InitExpr = BO->getLHS();
12688   }
12689 
12690   // This checks if the elements are from the same enum.
12691   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12692   if (!DRE)
12693     return true;
12694 
12695   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12696   if (!EnumConstant)
12697     return true;
12698 
12699   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12700       Enum)
12701     return true;
12702 
12703   return false;
12704 }
12705 
12706 struct DupKey {
12707   int64_t val;
12708   bool isTombstoneOrEmptyKey;
12709   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12710     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12711 };
12712 
12713 static DupKey GetDupKey(const llvm::APSInt& Val) {
12714   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12715                 false);
12716 }
12717 
12718 struct DenseMapInfoDupKey {
12719   static DupKey getEmptyKey() { return DupKey(0, true); }
12720   static DupKey getTombstoneKey() { return DupKey(1, true); }
12721   static unsigned getHashValue(const DupKey Key) {
12722     return (unsigned)(Key.val * 37);
12723   }
12724   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12725     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12726            LHS.val == RHS.val;
12727   }
12728 };
12729 
12730 // Emits a warning when an element is implicitly set a value that
12731 // a previous element has already been set to.
12732 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12733                                         EnumDecl *Enum,
12734                                         QualType EnumType) {
12735   if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12736                                  Enum->getLocation()) ==
12737       DiagnosticsEngine::Ignored)
12738     return;
12739   // Avoid anonymous enums
12740   if (!Enum->getIdentifier())
12741     return;
12742 
12743   // Only check for small enums.
12744   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12745     return;
12746 
12747   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12748   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
12749 
12750   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12751   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12752           ValueToVectorMap;
12753 
12754   DuplicatesVector DupVector;
12755   ValueToVectorMap EnumMap;
12756 
12757   // Populate the EnumMap with all values represented by enum constants without
12758   // an initialier.
12759   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12760     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12761 
12762     // Null EnumConstantDecl means a previous diagnostic has been emitted for
12763     // this constant.  Skip this enum since it may be ill-formed.
12764     if (!ECD) {
12765       return;
12766     }
12767 
12768     if (ECD->getInitExpr())
12769       continue;
12770 
12771     DupKey Key = GetDupKey(ECD->getInitVal());
12772     DeclOrVector &Entry = EnumMap[Key];
12773 
12774     // First time encountering this value.
12775     if (Entry.isNull())
12776       Entry = ECD;
12777   }
12778 
12779   // Create vectors for any values that has duplicates.
12780   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12781     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12782     if (!ValidDuplicateEnum(ECD, Enum))
12783       continue;
12784 
12785     DupKey Key = GetDupKey(ECD->getInitVal());
12786 
12787     DeclOrVector& Entry = EnumMap[Key];
12788     if (Entry.isNull())
12789       continue;
12790 
12791     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12792       // Ensure constants are different.
12793       if (D == ECD)
12794         continue;
12795 
12796       // Create new vector and push values onto it.
12797       ECDVector *Vec = new ECDVector();
12798       Vec->push_back(D);
12799       Vec->push_back(ECD);
12800 
12801       // Update entry to point to the duplicates vector.
12802       Entry = Vec;
12803 
12804       // Store the vector somewhere we can consult later for quick emission of
12805       // diagnostics.
12806       DupVector.push_back(Vec);
12807       continue;
12808     }
12809 
12810     ECDVector *Vec = Entry.get<ECDVector*>();
12811     // Make sure constants are not added more than once.
12812     if (*Vec->begin() == ECD)
12813       continue;
12814 
12815     Vec->push_back(ECD);
12816   }
12817 
12818   // Emit diagnostics.
12819   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12820                                   DupVectorEnd = DupVector.end();
12821        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12822     ECDVector *Vec = *DupVectorIter;
12823     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12824 
12825     // Emit warning for one enum constant.
12826     ECDVector::iterator I = Vec->begin();
12827     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12828       << (*I)->getName() << (*I)->getInitVal().toString(10)
12829       << (*I)->getSourceRange();
12830     ++I;
12831 
12832     // Emit one note for each of the remaining enum constants with
12833     // the same value.
12834     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12835       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12836         << (*I)->getName() << (*I)->getInitVal().toString(10)
12837         << (*I)->getSourceRange();
12838     delete Vec;
12839   }
12840 }
12841 
12842 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
12843                          SourceLocation RBraceLoc, Decl *EnumDeclX,
12844                          ArrayRef<Decl *> Elements,
12845                          Scope *S, AttributeList *Attr) {
12846   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
12847   QualType EnumType = Context.getTypeDeclType(Enum);
12848 
12849   if (Attr)
12850     ProcessDeclAttributeList(S, Enum, Attr);
12851 
12852   if (Enum->isDependentType()) {
12853     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12854       EnumConstantDecl *ECD =
12855         cast_or_null<EnumConstantDecl>(Elements[i]);
12856       if (!ECD) continue;
12857 
12858       ECD->setType(EnumType);
12859     }
12860 
12861     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
12862     return;
12863   }
12864 
12865   // TODO: If the result value doesn't fit in an int, it must be a long or long
12866   // long value.  ISO C does not support this, but GCC does as an extension,
12867   // emit a warning.
12868   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12869   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12870   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
12871 
12872   // Verify that all the values are okay, compute the size of the values, and
12873   // reverse the list.
12874   unsigned NumNegativeBits = 0;
12875   unsigned NumPositiveBits = 0;
12876 
12877   // Keep track of whether all elements have type int.
12878   bool AllElementsInt = true;
12879 
12880   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12881     EnumConstantDecl *ECD =
12882       cast_or_null<EnumConstantDecl>(Elements[i]);
12883     if (!ECD) continue;  // Already issued a diagnostic.
12884 
12885     const llvm::APSInt &InitVal = ECD->getInitVal();
12886 
12887     // Keep track of the size of positive and negative values.
12888     if (InitVal.isUnsigned() || InitVal.isNonNegative())
12889       NumPositiveBits = std::max(NumPositiveBits,
12890                                  (unsigned)InitVal.getActiveBits());
12891     else
12892       NumNegativeBits = std::max(NumNegativeBits,
12893                                  (unsigned)InitVal.getMinSignedBits());
12894 
12895     // Keep track of whether every enum element has type int (very commmon).
12896     if (AllElementsInt)
12897       AllElementsInt = ECD->getType() == Context.IntTy;
12898   }
12899 
12900   // Figure out the type that should be used for this enum.
12901   QualType BestType;
12902   unsigned BestWidth;
12903 
12904   // C++0x N3000 [conv.prom]p3:
12905   //   An rvalue of an unscoped enumeration type whose underlying
12906   //   type is not fixed can be converted to an rvalue of the first
12907   //   of the following types that can represent all the values of
12908   //   the enumeration: int, unsigned int, long int, unsigned long
12909   //   int, long long int, or unsigned long long int.
12910   // C99 6.4.4.3p2:
12911   //   An identifier declared as an enumeration constant has type int.
12912   // The C99 rule is modified by a gcc extension
12913   QualType BestPromotionType;
12914 
12915   bool Packed = Enum->hasAttr<PackedAttr>();
12916   // -fshort-enums is the equivalent to specifying the packed attribute on all
12917   // enum definitions.
12918   if (LangOpts.ShortEnums)
12919     Packed = true;
12920 
12921   if (Enum->isFixed()) {
12922     BestType = Enum->getIntegerType();
12923     if (BestType->isPromotableIntegerType())
12924       BestPromotionType = Context.getPromotedIntegerType(BestType);
12925     else
12926       BestPromotionType = BestType;
12927     // We don't need to set BestWidth, because BestType is going to be the type
12928     // of the enumerators, but we do anyway because otherwise some compilers
12929     // warn that it might be used uninitialized.
12930     BestWidth = CharWidth;
12931   }
12932   else if (NumNegativeBits) {
12933     // If there is a negative value, figure out the smallest integer type (of
12934     // int/long/longlong) that fits.
12935     // If it's packed, check also if it fits a char or a short.
12936     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
12937       BestType = Context.SignedCharTy;
12938       BestWidth = CharWidth;
12939     } else if (Packed && NumNegativeBits <= ShortWidth &&
12940                NumPositiveBits < ShortWidth) {
12941       BestType = Context.ShortTy;
12942       BestWidth = ShortWidth;
12943     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
12944       BestType = Context.IntTy;
12945       BestWidth = IntWidth;
12946     } else {
12947       BestWidth = Context.getTargetInfo().getLongWidth();
12948 
12949       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
12950         BestType = Context.LongTy;
12951       } else {
12952         BestWidth = Context.getTargetInfo().getLongLongWidth();
12953 
12954         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
12955           Diag(Enum->getLocation(), diag::ext_enum_too_large);
12956         BestType = Context.LongLongTy;
12957       }
12958     }
12959     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
12960   } else {
12961     // If there is no negative value, figure out the smallest type that fits
12962     // all of the enumerator values.
12963     // If it's packed, check also if it fits a char or a short.
12964     if (Packed && NumPositiveBits <= CharWidth) {
12965       BestType = Context.UnsignedCharTy;
12966       BestPromotionType = Context.IntTy;
12967       BestWidth = CharWidth;
12968     } else if (Packed && NumPositiveBits <= ShortWidth) {
12969       BestType = Context.UnsignedShortTy;
12970       BestPromotionType = Context.IntTy;
12971       BestWidth = ShortWidth;
12972     } else if (NumPositiveBits <= IntWidth) {
12973       BestType = Context.UnsignedIntTy;
12974       BestWidth = IntWidth;
12975       BestPromotionType
12976         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12977                            ? Context.UnsignedIntTy : Context.IntTy;
12978     } else if (NumPositiveBits <=
12979                (BestWidth = Context.getTargetInfo().getLongWidth())) {
12980       BestType = Context.UnsignedLongTy;
12981       BestPromotionType
12982         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12983                            ? Context.UnsignedLongTy : Context.LongTy;
12984     } else {
12985       BestWidth = Context.getTargetInfo().getLongLongWidth();
12986       assert(NumPositiveBits <= BestWidth &&
12987              "How could an initializer get larger than ULL?");
12988       BestType = Context.UnsignedLongLongTy;
12989       BestPromotionType
12990         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12991                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
12992     }
12993   }
12994 
12995   // Loop over all of the enumerator constants, changing their types to match
12996   // the type of the enum if needed.
12997   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12998     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12999     if (!ECD) continue;  // Already issued a diagnostic.
13000 
13001     // Standard C says the enumerators have int type, but we allow, as an
13002     // extension, the enumerators to be larger than int size.  If each
13003     // enumerator value fits in an int, type it as an int, otherwise type it the
13004     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
13005     // that X has type 'int', not 'unsigned'.
13006 
13007     // Determine whether the value fits into an int.
13008     llvm::APSInt InitVal = ECD->getInitVal();
13009 
13010     // If it fits into an integer type, force it.  Otherwise force it to match
13011     // the enum decl type.
13012     QualType NewTy;
13013     unsigned NewWidth;
13014     bool NewSign;
13015     if (!getLangOpts().CPlusPlus &&
13016         !Enum->isFixed() &&
13017         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
13018       NewTy = Context.IntTy;
13019       NewWidth = IntWidth;
13020       NewSign = true;
13021     } else if (ECD->getType() == BestType) {
13022       // Already the right type!
13023       if (getLangOpts().CPlusPlus)
13024         // C++ [dcl.enum]p4: Following the closing brace of an
13025         // enum-specifier, each enumerator has the type of its
13026         // enumeration.
13027         ECD->setType(EnumType);
13028       continue;
13029     } else {
13030       NewTy = BestType;
13031       NewWidth = BestWidth;
13032       NewSign = BestType->isSignedIntegerOrEnumerationType();
13033     }
13034 
13035     // Adjust the APSInt value.
13036     InitVal = InitVal.extOrTrunc(NewWidth);
13037     InitVal.setIsSigned(NewSign);
13038     ECD->setInitVal(InitVal);
13039 
13040     // Adjust the Expr initializer and type.
13041     if (ECD->getInitExpr() &&
13042         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
13043       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
13044                                                 CK_IntegralCast,
13045                                                 ECD->getInitExpr(),
13046                                                 /*base paths*/ 0,
13047                                                 VK_RValue));
13048     if (getLangOpts().CPlusPlus)
13049       // C++ [dcl.enum]p4: Following the closing brace of an
13050       // enum-specifier, each enumerator has the type of its
13051       // enumeration.
13052       ECD->setType(EnumType);
13053     else
13054       ECD->setType(NewTy);
13055   }
13056 
13057   Enum->completeDefinition(BestType, BestPromotionType,
13058                            NumPositiveBits, NumNegativeBits);
13059 
13060   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
13061 
13062   // Now that the enum type is defined, ensure it's not been underaligned.
13063   if (Enum->hasAttrs())
13064     CheckAlignasUnderalignment(Enum);
13065 }
13066 
13067 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
13068                                   SourceLocation StartLoc,
13069                                   SourceLocation EndLoc) {
13070   StringLiteral *AsmString = cast<StringLiteral>(expr);
13071 
13072   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
13073                                                    AsmString, StartLoc,
13074                                                    EndLoc);
13075   CurContext->addDecl(New);
13076   return New;
13077 }
13078 
13079 static void checkModuleImportContext(Sema &S, Module *M,
13080                                      SourceLocation ImportLoc,
13081                                      DeclContext *DC) {
13082   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
13083     switch (LSD->getLanguage()) {
13084     case LinkageSpecDecl::lang_c:
13085       if (!M->IsExternC) {
13086         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
13087           << M->getFullModuleName();
13088         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
13089         return;
13090       }
13091       break;
13092     case LinkageSpecDecl::lang_cxx:
13093       break;
13094     }
13095     DC = LSD->getParent();
13096   }
13097 
13098   while (isa<LinkageSpecDecl>(DC))
13099     DC = DC->getParent();
13100   if (!isa<TranslationUnitDecl>(DC)) {
13101     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
13102       << M->getFullModuleName() << DC;
13103     S.Diag(cast<Decl>(DC)->getLocStart(),
13104            diag::note_module_import_not_at_top_level)
13105       << DC;
13106   }
13107 }
13108 
13109 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
13110                                    SourceLocation ImportLoc,
13111                                    ModuleIdPath Path) {
13112   Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
13113                                                 Module::AllVisible,
13114                                                 /*IsIncludeDirective=*/false);
13115   if (!Mod)
13116     return true;
13117 
13118   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13119 
13120   SmallVector<SourceLocation, 2> IdentifierLocs;
13121   Module *ModCheck = Mod;
13122   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13123     // If we've run out of module parents, just drop the remaining identifiers.
13124     // We need the length to be consistent.
13125     if (!ModCheck)
13126       break;
13127     ModCheck = ModCheck->Parent;
13128 
13129     IdentifierLocs.push_back(Path[I].second);
13130   }
13131 
13132   ImportDecl *Import = ImportDecl::Create(Context,
13133                                           Context.getTranslationUnitDecl(),
13134                                           AtLoc.isValid()? AtLoc : ImportLoc,
13135                                           Mod, IdentifierLocs);
13136   Context.getTranslationUnitDecl()->addDecl(Import);
13137   return Import;
13138 }
13139 
13140 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13141   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13142 
13143   // FIXME: Should we synthesize an ImportDecl here?
13144   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13145                                          /*Complain=*/true);
13146 }
13147 
13148 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
13149   // Create the implicit import declaration.
13150   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13151   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13152                                                    Loc, Mod, Loc);
13153   TU->addDecl(ImportD);
13154   Consumer.HandleImplicitImportDecl(ImportD);
13155 
13156   // Make the module visible.
13157   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13158                                          /*Complain=*/false);
13159 }
13160 
13161 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13162                                       IdentifierInfo* AliasName,
13163                                       SourceLocation PragmaLoc,
13164                                       SourceLocation NameLoc,
13165                                       SourceLocation AliasNameLoc) {
13166   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13167                                     LookupOrdinaryName);
13168   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13169                                                     AliasName->getName(), 0);
13170 
13171   if (PrevDecl)
13172     PrevDecl->addAttr(Attr);
13173   else
13174     (void)ExtnameUndeclaredIdentifiers.insert(
13175       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13176 }
13177 
13178 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13179                              SourceLocation PragmaLoc,
13180                              SourceLocation NameLoc) {
13181   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13182 
13183   if (PrevDecl) {
13184     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13185   } else {
13186     (void)WeakUndeclaredIdentifiers.insert(
13187       std::pair<IdentifierInfo*,WeakInfo>
13188         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
13189   }
13190 }
13191 
13192 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13193                                 IdentifierInfo* AliasName,
13194                                 SourceLocation PragmaLoc,
13195                                 SourceLocation NameLoc,
13196                                 SourceLocation AliasNameLoc) {
13197   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13198                                     LookupOrdinaryName);
13199   WeakInfo W = WeakInfo(Name, NameLoc);
13200 
13201   if (PrevDecl) {
13202     if (!PrevDecl->hasAttr<AliasAttr>())
13203       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13204         DeclApplyPragmaWeak(TUScope, ND, W);
13205   } else {
13206     (void)WeakUndeclaredIdentifiers.insert(
13207       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13208   }
13209 }
13210 
13211 Decl *Sema::getObjCDeclContext() const {
13212   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13213 }
13214 
13215 AvailabilityResult Sema::getCurContextAvailability() const {
13216   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13217   // If we are within an Objective-C method, we should consult
13218   // both the availability of the method as well as the
13219   // enclosing class.  If the class is (say) deprecated,
13220   // the entire method is considered deprecated from the
13221   // purpose of checking if the current context is deprecated.
13222   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13223     AvailabilityResult R = MD->getAvailability();
13224     if (R != AR_Available)
13225       return R;
13226     D = MD->getClassInterface();
13227   }
13228   // If we are within an Objective-c @implementation, it
13229   // gets the same availability context as the @interface.
13230   else if (const ObjCImplementationDecl *ID =
13231             dyn_cast<ObjCImplementationDecl>(D)) {
13232     D = ID->getClassInterface();
13233   }
13234   return D->getAvailability();
13235 }
13236