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/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
31 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
32 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
33 #include "clang/Parse/ParseDiagnostic.h"
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/Triple.h"
44 #include <algorithm>
45 #include <cstring>
46 #include <functional>
47 using namespace clang;
48 using namespace sema;
49 
50 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
51   if (OwnedType) {
52     Decl *Group[2] = { OwnedType, Ptr };
53     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
54   }
55 
56   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
57 }
58 
59 namespace {
60 
61 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
62  public:
63   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
64       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
65     WantExpressionKeywords = false;
66     WantCXXNamedCasts = false;
67     WantRemainingKeywords = false;
68   }
69 
70   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
71     if (NamedDecl *ND = candidate.getCorrectionDecl())
72       return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
73           (AllowInvalidDecl || !ND->isInvalidDecl());
74     else
75       return !WantClassName && candidate.isKeyword();
76   }
77 
78  private:
79   bool AllowInvalidDecl;
80   bool WantClassName;
81 };
82 
83 }
84 
85 /// \brief Determine whether the token kind starts a simple-type-specifier.
86 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
87   switch (Kind) {
88   // FIXME: Take into account the current language when deciding whether a
89   // token kind is a valid type specifier
90   case tok::kw_short:
91   case tok::kw_long:
92   case tok::kw___int64:
93   case tok::kw___int128:
94   case tok::kw_signed:
95   case tok::kw_unsigned:
96   case tok::kw_void:
97   case tok::kw_char:
98   case tok::kw_int:
99   case tok::kw_half:
100   case tok::kw_float:
101   case tok::kw_double:
102   case tok::kw_wchar_t:
103   case tok::kw_bool:
104   case tok::kw___underlying_type:
105     return true;
106 
107   case tok::annot_typename:
108   case tok::kw_char16_t:
109   case tok::kw_char32_t:
110   case tok::kw_typeof:
111   case tok::annot_decltype:
112   case tok::kw_decltype:
113     return getLangOpts().CPlusPlus;
114 
115   default:
116     break;
117   }
118 
119   return false;
120 }
121 
122 /// \brief If the identifier refers to a type name within this scope,
123 /// return the declaration of that type.
124 ///
125 /// This routine performs ordinary name lookup of the identifier II
126 /// within the given scope, with optional C++ scope specifier SS, to
127 /// determine whether the name refers to a type. If so, returns an
128 /// opaque pointer (actually a QualType) corresponding to that
129 /// type. Otherwise, returns NULL.
130 ///
131 /// If name lookup results in an ambiguity, this routine will complain
132 /// and then return NULL.
133 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
134                              Scope *S, CXXScopeSpec *SS,
135                              bool isClassName, bool HasTrailingDot,
136                              ParsedType ObjectTypePtr,
137                              bool IsCtorOrDtorName,
138                              bool WantNontrivialTypeSourceInfo,
139                              IdentifierInfo **CorrectedII) {
140   // Determine where we will perform name lookup.
141   DeclContext *LookupCtx = 0;
142   if (ObjectTypePtr) {
143     QualType ObjectType = ObjectTypePtr.get();
144     if (ObjectType->isRecordType())
145       LookupCtx = computeDeclContext(ObjectType);
146   } else if (SS && SS->isNotEmpty()) {
147     LookupCtx = computeDeclContext(*SS, false);
148 
149     if (!LookupCtx) {
150       if (isDependentScopeSpecifier(*SS)) {
151         // C++ [temp.res]p3:
152         //   A qualified-id that refers to a type and in which the
153         //   nested-name-specifier depends on a template-parameter (14.6.2)
154         //   shall be prefixed by the keyword typename to indicate that the
155         //   qualified-id denotes a type, forming an
156         //   elaborated-type-specifier (7.1.5.3).
157         //
158         // We therefore do not perform any name lookup if the result would
159         // refer to a member of an unknown specialization.
160         if (!isClassName && !IsCtorOrDtorName)
161           return ParsedType();
162 
163         // We know from the grammar that this name refers to a type,
164         // so build a dependent node to describe the type.
165         if (WantNontrivialTypeSourceInfo)
166           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
167 
168         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
169         QualType T =
170           CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
171                             II, NameLoc);
172 
173           return ParsedType::make(T);
174       }
175 
176       return ParsedType();
177     }
178 
179     if (!LookupCtx->isDependentContext() &&
180         RequireCompleteDeclContext(*SS, LookupCtx))
181       return ParsedType();
182   }
183 
184   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
185   // lookup for class-names.
186   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
187                                       LookupOrdinaryName;
188   LookupResult Result(*this, &II, NameLoc, Kind);
189   if (LookupCtx) {
190     // Perform "qualified" name lookup into the declaration context we
191     // computed, which is either the type of the base of a member access
192     // expression or the declaration context associated with a prior
193     // nested-name-specifier.
194     LookupQualifiedName(Result, LookupCtx);
195 
196     if (ObjectTypePtr && Result.empty()) {
197       // C++ [basic.lookup.classref]p3:
198       //   If the unqualified-id is ~type-name, the type-name is looked up
199       //   in the context of the entire postfix-expression. If the type T of
200       //   the object expression is of a class type C, the type-name is also
201       //   looked up in the scope of class C. At least one of the lookups shall
202       //   find a name that refers to (possibly cv-qualified) T.
203       LookupName(Result, S);
204     }
205   } else {
206     // Perform unqualified name lookup.
207     LookupName(Result, S);
208   }
209 
210   NamedDecl *IIDecl = 0;
211   switch (Result.getResultKind()) {
212   case LookupResult::NotFound:
213   case LookupResult::NotFoundInCurrentInstantiation:
214     if (CorrectedII) {
215       TypeNameValidatorCCC Validator(true, isClassName);
216       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
217                                               Kind, S, SS, Validator);
218       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
219       TemplateTy Template;
220       bool MemberOfUnknownSpecialization;
221       UnqualifiedId TemplateName;
222       TemplateName.setIdentifier(NewII, NameLoc);
223       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
224       CXXScopeSpec NewSS, *NewSSPtr = SS;
225       if (SS && NNS) {
226         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
227         NewSSPtr = &NewSS;
228       }
229       if (Correction && (NNS || NewII != &II) &&
230           // Ignore a correction to a template type as the to-be-corrected
231           // identifier is not a template (typo correction for template names
232           // is handled elsewhere).
233           !(getLangOpts().CPlusPlus && NewSSPtr &&
234             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
235                            false, Template, MemberOfUnknownSpecialization))) {
236         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
237                                     isClassName, HasTrailingDot, ObjectTypePtr,
238                                     IsCtorOrDtorName,
239                                     WantNontrivialTypeSourceInfo);
240         if (Ty) {
241           diagnoseTypo(Correction,
242                        PDiag(diag::err_unknown_type_or_class_name_suggest)
243                          << Result.getLookupName() << isClassName);
244           if (SS && NNS)
245             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
246           *CorrectedII = NewII;
247           return Ty;
248         }
249       }
250     }
251     // If typo correction failed or was not performed, fall through
252   case LookupResult::FoundOverloaded:
253   case LookupResult::FoundUnresolvedValue:
254     Result.suppressDiagnostics();
255     return ParsedType();
256 
257   case LookupResult::Ambiguous:
258     // Recover from type-hiding ambiguities by hiding the type.  We'll
259     // do the lookup again when looking for an object, and we can
260     // diagnose the error then.  If we don't do this, then the error
261     // about hiding the type will be immediately followed by an error
262     // that only makes sense if the identifier was treated like a type.
263     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
264       Result.suppressDiagnostics();
265       return ParsedType();
266     }
267 
268     // Look to see if we have a type anywhere in the list of results.
269     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
270          Res != ResEnd; ++Res) {
271       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
272         if (!IIDecl ||
273             (*Res)->getLocation().getRawEncoding() <
274               IIDecl->getLocation().getRawEncoding())
275           IIDecl = *Res;
276       }
277     }
278 
279     if (!IIDecl) {
280       // None of the entities we found is a type, so there is no way
281       // to even assume that the result is a type. In this case, don't
282       // complain about the ambiguity. The parser will either try to
283       // perform this lookup again (e.g., as an object name), which
284       // will produce the ambiguity, or will complain that it expected
285       // a type name.
286       Result.suppressDiagnostics();
287       return ParsedType();
288     }
289 
290     // We found a type within the ambiguous lookup; diagnose the
291     // ambiguity and then return that type. This might be the right
292     // answer, or it might not be, but it suppresses any attempt to
293     // perform the name lookup again.
294     break;
295 
296   case LookupResult::Found:
297     IIDecl = Result.getFoundDecl();
298     break;
299   }
300 
301   assert(IIDecl && "Didn't find decl");
302 
303   QualType T;
304   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
305     DiagnoseUseOfDecl(IIDecl, NameLoc);
306 
307     if (T.isNull())
308       T = Context.getTypeDeclType(TD);
309 
310     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
311     // constructor or destructor name (in such a case, the scope specifier
312     // will be attached to the enclosing Expr or Decl node).
313     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
314       if (WantNontrivialTypeSourceInfo) {
315         // Construct a type with type-source information.
316         TypeLocBuilder Builder;
317         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
318 
319         T = getElaboratedType(ETK_None, *SS, T);
320         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
321         ElabTL.setElaboratedKeywordLoc(SourceLocation());
322         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
323         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
324       } else {
325         T = getElaboratedType(ETK_None, *SS, T);
326       }
327     }
328   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
329     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
330     if (!HasTrailingDot)
331       T = Context.getObjCInterfaceType(IDecl);
332   }
333 
334   if (T.isNull()) {
335     // If it's not plausibly a type, suppress diagnostics.
336     Result.suppressDiagnostics();
337     return ParsedType();
338   }
339   return ParsedType::make(T);
340 }
341 
342 /// isTagName() - This method is called *for error recovery purposes only*
343 /// to determine if the specified name is a valid tag name ("struct foo").  If
344 /// so, this returns the TST for the tag corresponding to it (TST_enum,
345 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
346 /// cases in C where the user forgot to specify the tag.
347 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
348   // Do a tag name lookup in this scope.
349   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
350   LookupName(R, S, false);
351   R.suppressDiagnostics();
352   if (R.getResultKind() == LookupResult::Found)
353     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
354       switch (TD->getTagKind()) {
355       case TTK_Struct: return DeclSpec::TST_struct;
356       case TTK_Interface: return DeclSpec::TST_interface;
357       case TTK_Union:  return DeclSpec::TST_union;
358       case TTK_Class:  return DeclSpec::TST_class;
359       case TTK_Enum:   return DeclSpec::TST_enum;
360       }
361     }
362 
363   return DeclSpec::TST_unspecified;
364 }
365 
366 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
367 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
368 /// then downgrade the missing typename error to a warning.
369 /// This is needed for MSVC compatibility; Example:
370 /// @code
371 /// template<class T> class A {
372 /// public:
373 ///   typedef int TYPE;
374 /// };
375 /// template<class T> class B : public A<T> {
376 /// public:
377 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
378 /// };
379 /// @endcode
380 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
381   if (CurContext->isRecord()) {
382     const Type *Ty = SS->getScopeRep()->getAsType();
383 
384     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
385     for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
386           BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
387       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
388         return true;
389     return S->isFunctionPrototypeScope();
390   }
391   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
392 }
393 
394 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
395                                    SourceLocation IILoc,
396                                    Scope *S,
397                                    CXXScopeSpec *SS,
398                                    ParsedType &SuggestedType) {
399   // We don't have anything to suggest (yet).
400   SuggestedType = ParsedType();
401 
402   // There may have been a typo in the name of the type. Look up typo
403   // results, in case we have something that we can suggest.
404   TypeNameValidatorCCC Validator(false);
405   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
406                                              LookupOrdinaryName, S, SS,
407                                              Validator)) {
408     if (Corrected.isKeyword()) {
409       // We corrected to a keyword.
410       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
411       II = Corrected.getCorrectionAsIdentifierInfo();
412     } else {
413       // We found a similarly-named type or interface; suggest that.
414       if (!SS || !SS->isSet()) {
415         diagnoseTypo(Corrected,
416                      PDiag(diag::err_unknown_typename_suggest) << II);
417       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
418         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
419         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
420                                 II->getName().equals(CorrectedStr);
421         diagnoseTypo(Corrected,
422                      PDiag(diag::err_unknown_nested_typename_suggest)
423                        << II << DC << DroppedSpecifier << SS->getRange());
424       } else {
425         llvm_unreachable("could not have corrected a typo here");
426       }
427 
428       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
429                                   IILoc, S, SS, false, false, ParsedType(),
430                                   /*IsCtorOrDtorName=*/false,
431                                   /*NonTrivialTypeSourceInfo=*/true);
432     }
433     return true;
434   }
435 
436   if (getLangOpts().CPlusPlus) {
437     // See if II is a class template that the user forgot to pass arguments to.
438     UnqualifiedId Name;
439     Name.setIdentifier(II, IILoc);
440     CXXScopeSpec EmptySS;
441     TemplateTy TemplateResult;
442     bool MemberOfUnknownSpecialization;
443     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
444                        Name, ParsedType(), true, TemplateResult,
445                        MemberOfUnknownSpecialization) == TNK_Type_template) {
446       TemplateName TplName = TemplateResult.get();
447       Diag(IILoc, diag::err_template_missing_args) << TplName;
448       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
449         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
450           << TplDecl->getTemplateParameters()->getSourceRange();
451       }
452       return true;
453     }
454   }
455 
456   // FIXME: Should we move the logic that tries to recover from a missing tag
457   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
458 
459   if (!SS || (!SS->isSet() && !SS->isInvalid()))
460     Diag(IILoc, diag::err_unknown_typename) << II;
461   else if (DeclContext *DC = computeDeclContext(*SS, false))
462     Diag(IILoc, diag::err_typename_nested_not_found)
463       << II << DC << SS->getRange();
464   else if (isDependentScopeSpecifier(*SS)) {
465     unsigned DiagID = diag::err_typename_missing;
466     if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
467       DiagID = diag::warn_typename_missing;
468 
469     Diag(SS->getRange().getBegin(), DiagID)
470       << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
471       << SourceRange(SS->getRange().getBegin(), IILoc)
472       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
473     SuggestedType = ActOnTypenameType(S, SourceLocation(),
474                                       *SS, *II, IILoc).get();
475   } else {
476     assert(SS && SS->isInvalid() &&
477            "Invalid scope specifier has already been diagnosed");
478   }
479 
480   return true;
481 }
482 
483 /// \brief Determine whether the given result set contains either a type name
484 /// or
485 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
486   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
487                        NextToken.is(tok::less);
488 
489   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
490     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
491       return true;
492 
493     if (CheckTemplate && isa<TemplateDecl>(*I))
494       return true;
495   }
496 
497   return false;
498 }
499 
500 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
501                                     Scope *S, CXXScopeSpec &SS,
502                                     IdentifierInfo *&Name,
503                                     SourceLocation NameLoc) {
504   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
505   SemaRef.LookupParsedName(R, S, &SS);
506   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
507     const char *TagName = 0;
508     const char *FixItTagName = 0;
509     switch (Tag->getTagKind()) {
510       case TTK_Class:
511         TagName = "class";
512         FixItTagName = "class ";
513         break;
514 
515       case TTK_Enum:
516         TagName = "enum";
517         FixItTagName = "enum ";
518         break;
519 
520       case TTK_Struct:
521         TagName = "struct";
522         FixItTagName = "struct ";
523         break;
524 
525       case TTK_Interface:
526         TagName = "__interface";
527         FixItTagName = "__interface ";
528         break;
529 
530       case TTK_Union:
531         TagName = "union";
532         FixItTagName = "union ";
533         break;
534     }
535 
536     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
537       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
538       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
539 
540     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
541          I != IEnd; ++I)
542       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
543         << Name << TagName;
544 
545     // Replace lookup results with just the tag decl.
546     Result.clear(Sema::LookupTagName);
547     SemaRef.LookupParsedName(Result, S, &SS);
548     return true;
549   }
550 
551   return false;
552 }
553 
554 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
555 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
556                                   QualType T, SourceLocation NameLoc) {
557   ASTContext &Context = S.Context;
558 
559   TypeLocBuilder Builder;
560   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
561 
562   T = S.getElaboratedType(ETK_None, SS, T);
563   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
564   ElabTL.setElaboratedKeywordLoc(SourceLocation());
565   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
566   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
567 }
568 
569 Sema::NameClassification Sema::ClassifyName(Scope *S,
570                                             CXXScopeSpec &SS,
571                                             IdentifierInfo *&Name,
572                                             SourceLocation NameLoc,
573                                             const Token &NextToken,
574                                             bool IsAddressOfOperand,
575                                             CorrectionCandidateCallback *CCC) {
576   DeclarationNameInfo NameInfo(Name, NameLoc);
577   ObjCMethodDecl *CurMethod = getCurMethodDecl();
578 
579   if (NextToken.is(tok::coloncolon)) {
580     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
581                                 QualType(), false, SS, 0, false);
582 
583   }
584 
585   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
586   LookupParsedName(Result, S, &SS, !CurMethod);
587 
588   // Perform lookup for Objective-C instance variables (including automatically
589   // synthesized instance variables), if we're in an Objective-C method.
590   // FIXME: This lookup really, really needs to be folded in to the normal
591   // unqualified lookup mechanism.
592   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
593     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
594     if (E.get() || E.isInvalid())
595       return E;
596   }
597 
598   bool SecondTry = false;
599   bool IsFilteredTemplateName = false;
600 
601 Corrected:
602   switch (Result.getResultKind()) {
603   case LookupResult::NotFound:
604     // If an unqualified-id is followed by a '(', then we have a function
605     // call.
606     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
607       // In C++, this is an ADL-only call.
608       // FIXME: Reference?
609       if (getLangOpts().CPlusPlus)
610         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
611 
612       // C90 6.3.2.2:
613       //   If the expression that precedes the parenthesized argument list in a
614       //   function call consists solely of an identifier, and if no
615       //   declaration is visible for this identifier, the identifier is
616       //   implicitly declared exactly as if, in the innermost block containing
617       //   the function call, the declaration
618       //
619       //     extern int identifier ();
620       //
621       //   appeared.
622       //
623       // We also allow this in C99 as an extension.
624       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
625         Result.addDecl(D);
626         Result.resolveKind();
627         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
628       }
629     }
630 
631     // In C, we first see whether there is a tag type by the same name, in
632     // which case it's likely that the user just forget to write "enum",
633     // "struct", or "union".
634     if (!getLangOpts().CPlusPlus && !SecondTry &&
635         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
636       break;
637     }
638 
639     // Perform typo correction to determine if there is another name that is
640     // close to this name.
641     if (!SecondTry && CCC) {
642       SecondTry = true;
643       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
644                                                  Result.getLookupKind(), S,
645                                                  &SS, *CCC)) {
646         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
647         unsigned QualifiedDiag = diag::err_no_member_suggest;
648 
649         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
650         NamedDecl *UnderlyingFirstDecl
651           = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
652         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
653             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
654           UnqualifiedDiag = diag::err_no_template_suggest;
655           QualifiedDiag = diag::err_no_member_template_suggest;
656         } else if (UnderlyingFirstDecl &&
657                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
658                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
659                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
660           UnqualifiedDiag = diag::err_unknown_typename_suggest;
661           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
662         }
663 
664         if (SS.isEmpty()) {
665           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
666         } else {// FIXME: is this even reachable? Test it.
667           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
668           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
669                                   Name->getName().equals(CorrectedStr);
670           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
671                                     << Name << computeDeclContext(SS, false)
672                                     << DroppedSpecifier << SS.getRange());
673         }
674 
675         // Update the name, so that the caller has the new name.
676         Name = Corrected.getCorrectionAsIdentifierInfo();
677 
678         // Typo correction corrected to a keyword.
679         if (Corrected.isKeyword())
680           return Name;
681 
682         // Also update the LookupResult...
683         // FIXME: This should probably go away at some point
684         Result.clear();
685         Result.setLookupName(Corrected.getCorrection());
686         if (FirstDecl)
687           Result.addDecl(FirstDecl);
688 
689         // If we found an Objective-C instance variable, let
690         // LookupInObjCMethod build the appropriate expression to
691         // reference the ivar.
692         // FIXME: This is a gross hack.
693         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
694           Result.clear();
695           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
696           return E;
697         }
698 
699         goto Corrected;
700       }
701     }
702 
703     // We failed to correct; just fall through and let the parser deal with it.
704     Result.suppressDiagnostics();
705     return NameClassification::Unknown();
706 
707   case LookupResult::NotFoundInCurrentInstantiation: {
708     // We performed name lookup into the current instantiation, and there were
709     // dependent bases, so we treat this result the same way as any other
710     // dependent nested-name-specifier.
711 
712     // C++ [temp.res]p2:
713     //   A name used in a template declaration or definition and that is
714     //   dependent on a template-parameter is assumed not to name a type
715     //   unless the applicable name lookup finds a type name or the name is
716     //   qualified by the keyword typename.
717     //
718     // FIXME: If the next token is '<', we might want to ask the parser to
719     // perform some heroics to see if we actually have a
720     // template-argument-list, which would indicate a missing 'template'
721     // keyword here.
722     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
723                                       NameInfo, IsAddressOfOperand,
724                                       /*TemplateArgs=*/0);
725   }
726 
727   case LookupResult::Found:
728   case LookupResult::FoundOverloaded:
729   case LookupResult::FoundUnresolvedValue:
730     break;
731 
732   case LookupResult::Ambiguous:
733     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
734         hasAnyAcceptableTemplateNames(Result)) {
735       // C++ [temp.local]p3:
736       //   A lookup that finds an injected-class-name (10.2) can result in an
737       //   ambiguity in certain cases (for example, if it is found in more than
738       //   one base class). If all of the injected-class-names that are found
739       //   refer to specializations of the same class template, and if the name
740       //   is followed by a template-argument-list, the reference refers to the
741       //   class template itself and not a specialization thereof, and is not
742       //   ambiguous.
743       //
744       // This filtering can make an ambiguous result into an unambiguous one,
745       // so try again after filtering out template names.
746       FilterAcceptableTemplateNames(Result);
747       if (!Result.isAmbiguous()) {
748         IsFilteredTemplateName = true;
749         break;
750       }
751     }
752 
753     // Diagnose the ambiguity and return an error.
754     return NameClassification::Error();
755   }
756 
757   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
758       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
759     // C++ [temp.names]p3:
760     //   After name lookup (3.4) finds that a name is a template-name or that
761     //   an operator-function-id or a literal- operator-id refers to a set of
762     //   overloaded functions any member of which is a function template if
763     //   this is followed by a <, the < is always taken as the delimiter of a
764     //   template-argument-list and never as the less-than operator.
765     if (!IsFilteredTemplateName)
766       FilterAcceptableTemplateNames(Result);
767 
768     if (!Result.empty()) {
769       bool IsFunctionTemplate;
770       bool IsVarTemplate;
771       TemplateName Template;
772       if (Result.end() - Result.begin() > 1) {
773         IsFunctionTemplate = true;
774         Template = Context.getOverloadedTemplateName(Result.begin(),
775                                                      Result.end());
776       } else {
777         TemplateDecl *TD
778           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
779         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
780         IsVarTemplate = isa<VarTemplateDecl>(TD);
781 
782         if (SS.isSet() && !SS.isInvalid())
783           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
784                                                     /*TemplateKeyword=*/false,
785                                                       TD);
786         else
787           Template = TemplateName(TD);
788       }
789 
790       if (IsFunctionTemplate) {
791         // Function templates always go through overload resolution, at which
792         // point we'll perform the various checks (e.g., accessibility) we need
793         // to based on which function we selected.
794         Result.suppressDiagnostics();
795 
796         return NameClassification::FunctionTemplate(Template);
797       }
798 
799       return IsVarTemplate ? NameClassification::VarTemplate(Template)
800                            : NameClassification::TypeTemplate(Template);
801     }
802   }
803 
804   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
805   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
806     DiagnoseUseOfDecl(Type, NameLoc);
807     QualType T = Context.getTypeDeclType(Type);
808     if (SS.isNotEmpty())
809       return buildNestedType(*this, SS, T, NameLoc);
810     return ParsedType::make(T);
811   }
812 
813   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
814   if (!Class) {
815     // FIXME: It's unfortunate that we don't have a Type node for handling this.
816     if (ObjCCompatibleAliasDecl *Alias
817                                 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
818       Class = Alias->getClassInterface();
819   }
820 
821   if (Class) {
822     DiagnoseUseOfDecl(Class, NameLoc);
823 
824     if (NextToken.is(tok::period)) {
825       // Interface. <something> is parsed as a property reference expression.
826       // Just return "unknown" as a fall-through for now.
827       Result.suppressDiagnostics();
828       return NameClassification::Unknown();
829     }
830 
831     QualType T = Context.getObjCInterfaceType(Class);
832     return ParsedType::make(T);
833   }
834 
835   // We can have a type template here if we're classifying a template argument.
836   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
837     return NameClassification::TypeTemplate(
838         TemplateName(cast<TemplateDecl>(FirstDecl)));
839 
840   // Check for a tag type hidden by a non-type decl in a few cases where it
841   // seems likely a type is wanted instead of the non-type that was found.
842   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
843   if ((NextToken.is(tok::identifier) ||
844        (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
845       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
846     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
847     DiagnoseUseOfDecl(Type, NameLoc);
848     QualType T = Context.getTypeDeclType(Type);
849     if (SS.isNotEmpty())
850       return buildNestedType(*this, SS, T, NameLoc);
851     return ParsedType::make(T);
852   }
853 
854   if (FirstDecl->isCXXClassMember())
855     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
856 
857   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
858   return BuildDeclarationNameExpr(SS, Result, ADL);
859 }
860 
861 // Determines the context to return to after temporarily entering a
862 // context.  This depends in an unnecessarily complicated way on the
863 // exact ordering of callbacks from the parser.
864 DeclContext *Sema::getContainingDC(DeclContext *DC) {
865 
866   // Functions defined inline within classes aren't parsed until we've
867   // finished parsing the top-level class, so the top-level class is
868   // the context we'll need to return to.
869   if (isa<FunctionDecl>(DC)) {
870     DC = DC->getLexicalParent();
871 
872     // A function not defined within a class will always return to its
873     // lexical context.
874     if (!isa<CXXRecordDecl>(DC))
875       return DC;
876 
877     // A C++ inline method/friend is parsed *after* the topmost class
878     // it was declared in is fully parsed ("complete");  the topmost
879     // class is the context we need to return to.
880     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
881       DC = RD;
882 
883     // Return the declaration context of the topmost class the inline method is
884     // declared in.
885     return DC;
886   }
887 
888   return DC->getLexicalParent();
889 }
890 
891 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
892   assert(getContainingDC(DC) == CurContext &&
893       "The next DeclContext should be lexically contained in the current one.");
894   CurContext = DC;
895   S->setEntity(DC);
896 }
897 
898 void Sema::PopDeclContext() {
899   assert(CurContext && "DeclContext imbalance!");
900 
901   CurContext = getContainingDC(CurContext);
902   assert(CurContext && "Popped translation unit!");
903 }
904 
905 /// EnterDeclaratorContext - Used when we must lookup names in the context
906 /// of a declarator's nested name specifier.
907 ///
908 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
909   // C++0x [basic.lookup.unqual]p13:
910   //   A name used in the definition of a static data member of class
911   //   X (after the qualified-id of the static member) is looked up as
912   //   if the name was used in a member function of X.
913   // C++0x [basic.lookup.unqual]p14:
914   //   If a variable member of a namespace is defined outside of the
915   //   scope of its namespace then any name used in the definition of
916   //   the variable member (after the declarator-id) is looked up as
917   //   if the definition of the variable member occurred in its
918   //   namespace.
919   // Both of these imply that we should push a scope whose context
920   // is the semantic context of the declaration.  We can't use
921   // PushDeclContext here because that context is not necessarily
922   // lexically contained in the current context.  Fortunately,
923   // the containing scope should have the appropriate information.
924 
925   assert(!S->getEntity() && "scope already has entity");
926 
927 #ifndef NDEBUG
928   Scope *Ancestor = S->getParent();
929   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
930   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
931 #endif
932 
933   CurContext = DC;
934   S->setEntity(DC);
935 }
936 
937 void Sema::ExitDeclaratorContext(Scope *S) {
938   assert(S->getEntity() == CurContext && "Context imbalance!");
939 
940   // Switch back to the lexical context.  The safety of this is
941   // enforced by an assert in EnterDeclaratorContext.
942   Scope *Ancestor = S->getParent();
943   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
944   CurContext = (DeclContext*) Ancestor->getEntity();
945 
946   // We don't need to do anything with the scope, which is going to
947   // disappear.
948 }
949 
950 
951 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
952   FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
953   if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
954     // We assume that the caller has already called
955     // ActOnReenterTemplateScope
956     FD = TFD->getTemplatedDecl();
957   }
958   if (!FD)
959     return;
960 
961   // Same implementation as PushDeclContext, but enters the context
962   // from the lexical parent, rather than the top-level class.
963   assert(CurContext == FD->getLexicalParent() &&
964     "The next DeclContext should be lexically contained in the current one.");
965   CurContext = FD;
966   S->setEntity(CurContext);
967 
968   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
969     ParmVarDecl *Param = FD->getParamDecl(P);
970     // If the parameter has an identifier, then add it to the scope
971     if (Param->getIdentifier()) {
972       S->AddDecl(Param);
973       IdResolver.AddDecl(Param);
974     }
975   }
976 }
977 
978 
979 void Sema::ActOnExitFunctionContext() {
980   // Same implementation as PopDeclContext, but returns to the lexical parent,
981   // rather than the top-level class.
982   assert(CurContext && "DeclContext imbalance!");
983   CurContext = CurContext->getLexicalParent();
984   assert(CurContext && "Popped translation unit!");
985 }
986 
987 
988 /// \brief Determine whether we allow overloading of the function
989 /// PrevDecl with another declaration.
990 ///
991 /// This routine determines whether overloading is possible, not
992 /// whether some new function is actually an overload. It will return
993 /// true in C++ (where we can always provide overloads) or, as an
994 /// extension, in C when the previous function is already an
995 /// overloaded function declaration or has the "overloadable"
996 /// attribute.
997 static bool AllowOverloadingOfFunction(LookupResult &Previous,
998                                        ASTContext &Context) {
999   if (Context.getLangOpts().CPlusPlus)
1000     return true;
1001 
1002   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1003     return true;
1004 
1005   return (Previous.getResultKind() == LookupResult::Found
1006           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1007 }
1008 
1009 /// Add this decl to the scope shadowed decl chains.
1010 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1011   // Move up the scope chain until we find the nearest enclosing
1012   // non-transparent context. The declaration will be introduced into this
1013   // scope.
1014   while (S->getEntity() &&
1015          ((DeclContext *)S->getEntity())->isTransparentContext())
1016     S = S->getParent();
1017 
1018   // Add scoped declarations into their context, so that they can be
1019   // found later. Declarations without a context won't be inserted
1020   // into any context.
1021   if (AddToContext)
1022     CurContext->addDecl(D);
1023 
1024   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1025   // are function-local declarations.
1026   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1027       !D->getDeclContext()->getRedeclContext()->Equals(
1028         D->getLexicalDeclContext()->getRedeclContext()) &&
1029       !D->getLexicalDeclContext()->isFunctionOrMethod())
1030     return;
1031 
1032   // Template instantiations should also not be pushed into scope.
1033   if (isa<FunctionDecl>(D) &&
1034       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1035     return;
1036 
1037   // If this replaces anything in the current scope,
1038   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1039                                IEnd = IdResolver.end();
1040   for (; I != IEnd; ++I) {
1041     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1042       S->RemoveDecl(*I);
1043       IdResolver.RemoveDecl(*I);
1044 
1045       // Should only need to replace one decl.
1046       break;
1047     }
1048   }
1049 
1050   S->AddDecl(D);
1051 
1052   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1053     // Implicitly-generated labels may end up getting generated in an order that
1054     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1055     // the label at the appropriate place in the identifier chain.
1056     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1057       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1058       if (IDC == CurContext) {
1059         if (!S->isDeclScope(*I))
1060           continue;
1061       } else if (IDC->Encloses(CurContext))
1062         break;
1063     }
1064 
1065     IdResolver.InsertDeclAfter(I, D);
1066   } else {
1067     IdResolver.AddDecl(D);
1068   }
1069 }
1070 
1071 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1072   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1073     TUScope->AddDecl(D);
1074 }
1075 
1076 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1077                          bool ExplicitInstantiationOrSpecialization) {
1078   return IdResolver.isDeclInScope(D, Ctx, S,
1079                                   ExplicitInstantiationOrSpecialization);
1080 }
1081 
1082 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1083   DeclContext *TargetDC = DC->getPrimaryContext();
1084   do {
1085     if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1086       if (ScopeDC->getPrimaryContext() == TargetDC)
1087         return S;
1088   } while ((S = S->getParent()));
1089 
1090   return 0;
1091 }
1092 
1093 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1094                                             DeclContext*,
1095                                             ASTContext&);
1096 
1097 /// Filters out lookup results that don't fall within the given scope
1098 /// as determined by isDeclInScope.
1099 void Sema::FilterLookupForScope(LookupResult &R,
1100                                 DeclContext *Ctx, Scope *S,
1101                                 bool ConsiderLinkage,
1102                                 bool ExplicitInstantiationOrSpecialization) {
1103   LookupResult::Filter F = R.makeFilter();
1104   while (F.hasNext()) {
1105     NamedDecl *D = F.next();
1106 
1107     if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1108       continue;
1109 
1110     if (ConsiderLinkage &&
1111         isOutOfScopePreviousDeclaration(D, Ctx, Context))
1112       continue;
1113 
1114     F.erase();
1115   }
1116 
1117   F.done();
1118 }
1119 
1120 static bool isUsingDecl(NamedDecl *D) {
1121   return isa<UsingShadowDecl>(D) ||
1122          isa<UnresolvedUsingTypenameDecl>(D) ||
1123          isa<UnresolvedUsingValueDecl>(D);
1124 }
1125 
1126 /// Removes using shadow declarations from the lookup results.
1127 static void RemoveUsingDecls(LookupResult &R) {
1128   LookupResult::Filter F = R.makeFilter();
1129   while (F.hasNext())
1130     if (isUsingDecl(F.next()))
1131       F.erase();
1132 
1133   F.done();
1134 }
1135 
1136 /// \brief Check for this common pattern:
1137 /// @code
1138 /// class S {
1139 ///   S(const S&); // DO NOT IMPLEMENT
1140 ///   void operator=(const S&); // DO NOT IMPLEMENT
1141 /// };
1142 /// @endcode
1143 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1144   // FIXME: Should check for private access too but access is set after we get
1145   // the decl here.
1146   if (D->doesThisDeclarationHaveABody())
1147     return false;
1148 
1149   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1150     return CD->isCopyConstructor();
1151   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1152     return Method->isCopyAssignmentOperator();
1153   return false;
1154 }
1155 
1156 // We need this to handle
1157 //
1158 // typedef struct {
1159 //   void *foo() { return 0; }
1160 // } A;
1161 //
1162 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1163 // for example. If 'A', foo will have external linkage. If we have '*A',
1164 // foo will have no linkage. Since we can't know untill we get to the end
1165 // of the typedef, this function finds out if D might have non external linkage.
1166 // Callers should verify at the end of the TU if it D has external linkage or
1167 // not.
1168 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1169   const DeclContext *DC = D->getDeclContext();
1170   while (!DC->isTranslationUnit()) {
1171     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1172       if (!RD->hasNameForLinkage())
1173         return true;
1174     }
1175     DC = DC->getParent();
1176   }
1177 
1178   return !D->isExternallyVisible();
1179 }
1180 
1181 // FIXME: This needs to be refactored; some other isInMainFile users want
1182 // these semantics.
1183 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1184   if (S.TUKind != TU_Complete)
1185     return false;
1186   return S.SourceMgr.isInMainFile(Loc);
1187 }
1188 
1189 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1190   assert(D);
1191 
1192   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1193     return false;
1194 
1195   // Ignore class templates.
1196   if (D->getDeclContext()->isDependentContext() ||
1197       D->getLexicalDeclContext()->isDependentContext())
1198     return false;
1199 
1200   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1201     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1202       return false;
1203 
1204     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1205       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1206         return false;
1207     } else {
1208       // 'static inline' functions are defined in headers; don't warn.
1209       if (FD->isInlineSpecified() &&
1210           !isMainFileLoc(*this, FD->getLocation()))
1211         return false;
1212     }
1213 
1214     if (FD->doesThisDeclarationHaveABody() &&
1215         Context.DeclMustBeEmitted(FD))
1216       return false;
1217   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1218     // Constants and utility variables are defined in headers with internal
1219     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1220     // like "inline".)
1221     if (!isMainFileLoc(*this, VD->getLocation()))
1222       return false;
1223 
1224     if (Context.DeclMustBeEmitted(VD))
1225       return false;
1226 
1227     if (VD->isStaticDataMember() &&
1228         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1229       return false;
1230   } else {
1231     return false;
1232   }
1233 
1234   // Only warn for unused decls internal to the translation unit.
1235   return mightHaveNonExternalLinkage(D);
1236 }
1237 
1238 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1239   if (!D)
1240     return;
1241 
1242   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1243     const FunctionDecl *First = FD->getFirstDeclaration();
1244     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1245       return; // First should already be in the vector.
1246   }
1247 
1248   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1249     const VarDecl *First = VD->getFirstDeclaration();
1250     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1251       return; // First should already be in the vector.
1252   }
1253 
1254   if (ShouldWarnIfUnusedFileScopedDecl(D))
1255     UnusedFileScopedDecls.push_back(D);
1256 }
1257 
1258 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1259   if (D->isInvalidDecl())
1260     return false;
1261 
1262   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1263     return false;
1264 
1265   if (isa<LabelDecl>(D))
1266     return true;
1267 
1268   // White-list anything that isn't a local variable.
1269   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1270       !D->getDeclContext()->isFunctionOrMethod())
1271     return false;
1272 
1273   // Types of valid local variables should be complete, so this should succeed.
1274   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1275 
1276     // White-list anything with an __attribute__((unused)) type.
1277     QualType Ty = VD->getType();
1278 
1279     // Only look at the outermost level of typedef.
1280     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1281       if (TT->getDecl()->hasAttr<UnusedAttr>())
1282         return false;
1283     }
1284 
1285     // If we failed to complete the type for some reason, or if the type is
1286     // dependent, don't diagnose the variable.
1287     if (Ty->isIncompleteType() || Ty->isDependentType())
1288       return false;
1289 
1290     if (const TagType *TT = Ty->getAs<TagType>()) {
1291       const TagDecl *Tag = TT->getDecl();
1292       if (Tag->hasAttr<UnusedAttr>())
1293         return false;
1294 
1295       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1296         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1297           return false;
1298 
1299         if (const Expr *Init = VD->getInit()) {
1300           if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1301             Init = Cleanups->getSubExpr();
1302           const CXXConstructExpr *Construct =
1303             dyn_cast<CXXConstructExpr>(Init);
1304           if (Construct && !Construct->isElidable()) {
1305             CXXConstructorDecl *CD = Construct->getConstructor();
1306             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1307               return false;
1308           }
1309         }
1310       }
1311     }
1312 
1313     // TODO: __attribute__((unused)) templates?
1314   }
1315 
1316   return true;
1317 }
1318 
1319 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1320                                      FixItHint &Hint) {
1321   if (isa<LabelDecl>(D)) {
1322     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1323                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1324     if (AfterColon.isInvalid())
1325       return;
1326     Hint = FixItHint::CreateRemoval(CharSourceRange::
1327                                     getCharRange(D->getLocStart(), AfterColon));
1328   }
1329   return;
1330 }
1331 
1332 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1333 /// unless they are marked attr(unused).
1334 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1335   FixItHint Hint;
1336   if (!ShouldDiagnoseUnusedDecl(D))
1337     return;
1338 
1339   GenerateFixForUnusedDecl(D, Context, Hint);
1340 
1341   unsigned DiagID;
1342   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1343     DiagID = diag::warn_unused_exception_param;
1344   else if (isa<LabelDecl>(D))
1345     DiagID = diag::warn_unused_label;
1346   else
1347     DiagID = diag::warn_unused_variable;
1348 
1349   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1350 }
1351 
1352 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1353   // Verify that we have no forward references left.  If so, there was a goto
1354   // or address of a label taken, but no definition of it.  Label fwd
1355   // definitions are indicated with a null substmt.
1356   if (L->getStmt() == 0)
1357     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1358 }
1359 
1360 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1361   if (S->decl_empty()) return;
1362   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1363          "Scope shouldn't contain decls!");
1364 
1365   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1366        I != E; ++I) {
1367     Decl *TmpD = (*I);
1368     assert(TmpD && "This decl didn't get pushed??");
1369 
1370     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1371     NamedDecl *D = cast<NamedDecl>(TmpD);
1372 
1373     if (!D->getDeclName()) continue;
1374 
1375     // Diagnose unused variables in this scope.
1376     if (!S->hasUnrecoverableErrorOccurred())
1377       DiagnoseUnusedDecl(D);
1378 
1379     // If this was a forward reference to a label, verify it was defined.
1380     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1381       CheckPoppedLabel(LD, *this);
1382 
1383     // Remove this name from our lexical scope.
1384     IdResolver.RemoveDecl(D);
1385   }
1386 }
1387 
1388 void Sema::ActOnStartFunctionDeclarator() {
1389   ++InFunctionDeclarator;
1390 }
1391 
1392 void Sema::ActOnEndFunctionDeclarator() {
1393   assert(InFunctionDeclarator);
1394   --InFunctionDeclarator;
1395 }
1396 
1397 /// \brief Look for an Objective-C class in the translation unit.
1398 ///
1399 /// \param Id The name of the Objective-C class we're looking for. If
1400 /// typo-correction fixes this name, the Id will be updated
1401 /// to the fixed name.
1402 ///
1403 /// \param IdLoc The location of the name in the translation unit.
1404 ///
1405 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1406 /// if there is no class with the given name.
1407 ///
1408 /// \returns The declaration of the named Objective-C class, or NULL if the
1409 /// class could not be found.
1410 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1411                                               SourceLocation IdLoc,
1412                                               bool DoTypoCorrection) {
1413   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1414   // creation from this context.
1415   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1416 
1417   if (!IDecl && DoTypoCorrection) {
1418     // Perform typo correction at the given location, but only if we
1419     // find an Objective-C class name.
1420     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1421     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1422                                        LookupOrdinaryName, TUScope, NULL,
1423                                        Validator)) {
1424       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1425       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1426       Id = IDecl->getIdentifier();
1427     }
1428   }
1429   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1430   // This routine must always return a class definition, if any.
1431   if (Def && Def->getDefinition())
1432       Def = Def->getDefinition();
1433   return Def;
1434 }
1435 
1436 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1437 /// from S, where a non-field would be declared. This routine copes
1438 /// with the difference between C and C++ scoping rules in structs and
1439 /// unions. For example, the following code is well-formed in C but
1440 /// ill-formed in C++:
1441 /// @code
1442 /// struct S6 {
1443 ///   enum { BAR } e;
1444 /// };
1445 ///
1446 /// void test_S6() {
1447 ///   struct S6 a;
1448 ///   a.e = BAR;
1449 /// }
1450 /// @endcode
1451 /// For the declaration of BAR, this routine will return a different
1452 /// scope. The scope S will be the scope of the unnamed enumeration
1453 /// within S6. In C++, this routine will return the scope associated
1454 /// with S6, because the enumeration's scope is a transparent
1455 /// context but structures can contain non-field names. In C, this
1456 /// routine will return the translation unit scope, since the
1457 /// enumeration's scope is a transparent context and structures cannot
1458 /// contain non-field names.
1459 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1460   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1461          (S->getEntity() &&
1462           ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1463          (S->isClassScope() && !getLangOpts().CPlusPlus))
1464     S = S->getParent();
1465   return S;
1466 }
1467 
1468 /// \brief Looks up the declaration of "struct objc_super" and
1469 /// saves it for later use in building builtin declaration of
1470 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1471 /// pre-existing declaration exists no action takes place.
1472 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1473                                         IdentifierInfo *II) {
1474   if (!II->isStr("objc_msgSendSuper"))
1475     return;
1476   ASTContext &Context = ThisSema.Context;
1477 
1478   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1479                       SourceLocation(), Sema::LookupTagName);
1480   ThisSema.LookupName(Result, S);
1481   if (Result.getResultKind() == LookupResult::Found)
1482     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1483       Context.setObjCSuperType(Context.getTagDeclType(TD));
1484 }
1485 
1486 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1487 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1488 /// if we're creating this built-in in anticipation of redeclaring the
1489 /// built-in.
1490 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1491                                      Scope *S, bool ForRedeclaration,
1492                                      SourceLocation Loc) {
1493   LookupPredefedObjCSuperType(*this, S, II);
1494 
1495   Builtin::ID BID = (Builtin::ID)bid;
1496 
1497   ASTContext::GetBuiltinTypeError Error;
1498   QualType R = Context.GetBuiltinType(BID, Error);
1499   switch (Error) {
1500   case ASTContext::GE_None:
1501     // Okay
1502     break;
1503 
1504   case ASTContext::GE_Missing_stdio:
1505     if (ForRedeclaration)
1506       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1507         << Context.BuiltinInfo.GetName(BID);
1508     return 0;
1509 
1510   case ASTContext::GE_Missing_setjmp:
1511     if (ForRedeclaration)
1512       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1513         << Context.BuiltinInfo.GetName(BID);
1514     return 0;
1515 
1516   case ASTContext::GE_Missing_ucontext:
1517     if (ForRedeclaration)
1518       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1519         << Context.BuiltinInfo.GetName(BID);
1520     return 0;
1521   }
1522 
1523   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1524     Diag(Loc, diag::ext_implicit_lib_function_decl)
1525       << Context.BuiltinInfo.GetName(BID)
1526       << R;
1527     if (Context.BuiltinInfo.getHeaderName(BID) &&
1528         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1529           != DiagnosticsEngine::Ignored)
1530       Diag(Loc, diag::note_please_include_header)
1531         << Context.BuiltinInfo.getHeaderName(BID)
1532         << Context.BuiltinInfo.GetName(BID);
1533   }
1534 
1535   FunctionDecl *New = FunctionDecl::Create(Context,
1536                                            Context.getTranslationUnitDecl(),
1537                                            Loc, Loc, II, R, /*TInfo=*/0,
1538                                            SC_Extern,
1539                                            false,
1540                                            /*hasPrototype=*/true);
1541   New->setImplicit();
1542 
1543   // Create Decl objects for each parameter, adding them to the
1544   // FunctionDecl.
1545   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1546     SmallVector<ParmVarDecl*, 16> Params;
1547     for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1548       ParmVarDecl *parm =
1549         ParmVarDecl::Create(Context, New, SourceLocation(),
1550                             SourceLocation(), 0,
1551                             FT->getArgType(i), /*TInfo=*/0,
1552                             SC_None, 0);
1553       parm->setScopeInfo(0, i);
1554       Params.push_back(parm);
1555     }
1556     New->setParams(Params);
1557   }
1558 
1559   AddKnownFunctionAttributes(New);
1560 
1561   // TUScope is the translation-unit scope to insert this function into.
1562   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1563   // relate Scopes to DeclContexts, and probably eliminate CurContext
1564   // entirely, but we're not there yet.
1565   DeclContext *SavedContext = CurContext;
1566   CurContext = Context.getTranslationUnitDecl();
1567   PushOnScopeChains(New, TUScope);
1568   CurContext = SavedContext;
1569   return New;
1570 }
1571 
1572 /// \brief Filter out any previous declarations that the given declaration
1573 /// should not consider because they are not permitted to conflict, e.g.,
1574 /// because they come from hidden sub-modules and do not refer to the same
1575 /// entity.
1576 static void filterNonConflictingPreviousDecls(ASTContext &context,
1577                                               NamedDecl *decl,
1578                                               LookupResult &previous){
1579   // This is only interesting when modules are enabled.
1580   if (!context.getLangOpts().Modules)
1581     return;
1582 
1583   // Empty sets are uninteresting.
1584   if (previous.empty())
1585     return;
1586 
1587   LookupResult::Filter filter = previous.makeFilter();
1588   while (filter.hasNext()) {
1589     NamedDecl *old = filter.next();
1590 
1591     // Non-hidden declarations are never ignored.
1592     if (!old->isHidden())
1593       continue;
1594 
1595     if (!old->isExternallyVisible())
1596       filter.erase();
1597   }
1598 
1599   filter.done();
1600 }
1601 
1602 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1603   QualType OldType;
1604   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1605     OldType = OldTypedef->getUnderlyingType();
1606   else
1607     OldType = Context.getTypeDeclType(Old);
1608   QualType NewType = New->getUnderlyingType();
1609 
1610   if (NewType->isVariablyModifiedType()) {
1611     // Must not redefine a typedef with a variably-modified type.
1612     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1613     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1614       << Kind << NewType;
1615     if (Old->getLocation().isValid())
1616       Diag(Old->getLocation(), diag::note_previous_definition);
1617     New->setInvalidDecl();
1618     return true;
1619   }
1620 
1621   if (OldType != NewType &&
1622       !OldType->isDependentType() &&
1623       !NewType->isDependentType() &&
1624       !Context.hasSameType(OldType, NewType)) {
1625     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1626     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1627       << Kind << NewType << OldType;
1628     if (Old->getLocation().isValid())
1629       Diag(Old->getLocation(), diag::note_previous_definition);
1630     New->setInvalidDecl();
1631     return true;
1632   }
1633   return false;
1634 }
1635 
1636 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1637 /// same name and scope as a previous declaration 'Old'.  Figure out
1638 /// how to resolve this situation, merging decls or emitting
1639 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1640 ///
1641 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1642   // If the new decl is known invalid already, don't bother doing any
1643   // merging checks.
1644   if (New->isInvalidDecl()) return;
1645 
1646   // Allow multiple definitions for ObjC built-in typedefs.
1647   // FIXME: Verify the underlying types are equivalent!
1648   if (getLangOpts().ObjC1) {
1649     const IdentifierInfo *TypeID = New->getIdentifier();
1650     switch (TypeID->getLength()) {
1651     default: break;
1652     case 2:
1653       {
1654         if (!TypeID->isStr("id"))
1655           break;
1656         QualType T = New->getUnderlyingType();
1657         if (!T->isPointerType())
1658           break;
1659         if (!T->isVoidPointerType()) {
1660           QualType PT = T->getAs<PointerType>()->getPointeeType();
1661           if (!PT->isStructureType())
1662             break;
1663         }
1664         Context.setObjCIdRedefinitionType(T);
1665         // Install the built-in type for 'id', ignoring the current definition.
1666         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1667         return;
1668       }
1669     case 5:
1670       if (!TypeID->isStr("Class"))
1671         break;
1672       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1673       // Install the built-in type for 'Class', ignoring the current definition.
1674       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1675       return;
1676     case 3:
1677       if (!TypeID->isStr("SEL"))
1678         break;
1679       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1680       // Install the built-in type for 'SEL', ignoring the current definition.
1681       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1682       return;
1683     }
1684     // Fall through - the typedef name was not a builtin type.
1685   }
1686 
1687   // Verify the old decl was also a type.
1688   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1689   if (!Old) {
1690     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1691       << New->getDeclName();
1692 
1693     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1694     if (OldD->getLocation().isValid())
1695       Diag(OldD->getLocation(), diag::note_previous_definition);
1696 
1697     return New->setInvalidDecl();
1698   }
1699 
1700   // If the old declaration is invalid, just give up here.
1701   if (Old->isInvalidDecl())
1702     return New->setInvalidDecl();
1703 
1704   // If the typedef types are not identical, reject them in all languages and
1705   // with any extensions enabled.
1706   if (isIncompatibleTypedef(Old, New))
1707     return;
1708 
1709   // The types match.  Link up the redeclaration chain if the old
1710   // declaration was a typedef.
1711   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1712     New->setPreviousDeclaration(Typedef);
1713 
1714   mergeDeclAttributes(New, Old);
1715 
1716   if (getLangOpts().MicrosoftExt)
1717     return;
1718 
1719   if (getLangOpts().CPlusPlus) {
1720     // C++ [dcl.typedef]p2:
1721     //   In a given non-class scope, a typedef specifier can be used to
1722     //   redefine the name of any type declared in that scope to refer
1723     //   to the type to which it already refers.
1724     if (!isa<CXXRecordDecl>(CurContext))
1725       return;
1726 
1727     // C++0x [dcl.typedef]p4:
1728     //   In a given class scope, a typedef specifier can be used to redefine
1729     //   any class-name declared in that scope that is not also a typedef-name
1730     //   to refer to the type to which it already refers.
1731     //
1732     // This wording came in via DR424, which was a correction to the
1733     // wording in DR56, which accidentally banned code like:
1734     //
1735     //   struct S {
1736     //     typedef struct A { } A;
1737     //   };
1738     //
1739     // in the C++03 standard. We implement the C++0x semantics, which
1740     // allow the above but disallow
1741     //
1742     //   struct S {
1743     //     typedef int I;
1744     //     typedef int I;
1745     //   };
1746     //
1747     // since that was the intent of DR56.
1748     if (!isa<TypedefNameDecl>(Old))
1749       return;
1750 
1751     Diag(New->getLocation(), diag::err_redefinition)
1752       << New->getDeclName();
1753     Diag(Old->getLocation(), diag::note_previous_definition);
1754     return New->setInvalidDecl();
1755   }
1756 
1757   // Modules always permit redefinition of typedefs, as does C11.
1758   if (getLangOpts().Modules || getLangOpts().C11)
1759     return;
1760 
1761   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1762   // is normally mapped to an error, but can be controlled with
1763   // -Wtypedef-redefinition.  If either the original or the redefinition is
1764   // in a system header, don't emit this for compatibility with GCC.
1765   if (getDiagnostics().getSuppressSystemWarnings() &&
1766       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1767        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1768     return;
1769 
1770   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1771     << New->getDeclName();
1772   Diag(Old->getLocation(), diag::note_previous_definition);
1773   return;
1774 }
1775 
1776 /// DeclhasAttr - returns true if decl Declaration already has the target
1777 /// attribute.
1778 static bool
1779 DeclHasAttr(const Decl *D, const Attr *A) {
1780   // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1781   // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1782   // responsible for making sure they are consistent.
1783   const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1784   if (AA)
1785     return false;
1786 
1787   // The following thread safety attributes can also be duplicated.
1788   switch (A->getKind()) {
1789     case attr::ExclusiveLocksRequired:
1790     case attr::SharedLocksRequired:
1791     case attr::LocksExcluded:
1792     case attr::ExclusiveLockFunction:
1793     case attr::SharedLockFunction:
1794     case attr::UnlockFunction:
1795     case attr::ExclusiveTrylockFunction:
1796     case attr::SharedTrylockFunction:
1797     case attr::GuardedBy:
1798     case attr::PtGuardedBy:
1799     case attr::AcquiredBefore:
1800     case attr::AcquiredAfter:
1801       return false;
1802     default:
1803       ;
1804   }
1805 
1806   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1807   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1808   for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1809     if ((*i)->getKind() == A->getKind()) {
1810       if (Ann) {
1811         if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1812           return true;
1813         continue;
1814       }
1815       // FIXME: Don't hardcode this check
1816       if (OA && isa<OwnershipAttr>(*i))
1817         return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1818       return true;
1819     }
1820 
1821   return false;
1822 }
1823 
1824 static bool isAttributeTargetADefinition(Decl *D) {
1825   if (VarDecl *VD = dyn_cast<VarDecl>(D))
1826     return VD->isThisDeclarationADefinition();
1827   if (TagDecl *TD = dyn_cast<TagDecl>(D))
1828     return TD->isCompleteDefinition() || TD->isBeingDefined();
1829   return true;
1830 }
1831 
1832 /// Merge alignment attributes from \p Old to \p New, taking into account the
1833 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1834 ///
1835 /// \return \c true if any attributes were added to \p New.
1836 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1837   // Look for alignas attributes on Old, and pick out whichever attribute
1838   // specifies the strictest alignment requirement.
1839   AlignedAttr *OldAlignasAttr = 0;
1840   AlignedAttr *OldStrictestAlignAttr = 0;
1841   unsigned OldAlign = 0;
1842   for (specific_attr_iterator<AlignedAttr>
1843          I = Old->specific_attr_begin<AlignedAttr>(),
1844          E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1845     // FIXME: We have no way of representing inherited dependent alignments
1846     // in a case like:
1847     //   template<int A, int B> struct alignas(A) X;
1848     //   template<int A, int B> struct alignas(B) X {};
1849     // For now, we just ignore any alignas attributes which are not on the
1850     // definition in such a case.
1851     if (I->isAlignmentDependent())
1852       return false;
1853 
1854     if (I->isAlignas())
1855       OldAlignasAttr = *I;
1856 
1857     unsigned Align = I->getAlignment(S.Context);
1858     if (Align > OldAlign) {
1859       OldAlign = Align;
1860       OldStrictestAlignAttr = *I;
1861     }
1862   }
1863 
1864   // Look for alignas attributes on New.
1865   AlignedAttr *NewAlignasAttr = 0;
1866   unsigned NewAlign = 0;
1867   for (specific_attr_iterator<AlignedAttr>
1868          I = New->specific_attr_begin<AlignedAttr>(),
1869          E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1870     if (I->isAlignmentDependent())
1871       return false;
1872 
1873     if (I->isAlignas())
1874       NewAlignasAttr = *I;
1875 
1876     unsigned Align = I->getAlignment(S.Context);
1877     if (Align > NewAlign)
1878       NewAlign = Align;
1879   }
1880 
1881   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1882     // Both declarations have 'alignas' attributes. We require them to match.
1883     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1884     // fall short. (If two declarations both have alignas, they must both match
1885     // every definition, and so must match each other if there is a definition.)
1886 
1887     // If either declaration only contains 'alignas(0)' specifiers, then it
1888     // specifies the natural alignment for the type.
1889     if (OldAlign == 0 || NewAlign == 0) {
1890       QualType Ty;
1891       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1892         Ty = VD->getType();
1893       else
1894         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1895 
1896       if (OldAlign == 0)
1897         OldAlign = S.Context.getTypeAlign(Ty);
1898       if (NewAlign == 0)
1899         NewAlign = S.Context.getTypeAlign(Ty);
1900     }
1901 
1902     if (OldAlign != NewAlign) {
1903       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1904         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1905         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1906       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1907     }
1908   }
1909 
1910   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1911     // C++11 [dcl.align]p6:
1912     //   if any declaration of an entity has an alignment-specifier,
1913     //   every defining declaration of that entity shall specify an
1914     //   equivalent alignment.
1915     // C11 6.7.5/7:
1916     //   If the definition of an object does not have an alignment
1917     //   specifier, any other declaration of that object shall also
1918     //   have no alignment specifier.
1919     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1920       << OldAlignasAttr->isC11();
1921     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1922       << OldAlignasAttr->isC11();
1923   }
1924 
1925   bool AnyAdded = false;
1926 
1927   // Ensure we have an attribute representing the strictest alignment.
1928   if (OldAlign > NewAlign) {
1929     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1930     Clone->setInherited(true);
1931     New->addAttr(Clone);
1932     AnyAdded = true;
1933   }
1934 
1935   // Ensure we have an alignas attribute if the old declaration had one.
1936   if (OldAlignasAttr && !NewAlignasAttr &&
1937       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1938     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1939     Clone->setInherited(true);
1940     New->addAttr(Clone);
1941     AnyAdded = true;
1942   }
1943 
1944   return AnyAdded;
1945 }
1946 
1947 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1948                                bool Override) {
1949   InheritableAttr *NewAttr = NULL;
1950   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1951   if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1952     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1953                                       AA->getIntroduced(), AA->getDeprecated(),
1954                                       AA->getObsoleted(), AA->getUnavailable(),
1955                                       AA->getMessage(), Override,
1956                                       AttrSpellingListIndex);
1957   else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1958     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1959                                     AttrSpellingListIndex);
1960   else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1961     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1962                                         AttrSpellingListIndex);
1963   else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1964     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1965                                    AttrSpellingListIndex);
1966   else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1967     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1968                                    AttrSpellingListIndex);
1969   else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1970     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1971                                 FA->getFormatIdx(), FA->getFirstArg(),
1972                                 AttrSpellingListIndex);
1973   else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1974     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1975                                  AttrSpellingListIndex);
1976   else if (isa<AlignedAttr>(Attr))
1977     // AlignedAttrs are handled separately, because we need to handle all
1978     // such attributes on a declaration at the same time.
1979     NewAttr = 0;
1980   else if (!DeclHasAttr(D, Attr))
1981     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
1982 
1983   if (NewAttr) {
1984     NewAttr->setInherited(true);
1985     D->addAttr(NewAttr);
1986     return true;
1987   }
1988 
1989   return false;
1990 }
1991 
1992 static const Decl *getDefinition(const Decl *D) {
1993   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
1994     return TD->getDefinition();
1995   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1996     return VD->getDefinition();
1997   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1998     const FunctionDecl* Def;
1999     if (FD->hasBody(Def))
2000       return Def;
2001   }
2002   return NULL;
2003 }
2004 
2005 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2006   for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2007        I != E; ++I) {
2008     Attr *Attribute = *I;
2009     if (Attribute->getKind() == Kind)
2010       return true;
2011   }
2012   return false;
2013 }
2014 
2015 /// checkNewAttributesAfterDef - If we already have a definition, check that
2016 /// there are no new attributes in this declaration.
2017 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2018   if (!New->hasAttrs())
2019     return;
2020 
2021   const Decl *Def = getDefinition(Old);
2022   if (!Def || Def == New)
2023     return;
2024 
2025   AttrVec &NewAttributes = New->getAttrs();
2026   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2027     const Attr *NewAttribute = NewAttributes[I];
2028     if (hasAttribute(Def, NewAttribute->getKind())) {
2029       ++I;
2030       continue; // regular attr merging will take care of validating this.
2031     }
2032 
2033     if (isa<C11NoReturnAttr>(NewAttribute)) {
2034       // C's _Noreturn is allowed to be added to a function after it is defined.
2035       ++I;
2036       continue;
2037     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2038       if (AA->isAlignas()) {
2039         // C++11 [dcl.align]p6:
2040         //   if any declaration of an entity has an alignment-specifier,
2041         //   every defining declaration of that entity shall specify an
2042         //   equivalent alignment.
2043         // C11 6.7.5/7:
2044         //   If the definition of an object does not have an alignment
2045         //   specifier, any other declaration of that object shall also
2046         //   have no alignment specifier.
2047         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2048           << AA->isC11();
2049         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2050           << AA->isC11();
2051         NewAttributes.erase(NewAttributes.begin() + I);
2052         --E;
2053         continue;
2054       }
2055     }
2056 
2057     S.Diag(NewAttribute->getLocation(),
2058            diag::warn_attribute_precede_definition);
2059     S.Diag(Def->getLocation(), diag::note_previous_definition);
2060     NewAttributes.erase(NewAttributes.begin() + I);
2061     --E;
2062   }
2063 }
2064 
2065 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2066 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2067                                AvailabilityMergeKind AMK) {
2068   if (!Old->hasAttrs() && !New->hasAttrs())
2069     return;
2070 
2071   // attributes declared post-definition are currently ignored
2072   checkNewAttributesAfterDef(*this, New, Old);
2073 
2074   if (!Old->hasAttrs())
2075     return;
2076 
2077   bool foundAny = New->hasAttrs();
2078 
2079   // Ensure that any moving of objects within the allocated map is done before
2080   // we process them.
2081   if (!foundAny) New->setAttrs(AttrVec());
2082 
2083   for (specific_attr_iterator<InheritableAttr>
2084          i = Old->specific_attr_begin<InheritableAttr>(),
2085          e = Old->specific_attr_end<InheritableAttr>();
2086        i != e; ++i) {
2087     bool Override = false;
2088     // Ignore deprecated/unavailable/availability attributes if requested.
2089     if (isa<DeprecatedAttr>(*i) ||
2090         isa<UnavailableAttr>(*i) ||
2091         isa<AvailabilityAttr>(*i)) {
2092       switch (AMK) {
2093       case AMK_None:
2094         continue;
2095 
2096       case AMK_Redeclaration:
2097         break;
2098 
2099       case AMK_Override:
2100         Override = true;
2101         break;
2102       }
2103     }
2104 
2105     if (mergeDeclAttribute(*this, New, *i, Override))
2106       foundAny = true;
2107   }
2108 
2109   if (mergeAlignedAttrs(*this, New, Old))
2110     foundAny = true;
2111 
2112   if (!foundAny) New->dropAttrs();
2113 }
2114 
2115 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2116 /// to the new one.
2117 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2118                                      const ParmVarDecl *oldDecl,
2119                                      Sema &S) {
2120   // C++11 [dcl.attr.depend]p2:
2121   //   The first declaration of a function shall specify the
2122   //   carries_dependency attribute for its declarator-id if any declaration
2123   //   of the function specifies the carries_dependency attribute.
2124   if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2125       !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2126     S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2127            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2128     // Find the first declaration of the parameter.
2129     // FIXME: Should we build redeclaration chains for function parameters?
2130     const FunctionDecl *FirstFD =
2131       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDeclaration();
2132     const ParmVarDecl *FirstVD =
2133       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2134     S.Diag(FirstVD->getLocation(),
2135            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2136   }
2137 
2138   if (!oldDecl->hasAttrs())
2139     return;
2140 
2141   bool foundAny = newDecl->hasAttrs();
2142 
2143   // Ensure that any moving of objects within the allocated map is
2144   // done before we process them.
2145   if (!foundAny) newDecl->setAttrs(AttrVec());
2146 
2147   for (specific_attr_iterator<InheritableParamAttr>
2148        i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2149        e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2150     if (!DeclHasAttr(newDecl, *i)) {
2151       InheritableAttr *newAttr =
2152         cast<InheritableParamAttr>((*i)->clone(S.Context));
2153       newAttr->setInherited(true);
2154       newDecl->addAttr(newAttr);
2155       foundAny = true;
2156     }
2157   }
2158 
2159   if (!foundAny) newDecl->dropAttrs();
2160 }
2161 
2162 namespace {
2163 
2164 /// Used in MergeFunctionDecl to keep track of function parameters in
2165 /// C.
2166 struct GNUCompatibleParamWarning {
2167   ParmVarDecl *OldParm;
2168   ParmVarDecl *NewParm;
2169   QualType PromotedType;
2170 };
2171 
2172 }
2173 
2174 /// getSpecialMember - get the special member enum for a method.
2175 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2176   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2177     if (Ctor->isDefaultConstructor())
2178       return Sema::CXXDefaultConstructor;
2179 
2180     if (Ctor->isCopyConstructor())
2181       return Sema::CXXCopyConstructor;
2182 
2183     if (Ctor->isMoveConstructor())
2184       return Sema::CXXMoveConstructor;
2185   } else if (isa<CXXDestructorDecl>(MD)) {
2186     return Sema::CXXDestructor;
2187   } else if (MD->isCopyAssignmentOperator()) {
2188     return Sema::CXXCopyAssignment;
2189   } else if (MD->isMoveAssignmentOperator()) {
2190     return Sema::CXXMoveAssignment;
2191   }
2192 
2193   return Sema::CXXInvalid;
2194 }
2195 
2196 /// canRedefineFunction - checks if a function can be redefined. Currently,
2197 /// only extern inline functions can be redefined, and even then only in
2198 /// GNU89 mode.
2199 static bool canRedefineFunction(const FunctionDecl *FD,
2200                                 const LangOptions& LangOpts) {
2201   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2202           !LangOpts.CPlusPlus &&
2203           FD->isInlineSpecified() &&
2204           FD->getStorageClass() == SC_Extern);
2205 }
2206 
2207 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2208   const AttributedType *AT = T->getAs<AttributedType>();
2209   while (AT && !AT->isCallingConv())
2210     AT = AT->getModifiedType()->getAs<AttributedType>();
2211   return AT;
2212 }
2213 
2214 template <typename T>
2215 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2216   const DeclContext *DC = Old->getDeclContext();
2217   if (DC->isRecord())
2218     return false;
2219 
2220   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2221   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2222     return true;
2223   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2224     return true;
2225   return false;
2226 }
2227 
2228 /// MergeFunctionDecl - We just parsed a function 'New' from
2229 /// declarator D which has the same name and scope as a previous
2230 /// declaration 'Old'.  Figure out how to resolve this situation,
2231 /// merging decls or emitting diagnostics as appropriate.
2232 ///
2233 /// In C++, New and Old must be declarations that are not
2234 /// overloaded. Use IsOverload to determine whether New and Old are
2235 /// overloaded, and to select the Old declaration that New should be
2236 /// merged with.
2237 ///
2238 /// Returns true if there was an error, false otherwise.
2239 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2240                              bool MergeTypeWithOld) {
2241   // Verify the old decl was also a function.
2242   FunctionDecl *Old = 0;
2243   if (FunctionTemplateDecl *OldFunctionTemplate
2244         = dyn_cast<FunctionTemplateDecl>(OldD))
2245     Old = OldFunctionTemplate->getTemplatedDecl();
2246   else
2247     Old = dyn_cast<FunctionDecl>(OldD);
2248   if (!Old) {
2249     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2250       if (New->getFriendObjectKind()) {
2251         Diag(New->getLocation(), diag::err_using_decl_friend);
2252         Diag(Shadow->getTargetDecl()->getLocation(),
2253              diag::note_using_decl_target);
2254         Diag(Shadow->getUsingDecl()->getLocation(),
2255              diag::note_using_decl) << 0;
2256         return true;
2257       }
2258 
2259       Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2260       Diag(Shadow->getTargetDecl()->getLocation(),
2261            diag::note_using_decl_target);
2262       Diag(Shadow->getUsingDecl()->getLocation(),
2263            diag::note_using_decl) << 0;
2264       return true;
2265     }
2266 
2267     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2268       << New->getDeclName();
2269     Diag(OldD->getLocation(), diag::note_previous_definition);
2270     return true;
2271   }
2272 
2273   // If the old declaration is invalid, just give up here.
2274   if (Old->isInvalidDecl())
2275     return true;
2276 
2277   // Determine whether the previous declaration was a definition,
2278   // implicit declaration, or a declaration.
2279   diag::kind PrevDiag;
2280   if (Old->isThisDeclarationADefinition())
2281     PrevDiag = diag::note_previous_definition;
2282   else if (Old->isImplicit())
2283     PrevDiag = diag::note_previous_implicit_declaration;
2284   else
2285     PrevDiag = diag::note_previous_declaration;
2286 
2287   // Don't complain about this if we're in GNU89 mode and the old function
2288   // is an extern inline function.
2289   // Don't complain about specializations. They are not supposed to have
2290   // storage classes.
2291   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2292       New->getStorageClass() == SC_Static &&
2293       Old->hasExternalFormalLinkage() &&
2294       !New->getTemplateSpecializationInfo() &&
2295       !canRedefineFunction(Old, getLangOpts())) {
2296     if (getLangOpts().MicrosoftExt) {
2297       Diag(New->getLocation(), diag::warn_static_non_static) << New;
2298       Diag(Old->getLocation(), PrevDiag);
2299     } else {
2300       Diag(New->getLocation(), diag::err_static_non_static) << New;
2301       Diag(Old->getLocation(), PrevDiag);
2302       return true;
2303     }
2304   }
2305 
2306 
2307   // If a function is first declared with a calling convention, but is later
2308   // declared or defined without one, all following decls assume the calling
2309   // convention of the first.
2310   //
2311   // It's OK if a function is first declared without a calling convention,
2312   // but is later declared or defined with the default calling convention.
2313   //
2314   // To test if either decl has an explicit calling convention, we look for
2315   // AttributedType sugar nodes on the type as written.  If they are missing or
2316   // were canonicalized away, we assume the calling convention was implicit.
2317   //
2318   // Note also that we DO NOT return at this point, because we still have
2319   // other tests to run.
2320   QualType OldQType = Context.getCanonicalType(Old->getType());
2321   QualType NewQType = Context.getCanonicalType(New->getType());
2322   const FunctionType *OldType = cast<FunctionType>(OldQType);
2323   const FunctionType *NewType = cast<FunctionType>(NewQType);
2324   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2325   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2326   bool RequiresAdjustment = false;
2327 
2328   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2329     FunctionDecl *First = Old->getFirstDeclaration();
2330     const FunctionType *FT =
2331         First->getType().getCanonicalType()->castAs<FunctionType>();
2332     FunctionType::ExtInfo FI = FT->getExtInfo();
2333     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2334     if (!NewCCExplicit) {
2335       // Inherit the CC from the previous declaration if it was specified
2336       // there but not here.
2337       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2338       RequiresAdjustment = true;
2339     } else {
2340       // Calling conventions aren't compatible, so complain.
2341       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2342       Diag(New->getLocation(), diag::err_cconv_change)
2343         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2344         << !FirstCCExplicit
2345         << (!FirstCCExplicit ? "" :
2346             FunctionType::getNameForCallConv(FI.getCC()));
2347 
2348       // Put the note on the first decl, since it is the one that matters.
2349       Diag(First->getLocation(), diag::note_previous_declaration);
2350       return true;
2351     }
2352   }
2353 
2354   // FIXME: diagnose the other way around?
2355   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2356     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2357     RequiresAdjustment = true;
2358   }
2359 
2360   // Merge regparm attribute.
2361   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2362       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2363     if (NewTypeInfo.getHasRegParm()) {
2364       Diag(New->getLocation(), diag::err_regparm_mismatch)
2365         << NewType->getRegParmType()
2366         << OldType->getRegParmType();
2367       Diag(Old->getLocation(), diag::note_previous_declaration);
2368       return true;
2369     }
2370 
2371     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2372     RequiresAdjustment = true;
2373   }
2374 
2375   // Merge ns_returns_retained attribute.
2376   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2377     if (NewTypeInfo.getProducesResult()) {
2378       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2379       Diag(Old->getLocation(), diag::note_previous_declaration);
2380       return true;
2381     }
2382 
2383     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2384     RequiresAdjustment = true;
2385   }
2386 
2387   if (RequiresAdjustment) {
2388     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2389     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2390     New->setType(QualType(AdjustedType, 0));
2391     NewQType = Context.getCanonicalType(New->getType());
2392     NewType = cast<FunctionType>(NewQType);
2393   }
2394 
2395   // If this redeclaration makes the function inline, we may need to add it to
2396   // UndefinedButUsed.
2397   if (!Old->isInlined() && New->isInlined() &&
2398       !New->hasAttr<GNUInlineAttr>() &&
2399       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2400       Old->isUsed(false) &&
2401       !Old->isDefined() && !New->isThisDeclarationADefinition())
2402     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2403                                            SourceLocation()));
2404 
2405   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2406   // about it.
2407   if (New->hasAttr<GNUInlineAttr>() &&
2408       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2409     UndefinedButUsed.erase(Old->getCanonicalDecl());
2410   }
2411 
2412   if (getLangOpts().CPlusPlus) {
2413     // (C++98 13.1p2):
2414     //   Certain function declarations cannot be overloaded:
2415     //     -- Function declarations that differ only in the return type
2416     //        cannot be overloaded.
2417 
2418     // Go back to the type source info to compare the declared return types,
2419     // per C++1y [dcl.type.auto]p13:
2420     //   Redeclarations or specializations of a function or function template
2421     //   with a declared return type that uses a placeholder type shall also
2422     //   use that placeholder, not a deduced type.
2423     QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2424       ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2425       : OldType)->getResultType();
2426     QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2427       ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2428       : NewType)->getResultType();
2429     QualType ResQT;
2430     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2431         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2432           New->isLocalExternDecl())) {
2433       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2434           OldDeclaredReturnType->isObjCObjectPointerType())
2435         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2436       if (ResQT.isNull()) {
2437         if (New->isCXXClassMember() && New->isOutOfLine())
2438           Diag(New->getLocation(),
2439                diag::err_member_def_does_not_match_ret_type) << New;
2440         else
2441           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2442         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2443         return true;
2444       }
2445       else
2446         NewQType = ResQT;
2447     }
2448 
2449     QualType OldReturnType = OldType->getResultType();
2450     QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2451     if (OldReturnType != NewReturnType) {
2452       // If this function has a deduced return type and has already been
2453       // defined, copy the deduced value from the old declaration.
2454       AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2455       if (OldAT && OldAT->isDeduced()) {
2456         New->setType(
2457             SubstAutoType(New->getType(),
2458                           OldAT->isDependentType() ? Context.DependentTy
2459                                                    : OldAT->getDeducedType()));
2460         NewQType = Context.getCanonicalType(
2461             SubstAutoType(NewQType,
2462                           OldAT->isDependentType() ? Context.DependentTy
2463                                                    : OldAT->getDeducedType()));
2464       }
2465     }
2466 
2467     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2468     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2469     if (OldMethod && NewMethod) {
2470       // Preserve triviality.
2471       NewMethod->setTrivial(OldMethod->isTrivial());
2472 
2473       // MSVC allows explicit template specialization at class scope:
2474       // 2 CXMethodDecls referring to the same function will be injected.
2475       // We don't want a redeclartion error.
2476       bool IsClassScopeExplicitSpecialization =
2477                               OldMethod->isFunctionTemplateSpecialization() &&
2478                               NewMethod->isFunctionTemplateSpecialization();
2479       bool isFriend = NewMethod->getFriendObjectKind();
2480 
2481       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2482           !IsClassScopeExplicitSpecialization) {
2483         //    -- Member function declarations with the same name and the
2484         //       same parameter types cannot be overloaded if any of them
2485         //       is a static member function declaration.
2486         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2487           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2488           Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2489           return true;
2490         }
2491 
2492         // C++ [class.mem]p1:
2493         //   [...] A member shall not be declared twice in the
2494         //   member-specification, except that a nested class or member
2495         //   class template can be declared and then later defined.
2496         if (ActiveTemplateInstantiations.empty()) {
2497           unsigned NewDiag;
2498           if (isa<CXXConstructorDecl>(OldMethod))
2499             NewDiag = diag::err_constructor_redeclared;
2500           else if (isa<CXXDestructorDecl>(NewMethod))
2501             NewDiag = diag::err_destructor_redeclared;
2502           else if (isa<CXXConversionDecl>(NewMethod))
2503             NewDiag = diag::err_conv_function_redeclared;
2504           else
2505             NewDiag = diag::err_member_redeclared;
2506 
2507           Diag(New->getLocation(), NewDiag);
2508         } else {
2509           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2510             << New << New->getType();
2511         }
2512         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2513 
2514       // Complain if this is an explicit declaration of a special
2515       // member that was initially declared implicitly.
2516       //
2517       // As an exception, it's okay to befriend such methods in order
2518       // to permit the implicit constructor/destructor/operator calls.
2519       } else if (OldMethod->isImplicit()) {
2520         if (isFriend) {
2521           NewMethod->setImplicit();
2522         } else {
2523           Diag(NewMethod->getLocation(),
2524                diag::err_definition_of_implicitly_declared_member)
2525             << New << getSpecialMember(OldMethod);
2526           return true;
2527         }
2528       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2529         Diag(NewMethod->getLocation(),
2530              diag::err_definition_of_explicitly_defaulted_member)
2531           << getSpecialMember(OldMethod);
2532         return true;
2533       }
2534     }
2535 
2536     // C++11 [dcl.attr.noreturn]p1:
2537     //   The first declaration of a function shall specify the noreturn
2538     //   attribute if any declaration of that function specifies the noreturn
2539     //   attribute.
2540     if (New->hasAttr<CXX11NoReturnAttr>() &&
2541         !Old->hasAttr<CXX11NoReturnAttr>()) {
2542       Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2543            diag::err_noreturn_missing_on_first_decl);
2544       Diag(Old->getFirstDeclaration()->getLocation(),
2545            diag::note_noreturn_missing_first_decl);
2546     }
2547 
2548     // C++11 [dcl.attr.depend]p2:
2549     //   The first declaration of a function shall specify the
2550     //   carries_dependency attribute for its declarator-id if any declaration
2551     //   of the function specifies the carries_dependency attribute.
2552     if (New->hasAttr<CarriesDependencyAttr>() &&
2553         !Old->hasAttr<CarriesDependencyAttr>()) {
2554       Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2555            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2556       Diag(Old->getFirstDeclaration()->getLocation(),
2557            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2558     }
2559 
2560     // (C++98 8.3.5p3):
2561     //   All declarations for a function shall agree exactly in both the
2562     //   return type and the parameter-type-list.
2563     // We also want to respect all the extended bits except noreturn.
2564 
2565     // noreturn should now match unless the old type info didn't have it.
2566     QualType OldQTypeForComparison = OldQType;
2567     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2568       assert(OldQType == QualType(OldType, 0));
2569       const FunctionType *OldTypeForComparison
2570         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2571       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2572       assert(OldQTypeForComparison.isCanonical());
2573     }
2574 
2575     if (haveIncompatibleLanguageLinkages(Old, New)) {
2576       Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2577       Diag(Old->getLocation(), PrevDiag);
2578       return true;
2579     }
2580 
2581     if (OldQTypeForComparison == NewQType)
2582       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2583 
2584     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2585         New->isLocalExternDecl()) {
2586       // It's OK if we couldn't merge types for a local function declaraton
2587       // if either the old or new type is dependent. We'll merge the types
2588       // when we instantiate the function.
2589       return false;
2590     }
2591 
2592     // Fall through for conflicting redeclarations and redefinitions.
2593   }
2594 
2595   // C: Function types need to be compatible, not identical. This handles
2596   // duplicate function decls like "void f(int); void f(enum X);" properly.
2597   if (!getLangOpts().CPlusPlus &&
2598       Context.typesAreCompatible(OldQType, NewQType)) {
2599     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2600     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2601     const FunctionProtoType *OldProto = 0;
2602     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2603         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2604       // The old declaration provided a function prototype, but the
2605       // new declaration does not. Merge in the prototype.
2606       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2607       SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2608                                                  OldProto->arg_type_end());
2609       NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2610                                          ParamTypes,
2611                                          OldProto->getExtProtoInfo());
2612       New->setType(NewQType);
2613       New->setHasInheritedPrototype();
2614 
2615       // Synthesize a parameter for each argument type.
2616       SmallVector<ParmVarDecl*, 16> Params;
2617       for (FunctionProtoType::arg_type_iterator
2618              ParamType = OldProto->arg_type_begin(),
2619              ParamEnd = OldProto->arg_type_end();
2620            ParamType != ParamEnd; ++ParamType) {
2621         ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2622                                                  SourceLocation(),
2623                                                  SourceLocation(), 0,
2624                                                  *ParamType, /*TInfo=*/0,
2625                                                  SC_None,
2626                                                  0);
2627         Param->setScopeInfo(0, Params.size());
2628         Param->setImplicit();
2629         Params.push_back(Param);
2630       }
2631 
2632       New->setParams(Params);
2633     }
2634 
2635     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2636   }
2637 
2638   // GNU C permits a K&R definition to follow a prototype declaration
2639   // if the declared types of the parameters in the K&R definition
2640   // match the types in the prototype declaration, even when the
2641   // promoted types of the parameters from the K&R definition differ
2642   // from the types in the prototype. GCC then keeps the types from
2643   // the prototype.
2644   //
2645   // If a variadic prototype is followed by a non-variadic K&R definition,
2646   // the K&R definition becomes variadic.  This is sort of an edge case, but
2647   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2648   // C99 6.9.1p8.
2649   if (!getLangOpts().CPlusPlus &&
2650       Old->hasPrototype() && !New->hasPrototype() &&
2651       New->getType()->getAs<FunctionProtoType>() &&
2652       Old->getNumParams() == New->getNumParams()) {
2653     SmallVector<QualType, 16> ArgTypes;
2654     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2655     const FunctionProtoType *OldProto
2656       = Old->getType()->getAs<FunctionProtoType>();
2657     const FunctionProtoType *NewProto
2658       = New->getType()->getAs<FunctionProtoType>();
2659 
2660     // Determine whether this is the GNU C extension.
2661     QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2662                                                NewProto->getResultType());
2663     bool LooseCompatible = !MergedReturn.isNull();
2664     for (unsigned Idx = 0, End = Old->getNumParams();
2665          LooseCompatible && Idx != End; ++Idx) {
2666       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2667       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2668       if (Context.typesAreCompatible(OldParm->getType(),
2669                                      NewProto->getArgType(Idx))) {
2670         ArgTypes.push_back(NewParm->getType());
2671       } else if (Context.typesAreCompatible(OldParm->getType(),
2672                                             NewParm->getType(),
2673                                             /*CompareUnqualified=*/true)) {
2674         GNUCompatibleParamWarning Warn
2675           = { OldParm, NewParm, NewProto->getArgType(Idx) };
2676         Warnings.push_back(Warn);
2677         ArgTypes.push_back(NewParm->getType());
2678       } else
2679         LooseCompatible = false;
2680     }
2681 
2682     if (LooseCompatible) {
2683       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2684         Diag(Warnings[Warn].NewParm->getLocation(),
2685              diag::ext_param_promoted_not_compatible_with_prototype)
2686           << Warnings[Warn].PromotedType
2687           << Warnings[Warn].OldParm->getType();
2688         if (Warnings[Warn].OldParm->getLocation().isValid())
2689           Diag(Warnings[Warn].OldParm->getLocation(),
2690                diag::note_previous_declaration);
2691       }
2692 
2693       if (MergeTypeWithOld)
2694         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2695                                              OldProto->getExtProtoInfo()));
2696       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2697     }
2698 
2699     // Fall through to diagnose conflicting types.
2700   }
2701 
2702   // A function that has already been declared has been redeclared or
2703   // defined with a different type; show an appropriate diagnostic.
2704 
2705   // If the previous declaration was an implicitly-generated builtin
2706   // declaration, then at the very least we should use a specialized note.
2707   unsigned BuiltinID;
2708   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2709     // If it's actually a library-defined builtin function like 'malloc'
2710     // or 'printf', just warn about the incompatible redeclaration.
2711     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2712       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2713       Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2714         << Old << Old->getType();
2715 
2716       // If this is a global redeclaration, just forget hereafter
2717       // about the "builtin-ness" of the function.
2718       //
2719       // Doing this for local extern declarations is problematic.  If
2720       // the builtin declaration remains visible, a second invalid
2721       // local declaration will produce a hard error; if it doesn't
2722       // remain visible, a single bogus local redeclaration (which is
2723       // actually only a warning) could break all the downstream code.
2724       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2725         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2726 
2727       return false;
2728     }
2729 
2730     PrevDiag = diag::note_previous_builtin_declaration;
2731   }
2732 
2733   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2734   Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2735   return true;
2736 }
2737 
2738 /// \brief Completes the merge of two function declarations that are
2739 /// known to be compatible.
2740 ///
2741 /// This routine handles the merging of attributes and other
2742 /// properties of function declarations form the old declaration to
2743 /// the new declaration, once we know that New is in fact a
2744 /// redeclaration of Old.
2745 ///
2746 /// \returns false
2747 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2748                                         Scope *S, bool MergeTypeWithOld) {
2749   // Merge the attributes
2750   mergeDeclAttributes(New, Old);
2751 
2752   // Merge "pure" flag.
2753   if (Old->isPure())
2754     New->setPure();
2755 
2756   // Merge "used" flag.
2757   New->setIsUsed(Old->isUsed(false));
2758 
2759   // Merge attributes from the parameters.  These can mismatch with K&R
2760   // declarations.
2761   if (New->getNumParams() == Old->getNumParams())
2762     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2763       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2764                                *this);
2765 
2766   if (getLangOpts().CPlusPlus)
2767     return MergeCXXFunctionDecl(New, Old, S);
2768 
2769   // Merge the function types so the we get the composite types for the return
2770   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2771   // was visible.
2772   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2773   if (!Merged.isNull() && MergeTypeWithOld)
2774     New->setType(Merged);
2775 
2776   return false;
2777 }
2778 
2779 
2780 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2781                                 ObjCMethodDecl *oldMethod) {
2782 
2783   // Merge the attributes, including deprecated/unavailable
2784   AvailabilityMergeKind MergeKind =
2785     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2786                                                    : AMK_Override;
2787   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
2788 
2789   // Merge attributes from the parameters.
2790   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2791                                        oe = oldMethod->param_end();
2792   for (ObjCMethodDecl::param_iterator
2793          ni = newMethod->param_begin(), ne = newMethod->param_end();
2794        ni != ne && oi != oe; ++ni, ++oi)
2795     mergeParamDeclAttributes(*ni, *oi, *this);
2796 
2797   CheckObjCMethodOverride(newMethod, oldMethod);
2798 }
2799 
2800 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2801 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2802 /// emitting diagnostics as appropriate.
2803 ///
2804 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2805 /// to here in AddInitializerToDecl. We can't check them before the initializer
2806 /// is attached.
2807 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2808                              bool MergeTypeWithOld) {
2809   if (New->isInvalidDecl() || Old->isInvalidDecl())
2810     return;
2811 
2812   QualType MergedT;
2813   if (getLangOpts().CPlusPlus) {
2814     if (New->getType()->isUndeducedType()) {
2815       // We don't know what the new type is until the initializer is attached.
2816       return;
2817     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2818       // These could still be something that needs exception specs checked.
2819       return MergeVarDeclExceptionSpecs(New, Old);
2820     }
2821     // C++ [basic.link]p10:
2822     //   [...] the types specified by all declarations referring to a given
2823     //   object or function shall be identical, except that declarations for an
2824     //   array object can specify array types that differ by the presence or
2825     //   absence of a major array bound (8.3.4).
2826     else if (Old->getType()->isIncompleteArrayType() &&
2827              New->getType()->isArrayType()) {
2828       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2829       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2830       if (Context.hasSameType(OldArray->getElementType(),
2831                               NewArray->getElementType()))
2832         MergedT = New->getType();
2833     } else if (Old->getType()->isArrayType() &&
2834                New->getType()->isIncompleteArrayType()) {
2835       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2836       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2837       if (Context.hasSameType(OldArray->getElementType(),
2838                               NewArray->getElementType()))
2839         MergedT = Old->getType();
2840     } else if (New->getType()->isObjCObjectPointerType() &&
2841                Old->getType()->isObjCObjectPointerType()) {
2842       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2843                                               Old->getType());
2844     }
2845   } else {
2846     // C 6.2.7p2:
2847     //   All declarations that refer to the same object or function shall have
2848     //   compatible type.
2849     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2850   }
2851   if (MergedT.isNull()) {
2852     // It's OK if we couldn't merge types if either type is dependent, for a
2853     // block-scope variable. In other cases (static data members of class
2854     // templates, variable templates, ...), we require the types to be
2855     // equivalent.
2856     // FIXME: The C++ standard doesn't say anything about this.
2857     if ((New->getType()->isDependentType() ||
2858          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2859       // If the old type was dependent, we can't merge with it, so the new type
2860       // becomes dependent for now. We'll reproduce the original type when we
2861       // instantiate the TypeSourceInfo for the variable.
2862       if (!New->getType()->isDependentType() && MergeTypeWithOld)
2863         New->setType(Context.DependentTy);
2864       return;
2865     }
2866 
2867     // FIXME: Even if this merging succeeds, some other non-visible declaration
2868     // of this variable might have an incompatible type. For instance:
2869     //
2870     //   extern int arr[];
2871     //   void f() { extern int arr[2]; }
2872     //   void g() { extern int arr[3]; }
2873     //
2874     // Neither C nor C++ requires a diagnostic for this, but we should still try
2875     // to diagnose it.
2876     Diag(New->getLocation(), diag::err_redefinition_different_type)
2877       << New->getDeclName() << New->getType() << Old->getType();
2878     Diag(Old->getLocation(), diag::note_previous_definition);
2879     return New->setInvalidDecl();
2880   }
2881 
2882   // Don't actually update the type on the new declaration if the old
2883   // declaration was an extern declaration in a different scope.
2884   if (MergeTypeWithOld)
2885     New->setType(MergedT);
2886 }
2887 
2888 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2889                                   LookupResult &Previous) {
2890   // C11 6.2.7p4:
2891   //   For an identifier with internal or external linkage declared
2892   //   in a scope in which a prior declaration of that identifier is
2893   //   visible, if the prior declaration specifies internal or
2894   //   external linkage, the type of the identifier at the later
2895   //   declaration becomes the composite type.
2896   //
2897   // If the variable isn't visible, we do not merge with its type.
2898   if (Previous.isShadowed())
2899     return false;
2900 
2901   if (S.getLangOpts().CPlusPlus) {
2902     // C++11 [dcl.array]p3:
2903     //   If there is a preceding declaration of the entity in the same
2904     //   scope in which the bound was specified, an omitted array bound
2905     //   is taken to be the same as in that earlier declaration.
2906     return NewVD->isPreviousDeclInSameBlockScope() ||
2907            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2908             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2909   } else {
2910     // If the old declaration was function-local, don't merge with its
2911     // type unless we're in the same function.
2912     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2913            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2914   }
2915 }
2916 
2917 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2918 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2919 /// situation, merging decls or emitting diagnostics as appropriate.
2920 ///
2921 /// Tentative definition rules (C99 6.9.2p2) are checked by
2922 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2923 /// definitions here, since the initializer hasn't been attached.
2924 ///
2925 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2926   // If the new decl is already invalid, don't do any other checking.
2927   if (New->isInvalidDecl())
2928     return;
2929 
2930   // Verify the old decl was also a variable or variable template.
2931   VarDecl *Old = 0;
2932   if (Previous.isSingleResult() &&
2933       (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2934     if (New->getDescribedVarTemplate())
2935       Old = Old->getDescribedVarTemplate() ? Old : 0;
2936     else
2937       Old = Old->getDescribedVarTemplate() ? 0 : Old;
2938   }
2939   if (!Old) {
2940     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2941       << New->getDeclName();
2942     Diag(Previous.getRepresentativeDecl()->getLocation(),
2943          diag::note_previous_definition);
2944     return New->setInvalidDecl();
2945   }
2946 
2947   if (!shouldLinkPossiblyHiddenDecl(Old, New))
2948     return;
2949 
2950   // C++ [class.mem]p1:
2951   //   A member shall not be declared twice in the member-specification [...]
2952   //
2953   // Here, we need only consider static data members.
2954   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2955     Diag(New->getLocation(), diag::err_duplicate_member)
2956       << New->getIdentifier();
2957     Diag(Old->getLocation(), diag::note_previous_declaration);
2958     New->setInvalidDecl();
2959   }
2960 
2961   mergeDeclAttributes(New, Old);
2962   // Warn if an already-declared variable is made a weak_import in a subsequent
2963   // declaration
2964   if (New->getAttr<WeakImportAttr>() &&
2965       Old->getStorageClass() == SC_None &&
2966       !Old->getAttr<WeakImportAttr>()) {
2967     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2968     Diag(Old->getLocation(), diag::note_previous_definition);
2969     // Remove weak_import attribute on new declaration.
2970     New->dropAttr<WeakImportAttr>();
2971   }
2972 
2973   // Merge the types.
2974   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
2975 
2976   if (New->isInvalidDecl())
2977     return;
2978 
2979   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
2980   if (New->getStorageClass() == SC_Static &&
2981       !New->isStaticDataMember() &&
2982       Old->hasExternalFormalLinkage()) {
2983     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2984     Diag(Old->getLocation(), diag::note_previous_definition);
2985     return New->setInvalidDecl();
2986   }
2987   // C99 6.2.2p4:
2988   //   For an identifier declared with the storage-class specifier
2989   //   extern in a scope in which a prior declaration of that
2990   //   identifier is visible,23) if the prior declaration specifies
2991   //   internal or external linkage, the linkage of the identifier at
2992   //   the later declaration is the same as the linkage specified at
2993   //   the prior declaration. If no prior declaration is visible, or
2994   //   if the prior declaration specifies no linkage, then the
2995   //   identifier has external linkage.
2996   if (New->hasExternalStorage() && Old->hasLinkage())
2997     /* Okay */;
2998   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
2999            !New->isStaticDataMember() &&
3000            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3001     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3002     Diag(Old->getLocation(), diag::note_previous_definition);
3003     return New->setInvalidDecl();
3004   }
3005 
3006   // Check if extern is followed by non-extern and vice-versa.
3007   if (New->hasExternalStorage() &&
3008       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3009     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3010     Diag(Old->getLocation(), diag::note_previous_definition);
3011     return New->setInvalidDecl();
3012   }
3013   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3014       !New->hasExternalStorage()) {
3015     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3016     Diag(Old->getLocation(), diag::note_previous_definition);
3017     return New->setInvalidDecl();
3018   }
3019 
3020   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3021 
3022   // FIXME: The test for external storage here seems wrong? We still
3023   // need to check for mismatches.
3024   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3025       // Don't complain about out-of-line definitions of static members.
3026       !(Old->getLexicalDeclContext()->isRecord() &&
3027         !New->getLexicalDeclContext()->isRecord())) {
3028     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3029     Diag(Old->getLocation(), diag::note_previous_definition);
3030     return New->setInvalidDecl();
3031   }
3032 
3033   if (New->getTLSKind() != Old->getTLSKind()) {
3034     if (!Old->getTLSKind()) {
3035       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3036       Diag(Old->getLocation(), diag::note_previous_declaration);
3037     } else if (!New->getTLSKind()) {
3038       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3039       Diag(Old->getLocation(), diag::note_previous_declaration);
3040     } else {
3041       // Do not allow redeclaration to change the variable between requiring
3042       // static and dynamic initialization.
3043       // FIXME: GCC allows this, but uses the TLS keyword on the first
3044       // declaration to determine the kind. Do we need to be compatible here?
3045       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3046         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3047       Diag(Old->getLocation(), diag::note_previous_declaration);
3048     }
3049   }
3050 
3051   // C++ doesn't have tentative definitions, so go right ahead and check here.
3052   const VarDecl *Def;
3053   if (getLangOpts().CPlusPlus &&
3054       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3055       (Def = Old->getDefinition())) {
3056     Diag(New->getLocation(), diag::err_redefinition) << New;
3057     Diag(Def->getLocation(), diag::note_previous_definition);
3058     New->setInvalidDecl();
3059     return;
3060   }
3061 
3062   if (haveIncompatibleLanguageLinkages(Old, New)) {
3063     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3064     Diag(Old->getLocation(), diag::note_previous_definition);
3065     New->setInvalidDecl();
3066     return;
3067   }
3068 
3069   // Merge "used" flag.
3070   New->setIsUsed(Old->isUsed(false));
3071 
3072   // Keep a chain of previous declarations.
3073   New->setPreviousDeclaration(Old);
3074 
3075   // Inherit access appropriately.
3076   New->setAccess(Old->getAccess());
3077 
3078   if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3079     if (New->isStaticDataMember() && New->isOutOfLine())
3080       VTD->setAccess(New->getAccess());
3081   }
3082 }
3083 
3084 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3085 /// no declarator (e.g. "struct foo;") is parsed.
3086 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3087                                        DeclSpec &DS) {
3088   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3089 }
3090 
3091 static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
3092   if (!S.Context.getLangOpts().CPlusPlus)
3093     return;
3094 
3095   if (isa<CXXRecordDecl>(Tag->getParent())) {
3096     // If this tag is the direct child of a class, number it if
3097     // it is anonymous.
3098     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3099       return;
3100     MangleNumberingContext &MCtx =
3101         S.Context.getManglingNumberContext(Tag->getParent());
3102     S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3103     return;
3104   }
3105 
3106   // If this tag isn't a direct child of a class, number it if it is local.
3107   Decl *ManglingContextDecl;
3108   if (MangleNumberingContext *MCtx =
3109           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3110                                           ManglingContextDecl)) {
3111     S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3112   }
3113 }
3114 
3115 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3116 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3117 /// parameters to cope with template friend declarations.
3118 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3119                                        DeclSpec &DS,
3120                                        MultiTemplateParamsArg TemplateParams,
3121                                        bool IsExplicitInstantiation) {
3122   Decl *TagD = 0;
3123   TagDecl *Tag = 0;
3124   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3125       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3126       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3127       DS.getTypeSpecType() == DeclSpec::TST_union ||
3128       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3129     TagD = DS.getRepAsDecl();
3130 
3131     if (!TagD) // We probably had an error
3132       return 0;
3133 
3134     // Note that the above type specs guarantee that the
3135     // type rep is a Decl, whereas in many of the others
3136     // it's a Type.
3137     if (isa<TagDecl>(TagD))
3138       Tag = cast<TagDecl>(TagD);
3139     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3140       Tag = CTD->getTemplatedDecl();
3141   }
3142 
3143   if (Tag) {
3144     HandleTagNumbering(*this, Tag);
3145     Tag->setFreeStanding();
3146     if (Tag->isInvalidDecl())
3147       return Tag;
3148   }
3149 
3150   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3151     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3152     // or incomplete types shall not be restrict-qualified."
3153     if (TypeQuals & DeclSpec::TQ_restrict)
3154       Diag(DS.getRestrictSpecLoc(),
3155            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3156            << DS.getSourceRange();
3157   }
3158 
3159   if (DS.isConstexprSpecified()) {
3160     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3161     // and definitions of functions and variables.
3162     if (Tag)
3163       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3164         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3165             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3166             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3167             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3168     else
3169       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3170     // Don't emit warnings after this error.
3171     return TagD;
3172   }
3173 
3174   DiagnoseFunctionSpecifiers(DS);
3175 
3176   if (DS.isFriendSpecified()) {
3177     // If we're dealing with a decl but not a TagDecl, assume that
3178     // whatever routines created it handled the friendship aspect.
3179     if (TagD && !Tag)
3180       return 0;
3181     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3182   }
3183 
3184   CXXScopeSpec &SS = DS.getTypeSpecScope();
3185   bool IsExplicitSpecialization =
3186     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3187   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3188       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3189     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3190     // nested-name-specifier unless it is an explicit instantiation
3191     // or an explicit specialization.
3192     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3193     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3194       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3195           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3196           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3197           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3198       << SS.getRange();
3199     return 0;
3200   }
3201 
3202   // Track whether this decl-specifier declares anything.
3203   bool DeclaresAnything = true;
3204 
3205   // Handle anonymous struct definitions.
3206   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3207     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3208         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3209       if (getLangOpts().CPlusPlus ||
3210           Record->getDeclContext()->isRecord())
3211         return BuildAnonymousStructOrUnion(S, DS, AS, Record);
3212 
3213       DeclaresAnything = false;
3214     }
3215   }
3216 
3217   // Check for Microsoft C extension: anonymous struct member.
3218   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3219       CurContext->isRecord() &&
3220       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3221     // Handle 2 kinds of anonymous struct:
3222     //   struct STRUCT;
3223     // and
3224     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3225     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3226     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3227         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3228          DS.getRepAsType().get()->isStructureType())) {
3229       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3230         << DS.getSourceRange();
3231       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3232     }
3233   }
3234 
3235   // Skip all the checks below if we have a type error.
3236   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3237       (TagD && TagD->isInvalidDecl()))
3238     return TagD;
3239 
3240   if (getLangOpts().CPlusPlus &&
3241       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3242     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3243       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3244           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3245         DeclaresAnything = false;
3246 
3247   if (!DS.isMissingDeclaratorOk()) {
3248     // Customize diagnostic for a typedef missing a name.
3249     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3250       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3251         << DS.getSourceRange();
3252     else
3253       DeclaresAnything = false;
3254   }
3255 
3256   if (DS.isModulePrivateSpecified() &&
3257       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3258     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3259       << Tag->getTagKind()
3260       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3261 
3262   ActOnDocumentableDecl(TagD);
3263 
3264   // C 6.7/2:
3265   //   A declaration [...] shall declare at least a declarator [...], a tag,
3266   //   or the members of an enumeration.
3267   // C++ [dcl.dcl]p3:
3268   //   [If there are no declarators], and except for the declaration of an
3269   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3270   //   names into the program, or shall redeclare a name introduced by a
3271   //   previous declaration.
3272   if (!DeclaresAnything) {
3273     // In C, we allow this as a (popular) extension / bug. Don't bother
3274     // producing further diagnostics for redundant qualifiers after this.
3275     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3276     return TagD;
3277   }
3278 
3279   // C++ [dcl.stc]p1:
3280   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3281   //   init-declarator-list of the declaration shall not be empty.
3282   // C++ [dcl.fct.spec]p1:
3283   //   If a cv-qualifier appears in a decl-specifier-seq, the
3284   //   init-declarator-list of the declaration shall not be empty.
3285   //
3286   // Spurious qualifiers here appear to be valid in C.
3287   unsigned DiagID = diag::warn_standalone_specifier;
3288   if (getLangOpts().CPlusPlus)
3289     DiagID = diag::ext_standalone_specifier;
3290 
3291   // Note that a linkage-specification sets a storage class, but
3292   // 'extern "C" struct foo;' is actually valid and not theoretically
3293   // useless.
3294   if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3295     if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3296       Diag(DS.getStorageClassSpecLoc(), DiagID)
3297         << DeclSpec::getSpecifierName(SCS);
3298 
3299   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3300     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3301       << DeclSpec::getSpecifierName(TSCS);
3302   if (DS.getTypeQualifiers()) {
3303     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3304       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3305     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3306       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3307     // Restrict is covered above.
3308     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3309       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3310   }
3311 
3312   // Warn about ignored type attributes, for example:
3313   // __attribute__((aligned)) struct A;
3314   // Attributes should be placed after tag to apply to type declaration.
3315   if (!DS.getAttributes().empty()) {
3316     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3317     if (TypeSpecType == DeclSpec::TST_class ||
3318         TypeSpecType == DeclSpec::TST_struct ||
3319         TypeSpecType == DeclSpec::TST_interface ||
3320         TypeSpecType == DeclSpec::TST_union ||
3321         TypeSpecType == DeclSpec::TST_enum) {
3322       AttributeList* attrs = DS.getAttributes().getList();
3323       while (attrs) {
3324         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3325         << attrs->getName()
3326         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3327             TypeSpecType == DeclSpec::TST_struct ? 1 :
3328             TypeSpecType == DeclSpec::TST_union ? 2 :
3329             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3330         attrs = attrs->getNext();
3331       }
3332     }
3333   }
3334 
3335   return TagD;
3336 }
3337 
3338 /// We are trying to inject an anonymous member into the given scope;
3339 /// check if there's an existing declaration that can't be overloaded.
3340 ///
3341 /// \return true if this is a forbidden redeclaration
3342 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3343                                          Scope *S,
3344                                          DeclContext *Owner,
3345                                          DeclarationName Name,
3346                                          SourceLocation NameLoc,
3347                                          unsigned diagnostic) {
3348   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3349                  Sema::ForRedeclaration);
3350   if (!SemaRef.LookupName(R, S)) return false;
3351 
3352   if (R.getAsSingle<TagDecl>())
3353     return false;
3354 
3355   // Pick a representative declaration.
3356   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3357   assert(PrevDecl && "Expected a non-null Decl");
3358 
3359   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3360     return false;
3361 
3362   SemaRef.Diag(NameLoc, diagnostic) << Name;
3363   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3364 
3365   return true;
3366 }
3367 
3368 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3369 /// anonymous struct or union AnonRecord into the owning context Owner
3370 /// and scope S. This routine will be invoked just after we realize
3371 /// that an unnamed union or struct is actually an anonymous union or
3372 /// struct, e.g.,
3373 ///
3374 /// @code
3375 /// union {
3376 ///   int i;
3377 ///   float f;
3378 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3379 ///    // f into the surrounding scope.x
3380 /// @endcode
3381 ///
3382 /// This routine is recursive, injecting the names of nested anonymous
3383 /// structs/unions into the owning context and scope as well.
3384 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3385                                          DeclContext *Owner,
3386                                          RecordDecl *AnonRecord,
3387                                          AccessSpecifier AS,
3388                                          SmallVectorImpl<NamedDecl *> &Chaining,
3389                                          bool MSAnonStruct) {
3390   unsigned diagKind
3391     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3392                             : diag::err_anonymous_struct_member_redecl;
3393 
3394   bool Invalid = false;
3395 
3396   // Look every FieldDecl and IndirectFieldDecl with a name.
3397   for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3398                                DEnd = AnonRecord->decls_end();
3399        D != DEnd; ++D) {
3400     if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3401         cast<NamedDecl>(*D)->getDeclName()) {
3402       ValueDecl *VD = cast<ValueDecl>(*D);
3403       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3404                                        VD->getLocation(), diagKind)) {
3405         // C++ [class.union]p2:
3406         //   The names of the members of an anonymous union shall be
3407         //   distinct from the names of any other entity in the
3408         //   scope in which the anonymous union is declared.
3409         Invalid = true;
3410       } else {
3411         // C++ [class.union]p2:
3412         //   For the purpose of name lookup, after the anonymous union
3413         //   definition, the members of the anonymous union are
3414         //   considered to have been defined in the scope in which the
3415         //   anonymous union is declared.
3416         unsigned OldChainingSize = Chaining.size();
3417         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3418           for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3419                PE = IF->chain_end(); PI != PE; ++PI)
3420             Chaining.push_back(*PI);
3421         else
3422           Chaining.push_back(VD);
3423 
3424         assert(Chaining.size() >= 2);
3425         NamedDecl **NamedChain =
3426           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3427         for (unsigned i = 0; i < Chaining.size(); i++)
3428           NamedChain[i] = Chaining[i];
3429 
3430         IndirectFieldDecl* IndirectField =
3431           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3432                                     VD->getIdentifier(), VD->getType(),
3433                                     NamedChain, Chaining.size());
3434 
3435         IndirectField->setAccess(AS);
3436         IndirectField->setImplicit();
3437         SemaRef.PushOnScopeChains(IndirectField, S);
3438 
3439         // That includes picking up the appropriate access specifier.
3440         if (AS != AS_none) IndirectField->setAccess(AS);
3441 
3442         Chaining.resize(OldChainingSize);
3443       }
3444     }
3445   }
3446 
3447   return Invalid;
3448 }
3449 
3450 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3451 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3452 /// illegal input values are mapped to SC_None.
3453 static StorageClass
3454 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3455   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3456   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3457          "Parser allowed 'typedef' as storage class VarDecl.");
3458   switch (StorageClassSpec) {
3459   case DeclSpec::SCS_unspecified:    return SC_None;
3460   case DeclSpec::SCS_extern:
3461     if (DS.isExternInLinkageSpec())
3462       return SC_None;
3463     return SC_Extern;
3464   case DeclSpec::SCS_static:         return SC_Static;
3465   case DeclSpec::SCS_auto:           return SC_Auto;
3466   case DeclSpec::SCS_register:       return SC_Register;
3467   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3468     // Illegal SCSs map to None: error reporting is up to the caller.
3469   case DeclSpec::SCS_mutable:        // Fall through.
3470   case DeclSpec::SCS_typedef:        return SC_None;
3471   }
3472   llvm_unreachable("unknown storage class specifier");
3473 }
3474 
3475 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3476 /// anonymous structure or union. Anonymous unions are a C++ feature
3477 /// (C++ [class.union]) and a C11 feature; anonymous structures
3478 /// are a C11 feature and GNU C++ extension.
3479 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3480                                              AccessSpecifier AS,
3481                                              RecordDecl *Record) {
3482   DeclContext *Owner = Record->getDeclContext();
3483 
3484   // Diagnose whether this anonymous struct/union is an extension.
3485   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3486     Diag(Record->getLocation(), diag::ext_anonymous_union);
3487   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3488     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3489   else if (!Record->isUnion() && !getLangOpts().C11)
3490     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3491 
3492   // C and C++ require different kinds of checks for anonymous
3493   // structs/unions.
3494   bool Invalid = false;
3495   if (getLangOpts().CPlusPlus) {
3496     const char* PrevSpec = 0;
3497     unsigned DiagID;
3498     if (Record->isUnion()) {
3499       // C++ [class.union]p6:
3500       //   Anonymous unions declared in a named namespace or in the
3501       //   global namespace shall be declared static.
3502       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3503           (isa<TranslationUnitDecl>(Owner) ||
3504            (isa<NamespaceDecl>(Owner) &&
3505             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3506         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3507           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3508 
3509         // Recover by adding 'static'.
3510         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3511                                PrevSpec, DiagID);
3512       }
3513       // C++ [class.union]p6:
3514       //   A storage class is not allowed in a declaration of an
3515       //   anonymous union in a class scope.
3516       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3517                isa<RecordDecl>(Owner)) {
3518         Diag(DS.getStorageClassSpecLoc(),
3519              diag::err_anonymous_union_with_storage_spec)
3520           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3521 
3522         // Recover by removing the storage specifier.
3523         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3524                                SourceLocation(),
3525                                PrevSpec, DiagID);
3526       }
3527     }
3528 
3529     // Ignore const/volatile/restrict qualifiers.
3530     if (DS.getTypeQualifiers()) {
3531       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3532         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3533           << Record->isUnion() << "const"
3534           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3535       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3536         Diag(DS.getVolatileSpecLoc(),
3537              diag::ext_anonymous_struct_union_qualified)
3538           << Record->isUnion() << "volatile"
3539           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3540       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3541         Diag(DS.getRestrictSpecLoc(),
3542              diag::ext_anonymous_struct_union_qualified)
3543           << Record->isUnion() << "restrict"
3544           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3545       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3546         Diag(DS.getAtomicSpecLoc(),
3547              diag::ext_anonymous_struct_union_qualified)
3548           << Record->isUnion() << "_Atomic"
3549           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3550 
3551       DS.ClearTypeQualifiers();
3552     }
3553 
3554     // C++ [class.union]p2:
3555     //   The member-specification of an anonymous union shall only
3556     //   define non-static data members. [Note: nested types and
3557     //   functions cannot be declared within an anonymous union. ]
3558     for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3559                                  MemEnd = Record->decls_end();
3560          Mem != MemEnd; ++Mem) {
3561       if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3562         // C++ [class.union]p3:
3563         //   An anonymous union shall not have private or protected
3564         //   members (clause 11).
3565         assert(FD->getAccess() != AS_none);
3566         if (FD->getAccess() != AS_public) {
3567           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3568             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3569           Invalid = true;
3570         }
3571 
3572         // C++ [class.union]p1
3573         //   An object of a class with a non-trivial constructor, a non-trivial
3574         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3575         //   assignment operator cannot be a member of a union, nor can an
3576         //   array of such objects.
3577         if (CheckNontrivialField(FD))
3578           Invalid = true;
3579       } else if ((*Mem)->isImplicit()) {
3580         // Any implicit members are fine.
3581       } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3582         // This is a type that showed up in an
3583         // elaborated-type-specifier inside the anonymous struct or
3584         // union, but which actually declares a type outside of the
3585         // anonymous struct or union. It's okay.
3586       } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3587         if (!MemRecord->isAnonymousStructOrUnion() &&
3588             MemRecord->getDeclName()) {
3589           // Visual C++ allows type definition in anonymous struct or union.
3590           if (getLangOpts().MicrosoftExt)
3591             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3592               << (int)Record->isUnion();
3593           else {
3594             // This is a nested type declaration.
3595             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3596               << (int)Record->isUnion();
3597             Invalid = true;
3598           }
3599         } else {
3600           // This is an anonymous type definition within another anonymous type.
3601           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3602           // not part of standard C++.
3603           Diag(MemRecord->getLocation(),
3604                diag::ext_anonymous_record_with_anonymous_type)
3605             << (int)Record->isUnion();
3606         }
3607       } else if (isa<AccessSpecDecl>(*Mem)) {
3608         // Any access specifier is fine.
3609       } else {
3610         // We have something that isn't a non-static data
3611         // member. Complain about it.
3612         unsigned DK = diag::err_anonymous_record_bad_member;
3613         if (isa<TypeDecl>(*Mem))
3614           DK = diag::err_anonymous_record_with_type;
3615         else if (isa<FunctionDecl>(*Mem))
3616           DK = diag::err_anonymous_record_with_function;
3617         else if (isa<VarDecl>(*Mem))
3618           DK = diag::err_anonymous_record_with_static;
3619 
3620         // Visual C++ allows type definition in anonymous struct or union.
3621         if (getLangOpts().MicrosoftExt &&
3622             DK == diag::err_anonymous_record_with_type)
3623           Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3624             << (int)Record->isUnion();
3625         else {
3626           Diag((*Mem)->getLocation(), DK)
3627               << (int)Record->isUnion();
3628           Invalid = true;
3629         }
3630       }
3631     }
3632   }
3633 
3634   if (!Record->isUnion() && !Owner->isRecord()) {
3635     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3636       << (int)getLangOpts().CPlusPlus;
3637     Invalid = true;
3638   }
3639 
3640   // Mock up a declarator.
3641   Declarator Dc(DS, Declarator::MemberContext);
3642   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3643   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3644 
3645   // Create a declaration for this anonymous struct/union.
3646   NamedDecl *Anon = 0;
3647   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3648     Anon = FieldDecl::Create(Context, OwningClass,
3649                              DS.getLocStart(),
3650                              Record->getLocation(),
3651                              /*IdentifierInfo=*/0,
3652                              Context.getTypeDeclType(Record),
3653                              TInfo,
3654                              /*BitWidth=*/0, /*Mutable=*/false,
3655                              /*InitStyle=*/ICIS_NoInit);
3656     Anon->setAccess(AS);
3657     if (getLangOpts().CPlusPlus)
3658       FieldCollector->Add(cast<FieldDecl>(Anon));
3659   } else {
3660     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3661     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3662     if (SCSpec == DeclSpec::SCS_mutable) {
3663       // mutable can only appear on non-static class members, so it's always
3664       // an error here
3665       Diag(Record->getLocation(), diag::err_mutable_nonmember);
3666       Invalid = true;
3667       SC = SC_None;
3668     }
3669 
3670     Anon = VarDecl::Create(Context, Owner,
3671                            DS.getLocStart(),
3672                            Record->getLocation(), /*IdentifierInfo=*/0,
3673                            Context.getTypeDeclType(Record),
3674                            TInfo, SC);
3675 
3676     // Default-initialize the implicit variable. This initialization will be
3677     // trivial in almost all cases, except if a union member has an in-class
3678     // initializer:
3679     //   union { int n = 0; };
3680     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3681   }
3682   Anon->setImplicit();
3683 
3684   // Add the anonymous struct/union object to the current
3685   // context. We'll be referencing this object when we refer to one of
3686   // its members.
3687   Owner->addDecl(Anon);
3688 
3689   // Inject the members of the anonymous struct/union into the owning
3690   // context and into the identifier resolver chain for name lookup
3691   // purposes.
3692   SmallVector<NamedDecl*, 2> Chain;
3693   Chain.push_back(Anon);
3694 
3695   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3696                                           Chain, false))
3697     Invalid = true;
3698 
3699   // Mark this as an anonymous struct/union type. Note that we do not
3700   // do this until after we have already checked and injected the
3701   // members of this anonymous struct/union type, because otherwise
3702   // the members could be injected twice: once by DeclContext when it
3703   // builds its lookup table, and once by
3704   // InjectAnonymousStructOrUnionMembers.
3705   Record->setAnonymousStructOrUnion(true);
3706 
3707   if (Invalid)
3708     Anon->setInvalidDecl();
3709 
3710   return Anon;
3711 }
3712 
3713 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3714 /// Microsoft C anonymous structure.
3715 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3716 /// Example:
3717 ///
3718 /// struct A { int a; };
3719 /// struct B { struct A; int b; };
3720 ///
3721 /// void foo() {
3722 ///   B var;
3723 ///   var.a = 3;
3724 /// }
3725 ///
3726 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3727                                            RecordDecl *Record) {
3728 
3729   // If there is no Record, get the record via the typedef.
3730   if (!Record)
3731     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3732 
3733   // Mock up a declarator.
3734   Declarator Dc(DS, Declarator::TypeNameContext);
3735   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3736   assert(TInfo && "couldn't build declarator info for anonymous struct");
3737 
3738   // Create a declaration for this anonymous struct.
3739   NamedDecl* Anon = FieldDecl::Create(Context,
3740                              cast<RecordDecl>(CurContext),
3741                              DS.getLocStart(),
3742                              DS.getLocStart(),
3743                              /*IdentifierInfo=*/0,
3744                              Context.getTypeDeclType(Record),
3745                              TInfo,
3746                              /*BitWidth=*/0, /*Mutable=*/false,
3747                              /*InitStyle=*/ICIS_NoInit);
3748   Anon->setImplicit();
3749 
3750   // Add the anonymous struct object to the current context.
3751   CurContext->addDecl(Anon);
3752 
3753   // Inject the members of the anonymous struct into the current
3754   // context and into the identifier resolver chain for name lookup
3755   // purposes.
3756   SmallVector<NamedDecl*, 2> Chain;
3757   Chain.push_back(Anon);
3758 
3759   RecordDecl *RecordDef = Record->getDefinition();
3760   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3761                                                         RecordDef, AS_none,
3762                                                         Chain, true))
3763     Anon->setInvalidDecl();
3764 
3765   return Anon;
3766 }
3767 
3768 /// GetNameForDeclarator - Determine the full declaration name for the
3769 /// given Declarator.
3770 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3771   return GetNameFromUnqualifiedId(D.getName());
3772 }
3773 
3774 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3775 DeclarationNameInfo
3776 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3777   DeclarationNameInfo NameInfo;
3778   NameInfo.setLoc(Name.StartLocation);
3779 
3780   switch (Name.getKind()) {
3781 
3782   case UnqualifiedId::IK_ImplicitSelfParam:
3783   case UnqualifiedId::IK_Identifier:
3784     NameInfo.setName(Name.Identifier);
3785     NameInfo.setLoc(Name.StartLocation);
3786     return NameInfo;
3787 
3788   case UnqualifiedId::IK_OperatorFunctionId:
3789     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3790                                            Name.OperatorFunctionId.Operator));
3791     NameInfo.setLoc(Name.StartLocation);
3792     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3793       = Name.OperatorFunctionId.SymbolLocations[0];
3794     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3795       = Name.EndLocation.getRawEncoding();
3796     return NameInfo;
3797 
3798   case UnqualifiedId::IK_LiteralOperatorId:
3799     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3800                                                            Name.Identifier));
3801     NameInfo.setLoc(Name.StartLocation);
3802     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3803     return NameInfo;
3804 
3805   case UnqualifiedId::IK_ConversionFunctionId: {
3806     TypeSourceInfo *TInfo;
3807     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3808     if (Ty.isNull())
3809       return DeclarationNameInfo();
3810     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3811                                                Context.getCanonicalType(Ty)));
3812     NameInfo.setLoc(Name.StartLocation);
3813     NameInfo.setNamedTypeInfo(TInfo);
3814     return NameInfo;
3815   }
3816 
3817   case UnqualifiedId::IK_ConstructorName: {
3818     TypeSourceInfo *TInfo;
3819     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3820     if (Ty.isNull())
3821       return DeclarationNameInfo();
3822     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3823                                               Context.getCanonicalType(Ty)));
3824     NameInfo.setLoc(Name.StartLocation);
3825     NameInfo.setNamedTypeInfo(TInfo);
3826     return NameInfo;
3827   }
3828 
3829   case UnqualifiedId::IK_ConstructorTemplateId: {
3830     // In well-formed code, we can only have a constructor
3831     // template-id that refers to the current context, so go there
3832     // to find the actual type being constructed.
3833     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3834     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3835       return DeclarationNameInfo();
3836 
3837     // Determine the type of the class being constructed.
3838     QualType CurClassType = Context.getTypeDeclType(CurClass);
3839 
3840     // FIXME: Check two things: that the template-id names the same type as
3841     // CurClassType, and that the template-id does not occur when the name
3842     // was qualified.
3843 
3844     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3845                                     Context.getCanonicalType(CurClassType)));
3846     NameInfo.setLoc(Name.StartLocation);
3847     // FIXME: should we retrieve TypeSourceInfo?
3848     NameInfo.setNamedTypeInfo(0);
3849     return NameInfo;
3850   }
3851 
3852   case UnqualifiedId::IK_DestructorName: {
3853     TypeSourceInfo *TInfo;
3854     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3855     if (Ty.isNull())
3856       return DeclarationNameInfo();
3857     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3858                                               Context.getCanonicalType(Ty)));
3859     NameInfo.setLoc(Name.StartLocation);
3860     NameInfo.setNamedTypeInfo(TInfo);
3861     return NameInfo;
3862   }
3863 
3864   case UnqualifiedId::IK_TemplateId: {
3865     TemplateName TName = Name.TemplateId->Template.get();
3866     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3867     return Context.getNameForTemplate(TName, TNameLoc);
3868   }
3869 
3870   } // switch (Name.getKind())
3871 
3872   llvm_unreachable("Unknown name kind");
3873 }
3874 
3875 static QualType getCoreType(QualType Ty) {
3876   do {
3877     if (Ty->isPointerType() || Ty->isReferenceType())
3878       Ty = Ty->getPointeeType();
3879     else if (Ty->isArrayType())
3880       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3881     else
3882       return Ty.withoutLocalFastQualifiers();
3883   } while (true);
3884 }
3885 
3886 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3887 /// and Definition have "nearly" matching parameters. This heuristic is
3888 /// used to improve diagnostics in the case where an out-of-line function
3889 /// definition doesn't match any declaration within the class or namespace.
3890 /// Also sets Params to the list of indices to the parameters that differ
3891 /// between the declaration and the definition. If hasSimilarParameters
3892 /// returns true and Params is empty, then all of the parameters match.
3893 static bool hasSimilarParameters(ASTContext &Context,
3894                                      FunctionDecl *Declaration,
3895                                      FunctionDecl *Definition,
3896                                      SmallVectorImpl<unsigned> &Params) {
3897   Params.clear();
3898   if (Declaration->param_size() != Definition->param_size())
3899     return false;
3900   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3901     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3902     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3903 
3904     // The parameter types are identical
3905     if (Context.hasSameType(DefParamTy, DeclParamTy))
3906       continue;
3907 
3908     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3909     QualType DefParamBaseTy = getCoreType(DefParamTy);
3910     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3911     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3912 
3913     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3914         (DeclTyName && DeclTyName == DefTyName))
3915       Params.push_back(Idx);
3916     else  // The two parameters aren't even close
3917       return false;
3918   }
3919 
3920   return true;
3921 }
3922 
3923 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3924 /// declarator needs to be rebuilt in the current instantiation.
3925 /// Any bits of declarator which appear before the name are valid for
3926 /// consideration here.  That's specifically the type in the decl spec
3927 /// and the base type in any member-pointer chunks.
3928 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3929                                                     DeclarationName Name) {
3930   // The types we specifically need to rebuild are:
3931   //   - typenames, typeofs, and decltypes
3932   //   - types which will become injected class names
3933   // Of course, we also need to rebuild any type referencing such a
3934   // type.  It's safest to just say "dependent", but we call out a
3935   // few cases here.
3936 
3937   DeclSpec &DS = D.getMutableDeclSpec();
3938   switch (DS.getTypeSpecType()) {
3939   case DeclSpec::TST_typename:
3940   case DeclSpec::TST_typeofType:
3941   case DeclSpec::TST_underlyingType:
3942   case DeclSpec::TST_atomic: {
3943     // Grab the type from the parser.
3944     TypeSourceInfo *TSI = 0;
3945     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3946     if (T.isNull() || !T->isDependentType()) break;
3947 
3948     // Make sure there's a type source info.  This isn't really much
3949     // of a waste; most dependent types should have type source info
3950     // attached already.
3951     if (!TSI)
3952       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3953 
3954     // Rebuild the type in the current instantiation.
3955     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3956     if (!TSI) return true;
3957 
3958     // Store the new type back in the decl spec.
3959     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3960     DS.UpdateTypeRep(LocType);
3961     break;
3962   }
3963 
3964   case DeclSpec::TST_decltype:
3965   case DeclSpec::TST_typeofExpr: {
3966     Expr *E = DS.getRepAsExpr();
3967     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3968     if (Result.isInvalid()) return true;
3969     DS.UpdateExprRep(Result.get());
3970     break;
3971   }
3972 
3973   default:
3974     // Nothing to do for these decl specs.
3975     break;
3976   }
3977 
3978   // It doesn't matter what order we do this in.
3979   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3980     DeclaratorChunk &Chunk = D.getTypeObject(I);
3981 
3982     // The only type information in the declarator which can come
3983     // before the declaration name is the base type of a member
3984     // pointer.
3985     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3986       continue;
3987 
3988     // Rebuild the scope specifier in-place.
3989     CXXScopeSpec &SS = Chunk.Mem.Scope();
3990     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3991       return true;
3992   }
3993 
3994   return false;
3995 }
3996 
3997 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3998   D.setFunctionDefinitionKind(FDK_Declaration);
3999   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4000 
4001   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4002       Dcl && Dcl->getDeclContext()->isFileContext())
4003     Dcl->setTopLevelDeclInObjCContainer();
4004 
4005   return Dcl;
4006 }
4007 
4008 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4009 ///   If T is the name of a class, then each of the following shall have a
4010 ///   name different from T:
4011 ///     - every static data member of class T;
4012 ///     - every member function of class T
4013 ///     - every member of class T that is itself a type;
4014 /// \returns true if the declaration name violates these rules.
4015 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4016                                    DeclarationNameInfo NameInfo) {
4017   DeclarationName Name = NameInfo.getName();
4018 
4019   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4020     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4021       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4022       return true;
4023     }
4024 
4025   return false;
4026 }
4027 
4028 /// \brief Diagnose a declaration whose declarator-id has the given
4029 /// nested-name-specifier.
4030 ///
4031 /// \param SS The nested-name-specifier of the declarator-id.
4032 ///
4033 /// \param DC The declaration context to which the nested-name-specifier
4034 /// resolves.
4035 ///
4036 /// \param Name The name of the entity being declared.
4037 ///
4038 /// \param Loc The location of the name of the entity being declared.
4039 ///
4040 /// \returns true if we cannot safely recover from this error, false otherwise.
4041 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4042                                         DeclarationName Name,
4043                                       SourceLocation Loc) {
4044   DeclContext *Cur = CurContext;
4045   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4046     Cur = Cur->getParent();
4047 
4048   // C++ [dcl.meaning]p1:
4049   //   A declarator-id shall not be qualified except for the definition
4050   //   of a member function (9.3) or static data member (9.4) outside of
4051   //   its class, the definition or explicit instantiation of a function
4052   //   or variable member of a namespace outside of its namespace, or the
4053   //   definition of an explicit specialization outside of its namespace,
4054   //   or the declaration of a friend function that is a member of
4055   //   another class or namespace (11.3). [...]
4056 
4057   // The user provided a superfluous scope specifier that refers back to the
4058   // class or namespaces in which the entity is already declared.
4059   //
4060   // class X {
4061   //   void X::f();
4062   // };
4063   if (Cur->Equals(DC)) {
4064     Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4065                                    : diag::err_member_extra_qualification)
4066       << Name << FixItHint::CreateRemoval(SS.getRange());
4067     SS.clear();
4068     return false;
4069   }
4070 
4071   // Check whether the qualifying scope encloses the scope of the original
4072   // declaration.
4073   if (!Cur->Encloses(DC)) {
4074     if (Cur->isRecord())
4075       Diag(Loc, diag::err_member_qualification)
4076         << Name << SS.getRange();
4077     else if (isa<TranslationUnitDecl>(DC))
4078       Diag(Loc, diag::err_invalid_declarator_global_scope)
4079         << Name << SS.getRange();
4080     else if (isa<FunctionDecl>(Cur))
4081       Diag(Loc, diag::err_invalid_declarator_in_function)
4082         << Name << SS.getRange();
4083     else if (isa<BlockDecl>(Cur))
4084       Diag(Loc, diag::err_invalid_declarator_in_block)
4085         << Name << SS.getRange();
4086     else
4087       Diag(Loc, diag::err_invalid_declarator_scope)
4088       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4089 
4090     return true;
4091   }
4092 
4093   if (Cur->isRecord()) {
4094     // Cannot qualify members within a class.
4095     Diag(Loc, diag::err_member_qualification)
4096       << Name << SS.getRange();
4097     SS.clear();
4098 
4099     // C++ constructors and destructors with incorrect scopes can break
4100     // our AST invariants by having the wrong underlying types. If
4101     // that's the case, then drop this declaration entirely.
4102     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4103          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4104         !Context.hasSameType(Name.getCXXNameType(),
4105                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4106       return true;
4107 
4108     return false;
4109   }
4110 
4111   // C++11 [dcl.meaning]p1:
4112   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4113   //   not begin with a decltype-specifer"
4114   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4115   while (SpecLoc.getPrefix())
4116     SpecLoc = SpecLoc.getPrefix();
4117   if (dyn_cast_or_null<DecltypeType>(
4118         SpecLoc.getNestedNameSpecifier()->getAsType()))
4119     Diag(Loc, diag::err_decltype_in_declarator)
4120       << SpecLoc.getTypeLoc().getSourceRange();
4121 
4122   return false;
4123 }
4124 
4125 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4126                                   MultiTemplateParamsArg TemplateParamLists) {
4127   // TODO: consider using NameInfo for diagnostic.
4128   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4129   DeclarationName Name = NameInfo.getName();
4130 
4131   // All of these full declarators require an identifier.  If it doesn't have
4132   // one, the ParsedFreeStandingDeclSpec action should be used.
4133   if (!Name) {
4134     if (!D.isInvalidType())  // Reject this if we think it is valid.
4135       Diag(D.getDeclSpec().getLocStart(),
4136            diag::err_declarator_need_ident)
4137         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4138     return 0;
4139   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4140     return 0;
4141 
4142   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4143   // we find one that is.
4144   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4145          (S->getFlags() & Scope::TemplateParamScope) != 0)
4146     S = S->getParent();
4147 
4148   DeclContext *DC = CurContext;
4149   if (D.getCXXScopeSpec().isInvalid())
4150     D.setInvalidType();
4151   else if (D.getCXXScopeSpec().isSet()) {
4152     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4153                                         UPPC_DeclarationQualifier))
4154       return 0;
4155 
4156     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4157     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4158     if (!DC) {
4159       // If we could not compute the declaration context, it's because the
4160       // declaration context is dependent but does not refer to a class,
4161       // class template, or class template partial specialization. Complain
4162       // and return early, to avoid the coming semantic disaster.
4163       Diag(D.getIdentifierLoc(),
4164            diag::err_template_qualified_declarator_no_match)
4165         << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4166         << D.getCXXScopeSpec().getRange();
4167       return 0;
4168     }
4169     bool IsDependentContext = DC->isDependentContext();
4170 
4171     if (!IsDependentContext &&
4172         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4173       return 0;
4174 
4175     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4176       Diag(D.getIdentifierLoc(),
4177            diag::err_member_def_undefined_record)
4178         << Name << DC << D.getCXXScopeSpec().getRange();
4179       D.setInvalidType();
4180     } else if (!D.getDeclSpec().isFriendSpecified()) {
4181       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4182                                       Name, D.getIdentifierLoc())) {
4183         if (DC->isRecord())
4184           return 0;
4185 
4186         D.setInvalidType();
4187       }
4188     }
4189 
4190     // Check whether we need to rebuild the type of the given
4191     // declaration in the current instantiation.
4192     if (EnteringContext && IsDependentContext &&
4193         TemplateParamLists.size() != 0) {
4194       ContextRAII SavedContext(*this, DC);
4195       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4196         D.setInvalidType();
4197     }
4198   }
4199 
4200   if (DiagnoseClassNameShadow(DC, NameInfo))
4201     // If this is a typedef, we'll end up spewing multiple diagnostics.
4202     // Just return early; it's safer.
4203     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4204       return 0;
4205 
4206   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4207   QualType R = TInfo->getType();
4208 
4209   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4210                                       UPPC_DeclarationType))
4211     D.setInvalidType();
4212 
4213   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4214                         ForRedeclaration);
4215 
4216   // See if this is a redefinition of a variable in the same scope.
4217   if (!D.getCXXScopeSpec().isSet()) {
4218     bool IsLinkageLookup = false;
4219     bool CreateBuiltins = false;
4220 
4221     // If the declaration we're planning to build will be a function
4222     // or object with linkage, then look for another declaration with
4223     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4224     //
4225     // If the declaration we're planning to build will be declared with
4226     // external linkage in the translation unit, create any builtin with
4227     // the same name.
4228     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4229       /* Do nothing*/;
4230     else if (CurContext->isFunctionOrMethod() &&
4231              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4232               R->isFunctionType())) {
4233       IsLinkageLookup = true;
4234       CreateBuiltins =
4235           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4236     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4237                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4238       CreateBuiltins = true;
4239 
4240     if (IsLinkageLookup)
4241       Previous.clear(LookupRedeclarationWithLinkage);
4242 
4243     LookupName(Previous, S, CreateBuiltins);
4244   } else { // Something like "int foo::x;"
4245     LookupQualifiedName(Previous, DC);
4246 
4247     // C++ [dcl.meaning]p1:
4248     //   When the declarator-id is qualified, the declaration shall refer to a
4249     //  previously declared member of the class or namespace to which the
4250     //  qualifier refers (or, in the case of a namespace, of an element of the
4251     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4252     //  thereof; [...]
4253     //
4254     // Note that we already checked the context above, and that we do not have
4255     // enough information to make sure that Previous contains the declaration
4256     // we want to match. For example, given:
4257     //
4258     //   class X {
4259     //     void f();
4260     //     void f(float);
4261     //   };
4262     //
4263     //   void X::f(int) { } // ill-formed
4264     //
4265     // In this case, Previous will point to the overload set
4266     // containing the two f's declared in X, but neither of them
4267     // matches.
4268 
4269     // C++ [dcl.meaning]p1:
4270     //   [...] the member shall not merely have been introduced by a
4271     //   using-declaration in the scope of the class or namespace nominated by
4272     //   the nested-name-specifier of the declarator-id.
4273     RemoveUsingDecls(Previous);
4274   }
4275 
4276   if (Previous.isSingleResult() &&
4277       Previous.getFoundDecl()->isTemplateParameter()) {
4278     // Maybe we will complain about the shadowed template parameter.
4279     if (!D.isInvalidType())
4280       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4281                                       Previous.getFoundDecl());
4282 
4283     // Just pretend that we didn't see the previous declaration.
4284     Previous.clear();
4285   }
4286 
4287   // In C++, the previous declaration we find might be a tag type
4288   // (class or enum). In this case, the new declaration will hide the
4289   // tag type. Note that this does does not apply if we're declaring a
4290   // typedef (C++ [dcl.typedef]p4).
4291   if (Previous.isSingleTagDecl() &&
4292       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4293     Previous.clear();
4294 
4295   // Check that there are no default arguments other than in the parameters
4296   // of a function declaration (C++ only).
4297   if (getLangOpts().CPlusPlus)
4298     CheckExtraCXXDefaultArguments(D);
4299 
4300   NamedDecl *New;
4301 
4302   bool AddToScope = true;
4303   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4304     if (TemplateParamLists.size()) {
4305       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4306       return 0;
4307     }
4308 
4309     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4310   } else if (R->isFunctionType()) {
4311     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4312                                   TemplateParamLists,
4313                                   AddToScope);
4314   } else {
4315     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4316                                   AddToScope);
4317   }
4318 
4319   if (New == 0)
4320     return 0;
4321 
4322   // If this has an identifier and is not an invalid redeclaration or
4323   // function template specialization, add it to the scope stack.
4324   if (New->getDeclName() && AddToScope &&
4325        !(D.isRedeclaration() && New->isInvalidDecl())) {
4326     // Only make a locally-scoped extern declaration visible if it is the first
4327     // declaration of this entity. Qualified lookup for such an entity should
4328     // only find this declaration if there is no visible declaration of it.
4329     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4330     PushOnScopeChains(New, S, AddToContext);
4331     if (!AddToContext)
4332       CurContext->addHiddenDecl(New);
4333   }
4334 
4335   return New;
4336 }
4337 
4338 /// Helper method to turn variable array types into constant array
4339 /// types in certain situations which would otherwise be errors (for
4340 /// GCC compatibility).
4341 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4342                                                     ASTContext &Context,
4343                                                     bool &SizeIsNegative,
4344                                                     llvm::APSInt &Oversized) {
4345   // This method tries to turn a variable array into a constant
4346   // array even when the size isn't an ICE.  This is necessary
4347   // for compatibility with code that depends on gcc's buggy
4348   // constant expression folding, like struct {char x[(int)(char*)2];}
4349   SizeIsNegative = false;
4350   Oversized = 0;
4351 
4352   if (T->isDependentType())
4353     return QualType();
4354 
4355   QualifierCollector Qs;
4356   const Type *Ty = Qs.strip(T);
4357 
4358   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4359     QualType Pointee = PTy->getPointeeType();
4360     QualType FixedType =
4361         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4362                                             Oversized);
4363     if (FixedType.isNull()) return FixedType;
4364     FixedType = Context.getPointerType(FixedType);
4365     return Qs.apply(Context, FixedType);
4366   }
4367   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4368     QualType Inner = PTy->getInnerType();
4369     QualType FixedType =
4370         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4371                                             Oversized);
4372     if (FixedType.isNull()) return FixedType;
4373     FixedType = Context.getParenType(FixedType);
4374     return Qs.apply(Context, FixedType);
4375   }
4376 
4377   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4378   if (!VLATy)
4379     return QualType();
4380   // FIXME: We should probably handle this case
4381   if (VLATy->getElementType()->isVariablyModifiedType())
4382     return QualType();
4383 
4384   llvm::APSInt Res;
4385   if (!VLATy->getSizeExpr() ||
4386       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4387     return QualType();
4388 
4389   // Check whether the array size is negative.
4390   if (Res.isSigned() && Res.isNegative()) {
4391     SizeIsNegative = true;
4392     return QualType();
4393   }
4394 
4395   // Check whether the array is too large to be addressed.
4396   unsigned ActiveSizeBits
4397     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4398                                               Res);
4399   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4400     Oversized = Res;
4401     return QualType();
4402   }
4403 
4404   return Context.getConstantArrayType(VLATy->getElementType(),
4405                                       Res, ArrayType::Normal, 0);
4406 }
4407 
4408 static void
4409 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4410   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4411     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4412     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4413                                       DstPTL.getPointeeLoc());
4414     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4415     return;
4416   }
4417   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4418     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4419     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4420                                       DstPTL.getInnerLoc());
4421     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4422     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4423     return;
4424   }
4425   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4426   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4427   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4428   TypeLoc DstElemTL = DstATL.getElementLoc();
4429   DstElemTL.initializeFullCopy(SrcElemTL);
4430   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4431   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4432   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4433 }
4434 
4435 /// Helper method to turn variable array types into constant array
4436 /// types in certain situations which would otherwise be errors (for
4437 /// GCC compatibility).
4438 static TypeSourceInfo*
4439 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4440                                               ASTContext &Context,
4441                                               bool &SizeIsNegative,
4442                                               llvm::APSInt &Oversized) {
4443   QualType FixedTy
4444     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4445                                           SizeIsNegative, Oversized);
4446   if (FixedTy.isNull())
4447     return 0;
4448   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4449   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4450                                     FixedTInfo->getTypeLoc());
4451   return FixedTInfo;
4452 }
4453 
4454 /// \brief Register the given locally-scoped extern "C" declaration so
4455 /// that it can be found later for redeclarations. We include any extern "C"
4456 /// declaration that is not visible in the translation unit here, not just
4457 /// function-scope declarations.
4458 void
4459 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4460   if (!getLangOpts().CPlusPlus &&
4461       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4462     // Don't need to track declarations in the TU in C.
4463     return;
4464 
4465   // Note that we have a locally-scoped external with this name.
4466   // FIXME: There can be multiple such declarations if they are functions marked
4467   // __attribute__((overloadable)) declared in function scope in C.
4468   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4469 }
4470 
4471 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4472   if (ExternalSource) {
4473     // Load locally-scoped external decls from the external source.
4474     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4475     SmallVector<NamedDecl *, 4> Decls;
4476     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4477     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4478       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4479         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4480       if (Pos == LocallyScopedExternCDecls.end())
4481         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4482     }
4483   }
4484 
4485   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4486   return D ? cast<NamedDecl>(D->getMostRecentDecl()) : 0;
4487 }
4488 
4489 /// \brief Diagnose function specifiers on a declaration of an identifier that
4490 /// does not identify a function.
4491 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4492   // FIXME: We should probably indicate the identifier in question to avoid
4493   // confusion for constructs like "inline int a(), b;"
4494   if (DS.isInlineSpecified())
4495     Diag(DS.getInlineSpecLoc(),
4496          diag::err_inline_non_function);
4497 
4498   if (DS.isVirtualSpecified())
4499     Diag(DS.getVirtualSpecLoc(),
4500          diag::err_virtual_non_function);
4501 
4502   if (DS.isExplicitSpecified())
4503     Diag(DS.getExplicitSpecLoc(),
4504          diag::err_explicit_non_function);
4505 
4506   if (DS.isNoreturnSpecified())
4507     Diag(DS.getNoreturnSpecLoc(),
4508          diag::err_noreturn_non_function);
4509 }
4510 
4511 NamedDecl*
4512 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4513                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4514   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4515   if (D.getCXXScopeSpec().isSet()) {
4516     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4517       << D.getCXXScopeSpec().getRange();
4518     D.setInvalidType();
4519     // Pretend we didn't see the scope specifier.
4520     DC = CurContext;
4521     Previous.clear();
4522   }
4523 
4524   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4525 
4526   if (D.getDeclSpec().isConstexprSpecified())
4527     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4528       << 1;
4529 
4530   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4531     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4532       << D.getName().getSourceRange();
4533     return 0;
4534   }
4535 
4536   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4537   if (!NewTD) return 0;
4538 
4539   // Handle attributes prior to checking for duplicates in MergeVarDecl
4540   ProcessDeclAttributes(S, NewTD, D);
4541 
4542   CheckTypedefForVariablyModifiedType(S, NewTD);
4543 
4544   bool Redeclaration = D.isRedeclaration();
4545   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4546   D.setRedeclaration(Redeclaration);
4547   return ND;
4548 }
4549 
4550 void
4551 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4552   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4553   // then it shall have block scope.
4554   // Note that variably modified types must be fixed before merging the decl so
4555   // that redeclarations will match.
4556   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4557   QualType T = TInfo->getType();
4558   if (T->isVariablyModifiedType()) {
4559     getCurFunction()->setHasBranchProtectedScope();
4560 
4561     if (S->getFnParent() == 0) {
4562       bool SizeIsNegative;
4563       llvm::APSInt Oversized;
4564       TypeSourceInfo *FixedTInfo =
4565         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4566                                                       SizeIsNegative,
4567                                                       Oversized);
4568       if (FixedTInfo) {
4569         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4570         NewTD->setTypeSourceInfo(FixedTInfo);
4571       } else {
4572         if (SizeIsNegative)
4573           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4574         else if (T->isVariableArrayType())
4575           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4576         else if (Oversized.getBoolValue())
4577           Diag(NewTD->getLocation(), diag::err_array_too_large)
4578             << Oversized.toString(10);
4579         else
4580           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4581         NewTD->setInvalidDecl();
4582       }
4583     }
4584   }
4585 }
4586 
4587 
4588 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4589 /// declares a typedef-name, either using the 'typedef' type specifier or via
4590 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4591 NamedDecl*
4592 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4593                            LookupResult &Previous, bool &Redeclaration) {
4594   // Merge the decl with the existing one if appropriate. If the decl is
4595   // in an outer scope, it isn't the same thing.
4596   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
4597                        /*ExplicitInstantiationOrSpecialization=*/false);
4598   filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4599   if (!Previous.empty()) {
4600     Redeclaration = true;
4601     MergeTypedefNameDecl(NewTD, Previous);
4602   }
4603 
4604   // If this is the C FILE type, notify the AST context.
4605   if (IdentifierInfo *II = NewTD->getIdentifier())
4606     if (!NewTD->isInvalidDecl() &&
4607         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4608       if (II->isStr("FILE"))
4609         Context.setFILEDecl(NewTD);
4610       else if (II->isStr("jmp_buf"))
4611         Context.setjmp_bufDecl(NewTD);
4612       else if (II->isStr("sigjmp_buf"))
4613         Context.setsigjmp_bufDecl(NewTD);
4614       else if (II->isStr("ucontext_t"))
4615         Context.setucontext_tDecl(NewTD);
4616     }
4617 
4618   return NewTD;
4619 }
4620 
4621 /// \brief Determines whether the given declaration is an out-of-scope
4622 /// previous declaration.
4623 ///
4624 /// This routine should be invoked when name lookup has found a
4625 /// previous declaration (PrevDecl) that is not in the scope where a
4626 /// new declaration by the same name is being introduced. If the new
4627 /// declaration occurs in a local scope, previous declarations with
4628 /// linkage may still be considered previous declarations (C99
4629 /// 6.2.2p4-5, C++ [basic.link]p6).
4630 ///
4631 /// \param PrevDecl the previous declaration found by name
4632 /// lookup
4633 ///
4634 /// \param DC the context in which the new declaration is being
4635 /// declared.
4636 ///
4637 /// \returns true if PrevDecl is an out-of-scope previous declaration
4638 /// for a new delcaration with the same name.
4639 static bool
4640 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4641                                 ASTContext &Context) {
4642   if (!PrevDecl)
4643     return false;
4644 
4645   if (!PrevDecl->hasLinkage())
4646     return false;
4647 
4648   if (Context.getLangOpts().CPlusPlus) {
4649     // C++ [basic.link]p6:
4650     //   If there is a visible declaration of an entity with linkage
4651     //   having the same name and type, ignoring entities declared
4652     //   outside the innermost enclosing namespace scope, the block
4653     //   scope declaration declares that same entity and receives the
4654     //   linkage of the previous declaration.
4655     DeclContext *OuterContext = DC->getRedeclContext();
4656     if (!OuterContext->isFunctionOrMethod())
4657       // This rule only applies to block-scope declarations.
4658       return false;
4659 
4660     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4661     if (PrevOuterContext->isRecord())
4662       // We found a member function: ignore it.
4663       return false;
4664 
4665     // Find the innermost enclosing namespace for the new and
4666     // previous declarations.
4667     OuterContext = OuterContext->getEnclosingNamespaceContext();
4668     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4669 
4670     // The previous declaration is in a different namespace, so it
4671     // isn't the same function.
4672     if (!OuterContext->Equals(PrevOuterContext))
4673       return false;
4674   }
4675 
4676   return true;
4677 }
4678 
4679 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4680   CXXScopeSpec &SS = D.getCXXScopeSpec();
4681   if (!SS.isSet()) return;
4682   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4683 }
4684 
4685 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4686   QualType type = decl->getType();
4687   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4688   if (lifetime == Qualifiers::OCL_Autoreleasing) {
4689     // Various kinds of declaration aren't allowed to be __autoreleasing.
4690     unsigned kind = -1U;
4691     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4692       if (var->hasAttr<BlocksAttr>())
4693         kind = 0; // __block
4694       else if (!var->hasLocalStorage())
4695         kind = 1; // global
4696     } else if (isa<ObjCIvarDecl>(decl)) {
4697       kind = 3; // ivar
4698     } else if (isa<FieldDecl>(decl)) {
4699       kind = 2; // field
4700     }
4701 
4702     if (kind != -1U) {
4703       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4704         << kind;
4705     }
4706   } else if (lifetime == Qualifiers::OCL_None) {
4707     // Try to infer lifetime.
4708     if (!type->isObjCLifetimeType())
4709       return false;
4710 
4711     lifetime = type->getObjCARCImplicitLifetime();
4712     type = Context.getLifetimeQualifiedType(type, lifetime);
4713     decl->setType(type);
4714   }
4715 
4716   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4717     // Thread-local variables cannot have lifetime.
4718     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4719         var->getTLSKind()) {
4720       Diag(var->getLocation(), diag::err_arc_thread_ownership)
4721         << var->getType();
4722       return true;
4723     }
4724   }
4725 
4726   return false;
4727 }
4728 
4729 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4730   // 'weak' only applies to declarations with external linkage.
4731   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4732     if (!ND.isExternallyVisible()) {
4733       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4734       ND.dropAttr<WeakAttr>();
4735     }
4736   }
4737   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4738     if (ND.isExternallyVisible()) {
4739       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4740       ND.dropAttr<WeakRefAttr>();
4741     }
4742   }
4743 
4744   // 'selectany' only applies to externally visible varable declarations.
4745   // It does not apply to functions.
4746   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4747     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4748       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4749       ND.dropAttr<SelectAnyAttr>();
4750     }
4751   }
4752 }
4753 
4754 /// Given that we are within the definition of the given function,
4755 /// will that definition behave like C99's 'inline', where the
4756 /// definition is discarded except for optimization purposes?
4757 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4758   // Try to avoid calling GetGVALinkageForFunction.
4759 
4760   // All cases of this require the 'inline' keyword.
4761   if (!FD->isInlined()) return false;
4762 
4763   // This is only possible in C++ with the gnu_inline attribute.
4764   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4765     return false;
4766 
4767   // Okay, go ahead and call the relatively-more-expensive function.
4768 
4769 #ifndef NDEBUG
4770   // AST quite reasonably asserts that it's working on a function
4771   // definition.  We don't really have a way to tell it that we're
4772   // currently defining the function, so just lie to it in +Asserts
4773   // builds.  This is an awful hack.
4774   FD->setLazyBody(1);
4775 #endif
4776 
4777   bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4778 
4779 #ifndef NDEBUG
4780   FD->setLazyBody(0);
4781 #endif
4782 
4783   return isC99Inline;
4784 }
4785 
4786 /// Determine whether a variable is extern "C" prior to attaching
4787 /// an initializer. We can't just call isExternC() here, because that
4788 /// will also compute and cache whether the declaration is externally
4789 /// visible, which might change when we attach the initializer.
4790 ///
4791 /// This can only be used if the declaration is known to not be a
4792 /// redeclaration of an internal linkage declaration.
4793 ///
4794 /// For instance:
4795 ///
4796 ///   auto x = []{};
4797 ///
4798 /// Attaching the initializer here makes this declaration not externally
4799 /// visible, because its type has internal linkage.
4800 ///
4801 /// FIXME: This is a hack.
4802 template<typename T>
4803 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4804   if (S.getLangOpts().CPlusPlus) {
4805     // In C++, the overloadable attribute negates the effects of extern "C".
4806     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4807       return false;
4808   }
4809   return D->isExternC();
4810 }
4811 
4812 static bool shouldConsiderLinkage(const VarDecl *VD) {
4813   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4814   if (DC->isFunctionOrMethod())
4815     return VD->hasExternalStorage();
4816   if (DC->isFileContext())
4817     return true;
4818   if (DC->isRecord())
4819     return false;
4820   llvm_unreachable("Unexpected context");
4821 }
4822 
4823 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4824   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4825   if (DC->isFileContext() || DC->isFunctionOrMethod())
4826     return true;
4827   if (DC->isRecord())
4828     return false;
4829   llvm_unreachable("Unexpected context");
4830 }
4831 
4832 /// Adjust the \c DeclContext for a function or variable that might be a
4833 /// function-local external declaration.
4834 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4835   if (!DC->isFunctionOrMethod())
4836     return false;
4837 
4838   // If this is a local extern function or variable declared within a function
4839   // template, don't add it into the enclosing namespace scope until it is
4840   // instantiated; it might have a dependent type right now.
4841   if (DC->isDependentContext())
4842     return true;
4843 
4844   // C++11 [basic.link]p7:
4845   //   When a block scope declaration of an entity with linkage is not found to
4846   //   refer to some other declaration, then that entity is a member of the
4847   //   innermost enclosing namespace.
4848   //
4849   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4850   // semantically-enclosing namespace, not a lexically-enclosing one.
4851   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4852     DC = DC->getParent();
4853   return true;
4854 }
4855 
4856 NamedDecl *
4857 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4858                               TypeSourceInfo *TInfo, LookupResult &Previous,
4859                               MultiTemplateParamsArg TemplateParamLists,
4860                               bool &AddToScope) {
4861   QualType R = TInfo->getType();
4862   DeclarationName Name = GetNameForDeclarator(D).getName();
4863 
4864   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4865   VarDecl::StorageClass SC =
4866     StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
4867 
4868   DeclContext *OriginalDC = DC;
4869   bool IsLocalExternDecl = SC == SC_Extern &&
4870                            adjustContextForLocalExternDecl(DC);
4871 
4872   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
4873     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4874     // half array type (unless the cl_khr_fp16 extension is enabled).
4875     if (Context.getBaseElementType(R)->isHalfType()) {
4876       Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4877       D.setInvalidType();
4878     }
4879   }
4880 
4881   if (SCSpec == DeclSpec::SCS_mutable) {
4882     // mutable can only appear on non-static class members, so it's always
4883     // an error here
4884     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
4885     D.setInvalidType();
4886     SC = SC_None;
4887   }
4888 
4889   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4890       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4891                               D.getDeclSpec().getStorageClassSpecLoc())) {
4892     // In C++11, the 'register' storage class specifier is deprecated.
4893     // Suppress the warning in system macros, it's used in macros in some
4894     // popular C system headers, such as in glibc's htonl() macro.
4895     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4896          diag::warn_deprecated_register)
4897       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4898   }
4899 
4900   IdentifierInfo *II = Name.getAsIdentifierInfo();
4901   if (!II) {
4902     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
4903       << Name;
4904     return 0;
4905   }
4906 
4907   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4908 
4909   if (!DC->isRecord() && S->getFnParent() == 0) {
4910     // C99 6.9p2: The storage-class specifiers auto and register shall not
4911     // appear in the declaration specifiers in an external declaration.
4912     if (SC == SC_Auto || SC == SC_Register) {
4913       // If this is a register variable with an asm label specified, then this
4914       // is a GNU extension.
4915       if (SC == SC_Register && D.getAsmLabel())
4916         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4917       else
4918         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
4919       D.setInvalidType();
4920     }
4921   }
4922 
4923   if (getLangOpts().OpenCL) {
4924     // Set up the special work-group-local storage class for variables in the
4925     // OpenCL __local address space.
4926     if (R.getAddressSpace() == LangAS::opencl_local) {
4927       SC = SC_OpenCLWorkGroupLocal;
4928     }
4929 
4930     // OpenCL v1.2 s6.9.b p4:
4931     // The sampler type cannot be used with the __local and __global address
4932     // space qualifiers.
4933     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
4934       R.getAddressSpace() == LangAS::opencl_global)) {
4935       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
4936     }
4937 
4938     // OpenCL 1.2 spec, p6.9 r:
4939     // The event type cannot be used to declare a program scope variable.
4940     // The event type cannot be used with the __local, __constant and __global
4941     // address space qualifiers.
4942     if (R->isEventT()) {
4943       if (S->getParent() == 0) {
4944         Diag(D.getLocStart(), diag::err_event_t_global_var);
4945         D.setInvalidType();
4946       }
4947 
4948       if (R.getAddressSpace()) {
4949         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
4950         D.setInvalidType();
4951       }
4952     }
4953   }
4954 
4955   bool IsExplicitSpecialization = false;
4956   bool IsVariableTemplateSpecialization = false;
4957   bool IsPartialSpecialization = false;
4958   bool IsVariableTemplate = false;
4959   VarTemplateDecl *PrevVarTemplate = 0;
4960   VarDecl *NewVD = 0;
4961   VarTemplateDecl *NewTemplate = 0;
4962   if (!getLangOpts().CPlusPlus) {
4963     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4964                             D.getIdentifierLoc(), II,
4965                             R, TInfo, SC);
4966 
4967     if (D.isInvalidType())
4968       NewVD->setInvalidDecl();
4969   } else {
4970     bool Invalid = false;
4971 
4972     if (DC->isRecord() && !CurContext->isRecord()) {
4973       // This is an out-of-line definition of a static data member.
4974       switch (SC) {
4975       case SC_None:
4976         break;
4977       case SC_Static:
4978         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4979              diag::err_static_out_of_line)
4980           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4981         break;
4982       case SC_Auto:
4983       case SC_Register:
4984       case SC_Extern:
4985         // [dcl.stc] p2: The auto or register specifiers shall be applied only
4986         // to names of variables declared in a block or to function parameters.
4987         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
4988         // of class members
4989 
4990         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4991              diag::err_storage_class_for_static_member)
4992           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4993         break;
4994       case SC_PrivateExtern:
4995         llvm_unreachable("C storage class in c++!");
4996       case SC_OpenCLWorkGroupLocal:
4997         llvm_unreachable("OpenCL storage class in c++!");
4998       }
4999     }
5000 
5001     if (SC == SC_Static && CurContext->isRecord()) {
5002       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5003         if (RD->isLocalClass())
5004           Diag(D.getIdentifierLoc(),
5005                diag::err_static_data_member_not_allowed_in_local_class)
5006             << Name << RD->getDeclName();
5007 
5008         // C++98 [class.union]p1: If a union contains a static data member,
5009         // the program is ill-formed. C++11 drops this restriction.
5010         if (RD->isUnion())
5011           Diag(D.getIdentifierLoc(),
5012                getLangOpts().CPlusPlus11
5013                  ? diag::warn_cxx98_compat_static_data_member_in_union
5014                  : diag::ext_static_data_member_in_union) << Name;
5015         // We conservatively disallow static data members in anonymous structs.
5016         else if (!RD->getDeclName())
5017           Diag(D.getIdentifierLoc(),
5018                diag::err_static_data_member_not_allowed_in_anon_struct)
5019             << Name << RD->isUnion();
5020       }
5021     }
5022 
5023     NamedDecl *PrevDecl = 0;
5024     if (Previous.begin() != Previous.end())
5025       PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5026     PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5027 
5028     // Match up the template parameter lists with the scope specifier, then
5029     // determine whether we have a template or a template specialization.
5030     TemplateParameterList *TemplateParams =
5031         MatchTemplateParametersToScopeSpecifier(
5032             D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5033             D.getCXXScopeSpec(), TemplateParamLists,
5034             /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5035     if (TemplateParams) {
5036       if (!TemplateParams->size() &&
5037           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5038         // There is an extraneous 'template<>' for this variable. Complain
5039         // about it, but allow the declaration of the variable.
5040         Diag(TemplateParams->getTemplateLoc(),
5041              diag::err_template_variable_noparams)
5042           << II
5043           << SourceRange(TemplateParams->getTemplateLoc(),
5044                          TemplateParams->getRAngleLoc());
5045       } else {
5046         // Only C++1y supports variable templates (N3651).
5047         Diag(D.getIdentifierLoc(),
5048              getLangOpts().CPlusPlus1y
5049                  ? diag::warn_cxx11_compat_variable_template
5050                  : diag::ext_variable_template);
5051 
5052         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5053           // This is an explicit specialization or a partial specialization.
5054           // Check that we can declare a specialization here
5055 
5056           IsVariableTemplateSpecialization = true;
5057           IsPartialSpecialization = TemplateParams->size() > 0;
5058 
5059         } else { // if (TemplateParams->size() > 0)
5060           // This is a template declaration.
5061           IsVariableTemplate = true;
5062 
5063           // Check that we can declare a template here.
5064           if (CheckTemplateDeclScope(S, TemplateParams))
5065             return 0;
5066 
5067           // If there is a previous declaration with the same name, check
5068           // whether this is a valid redeclaration.
5069           if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5070             PrevDecl = PrevVarTemplate = 0;
5071 
5072           if (PrevVarTemplate) {
5073             // Ensure that the template parameter lists are compatible.
5074             if (!TemplateParameterListsAreEqual(
5075                     TemplateParams, PrevVarTemplate->getTemplateParameters(),
5076                     /*Complain=*/true, TPL_TemplateMatch))
5077               return 0;
5078           } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5079             // Maybe we will complain about the shadowed template parameter.
5080             DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5081 
5082             // Just pretend that we didn't see the previous declaration.
5083             PrevDecl = 0;
5084           } else if (PrevDecl) {
5085             // C++ [temp]p5:
5086             // ... a template name declared in namespace scope or in class
5087             // scope shall be unique in that scope.
5088             Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5089                 << Name;
5090             Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5091             return 0;
5092           }
5093 
5094           // Check the template parameter list of this declaration, possibly
5095           // merging in the template parameter list from the previous variable
5096           // template declaration.
5097           if (CheckTemplateParameterList(
5098                   TemplateParams,
5099                   PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5100                                   : 0,
5101                   (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5102                    DC->isDependentContext())
5103                       ? TPC_ClassTemplateMember
5104                       : TPC_VarTemplate))
5105             Invalid = true;
5106 
5107           if (D.getCXXScopeSpec().isSet()) {
5108             // If the name of the template was qualified, we must be defining
5109             // the template out-of-line.
5110             if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5111                 !PrevVarTemplate) {
5112               Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5113                   << Name << DC << /*IsDefinition*/true
5114                   << D.getCXXScopeSpec().getRange();
5115               Invalid = true;
5116             }
5117           }
5118         }
5119       }
5120     } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5121       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5122 
5123       // We have encountered something that the user meant to be a
5124       // specialization (because it has explicitly-specified template
5125       // arguments) but that was not introduced with a "template<>" (or had
5126       // too few of them).
5127       // FIXME: Differentiate between attempts for explicit instantiations
5128       // (starting with "template") and the rest.
5129       Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5130           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5131           << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5132                                         "template<> ");
5133       IsVariableTemplateSpecialization = true;
5134     }
5135 
5136     if (IsVariableTemplateSpecialization) {
5137       if (!PrevVarTemplate) {
5138         Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5139             << IsPartialSpecialization;
5140         return 0;
5141       }
5142 
5143       SourceLocation TemplateKWLoc =
5144           TemplateParamLists.size() > 0
5145               ? TemplateParamLists[0]->getTemplateLoc()
5146               : SourceLocation();
5147       DeclResult Res = ActOnVarTemplateSpecialization(
5148           S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5149           IsPartialSpecialization);
5150       if (Res.isInvalid())
5151         return 0;
5152       NewVD = cast<VarDecl>(Res.get());
5153       AddToScope = false;
5154     } else
5155       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5156                               D.getIdentifierLoc(), II, R, TInfo, SC);
5157 
5158     // If this is supposed to be a variable template, create it as such.
5159     if (IsVariableTemplate) {
5160       NewTemplate =
5161           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5162                                   TemplateParams, NewVD, PrevVarTemplate);
5163       NewVD->setDescribedVarTemplate(NewTemplate);
5164     }
5165 
5166     // If this decl has an auto type in need of deduction, make a note of the
5167     // Decl so we can diagnose uses of it in its own initializer.
5168     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5169       ParsingInitForAutoVars.insert(NewVD);
5170 
5171     if (D.isInvalidType() || Invalid) {
5172       NewVD->setInvalidDecl();
5173       if (NewTemplate)
5174         NewTemplate->setInvalidDecl();
5175     }
5176 
5177     SetNestedNameSpecifier(NewVD, D);
5178 
5179     // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5180     if (TemplateParams && TemplateParamLists.size() > 1 &&
5181         (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5182       NewVD->setTemplateParameterListsInfo(
5183           Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5184     } else if (IsVariableTemplateSpecialization ||
5185                (!TemplateParams && TemplateParamLists.size() > 0 &&
5186                 (D.getCXXScopeSpec().isSet()))) {
5187       NewVD->setTemplateParameterListsInfo(Context,
5188                                            TemplateParamLists.size(),
5189                                            TemplateParamLists.data());
5190     }
5191 
5192     if (D.getDeclSpec().isConstexprSpecified())
5193       NewVD->setConstexpr(true);
5194   }
5195 
5196   // Set the lexical context. If the declarator has a C++ scope specifier, the
5197   // lexical context will be different from the semantic context.
5198   NewVD->setLexicalDeclContext(CurContext);
5199   if (NewTemplate)
5200     NewTemplate->setLexicalDeclContext(CurContext);
5201 
5202   if (IsLocalExternDecl)
5203     NewVD->setLocalExternDecl();
5204 
5205   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5206     if (NewVD->hasLocalStorage()) {
5207       // C++11 [dcl.stc]p4:
5208       //   When thread_local is applied to a variable of block scope the
5209       //   storage-class-specifier static is implied if it does not appear
5210       //   explicitly.
5211       // Core issue: 'static' is not implied if the variable is declared
5212       //   'extern'.
5213       if (SCSpec == DeclSpec::SCS_unspecified &&
5214           TSCS == DeclSpec::TSCS_thread_local &&
5215           DC->isFunctionOrMethod())
5216         NewVD->setTSCSpec(TSCS);
5217       else
5218         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5219              diag::err_thread_non_global)
5220           << DeclSpec::getSpecifierName(TSCS);
5221     } else if (!Context.getTargetInfo().isTLSSupported())
5222       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5223            diag::err_thread_unsupported);
5224     else
5225       NewVD->setTSCSpec(TSCS);
5226   }
5227 
5228   // C99 6.7.4p3
5229   //   An inline definition of a function with external linkage shall
5230   //   not contain a definition of a modifiable object with static or
5231   //   thread storage duration...
5232   // We only apply this when the function is required to be defined
5233   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5234   // that a local variable with thread storage duration still has to
5235   // be marked 'static'.  Also note that it's possible to get these
5236   // semantics in C++ using __attribute__((gnu_inline)).
5237   if (SC == SC_Static && S->getFnParent() != 0 &&
5238       !NewVD->getType().isConstQualified()) {
5239     FunctionDecl *CurFD = getCurFunctionDecl();
5240     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5241       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5242            diag::warn_static_local_in_extern_inline);
5243       MaybeSuggestAddingStaticToDecl(CurFD);
5244     }
5245   }
5246 
5247   if (D.getDeclSpec().isModulePrivateSpecified()) {
5248     if (IsVariableTemplateSpecialization)
5249       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5250           << (IsPartialSpecialization ? 1 : 0)
5251           << FixItHint::CreateRemoval(
5252                  D.getDeclSpec().getModulePrivateSpecLoc());
5253     else if (IsExplicitSpecialization)
5254       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5255         << 2
5256         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5257     else if (NewVD->hasLocalStorage())
5258       Diag(NewVD->getLocation(), diag::err_module_private_local)
5259         << 0 << NewVD->getDeclName()
5260         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5261         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5262     else {
5263       NewVD->setModulePrivate();
5264       if (NewTemplate)
5265         NewTemplate->setModulePrivate();
5266     }
5267   }
5268 
5269   // Handle attributes prior to checking for duplicates in MergeVarDecl
5270   ProcessDeclAttributes(S, NewVD, D);
5271 
5272   if (NewVD->hasAttrs())
5273     CheckAlignasUnderalignment(NewVD);
5274 
5275   if (getLangOpts().CUDA) {
5276     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5277     // storage [duration]."
5278     if (SC == SC_None && S->getFnParent() != 0 &&
5279         (NewVD->hasAttr<CUDASharedAttr>() ||
5280          NewVD->hasAttr<CUDAConstantAttr>())) {
5281       NewVD->setStorageClass(SC_Static);
5282     }
5283   }
5284 
5285   // In auto-retain/release, infer strong retension for variables of
5286   // retainable type.
5287   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5288     NewVD->setInvalidDecl();
5289 
5290   // Handle GNU asm-label extension (encoded as an attribute).
5291   if (Expr *E = (Expr*)D.getAsmLabel()) {
5292     // The parser guarantees this is a string.
5293     StringLiteral *SE = cast<StringLiteral>(E);
5294     StringRef Label = SE->getString();
5295     if (S->getFnParent() != 0) {
5296       switch (SC) {
5297       case SC_None:
5298       case SC_Auto:
5299         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5300         break;
5301       case SC_Register:
5302         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5303           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5304         break;
5305       case SC_Static:
5306       case SC_Extern:
5307       case SC_PrivateExtern:
5308       case SC_OpenCLWorkGroupLocal:
5309         break;
5310       }
5311     }
5312 
5313     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5314                                                 Context, Label));
5315   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5316     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5317       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5318     if (I != ExtnameUndeclaredIdentifiers.end()) {
5319       NewVD->addAttr(I->second);
5320       ExtnameUndeclaredIdentifiers.erase(I);
5321     }
5322   }
5323 
5324   // Diagnose shadowed variables before filtering for scope.
5325   if (!D.getCXXScopeSpec().isSet())
5326     CheckShadow(S, NewVD, Previous);
5327 
5328   // Don't consider existing declarations that are in a different
5329   // scope and are out-of-semantic-context declarations (if the new
5330   // declaration has linkage).
5331   FilterLookupForScope(
5332       Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5333       IsExplicitSpecialization || IsVariableTemplateSpecialization);
5334 
5335   // Check whether the previous declaration is in the same block scope. This
5336   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5337   if (getLangOpts().CPlusPlus &&
5338       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5339     NewVD->setPreviousDeclInSameBlockScope(
5340         Previous.isSingleResult() && !Previous.isShadowed() &&
5341         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5342 
5343   if (!getLangOpts().CPlusPlus) {
5344     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5345   } else {
5346     // Merge the decl with the existing one if appropriate.
5347     if (!Previous.empty()) {
5348       if (Previous.isSingleResult() &&
5349           isa<FieldDecl>(Previous.getFoundDecl()) &&
5350           D.getCXXScopeSpec().isSet()) {
5351         // The user tried to define a non-static data member
5352         // out-of-line (C++ [dcl.meaning]p1).
5353         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5354           << D.getCXXScopeSpec().getRange();
5355         Previous.clear();
5356         NewVD->setInvalidDecl();
5357       }
5358     } else if (D.getCXXScopeSpec().isSet()) {
5359       // No previous declaration in the qualifying scope.
5360       Diag(D.getIdentifierLoc(), diag::err_no_member)
5361         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5362         << D.getCXXScopeSpec().getRange();
5363       NewVD->setInvalidDecl();
5364     }
5365 
5366     if (!IsVariableTemplateSpecialization) {
5367       if (PrevVarTemplate) {
5368         LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5369                               LookupOrdinaryName, ForRedeclaration);
5370         PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
5371         D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
5372       } else
5373         D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5374     }
5375 
5376     // This is an explicit specialization of a static data member. Check it.
5377     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5378         CheckMemberSpecialization(NewVD, Previous))
5379       NewVD->setInvalidDecl();
5380   }
5381 
5382   ProcessPragmaWeak(S, NewVD);
5383   checkAttributesAfterMerging(*this, *NewVD);
5384 
5385   // If this is the first declaration of an extern C variable, update
5386   // the map of such variables.
5387   if (!NewVD->getPreviousDecl() && !NewVD->isInvalidDecl() &&
5388       isIncompleteDeclExternC(*this, NewVD))
5389     RegisterLocallyScopedExternCDecl(NewVD, S);
5390 
5391   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5392     Decl *ManglingContextDecl;
5393     if (MangleNumberingContext *MCtx =
5394             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5395                                           ManglingContextDecl)) {
5396       Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5397     }
5398   }
5399 
5400   // If we are providing an explicit specialization of a static variable
5401   // template, make a note of that.
5402   if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
5403     PrevVarTemplate->setMemberSpecialization();
5404 
5405   if (NewTemplate) {
5406     ActOnDocumentableDecl(NewTemplate);
5407     return NewTemplate;
5408   }
5409 
5410   return NewVD;
5411 }
5412 
5413 /// \brief Diagnose variable or built-in function shadowing.  Implements
5414 /// -Wshadow.
5415 ///
5416 /// This method is called whenever a VarDecl is added to a "useful"
5417 /// scope.
5418 ///
5419 /// \param S the scope in which the shadowing name is being declared
5420 /// \param R the lookup of the name
5421 ///
5422 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5423   // Return if warning is ignored.
5424   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
5425         DiagnosticsEngine::Ignored)
5426     return;
5427 
5428   // Don't diagnose declarations at file scope.
5429   if (D->hasGlobalStorage())
5430     return;
5431 
5432   DeclContext *NewDC = D->getDeclContext();
5433 
5434   // Only diagnose if we're shadowing an unambiguous field or variable.
5435   if (R.getResultKind() != LookupResult::Found)
5436     return;
5437 
5438   NamedDecl* ShadowedDecl = R.getFoundDecl();
5439   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5440     return;
5441 
5442   // Fields are not shadowed by variables in C++ static methods.
5443   if (isa<FieldDecl>(ShadowedDecl))
5444     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5445       if (MD->isStatic())
5446         return;
5447 
5448   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5449     if (shadowedVar->isExternC()) {
5450       // For shadowing external vars, make sure that we point to the global
5451       // declaration, not a locally scoped extern declaration.
5452       for (VarDecl::redecl_iterator
5453              I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5454            I != E; ++I)
5455         if (I->isFileVarDecl()) {
5456           ShadowedDecl = *I;
5457           break;
5458         }
5459     }
5460 
5461   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5462 
5463   // Only warn about certain kinds of shadowing for class members.
5464   if (NewDC && NewDC->isRecord()) {
5465     // In particular, don't warn about shadowing non-class members.
5466     if (!OldDC->isRecord())
5467       return;
5468 
5469     // TODO: should we warn about static data members shadowing
5470     // static data members from base classes?
5471 
5472     // TODO: don't diagnose for inaccessible shadowed members.
5473     // This is hard to do perfectly because we might friend the
5474     // shadowing context, but that's just a false negative.
5475   }
5476 
5477   // Determine what kind of declaration we're shadowing.
5478   unsigned Kind;
5479   if (isa<RecordDecl>(OldDC)) {
5480     if (isa<FieldDecl>(ShadowedDecl))
5481       Kind = 3; // field
5482     else
5483       Kind = 2; // static data member
5484   } else if (OldDC->isFileContext())
5485     Kind = 1; // global
5486   else
5487     Kind = 0; // local
5488 
5489   DeclarationName Name = R.getLookupName();
5490 
5491   // Emit warning and note.
5492   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5493   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5494 }
5495 
5496 /// \brief Check -Wshadow without the advantage of a previous lookup.
5497 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5498   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
5499         DiagnosticsEngine::Ignored)
5500     return;
5501 
5502   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5503                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5504   LookupName(R, S);
5505   CheckShadow(S, D, R);
5506 }
5507 
5508 /// Check for conflict between this global or extern "C" declaration and
5509 /// previous global or extern "C" declarations. This is only used in C++.
5510 template<typename T>
5511 static bool checkGlobalOrExternCConflict(
5512     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5513   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5514   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5515 
5516   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5517     // The common case: this global doesn't conflict with any extern "C"
5518     // declaration.
5519     return false;
5520   }
5521 
5522   if (Prev) {
5523     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5524       // Both the old and new declarations have C language linkage. This is a
5525       // redeclaration.
5526       Previous.clear();
5527       Previous.addDecl(Prev);
5528       return true;
5529     }
5530 
5531     // This is a global, non-extern "C" declaration, and there is a previous
5532     // non-global extern "C" declaration. Diagnose if this is a variable
5533     // declaration.
5534     if (!isa<VarDecl>(ND))
5535       return false;
5536   } else {
5537     // The declaration is extern "C". Check for any declaration in the
5538     // translation unit which might conflict.
5539     if (IsGlobal) {
5540       // We have already performed the lookup into the translation unit.
5541       IsGlobal = false;
5542       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5543            I != E; ++I) {
5544         if (isa<VarDecl>(*I)) {
5545           Prev = *I;
5546           break;
5547         }
5548       }
5549     } else {
5550       DeclContext::lookup_result R =
5551           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5552       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5553            I != E; ++I) {
5554         if (isa<VarDecl>(*I)) {
5555           Prev = *I;
5556           break;
5557         }
5558         // FIXME: If we have any other entity with this name in global scope,
5559         // the declaration is ill-formed, but that is a defect: it breaks the
5560         // 'stat' hack, for instance. Only variables can have mangled name
5561         // clashes with extern "C" declarations, so only they deserve a
5562         // diagnostic.
5563       }
5564     }
5565 
5566     if (!Prev)
5567       return false;
5568   }
5569 
5570   // Use the first declaration's location to ensure we point at something which
5571   // is lexically inside an extern "C" linkage-spec.
5572   assert(Prev && "should have found a previous declaration to diagnose");
5573   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5574     Prev = FD->getFirstDeclaration();
5575   else
5576     Prev = cast<VarDecl>(Prev)->getFirstDeclaration();
5577 
5578   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5579     << IsGlobal << ND;
5580   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5581     << IsGlobal;
5582   return false;
5583 }
5584 
5585 /// Apply special rules for handling extern "C" declarations. Returns \c true
5586 /// if we have found that this is a redeclaration of some prior entity.
5587 ///
5588 /// Per C++ [dcl.link]p6:
5589 ///   Two declarations [for a function or variable] with C language linkage
5590 ///   with the same name that appear in different scopes refer to the same
5591 ///   [entity]. An entity with C language linkage shall not be declared with
5592 ///   the same name as an entity in global scope.
5593 template<typename T>
5594 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5595                                                   LookupResult &Previous) {
5596   if (!S.getLangOpts().CPlusPlus) {
5597     // In C, when declaring a global variable, look for a corresponding 'extern'
5598     // variable declared in function scope. We don't need this in C++, because
5599     // we find local extern decls in the surrounding file-scope DeclContext.
5600     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5601       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5602         Previous.clear();
5603         Previous.addDecl(Prev);
5604         return true;
5605       }
5606     }
5607     return false;
5608   }
5609 
5610   // A declaration in the translation unit can conflict with an extern "C"
5611   // declaration.
5612   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5613     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5614 
5615   // An extern "C" declaration can conflict with a declaration in the
5616   // translation unit or can be a redeclaration of an extern "C" declaration
5617   // in another scope.
5618   if (isIncompleteDeclExternC(S,ND))
5619     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5620 
5621   // Neither global nor extern "C": nothing to do.
5622   return false;
5623 }
5624 
5625 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
5626   // If the decl is already known invalid, don't check it.
5627   if (NewVD->isInvalidDecl())
5628     return;
5629 
5630   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5631   QualType T = TInfo->getType();
5632 
5633   // Defer checking an 'auto' type until its initializer is attached.
5634   if (T->isUndeducedType())
5635     return;
5636 
5637   if (T->isObjCObjectType()) {
5638     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5639       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5640     T = Context.getObjCObjectPointerType(T);
5641     NewVD->setType(T);
5642   }
5643 
5644   // Emit an error if an address space was applied to decl with local storage.
5645   // This includes arrays of objects with address space qualifiers, but not
5646   // automatic variables that point to other address spaces.
5647   // ISO/IEC TR 18037 S5.1.2
5648   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5649     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5650     NewVD->setInvalidDecl();
5651     return;
5652   }
5653 
5654   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5655   // __constant address space.
5656   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5657       && T.getAddressSpace() != LangAS::opencl_constant
5658       && !T->isSamplerT()){
5659     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5660     NewVD->setInvalidDecl();
5661     return;
5662   }
5663 
5664   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5665   // scope.
5666   if ((getLangOpts().OpenCLVersion >= 120)
5667       && NewVD->isStaticLocal()) {
5668     Diag(NewVD->getLocation(), diag::err_static_function_scope);
5669     NewVD->setInvalidDecl();
5670     return;
5671   }
5672 
5673   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5674       && !NewVD->hasAttr<BlocksAttr>()) {
5675     if (getLangOpts().getGC() != LangOptions::NonGC)
5676       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5677     else {
5678       assert(!getLangOpts().ObjCAutoRefCount);
5679       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5680     }
5681   }
5682 
5683   bool isVM = T->isVariablyModifiedType();
5684   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5685       NewVD->hasAttr<BlocksAttr>())
5686     getCurFunction()->setHasBranchProtectedScope();
5687 
5688   if ((isVM && NewVD->hasLinkage()) ||
5689       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5690     bool SizeIsNegative;
5691     llvm::APSInt Oversized;
5692     TypeSourceInfo *FixedTInfo =
5693       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5694                                                     SizeIsNegative, Oversized);
5695     if (FixedTInfo == 0 && T->isVariableArrayType()) {
5696       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5697       // FIXME: This won't give the correct result for
5698       // int a[10][n];
5699       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5700 
5701       if (NewVD->isFileVarDecl())
5702         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5703         << SizeRange;
5704       else if (NewVD->isStaticLocal())
5705         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5706         << SizeRange;
5707       else
5708         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5709         << SizeRange;
5710       NewVD->setInvalidDecl();
5711       return;
5712     }
5713 
5714     if (FixedTInfo == 0) {
5715       if (NewVD->isFileVarDecl())
5716         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5717       else
5718         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5719       NewVD->setInvalidDecl();
5720       return;
5721     }
5722 
5723     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5724     NewVD->setType(FixedTInfo->getType());
5725     NewVD->setTypeSourceInfo(FixedTInfo);
5726   }
5727 
5728   if (T->isVoidType()) {
5729     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5730     //                    of objects and functions.
5731     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5732       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5733         << T;
5734       NewVD->setInvalidDecl();
5735       return;
5736     }
5737   }
5738 
5739   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5740     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5741     NewVD->setInvalidDecl();
5742     return;
5743   }
5744 
5745   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5746     Diag(NewVD->getLocation(), diag::err_block_on_vm);
5747     NewVD->setInvalidDecl();
5748     return;
5749   }
5750 
5751   if (NewVD->isConstexpr() && !T->isDependentType() &&
5752       RequireLiteralType(NewVD->getLocation(), T,
5753                          diag::err_constexpr_var_non_literal)) {
5754     // Can't perform this check until the type is deduced.
5755     NewVD->setInvalidDecl();
5756     return;
5757   }
5758 }
5759 
5760 /// \brief Perform semantic checking on a newly-created variable
5761 /// declaration.
5762 ///
5763 /// This routine performs all of the type-checking required for a
5764 /// variable declaration once it has been built. It is used both to
5765 /// check variables after they have been parsed and their declarators
5766 /// have been translated into a declaration, and to check variables
5767 /// that have been instantiated from a template.
5768 ///
5769 /// Sets NewVD->isInvalidDecl() if an error was encountered.
5770 ///
5771 /// Returns true if the variable declaration is a redeclaration.
5772 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
5773   CheckVariableDeclarationType(NewVD);
5774 
5775   // If the decl is already known invalid, don't check it.
5776   if (NewVD->isInvalidDecl())
5777     return false;
5778 
5779   // If we did not find anything by this name, look for a non-visible
5780   // extern "C" declaration with the same name.
5781   if (Previous.empty() &&
5782       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
5783     Previous.setShadowed();
5784 
5785   // Filter out any non-conflicting previous declarations.
5786   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5787 
5788   if (!Previous.empty()) {
5789     MergeVarDecl(NewVD, Previous);
5790     return true;
5791   }
5792   return false;
5793 }
5794 
5795 /// \brief Data used with FindOverriddenMethod
5796 struct FindOverriddenMethodData {
5797   Sema *S;
5798   CXXMethodDecl *Method;
5799 };
5800 
5801 /// \brief Member lookup function that determines whether a given C++
5802 /// method overrides a method in a base class, to be used with
5803 /// CXXRecordDecl::lookupInBases().
5804 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
5805                                  CXXBasePath &Path,
5806                                  void *UserData) {
5807   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5808 
5809   FindOverriddenMethodData *Data
5810     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
5811 
5812   DeclarationName Name = Data->Method->getDeclName();
5813 
5814   // FIXME: Do we care about other names here too?
5815   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5816     // We really want to find the base class destructor here.
5817     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5818     CanQualType CT = Data->S->Context.getCanonicalType(T);
5819 
5820     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
5821   }
5822 
5823   for (Path.Decls = BaseRecord->lookup(Name);
5824        !Path.Decls.empty();
5825        Path.Decls = Path.Decls.slice(1)) {
5826     NamedDecl *D = Path.Decls.front();
5827     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5828       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
5829         return true;
5830     }
5831   }
5832 
5833   return false;
5834 }
5835 
5836 namespace {
5837   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5838 }
5839 /// \brief Report an error regarding overriding, along with any relevant
5840 /// overriden methods.
5841 ///
5842 /// \param DiagID the primary error to report.
5843 /// \param MD the overriding method.
5844 /// \param OEK which overrides to include as notes.
5845 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5846                             OverrideErrorKind OEK = OEK_All) {
5847   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5848   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5849                                       E = MD->end_overridden_methods();
5850        I != E; ++I) {
5851     // This check (& the OEK parameter) could be replaced by a predicate, but
5852     // without lambdas that would be overkill. This is still nicer than writing
5853     // out the diag loop 3 times.
5854     if ((OEK == OEK_All) ||
5855         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5856         (OEK == OEK_Deleted && (*I)->isDeleted()))
5857       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5858   }
5859 }
5860 
5861 /// AddOverriddenMethods - See if a method overrides any in the base classes,
5862 /// and if so, check that it's a valid override and remember it.
5863 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5864   // Look for virtual methods in base classes that this method might override.
5865   CXXBasePaths Paths;
5866   FindOverriddenMethodData Data;
5867   Data.Method = MD;
5868   Data.S = this;
5869   bool hasDeletedOverridenMethods = false;
5870   bool hasNonDeletedOverridenMethods = false;
5871   bool AddedAny = false;
5872   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5873     for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5874          E = Paths.found_decls_end(); I != E; ++I) {
5875       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
5876         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
5877         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
5878             !CheckOverridingFunctionAttributes(MD, OldMD) &&
5879             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
5880             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
5881           hasDeletedOverridenMethods |= OldMD->isDeleted();
5882           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
5883           AddedAny = true;
5884         }
5885       }
5886     }
5887   }
5888 
5889   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5890     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5891   }
5892   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5893     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5894   }
5895 
5896   return AddedAny;
5897 }
5898 
5899 namespace {
5900   // Struct for holding all of the extra arguments needed by
5901   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5902   struct ActOnFDArgs {
5903     Scope *S;
5904     Declarator &D;
5905     MultiTemplateParamsArg TemplateParamLists;
5906     bool AddToScope;
5907   };
5908 }
5909 
5910 namespace {
5911 
5912 // Callback to only accept typo corrections that have a non-zero edit distance.
5913 // Also only accept corrections that have the same parent decl.
5914 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5915  public:
5916   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5917                             CXXRecordDecl *Parent)
5918       : Context(Context), OriginalFD(TypoFD),
5919         ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
5920 
5921   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5922     if (candidate.getEditDistance() == 0)
5923       return false;
5924 
5925     SmallVector<unsigned, 1> MismatchedParams;
5926     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5927                                           CDeclEnd = candidate.end();
5928          CDecl != CDeclEnd; ++CDecl) {
5929       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5930 
5931       if (FD && !FD->hasBody() &&
5932           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
5933         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5934           CXXRecordDecl *Parent = MD->getParent();
5935           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
5936             return true;
5937         } else if (!ExpectedParent) {
5938           return true;
5939         }
5940       }
5941     }
5942 
5943     return false;
5944   }
5945 
5946  private:
5947   ASTContext &Context;
5948   FunctionDecl *OriginalFD;
5949   CXXRecordDecl *ExpectedParent;
5950 };
5951 
5952 }
5953 
5954 /// \brief Generate diagnostics for an invalid function redeclaration.
5955 ///
5956 /// This routine handles generating the diagnostic messages for an invalid
5957 /// function redeclaration, including finding possible similar declarations
5958 /// or performing typo correction if there are no previous declarations with
5959 /// the same name.
5960 ///
5961 /// Returns a NamedDecl iff typo correction was performed and substituting in
5962 /// the new declaration name does not cause new errors.
5963 static NamedDecl *DiagnoseInvalidRedeclaration(
5964     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
5965     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
5966   DeclarationName Name = NewFD->getDeclName();
5967   DeclContext *NewDC = NewFD->getDeclContext();
5968   SmallVector<unsigned, 1> MismatchedParams;
5969   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
5970   TypoCorrection Correction;
5971   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
5972   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
5973                                    : diag::err_member_decl_does_not_match;
5974   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
5975                     IsLocalFriend ? Sema::LookupLocalFriendName
5976                                   : Sema::LookupOrdinaryName,
5977                     Sema::ForRedeclaration);
5978 
5979   NewFD->setInvalidDecl();
5980   if (IsLocalFriend)
5981     SemaRef.LookupName(Prev, S);
5982   else
5983     SemaRef.LookupQualifiedName(Prev, NewDC);
5984   assert(!Prev.isAmbiguous() &&
5985          "Cannot have an ambiguity in previous-declaration lookup");
5986   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
5987   DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
5988                                       MD ? MD->getParent() : 0);
5989   if (!Prev.empty()) {
5990     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
5991          Func != FuncEnd; ++Func) {
5992       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
5993       if (FD &&
5994           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
5995         // Add 1 to the index so that 0 can mean the mismatch didn't
5996         // involve a parameter
5997         unsigned ParamNum =
5998             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
5999         NearMatches.push_back(std::make_pair(FD, ParamNum));
6000       }
6001     }
6002   // If the qualified name lookup yielded nothing, try typo correction
6003   } else if ((Correction = SemaRef.CorrectTypo(
6004                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6005                  &ExtraArgs.D.getCXXScopeSpec(), Validator,
6006                  IsLocalFriend ? 0 : NewDC))) {
6007     // Set up everything for the call to ActOnFunctionDeclarator
6008     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6009                               ExtraArgs.D.getIdentifierLoc());
6010     Previous.clear();
6011     Previous.setLookupName(Correction.getCorrection());
6012     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6013                                     CDeclEnd = Correction.end();
6014          CDecl != CDeclEnd; ++CDecl) {
6015       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6016       if (FD && !FD->hasBody() &&
6017           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6018         Previous.addDecl(FD);
6019       }
6020     }
6021     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6022 
6023     NamedDecl *Result;
6024     // Retry building the function declaration with the new previous
6025     // declarations, and with errors suppressed.
6026     {
6027       // Trap errors.
6028       Sema::SFINAETrap Trap(SemaRef);
6029 
6030       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6031       // pieces need to verify the typo-corrected C++ declaration and hopefully
6032       // eliminate the need for the parameter pack ExtraArgs.
6033       Result = SemaRef.ActOnFunctionDeclarator(
6034           ExtraArgs.S, ExtraArgs.D,
6035           Correction.getCorrectionDecl()->getDeclContext(),
6036           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6037           ExtraArgs.AddToScope);
6038 
6039       if (Trap.hasErrorOccurred())
6040         Result = 0;
6041     }
6042 
6043     if (Result) {
6044       // Determine which correction we picked.
6045       Decl *Canonical = Result->getCanonicalDecl();
6046       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6047            I != E; ++I)
6048         if ((*I)->getCanonicalDecl() == Canonical)
6049           Correction.setCorrectionDecl(*I);
6050 
6051       SemaRef.diagnoseTypo(
6052           Correction,
6053           SemaRef.PDiag(IsLocalFriend
6054                           ? diag::err_no_matching_local_friend_suggest
6055                           : diag::err_member_decl_does_not_match_suggest)
6056             << Name << NewDC << IsDefinition);
6057       return Result;
6058     }
6059 
6060     // Pretend the typo correction never occurred
6061     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6062                               ExtraArgs.D.getIdentifierLoc());
6063     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6064     Previous.clear();
6065     Previous.setLookupName(Name);
6066   }
6067 
6068   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6069       << Name << NewDC << IsDefinition << NewFD->getLocation();
6070 
6071   bool NewFDisConst = false;
6072   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6073     NewFDisConst = NewMD->isConst();
6074 
6075   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6076        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6077        NearMatch != NearMatchEnd; ++NearMatch) {
6078     FunctionDecl *FD = NearMatch->first;
6079     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6080     bool FDisConst = MD && MD->isConst();
6081     bool IsMember = MD || !IsLocalFriend;
6082 
6083     // FIXME: These notes are poorly worded for the local friend case.
6084     if (unsigned Idx = NearMatch->second) {
6085       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6086       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6087       if (Loc.isInvalid()) Loc = FD->getLocation();
6088       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6089                                  : diag::note_local_decl_close_param_match)
6090         << Idx << FDParam->getType()
6091         << NewFD->getParamDecl(Idx - 1)->getType();
6092     } else if (FDisConst != NewFDisConst) {
6093       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6094           << NewFDisConst << FD->getSourceRange().getEnd();
6095     } else
6096       SemaRef.Diag(FD->getLocation(),
6097                    IsMember ? diag::note_member_def_close_match
6098                             : diag::note_local_decl_close_match);
6099   }
6100   return 0;
6101 }
6102 
6103 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6104                                                           Declarator &D) {
6105   switch (D.getDeclSpec().getStorageClassSpec()) {
6106   default: llvm_unreachable("Unknown storage class!");
6107   case DeclSpec::SCS_auto:
6108   case DeclSpec::SCS_register:
6109   case DeclSpec::SCS_mutable:
6110     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6111                  diag::err_typecheck_sclass_func);
6112     D.setInvalidType();
6113     break;
6114   case DeclSpec::SCS_unspecified: break;
6115   case DeclSpec::SCS_extern:
6116     if (D.getDeclSpec().isExternInLinkageSpec())
6117       return SC_None;
6118     return SC_Extern;
6119   case DeclSpec::SCS_static: {
6120     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6121       // C99 6.7.1p5:
6122       //   The declaration of an identifier for a function that has
6123       //   block scope shall have no explicit storage-class specifier
6124       //   other than extern
6125       // See also (C++ [dcl.stc]p4).
6126       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6127                    diag::err_static_block_func);
6128       break;
6129     } else
6130       return SC_Static;
6131   }
6132   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6133   }
6134 
6135   // No explicit storage class has already been returned
6136   return SC_None;
6137 }
6138 
6139 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6140                                            DeclContext *DC, QualType &R,
6141                                            TypeSourceInfo *TInfo,
6142                                            FunctionDecl::StorageClass SC,
6143                                            bool &IsVirtualOkay) {
6144   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6145   DeclarationName Name = NameInfo.getName();
6146 
6147   FunctionDecl *NewFD = 0;
6148   bool isInline = D.getDeclSpec().isInlineSpecified();
6149 
6150   if (!SemaRef.getLangOpts().CPlusPlus) {
6151     // Determine whether the function was written with a
6152     // prototype. This true when:
6153     //   - there is a prototype in the declarator, or
6154     //   - the type R of the function is some kind of typedef or other reference
6155     //     to a type name (which eventually refers to a function type).
6156     bool HasPrototype =
6157       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6158       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6159 
6160     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6161                                  D.getLocStart(), NameInfo, R,
6162                                  TInfo, SC, isInline,
6163                                  HasPrototype, false);
6164     if (D.isInvalidType())
6165       NewFD->setInvalidDecl();
6166 
6167     // Set the lexical context.
6168     NewFD->setLexicalDeclContext(SemaRef.CurContext);
6169 
6170     return NewFD;
6171   }
6172 
6173   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6174   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6175 
6176   // Check that the return type is not an abstract class type.
6177   // For record types, this is done by the AbstractClassUsageDiagnoser once
6178   // the class has been completely parsed.
6179   if (!DC->isRecord() &&
6180       SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6181                                      R->getAs<FunctionType>()->getResultType(),
6182                                      diag::err_abstract_type_in_decl,
6183                                      SemaRef.AbstractReturnType))
6184     D.setInvalidType();
6185 
6186   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6187     // This is a C++ constructor declaration.
6188     assert(DC->isRecord() &&
6189            "Constructors can only be declared in a member context");
6190 
6191     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6192     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6193                                       D.getLocStart(), NameInfo,
6194                                       R, TInfo, isExplicit, isInline,
6195                                       /*isImplicitlyDeclared=*/false,
6196                                       isConstexpr);
6197 
6198   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6199     // This is a C++ destructor declaration.
6200     if (DC->isRecord()) {
6201       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6202       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6203       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6204                                         SemaRef.Context, Record,
6205                                         D.getLocStart(),
6206                                         NameInfo, R, TInfo, isInline,
6207                                         /*isImplicitlyDeclared=*/false);
6208 
6209       // If the class is complete, then we now create the implicit exception
6210       // specification. If the class is incomplete or dependent, we can't do
6211       // it yet.
6212       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6213           Record->getDefinition() && !Record->isBeingDefined() &&
6214           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6215         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6216       }
6217 
6218       // The Microsoft ABI requires that we perform the destructor body
6219       // checks (i.e. operator delete() lookup) at every declaration, as
6220       // any translation unit may need to emit a deleting destructor.
6221       if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6222           !Record->isDependentType() && Record->getDefinition() &&
6223           !Record->isBeingDefined()) {
6224         SemaRef.CheckDestructor(NewDD);
6225       }
6226 
6227       IsVirtualOkay = true;
6228       return NewDD;
6229 
6230     } else {
6231       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6232       D.setInvalidType();
6233 
6234       // Create a FunctionDecl to satisfy the function definition parsing
6235       // code path.
6236       return FunctionDecl::Create(SemaRef.Context, DC,
6237                                   D.getLocStart(),
6238                                   D.getIdentifierLoc(), Name, R, TInfo,
6239                                   SC, isInline,
6240                                   /*hasPrototype=*/true, isConstexpr);
6241     }
6242 
6243   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6244     if (!DC->isRecord()) {
6245       SemaRef.Diag(D.getIdentifierLoc(),
6246            diag::err_conv_function_not_member);
6247       return 0;
6248     }
6249 
6250     SemaRef.CheckConversionDeclarator(D, R, SC);
6251     IsVirtualOkay = true;
6252     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6253                                      D.getLocStart(), NameInfo,
6254                                      R, TInfo, isInline, isExplicit,
6255                                      isConstexpr, SourceLocation());
6256 
6257   } else if (DC->isRecord()) {
6258     // If the name of the function is the same as the name of the record,
6259     // then this must be an invalid constructor that has a return type.
6260     // (The parser checks for a return type and makes the declarator a
6261     // constructor if it has no return type).
6262     if (Name.getAsIdentifierInfo() &&
6263         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6264       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6265         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6266         << SourceRange(D.getIdentifierLoc());
6267       return 0;
6268     }
6269 
6270     // This is a C++ method declaration.
6271     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6272                                                cast<CXXRecordDecl>(DC),
6273                                                D.getLocStart(), NameInfo, R,
6274                                                TInfo, SC, isInline,
6275                                                isConstexpr, SourceLocation());
6276     IsVirtualOkay = !Ret->isStatic();
6277     return Ret;
6278   } else {
6279     // Determine whether the function was written with a
6280     // prototype. This true when:
6281     //   - we're in C++ (where every function has a prototype),
6282     return FunctionDecl::Create(SemaRef.Context, DC,
6283                                 D.getLocStart(),
6284                                 NameInfo, R, TInfo, SC, isInline,
6285                                 true/*HasPrototype*/, isConstexpr);
6286   }
6287 }
6288 
6289 void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6290   // In C++, the empty parameter-type-list must be spelled "void"; a
6291   // typedef of void is not permitted.
6292   if (getLangOpts().CPlusPlus &&
6293       Param->getType().getUnqualifiedType() != Context.VoidTy) {
6294     bool IsTypeAlias = false;
6295     if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6296       IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6297     else if (const TemplateSpecializationType *TST =
6298                Param->getType()->getAs<TemplateSpecializationType>())
6299       IsTypeAlias = TST->isTypeAlias();
6300     Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6301       << IsTypeAlias;
6302   }
6303 }
6304 
6305 enum OpenCLParamType {
6306   ValidKernelParam,
6307   PtrPtrKernelParam,
6308   PtrKernelParam,
6309   InvalidKernelParam,
6310   RecordKernelParam
6311 };
6312 
6313 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6314   if (PT->isPointerType()) {
6315     QualType PointeeType = PT->getPointeeType();
6316     return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6317   }
6318 
6319   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6320   // be used as builtin types.
6321 
6322   if (PT->isImageType())
6323     return PtrKernelParam;
6324 
6325   if (PT->isBooleanType())
6326     return InvalidKernelParam;
6327 
6328   if (PT->isEventT())
6329     return InvalidKernelParam;
6330 
6331   if (PT->isHalfType())
6332     return InvalidKernelParam;
6333 
6334   if (PT->isRecordType())
6335     return RecordKernelParam;
6336 
6337   return ValidKernelParam;
6338 }
6339 
6340 static void checkIsValidOpenCLKernelParameter(
6341   Sema &S,
6342   Declarator &D,
6343   ParmVarDecl *Param,
6344   llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6345   QualType PT = Param->getType();
6346 
6347   // Cache the valid types we encounter to avoid rechecking structs that are
6348   // used again
6349   if (ValidTypes.count(PT.getTypePtr()))
6350     return;
6351 
6352   switch (getOpenCLKernelParameterType(PT)) {
6353   case PtrPtrKernelParam:
6354     // OpenCL v1.2 s6.9.a:
6355     // A kernel function argument cannot be declared as a
6356     // pointer to a pointer type.
6357     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6358     D.setInvalidType();
6359     return;
6360 
6361     // OpenCL v1.2 s6.9.k:
6362     // Arguments to kernel functions in a program cannot be declared with the
6363     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6364     // uintptr_t or a struct and/or union that contain fields declared to be
6365     // one of these built-in scalar types.
6366 
6367   case InvalidKernelParam:
6368     // OpenCL v1.2 s6.8 n:
6369     // A kernel function argument cannot be declared
6370     // of event_t type.
6371     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6372     D.setInvalidType();
6373     return;
6374 
6375   case PtrKernelParam:
6376   case ValidKernelParam:
6377     ValidTypes.insert(PT.getTypePtr());
6378     return;
6379 
6380   case RecordKernelParam:
6381     break;
6382   }
6383 
6384   // Track nested structs we will inspect
6385   SmallVector<const Decl *, 4> VisitStack;
6386 
6387   // Track where we are in the nested structs. Items will migrate from
6388   // VisitStack to HistoryStack as we do the DFS for bad field.
6389   SmallVector<const FieldDecl *, 4> HistoryStack;
6390   HistoryStack.push_back((const FieldDecl *) 0);
6391 
6392   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6393   VisitStack.push_back(PD);
6394 
6395   assert(VisitStack.back() && "First decl null?");
6396 
6397   do {
6398     const Decl *Next = VisitStack.pop_back_val();
6399     if (!Next) {
6400       assert(!HistoryStack.empty());
6401       // Found a marker, we have gone up a level
6402       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6403         ValidTypes.insert(Hist->getType().getTypePtr());
6404 
6405       continue;
6406     }
6407 
6408     // Adds everything except the original parameter declaration (which is not a
6409     // field itself) to the history stack.
6410     const RecordDecl *RD;
6411     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6412       HistoryStack.push_back(Field);
6413       RD = Field->getType()->castAs<RecordType>()->getDecl();
6414     } else {
6415       RD = cast<RecordDecl>(Next);
6416     }
6417 
6418     // Add a null marker so we know when we've gone back up a level
6419     VisitStack.push_back((const Decl *) 0);
6420 
6421     for (RecordDecl::field_iterator I = RD->field_begin(),
6422            E = RD->field_end(); I != E; ++I) {
6423       const FieldDecl *FD = *I;
6424       QualType QT = FD->getType();
6425 
6426       if (ValidTypes.count(QT.getTypePtr()))
6427         continue;
6428 
6429       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6430       if (ParamType == ValidKernelParam)
6431         continue;
6432 
6433       if (ParamType == RecordKernelParam) {
6434         VisitStack.push_back(FD);
6435         continue;
6436       }
6437 
6438       // OpenCL v1.2 s6.9.p:
6439       // Arguments to kernel functions that are declared to be a struct or union
6440       // do not allow OpenCL objects to be passed as elements of the struct or
6441       // union.
6442       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6443         S.Diag(Param->getLocation(),
6444                diag::err_record_with_pointers_kernel_param)
6445           << PT->isUnionType()
6446           << PT;
6447       } else {
6448         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6449       }
6450 
6451       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6452         << PD->getDeclName();
6453 
6454       // We have an error, now let's go back up through history and show where
6455       // the offending field came from
6456       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6457              E = HistoryStack.end(); I != E; ++I) {
6458         const FieldDecl *OuterField = *I;
6459         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6460           << OuterField->getType();
6461       }
6462 
6463       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6464         << QT->isPointerType()
6465         << QT;
6466       D.setInvalidType();
6467       return;
6468     }
6469   } while (!VisitStack.empty());
6470 }
6471 
6472 NamedDecl*
6473 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6474                               TypeSourceInfo *TInfo, LookupResult &Previous,
6475                               MultiTemplateParamsArg TemplateParamLists,
6476                               bool &AddToScope) {
6477   QualType R = TInfo->getType();
6478 
6479   assert(R.getTypePtr()->isFunctionType());
6480 
6481   // TODO: consider using NameInfo for diagnostic.
6482   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6483   DeclarationName Name = NameInfo.getName();
6484   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6485 
6486   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6487     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6488          diag::err_invalid_thread)
6489       << DeclSpec::getSpecifierName(TSCS);
6490 
6491   if (DC->isRecord() &&
6492       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
6493       !D.getDeclSpec().isFriendSpecified())
6494     adjustMemberFunctionCC(R);
6495 
6496   bool isFriend = false;
6497   FunctionTemplateDecl *FunctionTemplate = 0;
6498   bool isExplicitSpecialization = false;
6499   bool isFunctionTemplateSpecialization = false;
6500 
6501   bool isDependentClassScopeExplicitSpecialization = false;
6502   bool HasExplicitTemplateArgs = false;
6503   TemplateArgumentListInfo TemplateArgs;
6504 
6505   bool isVirtualOkay = false;
6506 
6507   DeclContext *OriginalDC = DC;
6508   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6509 
6510   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6511                                               isVirtualOkay);
6512   if (!NewFD) return 0;
6513 
6514   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6515     NewFD->setTopLevelDeclInObjCContainer();
6516 
6517   // Set the lexical context. If this is a function-scope declaration, or has a
6518   // C++ scope specifier, or is the object of a friend declaration, the lexical
6519   // context will be different from the semantic context.
6520   NewFD->setLexicalDeclContext(CurContext);
6521 
6522   if (IsLocalExternDecl)
6523     NewFD->setLocalExternDecl();
6524 
6525   if (getLangOpts().CPlusPlus) {
6526     bool isInline = D.getDeclSpec().isInlineSpecified();
6527     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6528     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6529     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6530     isFriend = D.getDeclSpec().isFriendSpecified();
6531     if (isFriend && !isInline && D.isFunctionDefinition()) {
6532       // C++ [class.friend]p5
6533       //   A function can be defined in a friend declaration of a
6534       //   class . . . . Such a function is implicitly inline.
6535       NewFD->setImplicitlyInline();
6536     }
6537 
6538     // If this is a method defined in an __interface, and is not a constructor
6539     // or an overloaded operator, then set the pure flag (isVirtual will already
6540     // return true).
6541     if (const CXXRecordDecl *Parent =
6542           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6543       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6544         NewFD->setPure(true);
6545     }
6546 
6547     SetNestedNameSpecifier(NewFD, D);
6548     isExplicitSpecialization = false;
6549     isFunctionTemplateSpecialization = false;
6550     if (D.isInvalidType())
6551       NewFD->setInvalidDecl();
6552 
6553     // Match up the template parameter lists with the scope specifier, then
6554     // determine whether we have a template or a template specialization.
6555     bool Invalid = false;
6556     if (TemplateParameterList *TemplateParams =
6557             MatchTemplateParametersToScopeSpecifier(
6558                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6559                 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6560                 isExplicitSpecialization, Invalid)) {
6561       if (TemplateParams->size() > 0) {
6562         // This is a function template
6563 
6564         // Check that we can declare a template here.
6565         if (CheckTemplateDeclScope(S, TemplateParams))
6566           return 0;
6567 
6568         // A destructor cannot be a template.
6569         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6570           Diag(NewFD->getLocation(), diag::err_destructor_template);
6571           return 0;
6572         }
6573 
6574         // If we're adding a template to a dependent context, we may need to
6575         // rebuilding some of the types used within the template parameter list,
6576         // now that we know what the current instantiation is.
6577         if (DC->isDependentContext()) {
6578           ContextRAII SavedContext(*this, DC);
6579           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6580             Invalid = true;
6581         }
6582 
6583 
6584         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6585                                                         NewFD->getLocation(),
6586                                                         Name, TemplateParams,
6587                                                         NewFD);
6588         FunctionTemplate->setLexicalDeclContext(CurContext);
6589         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6590 
6591         // For source fidelity, store the other template param lists.
6592         if (TemplateParamLists.size() > 1) {
6593           NewFD->setTemplateParameterListsInfo(Context,
6594                                                TemplateParamLists.size() - 1,
6595                                                TemplateParamLists.data());
6596         }
6597       } else {
6598         // This is a function template specialization.
6599         isFunctionTemplateSpecialization = true;
6600         // For source fidelity, store all the template param lists.
6601         NewFD->setTemplateParameterListsInfo(Context,
6602                                              TemplateParamLists.size(),
6603                                              TemplateParamLists.data());
6604 
6605         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6606         if (isFriend) {
6607           // We want to remove the "template<>", found here.
6608           SourceRange RemoveRange = TemplateParams->getSourceRange();
6609 
6610           // If we remove the template<> and the name is not a
6611           // template-id, we're actually silently creating a problem:
6612           // the friend declaration will refer to an untemplated decl,
6613           // and clearly the user wants a template specialization.  So
6614           // we need to insert '<>' after the name.
6615           SourceLocation InsertLoc;
6616           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6617             InsertLoc = D.getName().getSourceRange().getEnd();
6618             InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6619           }
6620 
6621           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6622             << Name << RemoveRange
6623             << FixItHint::CreateRemoval(RemoveRange)
6624             << FixItHint::CreateInsertion(InsertLoc, "<>");
6625         }
6626       }
6627     }
6628     else {
6629       // All template param lists were matched against the scope specifier:
6630       // this is NOT (an explicit specialization of) a template.
6631       if (TemplateParamLists.size() > 0)
6632         // For source fidelity, store all the template param lists.
6633         NewFD->setTemplateParameterListsInfo(Context,
6634                                              TemplateParamLists.size(),
6635                                              TemplateParamLists.data());
6636     }
6637 
6638     if (Invalid) {
6639       NewFD->setInvalidDecl();
6640       if (FunctionTemplate)
6641         FunctionTemplate->setInvalidDecl();
6642     }
6643 
6644     // C++ [dcl.fct.spec]p5:
6645     //   The virtual specifier shall only be used in declarations of
6646     //   nonstatic class member functions that appear within a
6647     //   member-specification of a class declaration; see 10.3.
6648     //
6649     if (isVirtual && !NewFD->isInvalidDecl()) {
6650       if (!isVirtualOkay) {
6651         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6652              diag::err_virtual_non_function);
6653       } else if (!CurContext->isRecord()) {
6654         // 'virtual' was specified outside of the class.
6655         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6656              diag::err_virtual_out_of_class)
6657           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6658       } else if (NewFD->getDescribedFunctionTemplate()) {
6659         // C++ [temp.mem]p3:
6660         //  A member function template shall not be virtual.
6661         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6662              diag::err_virtual_member_function_template)
6663           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6664       } else {
6665         // Okay: Add virtual to the method.
6666         NewFD->setVirtualAsWritten(true);
6667       }
6668 
6669       if (getLangOpts().CPlusPlus1y &&
6670           NewFD->getResultType()->isUndeducedType())
6671         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
6672     }
6673 
6674     if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() &&
6675         NewFD->getResultType()->isUndeducedType()) {
6676       // If the function template is referenced directly (for instance, as a
6677       // member of the current instantiation), pretend it has a dependent type.
6678       // This is not really justified by the standard, but is the only sane
6679       // thing to do.
6680       const FunctionProtoType *FPT =
6681           NewFD->getType()->castAs<FunctionProtoType>();
6682       QualType Result = SubstAutoType(FPT->getResultType(),
6683                                        Context.DependentTy);
6684       NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6685                                              FPT->getExtProtoInfo()));
6686     }
6687 
6688     // C++ [dcl.fct.spec]p3:
6689     //  The inline specifier shall not appear on a block scope function
6690     //  declaration.
6691     if (isInline && !NewFD->isInvalidDecl()) {
6692       if (CurContext->isFunctionOrMethod()) {
6693         // 'inline' is not allowed on block scope function declaration.
6694         Diag(D.getDeclSpec().getInlineSpecLoc(),
6695              diag::err_inline_declaration_block_scope) << Name
6696           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6697       }
6698     }
6699 
6700     // C++ [dcl.fct.spec]p6:
6701     //  The explicit specifier shall be used only in the declaration of a
6702     //  constructor or conversion function within its class definition;
6703     //  see 12.3.1 and 12.3.2.
6704     if (isExplicit && !NewFD->isInvalidDecl()) {
6705       if (!CurContext->isRecord()) {
6706         // 'explicit' was specified outside of the class.
6707         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6708              diag::err_explicit_out_of_class)
6709           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6710       } else if (!isa<CXXConstructorDecl>(NewFD) &&
6711                  !isa<CXXConversionDecl>(NewFD)) {
6712         // 'explicit' was specified on a function that wasn't a constructor
6713         // or conversion function.
6714         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6715              diag::err_explicit_non_ctor_or_conv_function)
6716           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6717       }
6718     }
6719 
6720     if (isConstexpr) {
6721       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6722       // are implicitly inline.
6723       NewFD->setImplicitlyInline();
6724 
6725       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6726       // be either constructors or to return a literal type. Therefore,
6727       // destructors cannot be declared constexpr.
6728       if (isa<CXXDestructorDecl>(NewFD))
6729         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6730     }
6731 
6732     // If __module_private__ was specified, mark the function accordingly.
6733     if (D.getDeclSpec().isModulePrivateSpecified()) {
6734       if (isFunctionTemplateSpecialization) {
6735         SourceLocation ModulePrivateLoc
6736           = D.getDeclSpec().getModulePrivateSpecLoc();
6737         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6738           << 0
6739           << FixItHint::CreateRemoval(ModulePrivateLoc);
6740       } else {
6741         NewFD->setModulePrivate();
6742         if (FunctionTemplate)
6743           FunctionTemplate->setModulePrivate();
6744       }
6745     }
6746 
6747     if (isFriend) {
6748       if (FunctionTemplate) {
6749         FunctionTemplate->setObjectOfFriendDecl();
6750         FunctionTemplate->setAccess(AS_public);
6751       }
6752       NewFD->setObjectOfFriendDecl();
6753       NewFD->setAccess(AS_public);
6754     }
6755 
6756     // If a function is defined as defaulted or deleted, mark it as such now.
6757     switch (D.getFunctionDefinitionKind()) {
6758       case FDK_Declaration:
6759       case FDK_Definition:
6760         break;
6761 
6762       case FDK_Defaulted:
6763         NewFD->setDefaulted();
6764         break;
6765 
6766       case FDK_Deleted:
6767         NewFD->setDeletedAsWritten();
6768         break;
6769     }
6770 
6771     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6772         D.isFunctionDefinition()) {
6773       // C++ [class.mfct]p2:
6774       //   A member function may be defined (8.4) in its class definition, in
6775       //   which case it is an inline member function (7.1.2)
6776       NewFD->setImplicitlyInline();
6777     }
6778 
6779     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6780         !CurContext->isRecord()) {
6781       // C++ [class.static]p1:
6782       //   A data or function member of a class may be declared static
6783       //   in a class definition, in which case it is a static member of
6784       //   the class.
6785 
6786       // Complain about the 'static' specifier if it's on an out-of-line
6787       // member function definition.
6788       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6789            diag::err_static_out_of_line)
6790         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6791     }
6792 
6793     // C++11 [except.spec]p15:
6794     //   A deallocation function with no exception-specification is treated
6795     //   as if it were specified with noexcept(true).
6796     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6797     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6798          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
6799         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
6800       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6801       EPI.ExceptionSpecType = EST_BasicNoexcept;
6802       NewFD->setType(Context.getFunctionType(FPT->getResultType(),
6803                                              FPT->getArgTypes(), EPI));
6804     }
6805   }
6806 
6807   // Filter out previous declarations that don't match the scope.
6808   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
6809                        isExplicitSpecialization ||
6810                        isFunctionTemplateSpecialization);
6811 
6812   // Handle GNU asm-label extension (encoded as an attribute).
6813   if (Expr *E = (Expr*) D.getAsmLabel()) {
6814     // The parser guarantees this is a string.
6815     StringLiteral *SE = cast<StringLiteral>(E);
6816     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6817                                                 SE->getString()));
6818   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6819     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6820       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6821     if (I != ExtnameUndeclaredIdentifiers.end()) {
6822       NewFD->addAttr(I->second);
6823       ExtnameUndeclaredIdentifiers.erase(I);
6824     }
6825   }
6826 
6827   // Copy the parameter declarations from the declarator D to the function
6828   // declaration NewFD, if they are available.  First scavenge them into Params.
6829   SmallVector<ParmVarDecl*, 16> Params;
6830   if (D.isFunctionDeclarator()) {
6831     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6832 
6833     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6834     // function that takes no arguments, not a function that takes a
6835     // single void argument.
6836     // We let through "const void" here because Sema::GetTypeForDeclarator
6837     // already checks for that case.
6838     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6839         FTI.ArgInfo[0].Param &&
6840         cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
6841       // Empty arg list, don't push any params.
6842       checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
6843     } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
6844       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6845         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
6846         assert(Param->getDeclContext() != NewFD && "Was set before ?");
6847         Param->setDeclContext(NewFD);
6848         Params.push_back(Param);
6849 
6850         if (Param->isInvalidDecl())
6851           NewFD->setInvalidDecl();
6852       }
6853     }
6854 
6855   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
6856     // When we're declaring a function with a typedef, typeof, etc as in the
6857     // following example, we'll need to synthesize (unnamed)
6858     // parameters for use in the declaration.
6859     //
6860     // @code
6861     // typedef void fn(int);
6862     // fn f;
6863     // @endcode
6864 
6865     // Synthesize a parameter for each argument type.
6866     for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6867          AE = FT->arg_type_end(); AI != AE; ++AI) {
6868       ParmVarDecl *Param =
6869         BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
6870       Param->setScopeInfo(0, Params.size());
6871       Params.push_back(Param);
6872     }
6873   } else {
6874     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6875            "Should not need args for typedef of non-prototype fn");
6876   }
6877 
6878   // Finally, we know we have the right number of parameters, install them.
6879   NewFD->setParams(Params);
6880 
6881   // Find all anonymous symbols defined during the declaration of this function
6882   // and add to NewFD. This lets us track decls such 'enum Y' in:
6883   //
6884   //   void f(enum Y {AA} x) {}
6885   //
6886   // which would otherwise incorrectly end up in the translation unit scope.
6887   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6888   DeclsInPrototypeScope.clear();
6889 
6890   if (D.getDeclSpec().isNoreturnSpecified())
6891     NewFD->addAttr(
6892         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6893                                        Context));
6894 
6895   // Functions returning a variably modified type violate C99 6.7.5.2p2
6896   // because all functions have linkage.
6897   if (!NewFD->isInvalidDecl() &&
6898       NewFD->getResultType()->isVariablyModifiedType()) {
6899     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6900     NewFD->setInvalidDecl();
6901   }
6902 
6903   // Handle attributes.
6904   ProcessDeclAttributes(S, NewFD, D);
6905 
6906   QualType RetType = NewFD->getResultType();
6907   const CXXRecordDecl *Ret = RetType->isRecordType() ?
6908       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6909   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6910       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
6911     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6912     if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
6913       NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6914                                                         Context));
6915     }
6916   }
6917 
6918   if (!getLangOpts().CPlusPlus) {
6919     // Perform semantic checking on the function declaration.
6920     bool isExplicitSpecialization=false;
6921     if (!NewFD->isInvalidDecl() && NewFD->isMain())
6922       CheckMain(NewFD, D.getDeclSpec());
6923 
6924     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6925       CheckMSVCRTEntryPoint(NewFD);
6926 
6927     if (!NewFD->isInvalidDecl())
6928       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6929                                                   isExplicitSpecialization));
6930     else if (!Previous.empty())
6931       // Make graceful recovery from an invalid redeclaration.
6932       D.setRedeclaration(true);
6933     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
6934             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
6935            "previous declaration set still overloaded");
6936   } else {
6937     // If the declarator is a template-id, translate the parser's template
6938     // argument list into our AST format.
6939     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6940       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
6941       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6942       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
6943       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6944                                          TemplateId->NumArgs);
6945       translateTemplateArguments(TemplateArgsPtr,
6946                                  TemplateArgs);
6947 
6948       HasExplicitTemplateArgs = true;
6949 
6950       if (NewFD->isInvalidDecl()) {
6951         HasExplicitTemplateArgs = false;
6952       } else if (FunctionTemplate) {
6953         // Function template with explicit template arguments.
6954         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
6955           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
6956 
6957         HasExplicitTemplateArgs = false;
6958       } else if (!isFunctionTemplateSpecialization &&
6959                  !D.getDeclSpec().isFriendSpecified()) {
6960         // We have encountered something that the user meant to be a
6961         // specialization (because it has explicitly-specified template
6962         // arguments) but that was not introduced with a "template<>" (or had
6963         // too few of them).
6964         // FIXME: Differentiate between attempts for explicit instantiations
6965         // (starting with "template") and the rest.
6966         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
6967           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
6968           << FixItHint::CreateInsertion(
6969                                     D.getDeclSpec().getLocStart(),
6970                                         "template<> ");
6971         isFunctionTemplateSpecialization = true;
6972       } else {
6973         // "friend void foo<>(int);" is an implicit specialization decl.
6974         isFunctionTemplateSpecialization = true;
6975       }
6976     } else if (isFriend && isFunctionTemplateSpecialization) {
6977       // This combination is only possible in a recovery case;  the user
6978       // wrote something like:
6979       //   template <> friend void foo(int);
6980       // which we're recovering from as if the user had written:
6981       //   friend void foo<>(int);
6982       // Go ahead and fake up a template id.
6983       HasExplicitTemplateArgs = true;
6984         TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
6985       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
6986     }
6987 
6988     // If it's a friend (and only if it's a friend), it's possible
6989     // that either the specialized function type or the specialized
6990     // template is dependent, and therefore matching will fail.  In
6991     // this case, don't check the specialization yet.
6992     bool InstantiationDependent = false;
6993     if (isFunctionTemplateSpecialization && isFriend &&
6994         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
6995          TemplateSpecializationType::anyDependentTemplateArguments(
6996             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
6997             InstantiationDependent))) {
6998       assert(HasExplicitTemplateArgs &&
6999              "friend function specialization without template args");
7000       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7001                                                        Previous))
7002         NewFD->setInvalidDecl();
7003     } else if (isFunctionTemplateSpecialization) {
7004       if (CurContext->isDependentContext() && CurContext->isRecord()
7005           && !isFriend) {
7006         isDependentClassScopeExplicitSpecialization = true;
7007         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7008           diag::ext_function_specialization_in_class :
7009           diag::err_function_specialization_in_class)
7010           << NewFD->getDeclName();
7011       } else if (CheckFunctionTemplateSpecialization(NewFD,
7012                                   (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7013                                                      Previous))
7014         NewFD->setInvalidDecl();
7015 
7016       // C++ [dcl.stc]p1:
7017       //   A storage-class-specifier shall not be specified in an explicit
7018       //   specialization (14.7.3)
7019       FunctionTemplateSpecializationInfo *Info =
7020           NewFD->getTemplateSpecializationInfo();
7021       if (Info && SC != SC_None) {
7022         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7023           Diag(NewFD->getLocation(),
7024                diag::err_explicit_specialization_inconsistent_storage_class)
7025             << SC
7026             << FixItHint::CreateRemoval(
7027                                       D.getDeclSpec().getStorageClassSpecLoc());
7028 
7029         else
7030           Diag(NewFD->getLocation(),
7031                diag::ext_explicit_specialization_storage_class)
7032             << FixItHint::CreateRemoval(
7033                                       D.getDeclSpec().getStorageClassSpecLoc());
7034       }
7035 
7036     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7037       if (CheckMemberSpecialization(NewFD, Previous))
7038           NewFD->setInvalidDecl();
7039     }
7040 
7041     // Perform semantic checking on the function declaration.
7042     if (!isDependentClassScopeExplicitSpecialization) {
7043       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7044         CheckMain(NewFD, D.getDeclSpec());
7045 
7046       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7047         CheckMSVCRTEntryPoint(NewFD);
7048 
7049       if (NewFD->isInvalidDecl()) {
7050         // If this is a class member, mark the class invalid immediately.
7051         // This avoids some consistency errors later.
7052         if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7053           methodDecl->getParent()->setInvalidDecl();
7054       } else
7055         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7056                                                     isExplicitSpecialization));
7057     }
7058 
7059     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7060             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7061            "previous declaration set still overloaded");
7062 
7063     NamedDecl *PrincipalDecl = (FunctionTemplate
7064                                 ? cast<NamedDecl>(FunctionTemplate)
7065                                 : NewFD);
7066 
7067     if (isFriend && D.isRedeclaration()) {
7068       AccessSpecifier Access = AS_public;
7069       if (!NewFD->isInvalidDecl())
7070         Access = NewFD->getPreviousDecl()->getAccess();
7071 
7072       NewFD->setAccess(Access);
7073       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7074     }
7075 
7076     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7077         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7078       PrincipalDecl->setNonMemberOperator();
7079 
7080     // If we have a function template, check the template parameter
7081     // list. This will check and merge default template arguments.
7082     if (FunctionTemplate) {
7083       FunctionTemplateDecl *PrevTemplate =
7084                                      FunctionTemplate->getPreviousDecl();
7085       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7086                        PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
7087                             D.getDeclSpec().isFriendSpecified()
7088                               ? (D.isFunctionDefinition()
7089                                    ? TPC_FriendFunctionTemplateDefinition
7090                                    : TPC_FriendFunctionTemplate)
7091                               : (D.getCXXScopeSpec().isSet() &&
7092                                  DC && DC->isRecord() &&
7093                                  DC->isDependentContext())
7094                                   ? TPC_ClassTemplateMember
7095                                   : TPC_FunctionTemplate);
7096     }
7097 
7098     if (NewFD->isInvalidDecl()) {
7099       // Ignore all the rest of this.
7100     } else if (!D.isRedeclaration()) {
7101       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7102                                        AddToScope };
7103       // Fake up an access specifier if it's supposed to be a class member.
7104       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7105         NewFD->setAccess(AS_public);
7106 
7107       // Qualified decls generally require a previous declaration.
7108       if (D.getCXXScopeSpec().isSet()) {
7109         // ...with the major exception of templated-scope or
7110         // dependent-scope friend declarations.
7111 
7112         // TODO: we currently also suppress this check in dependent
7113         // contexts because (1) the parameter depth will be off when
7114         // matching friend templates and (2) we might actually be
7115         // selecting a friend based on a dependent factor.  But there
7116         // are situations where these conditions don't apply and we
7117         // can actually do this check immediately.
7118         if (isFriend &&
7119             (TemplateParamLists.size() ||
7120              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7121              CurContext->isDependentContext())) {
7122           // ignore these
7123         } else {
7124           // The user tried to provide an out-of-line definition for a
7125           // function that is a member of a class or namespace, but there
7126           // was no such member function declared (C++ [class.mfct]p2,
7127           // C++ [namespace.memdef]p2). For example:
7128           //
7129           // class X {
7130           //   void f() const;
7131           // };
7132           //
7133           // void X::f() { } // ill-formed
7134           //
7135           // Complain about this problem, and attempt to suggest close
7136           // matches (e.g., those that differ only in cv-qualifiers and
7137           // whether the parameter types are references).
7138 
7139           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7140                   *this, Previous, NewFD, ExtraArgs, false, 0)) {
7141             AddToScope = ExtraArgs.AddToScope;
7142             return Result;
7143           }
7144         }
7145 
7146         // Unqualified local friend declarations are required to resolve
7147         // to something.
7148       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7149         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7150                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7151           AddToScope = ExtraArgs.AddToScope;
7152           return Result;
7153         }
7154       }
7155 
7156     } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
7157                !isFriend && !isFunctionTemplateSpecialization &&
7158                !isExplicitSpecialization) {
7159       // An out-of-line member function declaration must also be a
7160       // definition (C++ [dcl.meaning]p1).
7161       // Note that this is not the case for explicit specializations of
7162       // function templates or member functions of class templates, per
7163       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7164       // extension for compatibility with old SWIG code which likes to
7165       // generate them.
7166       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7167         << D.getCXXScopeSpec().getRange();
7168     }
7169   }
7170 
7171   ProcessPragmaWeak(S, NewFD);
7172   checkAttributesAfterMerging(*this, *NewFD);
7173 
7174   AddKnownFunctionAttributes(NewFD);
7175 
7176   if (NewFD->hasAttr<OverloadableAttr>() &&
7177       !NewFD->getType()->getAs<FunctionProtoType>()) {
7178     Diag(NewFD->getLocation(),
7179          diag::err_attribute_overloadable_no_prototype)
7180       << NewFD;
7181 
7182     // Turn this into a variadic function with no parameters.
7183     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7184     FunctionProtoType::ExtProtoInfo EPI(
7185         Context.getDefaultCallingConvention(true, false));
7186     EPI.Variadic = true;
7187     EPI.ExtInfo = FT->getExtInfo();
7188 
7189     QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
7190     NewFD->setType(R);
7191   }
7192 
7193   // If there's a #pragma GCC visibility in scope, and this isn't a class
7194   // member, set the visibility of this function.
7195   if (!DC->isRecord() && NewFD->isExternallyVisible())
7196     AddPushedVisibilityAttribute(NewFD);
7197 
7198   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7199   // marking the function.
7200   AddCFAuditedAttribute(NewFD);
7201 
7202   // If this is the first declaration of an extern C variable, update
7203   // the map of such variables.
7204   if (!NewFD->getPreviousDecl() && !NewFD->isInvalidDecl() &&
7205       isIncompleteDeclExternC(*this, NewFD))
7206     RegisterLocallyScopedExternCDecl(NewFD, S);
7207 
7208   // Set this FunctionDecl's range up to the right paren.
7209   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7210 
7211   if (getLangOpts().CPlusPlus) {
7212     if (FunctionTemplate) {
7213       if (NewFD->isInvalidDecl())
7214         FunctionTemplate->setInvalidDecl();
7215       return FunctionTemplate;
7216     }
7217   }
7218 
7219   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7220     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7221     if ((getLangOpts().OpenCLVersion >= 120)
7222         && (SC == SC_Static)) {
7223       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7224       D.setInvalidType();
7225     }
7226 
7227     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7228     if (!NewFD->getResultType()->isVoidType()) {
7229       Diag(D.getIdentifierLoc(),
7230            diag::err_expected_kernel_void_return_type);
7231       D.setInvalidType();
7232     }
7233 
7234     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7235     for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7236          PE = NewFD->param_end(); PI != PE; ++PI) {
7237       ParmVarDecl *Param = *PI;
7238       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7239     }
7240   }
7241 
7242   MarkUnusedFileScopedDecl(NewFD);
7243 
7244   if (getLangOpts().CUDA)
7245     if (IdentifierInfo *II = NewFD->getIdentifier())
7246       if (!NewFD->isInvalidDecl() &&
7247           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7248         if (II->isStr("cudaConfigureCall")) {
7249           if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7250             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7251 
7252           Context.setcudaConfigureCallDecl(NewFD);
7253         }
7254       }
7255 
7256   // Here we have an function template explicit specialization at class scope.
7257   // The actually specialization will be postponed to template instatiation
7258   // time via the ClassScopeFunctionSpecializationDecl node.
7259   if (isDependentClassScopeExplicitSpecialization) {
7260     ClassScopeFunctionSpecializationDecl *NewSpec =
7261                          ClassScopeFunctionSpecializationDecl::Create(
7262                                 Context, CurContext, SourceLocation(),
7263                                 cast<CXXMethodDecl>(NewFD),
7264                                 HasExplicitTemplateArgs, TemplateArgs);
7265     CurContext->addDecl(NewSpec);
7266     AddToScope = false;
7267   }
7268 
7269   return NewFD;
7270 }
7271 
7272 /// \brief Perform semantic checking of a new function declaration.
7273 ///
7274 /// Performs semantic analysis of the new function declaration
7275 /// NewFD. This routine performs all semantic checking that does not
7276 /// require the actual declarator involved in the declaration, and is
7277 /// used both for the declaration of functions as they are parsed
7278 /// (called via ActOnDeclarator) and for the declaration of functions
7279 /// that have been instantiated via C++ template instantiation (called
7280 /// via InstantiateDecl).
7281 ///
7282 /// \param IsExplicitSpecialization whether this new function declaration is
7283 /// an explicit specialization of the previous declaration.
7284 ///
7285 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7286 ///
7287 /// \returns true if the function declaration is a redeclaration.
7288 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7289                                     LookupResult &Previous,
7290                                     bool IsExplicitSpecialization) {
7291   assert(!NewFD->getResultType()->isVariablyModifiedType()
7292          && "Variably modified return types are not handled here");
7293 
7294   // Determine whether the type of this function should be merged with
7295   // a previous visible declaration. This never happens for functions in C++,
7296   // and always happens in C if the previous declaration was visible.
7297   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7298                                !Previous.isShadowed();
7299 
7300   // Filter out any non-conflicting previous declarations.
7301   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7302 
7303   bool Redeclaration = false;
7304   NamedDecl *OldDecl = 0;
7305 
7306   // Merge or overload the declaration with an existing declaration of
7307   // the same name, if appropriate.
7308   if (!Previous.empty()) {
7309     // Determine whether NewFD is an overload of PrevDecl or
7310     // a declaration that requires merging. If it's an overload,
7311     // there's no more work to do here; we'll just add the new
7312     // function to the scope.
7313     if (!AllowOverloadingOfFunction(Previous, Context)) {
7314       NamedDecl *Candidate = Previous.getFoundDecl();
7315       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7316         Redeclaration = true;
7317         OldDecl = Candidate;
7318       }
7319     } else {
7320       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7321                             /*NewIsUsingDecl*/ false)) {
7322       case Ovl_Match:
7323         Redeclaration = true;
7324         break;
7325 
7326       case Ovl_NonFunction:
7327         Redeclaration = true;
7328         break;
7329 
7330       case Ovl_Overload:
7331         Redeclaration = false;
7332         break;
7333       }
7334 
7335       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7336         // If a function name is overloadable in C, then every function
7337         // with that name must be marked "overloadable".
7338         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7339           << Redeclaration << NewFD;
7340         NamedDecl *OverloadedDecl = 0;
7341         if (Redeclaration)
7342           OverloadedDecl = OldDecl;
7343         else if (!Previous.empty())
7344           OverloadedDecl = Previous.getRepresentativeDecl();
7345         if (OverloadedDecl)
7346           Diag(OverloadedDecl->getLocation(),
7347                diag::note_attribute_overloadable_prev_overload);
7348         NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7349                                                         Context));
7350       }
7351     }
7352   }
7353 
7354   // Check for a previous extern "C" declaration with this name.
7355   if (!Redeclaration &&
7356       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7357     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7358     if (!Previous.empty()) {
7359       // This is an extern "C" declaration with the same name as a previous
7360       // declaration, and thus redeclares that entity...
7361       Redeclaration = true;
7362       OldDecl = Previous.getFoundDecl();
7363       MergeTypeWithPrevious = false;
7364 
7365       // ... except in the presence of __attribute__((overloadable)).
7366       if (OldDecl->hasAttr<OverloadableAttr>()) {
7367         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7368           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7369             << Redeclaration << NewFD;
7370           Diag(Previous.getFoundDecl()->getLocation(),
7371                diag::note_attribute_overloadable_prev_overload);
7372           NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7373                                                           Context));
7374         }
7375         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7376           Redeclaration = false;
7377           OldDecl = 0;
7378         }
7379       }
7380     }
7381   }
7382 
7383   // C++11 [dcl.constexpr]p8:
7384   //   A constexpr specifier for a non-static member function that is not
7385   //   a constructor declares that member function to be const.
7386   //
7387   // This needs to be delayed until we know whether this is an out-of-line
7388   // definition of a static member function.
7389   //
7390   // This rule is not present in C++1y, so we produce a backwards
7391   // compatibility warning whenever it happens in C++11.
7392   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7393   if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7394       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7395       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7396     CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7397     if (FunctionTemplateDecl *OldTD =
7398           dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7399       OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7400     if (!OldMD || !OldMD->isStatic()) {
7401       const FunctionProtoType *FPT =
7402         MD->getType()->castAs<FunctionProtoType>();
7403       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7404       EPI.TypeQuals |= Qualifiers::Const;
7405       MD->setType(Context.getFunctionType(FPT->getResultType(),
7406                                           FPT->getArgTypes(), EPI));
7407 
7408       // Warn that we did this, if we're not performing template instantiation.
7409       // In that case, we'll have warned already when the template was defined.
7410       if (ActiveTemplateInstantiations.empty()) {
7411         SourceLocation AddConstLoc;
7412         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7413                 .IgnoreParens().getAs<FunctionTypeLoc>())
7414           AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7415 
7416         Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7417           << FixItHint::CreateInsertion(AddConstLoc, " const");
7418       }
7419     }
7420   }
7421 
7422   if (Redeclaration) {
7423     // NewFD and OldDecl represent declarations that need to be
7424     // merged.
7425     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7426       NewFD->setInvalidDecl();
7427       return Redeclaration;
7428     }
7429 
7430     Previous.clear();
7431     Previous.addDecl(OldDecl);
7432 
7433     if (FunctionTemplateDecl *OldTemplateDecl
7434                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7435       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7436       FunctionTemplateDecl *NewTemplateDecl
7437         = NewFD->getDescribedFunctionTemplate();
7438       assert(NewTemplateDecl && "Template/non-template mismatch");
7439       if (CXXMethodDecl *Method
7440             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7441         Method->setAccess(OldTemplateDecl->getAccess());
7442         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7443       }
7444 
7445       // If this is an explicit specialization of a member that is a function
7446       // template, mark it as a member specialization.
7447       if (IsExplicitSpecialization &&
7448           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7449         NewTemplateDecl->setMemberSpecialization();
7450         assert(OldTemplateDecl->isMemberSpecialization());
7451       }
7452 
7453     } else {
7454       // This needs to happen first so that 'inline' propagates.
7455       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7456 
7457       if (isa<CXXMethodDecl>(NewFD)) {
7458         // A valid redeclaration of a C++ method must be out-of-line,
7459         // but (unfortunately) it's not necessarily a definition
7460         // because of templates, which means that the previous
7461         // declaration is not necessarily from the class definition.
7462 
7463         // For just setting the access, that doesn't matter.
7464         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7465         NewFD->setAccess(oldMethod->getAccess());
7466 
7467         // Update the key-function state if necessary for this ABI.
7468         if (NewFD->isInlined() &&
7469             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7470           // setNonKeyFunction needs to work with the original
7471           // declaration from the class definition, and isVirtual() is
7472           // just faster in that case, so map back to that now.
7473           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDeclaration());
7474           if (oldMethod->isVirtual()) {
7475             Context.setNonKeyFunction(oldMethod);
7476           }
7477         }
7478       }
7479     }
7480   }
7481 
7482   // Semantic checking for this function declaration (in isolation).
7483   if (getLangOpts().CPlusPlus) {
7484     // C++-specific checks.
7485     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7486       CheckConstructor(Constructor);
7487     } else if (CXXDestructorDecl *Destructor =
7488                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7489       CXXRecordDecl *Record = Destructor->getParent();
7490       QualType ClassType = Context.getTypeDeclType(Record);
7491 
7492       // FIXME: Shouldn't we be able to perform this check even when the class
7493       // type is dependent? Both gcc and edg can handle that.
7494       if (!ClassType->isDependentType()) {
7495         DeclarationName Name
7496           = Context.DeclarationNames.getCXXDestructorName(
7497                                         Context.getCanonicalType(ClassType));
7498         if (NewFD->getDeclName() != Name) {
7499           Diag(NewFD->getLocation(), diag::err_destructor_name);
7500           NewFD->setInvalidDecl();
7501           return Redeclaration;
7502         }
7503       }
7504     } else if (CXXConversionDecl *Conversion
7505                = dyn_cast<CXXConversionDecl>(NewFD)) {
7506       ActOnConversionDeclarator(Conversion);
7507     }
7508 
7509     // Find any virtual functions that this function overrides.
7510     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7511       if (!Method->isFunctionTemplateSpecialization() &&
7512           !Method->getDescribedFunctionTemplate() &&
7513           Method->isCanonicalDecl()) {
7514         if (AddOverriddenMethods(Method->getParent(), Method)) {
7515           // If the function was marked as "static", we have a problem.
7516           if (NewFD->getStorageClass() == SC_Static) {
7517             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7518           }
7519         }
7520       }
7521 
7522       if (Method->isStatic())
7523         checkThisInStaticMemberFunctionType(Method);
7524     }
7525 
7526     // Extra checking for C++ overloaded operators (C++ [over.oper]).
7527     if (NewFD->isOverloadedOperator() &&
7528         CheckOverloadedOperatorDeclaration(NewFD)) {
7529       NewFD->setInvalidDecl();
7530       return Redeclaration;
7531     }
7532 
7533     // Extra checking for C++0x literal operators (C++0x [over.literal]).
7534     if (NewFD->getLiteralIdentifier() &&
7535         CheckLiteralOperatorDeclaration(NewFD)) {
7536       NewFD->setInvalidDecl();
7537       return Redeclaration;
7538     }
7539 
7540     // In C++, check default arguments now that we have merged decls. Unless
7541     // the lexical context is the class, because in this case this is done
7542     // during delayed parsing anyway.
7543     if (!CurContext->isRecord())
7544       CheckCXXDefaultArguments(NewFD);
7545 
7546     // If this function declares a builtin function, check the type of this
7547     // declaration against the expected type for the builtin.
7548     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7549       ASTContext::GetBuiltinTypeError Error;
7550       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
7551       QualType T = Context.GetBuiltinType(BuiltinID, Error);
7552       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7553         // The type of this function differs from the type of the builtin,
7554         // so forget about the builtin entirely.
7555         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7556       }
7557     }
7558 
7559     // If this function is declared as being extern "C", then check to see if
7560     // the function returns a UDT (class, struct, or union type) that is not C
7561     // compatible, and if it does, warn the user.
7562     // But, issue any diagnostic on the first declaration only.
7563     if (NewFD->isExternC() && Previous.empty()) {
7564       QualType R = NewFD->getResultType();
7565       if (R->isIncompleteType() && !R->isVoidType())
7566         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7567             << NewFD << R;
7568       else if (!R.isPODType(Context) && !R->isVoidType() &&
7569                !R->isObjCObjectPointerType())
7570         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
7571     }
7572   }
7573   return Redeclaration;
7574 }
7575 
7576 static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7577   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7578   if (!TSI)
7579     return SourceRange();
7580 
7581   TypeLoc TL = TSI->getTypeLoc();
7582   FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
7583   if (!FunctionTL)
7584     return SourceRange();
7585 
7586   TypeLoc ResultTL = FunctionTL.getResultLoc();
7587   if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
7588     return ResultTL.getSourceRange();
7589 
7590   return SourceRange();
7591 }
7592 
7593 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
7594   // C++11 [basic.start.main]p3:  A program that declares main to be inline,
7595   //   static or constexpr is ill-formed.
7596   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
7597   //   appear in a declaration of main.
7598   // static main is not an error under C99, but we should warn about it.
7599   // We accept _Noreturn main as an extension.
7600   if (FD->getStorageClass() == SC_Static)
7601     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
7602          ? diag::err_static_main : diag::warn_static_main)
7603       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7604   if (FD->isInlineSpecified())
7605     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7606       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
7607   if (DS.isNoreturnSpecified()) {
7608     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7609     SourceRange NoreturnRange(NoreturnLoc,
7610                               PP.getLocForEndOfToken(NoreturnLoc));
7611     Diag(NoreturnLoc, diag::ext_noreturn_main);
7612     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7613       << FixItHint::CreateRemoval(NoreturnRange);
7614   }
7615   if (FD->isConstexpr()) {
7616     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7617       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7618     FD->setConstexpr(false);
7619   }
7620 
7621   QualType T = FD->getType();
7622   assert(T->isFunctionType() && "function decl is not of function type");
7623   const FunctionType* FT = T->castAs<FunctionType>();
7624 
7625   // All the standards say that main() should should return 'int'.
7626   if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7627     // In C and C++, main magically returns 0 if you fall off the end;
7628     // set the flag which tells us that.
7629     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7630     FD->setHasImplicitReturnZero(true);
7631 
7632   // In C with GNU extensions we allow main() to have non-integer return
7633   // type, but we should warn about the extension, and we disable the
7634   // implicit-return-zero rule.
7635   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
7636     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7637 
7638     SourceRange ResultRange = getResultSourceRange(FD);
7639     if (ResultRange.isValid())
7640       Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7641           << FixItHint::CreateReplacement(ResultRange, "int");
7642 
7643   // Otherwise, this is just a flat-out error.
7644   } else {
7645     SourceRange ResultRange = getResultSourceRange(FD);
7646     if (ResultRange.isValid())
7647       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7648           << FixItHint::CreateReplacement(ResultRange, "int");
7649     else
7650       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7651 
7652     FD->setInvalidDecl(true);
7653   }
7654 
7655   // Treat protoless main() as nullary.
7656   if (isa<FunctionNoProtoType>(FT)) return;
7657 
7658   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7659   unsigned nparams = FTP->getNumArgs();
7660   assert(FD->getNumParams() == nparams);
7661 
7662   bool HasExtraParameters = (nparams > 3);
7663 
7664   // Darwin passes an undocumented fourth argument of type char**.  If
7665   // other platforms start sprouting these, the logic below will start
7666   // getting shifty.
7667   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
7668     HasExtraParameters = false;
7669 
7670   if (HasExtraParameters) {
7671     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7672     FD->setInvalidDecl(true);
7673     nparams = 3;
7674   }
7675 
7676   // FIXME: a lot of the following diagnostics would be improved
7677   // if we had some location information about types.
7678 
7679   QualType CharPP =
7680     Context.getPointerType(Context.getPointerType(Context.CharTy));
7681   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
7682 
7683   for (unsigned i = 0; i < nparams; ++i) {
7684     QualType AT = FTP->getArgType(i);
7685 
7686     bool mismatch = true;
7687 
7688     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7689       mismatch = false;
7690     else if (Expected[i] == CharPP) {
7691       // As an extension, the following forms are okay:
7692       //   char const **
7693       //   char const * const *
7694       //   char * const *
7695 
7696       QualifierCollector qs;
7697       const PointerType* PT;
7698       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7699           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
7700           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7701                               Context.CharTy)) {
7702         qs.removeConst();
7703         mismatch = !qs.empty();
7704       }
7705     }
7706 
7707     if (mismatch) {
7708       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7709       // TODO: suggest replacing given type with expected type
7710       FD->setInvalidDecl(true);
7711     }
7712   }
7713 
7714   if (nparams == 1 && !FD->isInvalidDecl()) {
7715     Diag(FD->getLocation(), diag::warn_main_one_arg);
7716   }
7717 
7718   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7719     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7720     FD->setInvalidDecl();
7721   }
7722 }
7723 
7724 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7725   QualType T = FD->getType();
7726   assert(T->isFunctionType() && "function decl is not of function type");
7727   const FunctionType *FT = T->castAs<FunctionType>();
7728 
7729   // Set an implicit return of 'zero' if the function can return some integral,
7730   // enumeration, pointer or nullptr type.
7731   if (FT->getResultType()->isIntegralOrEnumerationType() ||
7732       FT->getResultType()->isAnyPointerType() ||
7733       FT->getResultType()->isNullPtrType())
7734     // DllMain is exempt because a return value of zero means it failed.
7735     if (FD->getName() != "DllMain")
7736       FD->setHasImplicitReturnZero(true);
7737 
7738   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7739     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7740     FD->setInvalidDecl();
7741   }
7742 }
7743 
7744 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
7745   // FIXME: Need strict checking.  In C89, we need to check for
7746   // any assignment, increment, decrement, function-calls, or
7747   // commas outside of a sizeof.  In C99, it's the same list,
7748   // except that the aforementioned are allowed in unevaluated
7749   // expressions.  Everything else falls under the
7750   // "may accept other forms of constant expressions" exception.
7751   // (We never end up here for C++, so the constant expression
7752   // rules there don't matter.)
7753   if (Init->isConstantInitializer(Context, false))
7754     return false;
7755   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7756     << Init->getSourceRange();
7757   return true;
7758 }
7759 
7760 namespace {
7761   // Visits an initialization expression to see if OrigDecl is evaluated in
7762   // its own initialization and throws a warning if it does.
7763   class SelfReferenceChecker
7764       : public EvaluatedExprVisitor<SelfReferenceChecker> {
7765     Sema &S;
7766     Decl *OrigDecl;
7767     bool isRecordType;
7768     bool isPODType;
7769     bool isReferenceType;
7770 
7771   public:
7772     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7773 
7774     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
7775                                                     S(S), OrigDecl(OrigDecl) {
7776       isPODType = false;
7777       isRecordType = false;
7778       isReferenceType = false;
7779       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7780         isPODType = VD->getType().isPODType(S.Context);
7781         isRecordType = VD->getType()->isRecordType();
7782         isReferenceType = VD->getType()->isReferenceType();
7783       }
7784     }
7785 
7786     // For most expressions, the cast is directly above the DeclRefExpr.
7787     // For conditional operators, the cast can be outside the conditional
7788     // operator if both expressions are DeclRefExpr's.
7789     void HandleValue(Expr *E) {
7790       if (isReferenceType)
7791         return;
7792       E = E->IgnoreParenImpCasts();
7793       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7794         HandleDeclRefExpr(DRE);
7795         return;
7796       }
7797 
7798       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7799         HandleValue(CO->getTrueExpr());
7800         HandleValue(CO->getFalseExpr());
7801         return;
7802       }
7803 
7804       if (isa<MemberExpr>(E)) {
7805         Expr *Base = E->IgnoreParenImpCasts();
7806         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7807           // Check for static member variables and don't warn on them.
7808           if (!isa<FieldDecl>(ME->getMemberDecl()))
7809             return;
7810           Base = ME->getBase()->IgnoreParenImpCasts();
7811         }
7812         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7813           HandleDeclRefExpr(DRE);
7814         return;
7815       }
7816     }
7817 
7818     // Reference types are handled here since all uses of references are
7819     // bad, not just r-value uses.
7820     void VisitDeclRefExpr(DeclRefExpr *E) {
7821       if (isReferenceType)
7822         HandleDeclRefExpr(E);
7823     }
7824 
7825     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
7826       if (E->getCastKind() == CK_LValueToRValue ||
7827           (isRecordType && E->getCastKind() == CK_NoOp))
7828         HandleValue(E->getSubExpr());
7829 
7830       Inherited::VisitImplicitCastExpr(E);
7831     }
7832 
7833     void VisitMemberExpr(MemberExpr *E) {
7834       // Don't warn on arrays since they can be treated as pointers.
7835       if (E->getType()->canDecayToPointerType()) return;
7836 
7837       // Warn when a non-static method call is followed by non-static member
7838       // field accesses, which is followed by a DeclRefExpr.
7839       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7840       bool Warn = (MD && !MD->isStatic());
7841       Expr *Base = E->getBase()->IgnoreParenImpCasts();
7842       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7843         if (!isa<FieldDecl>(ME->getMemberDecl()))
7844           Warn = false;
7845         Base = ME->getBase()->IgnoreParenImpCasts();
7846       }
7847 
7848       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7849         if (Warn)
7850           HandleDeclRefExpr(DRE);
7851         return;
7852       }
7853 
7854       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7855       // Visit that expression.
7856       Visit(Base);
7857     }
7858 
7859     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7860       if (E->getNumArgs() > 0)
7861         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7862           HandleDeclRefExpr(DRE);
7863 
7864       Inherited::VisitCXXOperatorCallExpr(E);
7865     }
7866 
7867     void VisitUnaryOperator(UnaryOperator *E) {
7868       // For POD record types, addresses of its own members are well-defined.
7869       if (E->getOpcode() == UO_AddrOf && isRecordType &&
7870           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7871         if (!isPODType)
7872           HandleValue(E->getSubExpr());
7873         return;
7874       }
7875       Inherited::VisitUnaryOperator(E);
7876     }
7877 
7878     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7879 
7880     void HandleDeclRefExpr(DeclRefExpr *DRE) {
7881       Decl* ReferenceDecl = DRE->getDecl();
7882       if (OrigDecl != ReferenceDecl) return;
7883       unsigned diag;
7884       if (isReferenceType) {
7885         diag = diag::warn_uninit_self_reference_in_reference_init;
7886       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7887         diag = diag::warn_static_self_reference_in_init;
7888       } else {
7889         diag = diag::warn_uninit_self_reference_in_init;
7890       }
7891 
7892       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
7893                             S.PDiag(diag)
7894                               << DRE->getNameInfo().getName()
7895                               << OrigDecl->getLocation()
7896                               << DRE->getSourceRange());
7897     }
7898   };
7899 
7900   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7901   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7902                                  bool DirectInit) {
7903     // Parameters arguments are occassionially constructed with itself,
7904     // for instance, in recursive functions.  Skip them.
7905     if (isa<ParmVarDecl>(OrigDecl))
7906       return;
7907 
7908     E = E->IgnoreParens();
7909 
7910     // Skip checking T a = a where T is not a record or reference type.
7911     // Doing so is a way to silence uninitialized warnings.
7912     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7913       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7914         if (ICE->getCastKind() == CK_LValueToRValue)
7915           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7916             if (DRE->getDecl() == OrigDecl)
7917               return;
7918 
7919     SelfReferenceChecker(S, OrigDecl).Visit(E);
7920   }
7921 }
7922 
7923 /// AddInitializerToDecl - Adds the initializer Init to the
7924 /// declaration dcl. If DirectInit is true, this is C++ direct
7925 /// initialization rather than copy initialization.
7926 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
7927                                 bool DirectInit, bool TypeMayContainAuto) {
7928   // If there is no declaration, there was an error parsing it.  Just ignore
7929   // the initializer.
7930   if (RealDecl == 0 || RealDecl->isInvalidDecl())
7931     return;
7932 
7933   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
7934     // With declarators parsed the way they are, the parser cannot
7935     // distinguish between a normal initializer and a pure-specifier.
7936     // Thus this grotesque test.
7937     IntegerLiteral *IL;
7938     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
7939         Context.getCanonicalType(IL->getType()) == Context.IntTy)
7940       CheckPureMethod(Method, Init->getSourceRange());
7941     else {
7942       Diag(Method->getLocation(), diag::err_member_function_initialization)
7943         << Method->getDeclName() << Init->getSourceRange();
7944       Method->setInvalidDecl();
7945     }
7946     return;
7947   }
7948 
7949   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7950   if (!VDecl) {
7951     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
7952     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7953     RealDecl->setInvalidDecl();
7954     return;
7955   }
7956   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
7957 
7958   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7959   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
7960     Expr *DeduceInit = Init;
7961     // Initializer could be a C++ direct-initializer. Deduction only works if it
7962     // contains exactly one expression.
7963     if (CXXDirectInit) {
7964       if (CXXDirectInit->getNumExprs() == 0) {
7965         // It isn't possible to write this directly, but it is possible to
7966         // end up in this situation with "auto x(some_pack...);"
7967         Diag(CXXDirectInit->getLocStart(),
7968              diag::err_auto_var_init_no_expression)
7969           << VDecl->getDeclName() << VDecl->getType()
7970           << VDecl->getSourceRange();
7971         RealDecl->setInvalidDecl();
7972         return;
7973       } else if (CXXDirectInit->getNumExprs() > 1) {
7974         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
7975              diag::err_auto_var_init_multiple_expressions)
7976           << VDecl->getDeclName() << VDecl->getType()
7977           << VDecl->getSourceRange();
7978         RealDecl->setInvalidDecl();
7979         return;
7980       } else {
7981         DeduceInit = CXXDirectInit->getExpr(0);
7982       }
7983     }
7984 
7985     // Expressions default to 'id' when we're in a debugger.
7986     bool DefaultedToAuto = false;
7987     if (getLangOpts().DebuggerCastResultToId &&
7988         Init->getType() == Context.UnknownAnyTy) {
7989       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
7990       if (Result.isInvalid()) {
7991         VDecl->setInvalidDecl();
7992         return;
7993       }
7994       Init = Result.take();
7995       DefaultedToAuto = true;
7996     }
7997 
7998     QualType DeducedType;
7999     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8000             DAR_Failed)
8001       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8002     if (DeducedType.isNull()) {
8003       RealDecl->setInvalidDecl();
8004       return;
8005     }
8006     VDecl->setType(DeducedType);
8007     assert(VDecl->isLinkageValid());
8008 
8009     // In ARC, infer lifetime.
8010     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8011       VDecl->setInvalidDecl();
8012 
8013     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8014     // 'id' instead of a specific object type prevents most of our usual checks.
8015     // We only want to warn outside of template instantiations, though:
8016     // inside a template, the 'id' could have come from a parameter.
8017     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8018         DeducedType->isObjCIdType()) {
8019       SourceLocation Loc =
8020           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8021       Diag(Loc, diag::warn_auto_var_is_id)
8022         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8023     }
8024 
8025     // If this is a redeclaration, check that the type we just deduced matches
8026     // the previously declared type.
8027     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8028       // We never need to merge the type, because we cannot form an incomplete
8029       // array of auto, nor deduce such a type.
8030       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8031     }
8032 
8033     // Check the deduced type is valid for a variable declaration.
8034     CheckVariableDeclarationType(VDecl);
8035     if (VDecl->isInvalidDecl())
8036       return;
8037   }
8038 
8039   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8040     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8041     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8042     VDecl->setInvalidDecl();
8043     return;
8044   }
8045 
8046   if (!VDecl->getType()->isDependentType()) {
8047     // A definition must end up with a complete type, which means it must be
8048     // complete with the restriction that an array type might be completed by
8049     // the initializer; note that later code assumes this restriction.
8050     QualType BaseDeclType = VDecl->getType();
8051     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8052       BaseDeclType = Array->getElementType();
8053     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8054                             diag::err_typecheck_decl_incomplete_type)) {
8055       RealDecl->setInvalidDecl();
8056       return;
8057     }
8058 
8059     // The variable can not have an abstract class type.
8060     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8061                                diag::err_abstract_type_in_decl,
8062                                AbstractVariableType))
8063       VDecl->setInvalidDecl();
8064   }
8065 
8066   const VarDecl *Def;
8067   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8068     Diag(VDecl->getLocation(), diag::err_redefinition)
8069       << VDecl->getDeclName();
8070     Diag(Def->getLocation(), diag::note_previous_definition);
8071     VDecl->setInvalidDecl();
8072     return;
8073   }
8074 
8075   const VarDecl* PrevInit = 0;
8076   if (getLangOpts().CPlusPlus) {
8077     // C++ [class.static.data]p4
8078     //   If a static data member is of const integral or const
8079     //   enumeration type, its declaration in the class definition can
8080     //   specify a constant-initializer which shall be an integral
8081     //   constant expression (5.19). In that case, the member can appear
8082     //   in integral constant expressions. The member shall still be
8083     //   defined in a namespace scope if it is used in the program and the
8084     //   namespace scope definition shall not contain an initializer.
8085     //
8086     // We already performed a redefinition check above, but for static
8087     // data members we also need to check whether there was an in-class
8088     // declaration with an initializer.
8089     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8090       Diag(VDecl->getLocation(), diag::err_redefinition)
8091         << VDecl->getDeclName();
8092       Diag(PrevInit->getLocation(), diag::note_previous_definition);
8093       return;
8094     }
8095 
8096     if (VDecl->hasLocalStorage())
8097       getCurFunction()->setHasBranchProtectedScope();
8098 
8099     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8100       VDecl->setInvalidDecl();
8101       return;
8102     }
8103   }
8104 
8105   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8106   // a kernel function cannot be initialized."
8107   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8108     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8109     VDecl->setInvalidDecl();
8110     return;
8111   }
8112 
8113   // Get the decls type and save a reference for later, since
8114   // CheckInitializerTypes may change it.
8115   QualType DclT = VDecl->getType(), SavT = DclT;
8116 
8117   // Expressions default to 'id' when we're in a debugger
8118   // and we are assigning it to a variable of Objective-C pointer type.
8119   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8120       Init->getType() == Context.UnknownAnyTy) {
8121     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8122     if (Result.isInvalid()) {
8123       VDecl->setInvalidDecl();
8124       return;
8125     }
8126     Init = Result.take();
8127   }
8128 
8129   // Perform the initialization.
8130   if (!VDecl->isInvalidDecl()) {
8131     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8132     InitializationKind Kind
8133       = DirectInit ?
8134           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8135                                                            Init->getLocStart(),
8136                                                            Init->getLocEnd())
8137                         : InitializationKind::CreateDirectList(
8138                                                           VDecl->getLocation())
8139                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8140                                                     Init->getLocStart());
8141 
8142     MultiExprArg Args = Init;
8143     if (CXXDirectInit)
8144       Args = MultiExprArg(CXXDirectInit->getExprs(),
8145                           CXXDirectInit->getNumExprs());
8146 
8147     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8148     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8149     if (Result.isInvalid()) {
8150       VDecl->setInvalidDecl();
8151       return;
8152     }
8153 
8154     Init = Result.takeAs<Expr>();
8155   }
8156 
8157   // Check for self-references within variable initializers.
8158   // Variables declared within a function/method body (except for references)
8159   // are handled by a dataflow analysis.
8160   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8161       VDecl->getType()->isReferenceType()) {
8162     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8163   }
8164 
8165   // If the type changed, it means we had an incomplete type that was
8166   // completed by the initializer. For example:
8167   //   int ary[] = { 1, 3, 5 };
8168   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8169   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8170     VDecl->setType(DclT);
8171 
8172   if (!VDecl->isInvalidDecl()) {
8173     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8174 
8175     if (VDecl->hasAttr<BlocksAttr>())
8176       checkRetainCycles(VDecl, Init);
8177 
8178     // It is safe to assign a weak reference into a strong variable.
8179     // Although this code can still have problems:
8180     //   id x = self.weakProp;
8181     //   id y = self.weakProp;
8182     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8183     // paths through the function. This should be revisited if
8184     // -Wrepeated-use-of-weak is made flow-sensitive.
8185     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
8186       DiagnosticsEngine::Level Level =
8187         Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8188                                  Init->getLocStart());
8189       if (Level != DiagnosticsEngine::Ignored)
8190         getCurFunction()->markSafeWeakUse(Init);
8191     }
8192   }
8193 
8194   // The initialization is usually a full-expression.
8195   //
8196   // FIXME: If this is a braced initialization of an aggregate, it is not
8197   // an expression, and each individual field initializer is a separate
8198   // full-expression. For instance, in:
8199   //
8200   //   struct Temp { ~Temp(); };
8201   //   struct S { S(Temp); };
8202   //   struct T { S a, b; } t = { Temp(), Temp() }
8203   //
8204   // we should destroy the first Temp before constructing the second.
8205   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8206                                           false,
8207                                           VDecl->isConstexpr());
8208   if (Result.isInvalid()) {
8209     VDecl->setInvalidDecl();
8210     return;
8211   }
8212   Init = Result.take();
8213 
8214   // Attach the initializer to the decl.
8215   VDecl->setInit(Init);
8216 
8217   if (VDecl->isLocalVarDecl()) {
8218     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8219     // static storage duration shall be constant expressions or string literals.
8220     // C++ does not have this restriction.
8221     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8222       if (VDecl->getStorageClass() == SC_Static)
8223         CheckForConstantInitializer(Init, DclT);
8224       // C89 is stricter than C99 for non-static aggregate types.
8225       // C89 6.5.7p3: All the expressions [...] in an initializer list
8226       // for an object that has aggregate or union type shall be
8227       // constant expressions.
8228       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8229                isa<InitListExpr>(Init) &&
8230                !Init->isConstantInitializer(Context, false))
8231         Diag(Init->getExprLoc(),
8232              diag::ext_aggregate_init_not_constant)
8233           << Init->getSourceRange();
8234     }
8235   } else if (VDecl->isStaticDataMember() &&
8236              VDecl->getLexicalDeclContext()->isRecord()) {
8237     // This is an in-class initialization for a static data member, e.g.,
8238     //
8239     // struct S {
8240     //   static const int value = 17;
8241     // };
8242 
8243     // C++ [class.mem]p4:
8244     //   A member-declarator can contain a constant-initializer only
8245     //   if it declares a static member (9.4) of const integral or
8246     //   const enumeration type, see 9.4.2.
8247     //
8248     // C++11 [class.static.data]p3:
8249     //   If a non-volatile const static data member is of integral or
8250     //   enumeration type, its declaration in the class definition can
8251     //   specify a brace-or-equal-initializer in which every initalizer-clause
8252     //   that is an assignment-expression is a constant expression. A static
8253     //   data member of literal type can be declared in the class definition
8254     //   with the constexpr specifier; if so, its declaration shall specify a
8255     //   brace-or-equal-initializer in which every initializer-clause that is
8256     //   an assignment-expression is a constant expression.
8257 
8258     // Do nothing on dependent types.
8259     if (DclT->isDependentType()) {
8260 
8261     // Allow any 'static constexpr' members, whether or not they are of literal
8262     // type. We separately check that every constexpr variable is of literal
8263     // type.
8264     } else if (VDecl->isConstexpr()) {
8265 
8266     // Require constness.
8267     } else if (!DclT.isConstQualified()) {
8268       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8269         << Init->getSourceRange();
8270       VDecl->setInvalidDecl();
8271 
8272     // We allow integer constant expressions in all cases.
8273     } else if (DclT->isIntegralOrEnumerationType()) {
8274       // Check whether the expression is a constant expression.
8275       SourceLocation Loc;
8276       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8277         // In C++11, a non-constexpr const static data member with an
8278         // in-class initializer cannot be volatile.
8279         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8280       else if (Init->isValueDependent())
8281         ; // Nothing to check.
8282       else if (Init->isIntegerConstantExpr(Context, &Loc))
8283         ; // Ok, it's an ICE!
8284       else if (Init->isEvaluatable(Context)) {
8285         // If we can constant fold the initializer through heroics, accept it,
8286         // but report this as a use of an extension for -pedantic.
8287         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8288           << Init->getSourceRange();
8289       } else {
8290         // Otherwise, this is some crazy unknown case.  Report the issue at the
8291         // location provided by the isIntegerConstantExpr failed check.
8292         Diag(Loc, diag::err_in_class_initializer_non_constant)
8293           << Init->getSourceRange();
8294         VDecl->setInvalidDecl();
8295       }
8296 
8297     // We allow foldable floating-point constants as an extension.
8298     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8299       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8300       // it anyway and provide a fixit to add the 'constexpr'.
8301       if (getLangOpts().CPlusPlus11) {
8302         Diag(VDecl->getLocation(),
8303              diag::ext_in_class_initializer_float_type_cxx11)
8304             << DclT << Init->getSourceRange();
8305         Diag(VDecl->getLocStart(),
8306              diag::note_in_class_initializer_float_type_cxx11)
8307             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8308       } else {
8309         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8310           << DclT << Init->getSourceRange();
8311 
8312         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8313           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8314             << Init->getSourceRange();
8315           VDecl->setInvalidDecl();
8316         }
8317       }
8318 
8319     // Suggest adding 'constexpr' in C++11 for literal types.
8320     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8321       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8322         << DclT << Init->getSourceRange()
8323         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8324       VDecl->setConstexpr(true);
8325 
8326     } else {
8327       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8328         << DclT << Init->getSourceRange();
8329       VDecl->setInvalidDecl();
8330     }
8331   } else if (VDecl->isFileVarDecl()) {
8332     if (VDecl->getStorageClass() == SC_Extern &&
8333         (!getLangOpts().CPlusPlus ||
8334          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8335            VDecl->isExternC())))
8336       Diag(VDecl->getLocation(), diag::warn_extern_init);
8337 
8338     // C99 6.7.8p4. All file scoped initializers need to be constant.
8339     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8340       CheckForConstantInitializer(Init, DclT);
8341     else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8342              !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8343              !Init->isValueDependent() && !VDecl->isConstexpr() &&
8344              !Init->isConstantInitializer(
8345                  Context, VDecl->getType()->isReferenceType())) {
8346       // GNU C++98 edits for __thread, [basic.start.init]p4:
8347       //   An object of thread storage duration shall not require dynamic
8348       //   initialization.
8349       // FIXME: Need strict checking here.
8350       Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8351       if (getLangOpts().CPlusPlus11)
8352         Diag(VDecl->getLocation(), diag::note_use_thread_local);
8353     }
8354   }
8355 
8356   // We will represent direct-initialization similarly to copy-initialization:
8357   //    int x(1);  -as-> int x = 1;
8358   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8359   //
8360   // Clients that want to distinguish between the two forms, can check for
8361   // direct initializer using VarDecl::getInitStyle().
8362   // A major benefit is that clients that don't particularly care about which
8363   // exactly form was it (like the CodeGen) can handle both cases without
8364   // special case code.
8365 
8366   // C++ 8.5p11:
8367   // The form of initialization (using parentheses or '=') is generally
8368   // insignificant, but does matter when the entity being initialized has a
8369   // class type.
8370   if (CXXDirectInit) {
8371     assert(DirectInit && "Call-style initializer must be direct init.");
8372     VDecl->setInitStyle(VarDecl::CallInit);
8373   } else if (DirectInit) {
8374     // This must be list-initialization. No other way is direct-initialization.
8375     VDecl->setInitStyle(VarDecl::ListInit);
8376   }
8377 
8378   CheckCompleteVariableDeclaration(VDecl);
8379 }
8380 
8381 /// ActOnInitializerError - Given that there was an error parsing an
8382 /// initializer for the given declaration, try to return to some form
8383 /// of sanity.
8384 void Sema::ActOnInitializerError(Decl *D) {
8385   // Our main concern here is re-establishing invariants like "a
8386   // variable's type is either dependent or complete".
8387   if (!D || D->isInvalidDecl()) return;
8388 
8389   VarDecl *VD = dyn_cast<VarDecl>(D);
8390   if (!VD) return;
8391 
8392   // Auto types are meaningless if we can't make sense of the initializer.
8393   if (ParsingInitForAutoVars.count(D)) {
8394     D->setInvalidDecl();
8395     return;
8396   }
8397 
8398   QualType Ty = VD->getType();
8399   if (Ty->isDependentType()) return;
8400 
8401   // Require a complete type.
8402   if (RequireCompleteType(VD->getLocation(),
8403                           Context.getBaseElementType(Ty),
8404                           diag::err_typecheck_decl_incomplete_type)) {
8405     VD->setInvalidDecl();
8406     return;
8407   }
8408 
8409   // Require an abstract type.
8410   if (RequireNonAbstractType(VD->getLocation(), Ty,
8411                              diag::err_abstract_type_in_decl,
8412                              AbstractVariableType)) {
8413     VD->setInvalidDecl();
8414     return;
8415   }
8416 
8417   // Don't bother complaining about constructors or destructors,
8418   // though.
8419 }
8420 
8421 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
8422                                   bool TypeMayContainAuto) {
8423   // If there is no declaration, there was an error parsing it. Just ignore it.
8424   if (RealDecl == 0)
8425     return;
8426 
8427   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8428     QualType Type = Var->getType();
8429 
8430     // C++11 [dcl.spec.auto]p3
8431     if (TypeMayContainAuto && Type->getContainedAutoType()) {
8432       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8433         << Var->getDeclName() << Type;
8434       Var->setInvalidDecl();
8435       return;
8436     }
8437 
8438     // C++11 [class.static.data]p3: A static data member can be declared with
8439     // the constexpr specifier; if so, its declaration shall specify
8440     // a brace-or-equal-initializer.
8441     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8442     // the definition of a variable [...] or the declaration of a static data
8443     // member.
8444     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8445       if (Var->isStaticDataMember())
8446         Diag(Var->getLocation(),
8447              diag::err_constexpr_static_mem_var_requires_init)
8448           << Var->getDeclName();
8449       else
8450         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8451       Var->setInvalidDecl();
8452       return;
8453     }
8454 
8455     switch (Var->isThisDeclarationADefinition()) {
8456     case VarDecl::Definition:
8457       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8458         break;
8459 
8460       // We have an out-of-line definition of a static data member
8461       // that has an in-class initializer, so we type-check this like
8462       // a declaration.
8463       //
8464       // Fall through
8465 
8466     case VarDecl::DeclarationOnly:
8467       // It's only a declaration.
8468 
8469       // Block scope. C99 6.7p7: If an identifier for an object is
8470       // declared with no linkage (C99 6.2.2p6), the type for the
8471       // object shall be complete.
8472       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
8473           !Var->hasLinkage() && !Var->isInvalidDecl() &&
8474           RequireCompleteType(Var->getLocation(), Type,
8475                               diag::err_typecheck_decl_incomplete_type))
8476         Var->setInvalidDecl();
8477 
8478       // Make sure that the type is not abstract.
8479       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8480           RequireNonAbstractType(Var->getLocation(), Type,
8481                                  diag::err_abstract_type_in_decl,
8482                                  AbstractVariableType))
8483         Var->setInvalidDecl();
8484       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8485           Var->getStorageClass() == SC_PrivateExtern) {
8486         Diag(Var->getLocation(), diag::warn_private_extern);
8487         Diag(Var->getLocation(), diag::note_private_extern);
8488       }
8489 
8490       return;
8491 
8492     case VarDecl::TentativeDefinition:
8493       // File scope. C99 6.9.2p2: A declaration of an identifier for an
8494       // object that has file scope without an initializer, and without a
8495       // storage-class specifier or with the storage-class specifier "static",
8496       // constitutes a tentative definition. Note: A tentative definition with
8497       // external linkage is valid (C99 6.2.2p5).
8498       if (!Var->isInvalidDecl()) {
8499         if (const IncompleteArrayType *ArrayT
8500                                     = Context.getAsIncompleteArrayType(Type)) {
8501           if (RequireCompleteType(Var->getLocation(),
8502                                   ArrayT->getElementType(),
8503                                   diag::err_illegal_decl_array_incomplete_type))
8504             Var->setInvalidDecl();
8505         } else if (Var->getStorageClass() == SC_Static) {
8506           // C99 6.9.2p3: If the declaration of an identifier for an object is
8507           // a tentative definition and has internal linkage (C99 6.2.2p3), the
8508           // declared type shall not be an incomplete type.
8509           // NOTE: code such as the following
8510           //     static struct s;
8511           //     struct s { int a; };
8512           // is accepted by gcc. Hence here we issue a warning instead of
8513           // an error and we do not invalidate the static declaration.
8514           // NOTE: to avoid multiple warnings, only check the first declaration.
8515           if (Var->getPreviousDecl() == 0)
8516             RequireCompleteType(Var->getLocation(), Type,
8517                                 diag::ext_typecheck_decl_incomplete_type);
8518         }
8519       }
8520 
8521       // Record the tentative definition; we're done.
8522       if (!Var->isInvalidDecl())
8523         TentativeDefinitions.push_back(Var);
8524       return;
8525     }
8526 
8527     // Provide a specific diagnostic for uninitialized variable
8528     // definitions with incomplete array type.
8529     if (Type->isIncompleteArrayType()) {
8530       Diag(Var->getLocation(),
8531            diag::err_typecheck_incomplete_array_needs_initializer);
8532       Var->setInvalidDecl();
8533       return;
8534     }
8535 
8536     // Provide a specific diagnostic for uninitialized variable
8537     // definitions with reference type.
8538     if (Type->isReferenceType()) {
8539       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8540         << Var->getDeclName()
8541         << SourceRange(Var->getLocation(), Var->getLocation());
8542       Var->setInvalidDecl();
8543       return;
8544     }
8545 
8546     // Do not attempt to type-check the default initializer for a
8547     // variable with dependent type.
8548     if (Type->isDependentType())
8549       return;
8550 
8551     if (Var->isInvalidDecl())
8552       return;
8553 
8554     if (RequireCompleteType(Var->getLocation(),
8555                             Context.getBaseElementType(Type),
8556                             diag::err_typecheck_decl_incomplete_type)) {
8557       Var->setInvalidDecl();
8558       return;
8559     }
8560 
8561     // The variable can not have an abstract class type.
8562     if (RequireNonAbstractType(Var->getLocation(), Type,
8563                                diag::err_abstract_type_in_decl,
8564                                AbstractVariableType)) {
8565       Var->setInvalidDecl();
8566       return;
8567     }
8568 
8569     // Check for jumps past the implicit initializer.  C++0x
8570     // clarifies that this applies to a "variable with automatic
8571     // storage duration", not a "local variable".
8572     // C++11 [stmt.dcl]p3
8573     //   A program that jumps from a point where a variable with automatic
8574     //   storage duration is not in scope to a point where it is in scope is
8575     //   ill-formed unless the variable has scalar type, class type with a
8576     //   trivial default constructor and a trivial destructor, a cv-qualified
8577     //   version of one of these types, or an array of one of the preceding
8578     //   types and is declared without an initializer.
8579     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
8580       if (const RecordType *Record
8581             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
8582         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
8583         // Mark the function for further checking even if the looser rules of
8584         // C++11 do not require such checks, so that we can diagnose
8585         // incompatibilities with C++98.
8586         if (!CXXRecord->isPOD())
8587           getCurFunction()->setHasBranchProtectedScope();
8588       }
8589     }
8590 
8591     // C++03 [dcl.init]p9:
8592     //   If no initializer is specified for an object, and the
8593     //   object is of (possibly cv-qualified) non-POD class type (or
8594     //   array thereof), the object shall be default-initialized; if
8595     //   the object is of const-qualified type, the underlying class
8596     //   type shall have a user-declared default
8597     //   constructor. Otherwise, if no initializer is specified for
8598     //   a non- static object, the object and its subobjects, if
8599     //   any, have an indeterminate initial value); if the object
8600     //   or any of its subobjects are of const-qualified type, the
8601     //   program is ill-formed.
8602     // C++0x [dcl.init]p11:
8603     //   If no initializer is specified for an object, the object is
8604     //   default-initialized; [...].
8605     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8606     InitializationKind Kind
8607       = InitializationKind::CreateDefault(Var->getLocation());
8608 
8609     InitializationSequence InitSeq(*this, Entity, Kind, None);
8610     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
8611     if (Init.isInvalid())
8612       Var->setInvalidDecl();
8613     else if (Init.get()) {
8614       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
8615       // This is important for template substitution.
8616       Var->setInitStyle(VarDecl::CallInit);
8617     }
8618 
8619     CheckCompleteVariableDeclaration(Var);
8620   }
8621 }
8622 
8623 void Sema::ActOnCXXForRangeDecl(Decl *D) {
8624   VarDecl *VD = dyn_cast<VarDecl>(D);
8625   if (!VD) {
8626     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8627     D->setInvalidDecl();
8628     return;
8629   }
8630 
8631   VD->setCXXForRangeDecl(true);
8632 
8633   // for-range-declaration cannot be given a storage class specifier.
8634   int Error = -1;
8635   switch (VD->getStorageClass()) {
8636   case SC_None:
8637     break;
8638   case SC_Extern:
8639     Error = 0;
8640     break;
8641   case SC_Static:
8642     Error = 1;
8643     break;
8644   case SC_PrivateExtern:
8645     Error = 2;
8646     break;
8647   case SC_Auto:
8648     Error = 3;
8649     break;
8650   case SC_Register:
8651     Error = 4;
8652     break;
8653   case SC_OpenCLWorkGroupLocal:
8654     llvm_unreachable("Unexpected storage class");
8655   }
8656   if (VD->isConstexpr())
8657     Error = 5;
8658   if (Error != -1) {
8659     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8660       << VD->getDeclName() << Error;
8661     D->setInvalidDecl();
8662   }
8663 }
8664 
8665 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8666   if (var->isInvalidDecl()) return;
8667 
8668   // In ARC, don't allow jumps past the implicit initialization of a
8669   // local retaining variable.
8670   if (getLangOpts().ObjCAutoRefCount &&
8671       var->hasLocalStorage()) {
8672     switch (var->getType().getObjCLifetime()) {
8673     case Qualifiers::OCL_None:
8674     case Qualifiers::OCL_ExplicitNone:
8675     case Qualifiers::OCL_Autoreleasing:
8676       break;
8677 
8678     case Qualifiers::OCL_Weak:
8679     case Qualifiers::OCL_Strong:
8680       getCurFunction()->setHasBranchProtectedScope();
8681       break;
8682     }
8683   }
8684 
8685   if (var->isThisDeclarationADefinition() &&
8686       var->isExternallyVisible() && var->hasLinkage() &&
8687       getDiagnostics().getDiagnosticLevel(
8688                        diag::warn_missing_variable_declarations,
8689                        var->getLocation())) {
8690     // Find a previous declaration that's not a definition.
8691     VarDecl *prev = var->getPreviousDecl();
8692     while (prev && prev->isThisDeclarationADefinition())
8693       prev = prev->getPreviousDecl();
8694 
8695     if (!prev)
8696       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8697   }
8698 
8699   if (var->getTLSKind() == VarDecl::TLS_Static &&
8700       var->getType().isDestructedType()) {
8701     // GNU C++98 edits for __thread, [basic.start.term]p3:
8702     //   The type of an object with thread storage duration shall not
8703     //   have a non-trivial destructor.
8704     Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8705     if (getLangOpts().CPlusPlus11)
8706       Diag(var->getLocation(), diag::note_use_thread_local);
8707   }
8708 
8709   // All the following checks are C++ only.
8710   if (!getLangOpts().CPlusPlus) return;
8711 
8712   QualType type = var->getType();
8713   if (type->isDependentType()) return;
8714 
8715   // __block variables might require us to capture a copy-initializer.
8716   if (var->hasAttr<BlocksAttr>()) {
8717     // It's currently invalid to ever have a __block variable with an
8718     // array type; should we diagnose that here?
8719 
8720     // Regardless, we don't want to ignore array nesting when
8721     // constructing this copy.
8722     if (type->isStructureOrClassType()) {
8723       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
8724       SourceLocation poi = var->getLocation();
8725       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
8726       ExprResult result
8727         = PerformMoveOrCopyInitialization(
8728             InitializedEntity::InitializeBlock(poi, type, false),
8729             var, var->getType(), varRef, /*AllowNRVO=*/true);
8730       if (!result.isInvalid()) {
8731         result = MaybeCreateExprWithCleanups(result);
8732         Expr *init = result.takeAs<Expr>();
8733         Context.setBlockVarCopyInits(var, init);
8734       }
8735     }
8736   }
8737 
8738   Expr *Init = var->getInit();
8739   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
8740   QualType baseType = Context.getBaseElementType(type);
8741 
8742   if (!var->getDeclContext()->isDependentContext() &&
8743       Init && !Init->isValueDependent()) {
8744     if (IsGlobal && !var->isConstexpr() &&
8745         getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8746                                             var->getLocation())
8747           != DiagnosticsEngine::Ignored) {
8748       // Warn about globals which don't have a constant initializer.  Don't
8749       // warn about globals with a non-trivial destructor because we already
8750       // warned about them.
8751       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8752       if (!(RD && !RD->hasTrivialDestructor()) &&
8753           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8754         Diag(var->getLocation(), diag::warn_global_constructor)
8755           << Init->getSourceRange();
8756     }
8757 
8758     if (var->isConstexpr()) {
8759       SmallVector<PartialDiagnosticAt, 8> Notes;
8760       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8761         SourceLocation DiagLoc = var->getLocation();
8762         // If the note doesn't add any useful information other than a source
8763         // location, fold it into the primary diagnostic.
8764         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8765               diag::note_invalid_subexpr_in_const_expr) {
8766           DiagLoc = Notes[0].first;
8767           Notes.clear();
8768         }
8769         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8770           << var << Init->getSourceRange();
8771         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8772           Diag(Notes[I].first, Notes[I].second);
8773       }
8774     } else if (var->isUsableInConstantExpressions(Context)) {
8775       // Check whether the initializer of a const variable of integral or
8776       // enumeration type is an ICE now, since we can't tell whether it was
8777       // initialized by a constant expression if we check later.
8778       var->checkInitIsICE();
8779     }
8780   }
8781 
8782   // Require the destructor.
8783   if (const RecordType *recordType = baseType->getAs<RecordType>())
8784     FinalizeVarWithDestructor(var, recordType);
8785 }
8786 
8787 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8788 /// any semantic actions necessary after any initializer has been attached.
8789 void
8790 Sema::FinalizeDeclaration(Decl *ThisDecl) {
8791   // Note that we are no longer parsing the initializer for this declaration.
8792   ParsingInitForAutoVars.erase(ThisDecl);
8793 
8794   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
8795   if (!VD)
8796     return;
8797 
8798   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8799     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8800       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8801       VD->dropAttr<UsedAttr>();
8802     }
8803   }
8804 
8805   const DeclContext *DC = VD->getDeclContext();
8806   // If there's a #pragma GCC visibility in scope, and this isn't a class
8807   // member, set the visibility of this variable.
8808   if (!DC->isRecord() && VD->isExternallyVisible())
8809     AddPushedVisibilityAttribute(VD);
8810 
8811   if (VD->isFileVarDecl())
8812     MarkUnusedFileScopedDecl(VD);
8813 
8814   // Now we have parsed the initializer and can update the table of magic
8815   // tag values.
8816   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8817       !VD->getType()->isIntegralOrEnumerationType())
8818     return;
8819 
8820   for (specific_attr_iterator<TypeTagForDatatypeAttr>
8821          I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8822          E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8823        I != E; ++I) {
8824     const Expr *MagicValueExpr = VD->getInit();
8825     if (!MagicValueExpr) {
8826       continue;
8827     }
8828     llvm::APSInt MagicValueInt;
8829     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8830       Diag(I->getRange().getBegin(),
8831            diag::err_type_tag_for_datatype_not_ice)
8832         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8833       continue;
8834     }
8835     if (MagicValueInt.getActiveBits() > 64) {
8836       Diag(I->getRange().getBegin(),
8837            diag::err_type_tag_for_datatype_too_large)
8838         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8839       continue;
8840     }
8841     uint64_t MagicValue = MagicValueInt.getZExtValue();
8842     RegisterTypeTagForDatatype(I->getArgumentKind(),
8843                                MagicValue,
8844                                I->getMatchingCType(),
8845                                I->getLayoutCompatible(),
8846                                I->getMustBeNull());
8847   }
8848 }
8849 
8850 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8851                                                    ArrayRef<Decl *> Group) {
8852   SmallVector<Decl*, 8> Decls;
8853 
8854   if (DS.isTypeSpecOwned())
8855     Decls.push_back(DS.getRepAsDecl());
8856 
8857   DeclaratorDecl *FirstDeclaratorInGroup = 0;
8858   for (unsigned i = 0, e = Group.size(); i != e; ++i)
8859     if (Decl *D = Group[i]) {
8860       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8861         if (!FirstDeclaratorInGroup)
8862           FirstDeclaratorInGroup = DD;
8863       Decls.push_back(D);
8864     }
8865 
8866   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
8867     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
8868       HandleTagNumbering(*this, Tag);
8869       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8870         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8871     }
8872   }
8873 
8874   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
8875 }
8876 
8877 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
8878 /// group, performing any necessary semantic checking.
8879 Sema::DeclGroupPtrTy
8880 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
8881                            bool TypeMayContainAuto) {
8882   // C++0x [dcl.spec.auto]p7:
8883   //   If the type deduced for the template parameter U is not the same in each
8884   //   deduction, the program is ill-formed.
8885   // FIXME: When initializer-list support is added, a distinction is needed
8886   // between the deduced type U and the deduced type which 'auto' stands for.
8887   //   auto a = 0, b = { 1, 2, 3 };
8888   // is legal because the deduced type U is 'int' in both cases.
8889   if (TypeMayContainAuto && Group.size() > 1) {
8890     QualType Deduced;
8891     CanQualType DeducedCanon;
8892     VarDecl *DeducedDecl = 0;
8893     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
8894       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8895         AutoType *AT = D->getType()->getContainedAutoType();
8896         // Don't reissue diagnostics when instantiating a template.
8897         if (AT && D->isInvalidDecl())
8898           break;
8899         QualType U = AT ? AT->getDeducedType() : QualType();
8900         if (!U.isNull()) {
8901           CanQualType UCanon = Context.getCanonicalType(U);
8902           if (Deduced.isNull()) {
8903             Deduced = U;
8904             DeducedCanon = UCanon;
8905             DeducedDecl = D;
8906           } else if (DeducedCanon != UCanon) {
8907             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
8908                  diag::err_auto_different_deductions)
8909               << (AT->isDecltypeAuto() ? 1 : 0)
8910               << Deduced << DeducedDecl->getDeclName()
8911               << U << D->getDeclName()
8912               << DeducedDecl->getInit()->getSourceRange()
8913               << D->getInit()->getSourceRange();
8914             D->setInvalidDecl();
8915             break;
8916           }
8917         }
8918       }
8919     }
8920   }
8921 
8922   ActOnDocumentableDecls(Group);
8923 
8924   return DeclGroupPtrTy::make(
8925       DeclGroupRef::Create(Context, Group.data(), Group.size()));
8926 }
8927 
8928 void Sema::ActOnDocumentableDecl(Decl *D) {
8929   ActOnDocumentableDecls(D);
8930 }
8931 
8932 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
8933   // Don't parse the comment if Doxygen diagnostics are ignored.
8934   if (Group.empty() || !Group[0])
8935    return;
8936 
8937   if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
8938                                Group[0]->getLocation())
8939         == DiagnosticsEngine::Ignored)
8940     return;
8941 
8942   if (Group.size() >= 2) {
8943     // This is a decl group.  Normally it will contain only declarations
8944     // produced from declarator list.  But in case we have any definitions or
8945     // additional declaration references:
8946     //   'typedef struct S {} S;'
8947     //   'typedef struct S *S;'
8948     //   'struct S *pS;'
8949     // FinalizeDeclaratorGroup adds these as separate declarations.
8950     Decl *MaybeTagDecl = Group[0];
8951     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
8952       Group = Group.slice(1);
8953     }
8954   }
8955 
8956   // See if there are any new comments that are not attached to a decl.
8957   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
8958   if (!Comments.empty() &&
8959       !Comments.back()->isAttached()) {
8960     // There is at least one comment that not attached to a decl.
8961     // Maybe it should be attached to one of these decls?
8962     //
8963     // Note that this way we pick up not only comments that precede the
8964     // declaration, but also comments that *follow* the declaration -- thanks to
8965     // the lookahead in the lexer: we've consumed the semicolon and looked
8966     // ahead through comments.
8967     for (unsigned i = 0, e = Group.size(); i != e; ++i)
8968       Context.getCommentForDecl(Group[i], &PP);
8969   }
8970 }
8971 
8972 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
8973 /// to introduce parameters into function prototype scope.
8974 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
8975   const DeclSpec &DS = D.getDeclSpec();
8976 
8977   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
8978   // C++03 [dcl.stc]p2 also permits 'auto'.
8979   VarDecl::StorageClass StorageClass = SC_None;
8980   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
8981     StorageClass = SC_Register;
8982   } else if (getLangOpts().CPlusPlus &&
8983              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
8984     StorageClass = SC_Auto;
8985   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
8986     Diag(DS.getStorageClassSpecLoc(),
8987          diag::err_invalid_storage_class_in_func_decl);
8988     D.getMutableDeclSpec().ClearStorageClassSpecs();
8989   }
8990 
8991   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
8992     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
8993       << DeclSpec::getSpecifierName(TSCS);
8994   if (DS.isConstexprSpecified())
8995     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
8996       << 0;
8997 
8998   DiagnoseFunctionSpecifiers(DS);
8999 
9000   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9001   QualType parmDeclType = TInfo->getType();
9002 
9003   if (getLangOpts().CPlusPlus) {
9004     // Check that there are no default arguments inside the type of this
9005     // parameter.
9006     CheckExtraCXXDefaultArguments(D);
9007 
9008     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9009     if (D.getCXXScopeSpec().isSet()) {
9010       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9011         << D.getCXXScopeSpec().getRange();
9012       D.getCXXScopeSpec().clear();
9013     }
9014   }
9015 
9016   // Ensure we have a valid name
9017   IdentifierInfo *II = 0;
9018   if (D.hasName()) {
9019     II = D.getIdentifier();
9020     if (!II) {
9021       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9022         << GetNameForDeclarator(D).getName().getAsString();
9023       D.setInvalidType(true);
9024     }
9025   }
9026 
9027   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9028   if (II) {
9029     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9030                    ForRedeclaration);
9031     LookupName(R, S);
9032     if (R.isSingleResult()) {
9033       NamedDecl *PrevDecl = R.getFoundDecl();
9034       if (PrevDecl->isTemplateParameter()) {
9035         // Maybe we will complain about the shadowed template parameter.
9036         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9037         // Just pretend that we didn't see the previous declaration.
9038         PrevDecl = 0;
9039       } else if (S->isDeclScope(PrevDecl)) {
9040         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9041         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9042 
9043         // Recover by removing the name
9044         II = 0;
9045         D.SetIdentifier(0, D.getIdentifierLoc());
9046         D.setInvalidType(true);
9047       }
9048     }
9049   }
9050 
9051   // Temporarily put parameter variables in the translation unit, not
9052   // the enclosing context.  This prevents them from accidentally
9053   // looking like class members in C++.
9054   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9055                                     D.getLocStart(),
9056                                     D.getIdentifierLoc(), II,
9057                                     parmDeclType, TInfo,
9058                                     StorageClass);
9059 
9060   if (D.isInvalidType())
9061     New->setInvalidDecl();
9062 
9063   assert(S->isFunctionPrototypeScope());
9064   assert(S->getFunctionPrototypeDepth() >= 1);
9065   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9066                     S->getNextFunctionPrototypeIndex());
9067 
9068   // Add the parameter declaration into this scope.
9069   S->AddDecl(New);
9070   if (II)
9071     IdResolver.AddDecl(New);
9072 
9073   ProcessDeclAttributes(S, New, D);
9074 
9075   if (D.getDeclSpec().isModulePrivateSpecified())
9076     Diag(New->getLocation(), diag::err_module_private_local)
9077       << 1 << New->getDeclName()
9078       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9079       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9080 
9081   if (New->hasAttr<BlocksAttr>()) {
9082     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9083   }
9084   return New;
9085 }
9086 
9087 /// \brief Synthesizes a variable for a parameter arising from a
9088 /// typedef.
9089 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9090                                               SourceLocation Loc,
9091                                               QualType T) {
9092   /* FIXME: setting StartLoc == Loc.
9093      Would it be worth to modify callers so as to provide proper source
9094      location for the unnamed parameters, embedding the parameter's type? */
9095   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
9096                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9097                                            SC_None, 0);
9098   Param->setImplicit();
9099   return Param;
9100 }
9101 
9102 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9103                                     ParmVarDecl * const *ParamEnd) {
9104   // Don't diagnose unused-parameter errors in template instantiations; we
9105   // will already have done so in the template itself.
9106   if (!ActiveTemplateInstantiations.empty())
9107     return;
9108 
9109   for (; Param != ParamEnd; ++Param) {
9110     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9111         !(*Param)->hasAttr<UnusedAttr>()) {
9112       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9113         << (*Param)->getDeclName();
9114     }
9115   }
9116 }
9117 
9118 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9119                                                   ParmVarDecl * const *ParamEnd,
9120                                                   QualType ReturnTy,
9121                                                   NamedDecl *D) {
9122   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9123     return;
9124 
9125   // Warn if the return value is pass-by-value and larger than the specified
9126   // threshold.
9127   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9128     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9129     if (Size > LangOpts.NumLargeByValueCopy)
9130       Diag(D->getLocation(), diag::warn_return_value_size)
9131           << D->getDeclName() << Size;
9132   }
9133 
9134   // Warn if any parameter is pass-by-value and larger than the specified
9135   // threshold.
9136   for (; Param != ParamEnd; ++Param) {
9137     QualType T = (*Param)->getType();
9138     if (T->isDependentType() || !T.isPODType(Context))
9139       continue;
9140     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9141     if (Size > LangOpts.NumLargeByValueCopy)
9142       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9143           << (*Param)->getDeclName() << Size;
9144   }
9145 }
9146 
9147 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9148                                   SourceLocation NameLoc, IdentifierInfo *Name,
9149                                   QualType T, TypeSourceInfo *TSInfo,
9150                                   VarDecl::StorageClass StorageClass) {
9151   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9152   if (getLangOpts().ObjCAutoRefCount &&
9153       T.getObjCLifetime() == Qualifiers::OCL_None &&
9154       T->isObjCLifetimeType()) {
9155 
9156     Qualifiers::ObjCLifetime lifetime;
9157 
9158     // Special cases for arrays:
9159     //   - if it's const, use __unsafe_unretained
9160     //   - otherwise, it's an error
9161     if (T->isArrayType()) {
9162       if (!T.isConstQualified()) {
9163         DelayedDiagnostics.add(
9164             sema::DelayedDiagnostic::makeForbiddenType(
9165             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9166       }
9167       lifetime = Qualifiers::OCL_ExplicitNone;
9168     } else {
9169       lifetime = T->getObjCARCImplicitLifetime();
9170     }
9171     T = Context.getLifetimeQualifiedType(T, lifetime);
9172   }
9173 
9174   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9175                                          Context.getAdjustedParameterType(T),
9176                                          TSInfo,
9177                                          StorageClass, 0);
9178 
9179   // Parameters can not be abstract class types.
9180   // For record types, this is done by the AbstractClassUsageDiagnoser once
9181   // the class has been completely parsed.
9182   if (!CurContext->isRecord() &&
9183       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9184                              AbstractParamType))
9185     New->setInvalidDecl();
9186 
9187   // Parameter declarators cannot be interface types. All ObjC objects are
9188   // passed by reference.
9189   if (T->isObjCObjectType()) {
9190     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9191     Diag(NameLoc,
9192          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9193       << FixItHint::CreateInsertion(TypeEndLoc, "*");
9194     T = Context.getObjCObjectPointerType(T);
9195     New->setType(T);
9196   }
9197 
9198   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9199   // duration shall not be qualified by an address-space qualifier."
9200   // Since all parameters have automatic store duration, they can not have
9201   // an address space.
9202   if (T.getAddressSpace() != 0) {
9203     Diag(NameLoc, diag::err_arg_with_address_space);
9204     New->setInvalidDecl();
9205   }
9206 
9207   return New;
9208 }
9209 
9210 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9211                                            SourceLocation LocAfterDecls) {
9212   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9213 
9214   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9215   // for a K&R function.
9216   if (!FTI.hasPrototype) {
9217     for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9218       --i;
9219       if (FTI.ArgInfo[i].Param == 0) {
9220         SmallString<256> Code;
9221         llvm::raw_svector_ostream(Code) << "  int "
9222                                         << FTI.ArgInfo[i].Ident->getName()
9223                                         << ";\n";
9224         Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
9225           << FTI.ArgInfo[i].Ident
9226           << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9227 
9228         // Implicitly declare the argument as type 'int' for lack of a better
9229         // type.
9230         AttributeFactory attrs;
9231         DeclSpec DS(attrs);
9232         const char* PrevSpec; // unused
9233         unsigned DiagID; // unused
9234         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
9235                            PrevSpec, DiagID);
9236         // Use the identifier location for the type source range.
9237         DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9238         DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
9239         Declarator ParamD(DS, Declarator::KNRTypeListContext);
9240         ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
9241         FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
9242       }
9243     }
9244   }
9245 }
9246 
9247 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9248   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
9249   assert(D.isFunctionDeclarator() && "Not a function declarator!");
9250   Scope *ParentScope = FnBodyScope->getParent();
9251 
9252   D.setFunctionDefinitionKind(FDK_Definition);
9253   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9254   return ActOnStartOfFunctionDef(FnBodyScope, DP);
9255 }
9256 
9257 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9258                              const FunctionDecl*& PossibleZeroParamPrototype) {
9259   // Don't warn about invalid declarations.
9260   if (FD->isInvalidDecl())
9261     return false;
9262 
9263   // Or declarations that aren't global.
9264   if (!FD->isGlobal())
9265     return false;
9266 
9267   // Don't warn about C++ member functions.
9268   if (isa<CXXMethodDecl>(FD))
9269     return false;
9270 
9271   // Don't warn about 'main'.
9272   if (FD->isMain())
9273     return false;
9274 
9275   // Don't warn about inline functions.
9276   if (FD->isInlined())
9277     return false;
9278 
9279   // Don't warn about function templates.
9280   if (FD->getDescribedFunctionTemplate())
9281     return false;
9282 
9283   // Don't warn about function template specializations.
9284   if (FD->isFunctionTemplateSpecialization())
9285     return false;
9286 
9287   // Don't warn for OpenCL kernels.
9288   if (FD->hasAttr<OpenCLKernelAttr>())
9289     return false;
9290 
9291   bool MissingPrototype = true;
9292   for (const FunctionDecl *Prev = FD->getPreviousDecl();
9293        Prev; Prev = Prev->getPreviousDecl()) {
9294     // Ignore any declarations that occur in function or method
9295     // scope, because they aren't visible from the header.
9296     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9297       continue;
9298 
9299     MissingPrototype = !Prev->getType()->isFunctionProtoType();
9300     if (FD->getNumParams() == 0)
9301       PossibleZeroParamPrototype = Prev;
9302     break;
9303   }
9304 
9305   return MissingPrototype;
9306 }
9307 
9308 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
9309   // Don't complain if we're in GNU89 mode and the previous definition
9310   // was an extern inline function.
9311   const FunctionDecl *Definition;
9312   if (FD->isDefined(Definition) &&
9313       !canRedefineFunction(Definition, getLangOpts())) {
9314     if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9315         Definition->getStorageClass() == SC_Extern)
9316       Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9317         << FD->getDeclName() << getLangOpts().CPlusPlus;
9318     else
9319       Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9320     Diag(Definition->getLocation(), diag::note_previous_definition);
9321     FD->setInvalidDecl();
9322   }
9323 }
9324 
9325 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
9326   // Clear the last template instantiation error context.
9327   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9328 
9329   if (!D)
9330     return D;
9331   FunctionDecl *FD = 0;
9332 
9333   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
9334     FD = FunTmpl->getTemplatedDecl();
9335   else
9336     FD = cast<FunctionDecl>(D);
9337 
9338   // Enter a new function scope
9339   PushFunctionScope();
9340 
9341   // See if this is a redefinition.
9342   if (!FD->isLateTemplateParsed())
9343     CheckForFunctionRedefinition(FD);
9344 
9345   // Builtin functions cannot be defined.
9346   if (unsigned BuiltinID = FD->getBuiltinID()) {
9347     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9348         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
9349       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
9350       FD->setInvalidDecl();
9351     }
9352   }
9353 
9354   // The return type of a function definition must be complete
9355   // (C99 6.9.1p3, C++ [dcl.fct]p6).
9356   QualType ResultType = FD->getResultType();
9357   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
9358       !FD->isInvalidDecl() &&
9359       RequireCompleteType(FD->getLocation(), ResultType,
9360                           diag::err_func_def_incomplete_result))
9361     FD->setInvalidDecl();
9362 
9363   // GNU warning -Wmissing-prototypes:
9364   //   Warn if a global function is defined without a previous
9365   //   prototype declaration. This warning is issued even if the
9366   //   definition itself provides a prototype. The aim is to detect
9367   //   global functions that fail to be declared in header files.
9368   const FunctionDecl *PossibleZeroParamPrototype = 0;
9369   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
9370     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
9371 
9372     if (PossibleZeroParamPrototype) {
9373       // We found a declaration that is not a prototype,
9374       // but that could be a zero-parameter prototype
9375       if (TypeSourceInfo *TI =
9376               PossibleZeroParamPrototype->getTypeSourceInfo()) {
9377         TypeLoc TL = TI->getTypeLoc();
9378         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9379           Diag(PossibleZeroParamPrototype->getLocation(),
9380                diag::note_declaration_not_a_prototype)
9381             << PossibleZeroParamPrototype
9382             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9383       }
9384     }
9385   }
9386 
9387   if (FnBodyScope)
9388     PushDeclContext(FnBodyScope, FD);
9389 
9390   // Check the validity of our function parameters
9391   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9392                            /*CheckParameterNames=*/true);
9393 
9394   // Introduce our parameters into the function scope
9395   for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9396     ParmVarDecl *Param = FD->getParamDecl(p);
9397     Param->setOwningFunction(FD);
9398 
9399     // If this has an identifier, add it to the scope stack.
9400     if (Param->getIdentifier() && FnBodyScope) {
9401       CheckShadow(FnBodyScope, Param);
9402 
9403       PushOnScopeChains(Param, FnBodyScope);
9404     }
9405   }
9406 
9407   // If we had any tags defined in the function prototype,
9408   // introduce them into the function scope.
9409   if (FnBodyScope) {
9410     for (ArrayRef<NamedDecl *>::iterator
9411              I = FD->getDeclsInPrototypeScope().begin(),
9412              E = FD->getDeclsInPrototypeScope().end();
9413          I != E; ++I) {
9414       NamedDecl *D = *I;
9415 
9416       // Some of these decls (like enums) may have been pinned to the translation unit
9417       // for lack of a real context earlier. If so, remove from the translation unit
9418       // and reattach to the current context.
9419       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9420         // Is the decl actually in the context?
9421         for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9422                DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9423           if (*DI == D) {
9424             Context.getTranslationUnitDecl()->removeDecl(D);
9425             break;
9426           }
9427         }
9428         // Either way, reassign the lexical decl context to our FunctionDecl.
9429         D->setLexicalDeclContext(CurContext);
9430       }
9431 
9432       // If the decl has a non-null name, make accessible in the current scope.
9433       if (!D->getName().empty())
9434         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9435 
9436       // Similarly, dive into enums and fish their constants out, making them
9437       // accessible in this scope.
9438       if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9439         for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9440                EE = ED->enumerator_end(); EI != EE; ++EI)
9441           PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
9442       }
9443     }
9444   }
9445 
9446   // Ensure that the function's exception specification is instantiated.
9447   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9448     ResolveExceptionSpec(D->getLocation(), FPT);
9449 
9450   // Checking attributes of current function definition
9451   // dllimport attribute.
9452   DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9453   if (DA && (!FD->getAttr<DLLExportAttr>())) {
9454     // dllimport attribute cannot be directly applied to definition.
9455     // Microsoft accepts dllimport for functions defined within class scope.
9456     if (!DA->isInherited() &&
9457         !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
9458       Diag(FD->getLocation(),
9459            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9460         << "dllimport";
9461       FD->setInvalidDecl();
9462       return D;
9463     }
9464 
9465     // Visual C++ appears to not think this is an issue, so only issue
9466     // a warning when Microsoft extensions are disabled.
9467     if (!LangOpts.MicrosoftExt) {
9468       // If a symbol previously declared dllimport is later defined, the
9469       // attribute is ignored in subsequent references, and a warning is
9470       // emitted.
9471       Diag(FD->getLocation(),
9472            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
9473         << FD->getName() << "dllimport";
9474     }
9475   }
9476   // We want to attach documentation to original Decl (which might be
9477   // a function template).
9478   ActOnDocumentableDecl(D);
9479   return D;
9480 }
9481 
9482 /// \brief Given the set of return statements within a function body,
9483 /// compute the variables that are subject to the named return value
9484 /// optimization.
9485 ///
9486 /// Each of the variables that is subject to the named return value
9487 /// optimization will be marked as NRVO variables in the AST, and any
9488 /// return statement that has a marked NRVO variable as its NRVO candidate can
9489 /// use the named return value optimization.
9490 ///
9491 /// This function applies a very simplistic algorithm for NRVO: if every return
9492 /// statement in the function has the same NRVO candidate, that candidate is
9493 /// the NRVO variable.
9494 ///
9495 /// FIXME: Employ a smarter algorithm that accounts for multiple return
9496 /// statements and the lifetimes of the NRVO candidates. We should be able to
9497 /// find a maximal set of NRVO variables.
9498 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
9499   ReturnStmt **Returns = Scope->Returns.data();
9500 
9501   const VarDecl *NRVOCandidate = 0;
9502   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
9503     if (!Returns[I]->getNRVOCandidate())
9504       return;
9505 
9506     if (!NRVOCandidate)
9507       NRVOCandidate = Returns[I]->getNRVOCandidate();
9508     else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9509       return;
9510   }
9511 
9512   if (NRVOCandidate)
9513     const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9514 }
9515 
9516 bool Sema::canSkipFunctionBody(Decl *D) {
9517   if (!Consumer.shouldSkipFunctionBody(D))
9518     return false;
9519 
9520   if (isa<ObjCMethodDecl>(D))
9521     return true;
9522 
9523   FunctionDecl *FD = 0;
9524   if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9525     FD = FTD->getTemplatedDecl();
9526   else
9527     FD = cast<FunctionDecl>(D);
9528 
9529   // We cannot skip the body of a function (or function template) which is
9530   // constexpr, since we may need to evaluate its body in order to parse the
9531   // rest of the file.
9532   // We cannot skip the body of a function with an undeduced return type,
9533   // because any callers of that function need to know the type.
9534   return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
9535 }
9536 
9537 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
9538   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
9539     FD->setHasSkippedBody();
9540   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
9541     MD->setHasSkippedBody();
9542   return ActOnFinishFunctionBody(Decl, 0);
9543 }
9544 
9545 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
9546   return ActOnFinishFunctionBody(D, BodyArg, false);
9547 }
9548 
9549 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9550                                     bool IsInstantiation) {
9551   FunctionDecl *FD = 0;
9552   FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9553   if (FunTmpl)
9554     FD = FunTmpl->getTemplatedDecl();
9555   else
9556     FD = dyn_cast_or_null<FunctionDecl>(dcl);
9557 
9558   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
9559   sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
9560 
9561   if (FD) {
9562     FD->setBody(Body);
9563 
9564     if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9565         !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9566       // If the function has a deduced result type but contains no 'return'
9567       // statements, the result type as written must be exactly 'auto', and
9568       // the deduced result type is 'void'.
9569       if (!FD->getResultType()->getAs<AutoType>()) {
9570         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9571           << FD->getResultType();
9572         FD->setInvalidDecl();
9573       } else {
9574         // Substitute 'void' for the 'auto' in the type.
9575         TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9576             IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9577         Context.adjustDeducedFunctionResultType(
9578             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
9579       }
9580     }
9581 
9582     // The only way to be included in UndefinedButUsed is if there is an
9583     // ODR use before the definition. Avoid the expensive map lookup if this
9584     // is the first declaration.
9585     if (FD->getPreviousDecl() != 0 && FD->getPreviousDecl()->isUsed()) {
9586       if (!FD->isExternallyVisible())
9587         UndefinedButUsed.erase(FD);
9588       else if (FD->isInlined() &&
9589                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9590                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9591         UndefinedButUsed.erase(FD);
9592     }
9593 
9594     // If the function implicitly returns zero (like 'main') or is naked,
9595     // don't complain about missing return statements.
9596     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
9597       WP.disableCheckFallThrough();
9598 
9599     // MSVC permits the use of pure specifier (=0) on function definition,
9600     // defined at class scope, warn about this non standard construct.
9601     if (getLangOpts().MicrosoftExt && FD->isPure())
9602       Diag(FD->getLocation(), diag::warn_pure_function_definition);
9603 
9604     if (!FD->isInvalidDecl()) {
9605       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
9606       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9607                                              FD->getResultType(), FD);
9608 
9609       // If this is a constructor, we need a vtable.
9610       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9611         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
9612 
9613       // Try to apply the named return value optimization. We have to check
9614       // if we can do this here because lambdas keep return statements around
9615       // to deduce an implicit return type.
9616       if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9617           !FD->isDependentContext())
9618         computeNRVO(Body, getCurFunction());
9619     }
9620 
9621     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9622            "Function parsing confused");
9623   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
9624     assert(MD == getCurMethodDecl() && "Method parsing confused");
9625     MD->setBody(Body);
9626     if (!MD->isInvalidDecl()) {
9627       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
9628       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9629                                              MD->getResultType(), MD);
9630 
9631       if (Body)
9632         computeNRVO(Body, getCurFunction());
9633     }
9634     if (getCurFunction()->ObjCShouldCallSuper) {
9635       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9636         << MD->getSelector().getAsString();
9637       getCurFunction()->ObjCShouldCallSuper = false;
9638     }
9639   } else {
9640     return 0;
9641   }
9642 
9643   assert(!getCurFunction()->ObjCShouldCallSuper &&
9644          "This should only be set for ObjC methods, which should have been "
9645          "handled in the block above.");
9646 
9647   // Verify and clean out per-function state.
9648   if (Body) {
9649     // C++ constructors that have function-try-blocks can't have return
9650     // statements in the handlers of that block. (C++ [except.handle]p14)
9651     // Verify this.
9652     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9653       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9654 
9655     // Verify that gotos and switch cases don't jump into scopes illegally.
9656     if (getCurFunction()->NeedsScopeChecking() &&
9657         !dcl->isInvalidDecl() &&
9658         !hasAnyUnrecoverableErrorsInThisFunction() &&
9659         !PP.isCodeCompletionEnabled())
9660       DiagnoseInvalidJumps(Body);
9661 
9662     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9663       if (!Destructor->getParent()->isDependentType())
9664         CheckDestructor(Destructor);
9665 
9666       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9667                                              Destructor->getParent());
9668     }
9669 
9670     // If any errors have occurred, clear out any temporaries that may have
9671     // been leftover. This ensures that these temporaries won't be picked up for
9672     // deletion in some later function.
9673     if (PP.getDiagnostics().hasErrorOccurred() ||
9674         PP.getDiagnostics().getSuppressAllDiagnostics()) {
9675       DiscardCleanupsInEvaluationContext();
9676     }
9677     if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9678         !isa<FunctionTemplateDecl>(dcl)) {
9679       // Since the body is valid, issue any analysis-based warnings that are
9680       // enabled.
9681       ActivePolicy = &WP;
9682     }
9683 
9684     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9685         (!CheckConstexprFunctionDecl(FD) ||
9686          !CheckConstexprFunctionBody(FD, Body)))
9687       FD->setInvalidDecl();
9688 
9689     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
9690     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
9691     assert(MaybeODRUseExprs.empty() &&
9692            "Leftover expressions for odr-use checking");
9693   }
9694 
9695   if (!IsInstantiation)
9696     PopDeclContext();
9697 
9698   PopFunctionScopeInfo(ActivePolicy, dcl);
9699 
9700   // If any errors have occurred, clear out any temporaries that may have
9701   // been leftover. This ensures that these temporaries won't be picked up for
9702   // deletion in some later function.
9703   if (getDiagnostics().hasErrorOccurred()) {
9704     DiscardCleanupsInEvaluationContext();
9705   }
9706 
9707   return dcl;
9708 }
9709 
9710 
9711 /// When we finish delayed parsing of an attribute, we must attach it to the
9712 /// relevant Decl.
9713 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9714                                        ParsedAttributes &Attrs) {
9715   // Always attach attributes to the underlying decl.
9716   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9717     D = TD->getTemplatedDecl();
9718   ProcessDeclAttributeList(S, D, Attrs.getList());
9719 
9720   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9721     if (Method->isStatic())
9722       checkThisInStaticMemberFunctionAttributes(Method);
9723 }
9724 
9725 
9726 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9727 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
9728 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
9729                                           IdentifierInfo &II, Scope *S) {
9730   // Before we produce a declaration for an implicitly defined
9731   // function, see whether there was a locally-scoped declaration of
9732   // this name as a function or variable. If so, use that
9733   // (non-visible) declaration, and complain about it.
9734   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9735     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9736     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9737     return ExternCPrev;
9738   }
9739 
9740   // Extension in C99.  Legal in C90, but warn about it.
9741   unsigned diag_id;
9742   if (II.getName().startswith("__builtin_"))
9743     diag_id = diag::warn_builtin_unknown;
9744   else if (getLangOpts().C99)
9745     diag_id = diag::ext_implicit_function_decl;
9746   else
9747     diag_id = diag::warn_implicit_function_decl;
9748   Diag(Loc, diag_id) << &II;
9749 
9750   // Because typo correction is expensive, only do it if the implicit
9751   // function declaration is going to be treated as an error.
9752   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9753     TypoCorrection Corrected;
9754     DeclFilterCCC<FunctionDecl> Validator;
9755     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
9756                                       LookupOrdinaryName, S, 0, Validator)))
9757       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9758                    /*ErrorRecovery*/false);
9759   }
9760 
9761   // Set a Declarator for the implicit definition: int foo();
9762   const char *Dummy;
9763   AttributeFactory attrFactory;
9764   DeclSpec DS(attrFactory);
9765   unsigned DiagID;
9766   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
9767   (void)Error; // Silence warning.
9768   assert(!Error && "Error setting up implicit decl!");
9769   SourceLocation NoLoc;
9770   Declarator D(DS, Declarator::BlockContext);
9771   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9772                                              /*IsAmbiguous=*/false,
9773                                              /*RParenLoc=*/NoLoc,
9774                                              /*ArgInfo=*/0,
9775                                              /*NumArgs=*/0,
9776                                              /*EllipsisLoc=*/NoLoc,
9777                                              /*RParenLoc=*/NoLoc,
9778                                              /*TypeQuals=*/0,
9779                                              /*RefQualifierIsLvalueRef=*/true,
9780                                              /*RefQualifierLoc=*/NoLoc,
9781                                              /*ConstQualifierLoc=*/NoLoc,
9782                                              /*VolatileQualifierLoc=*/NoLoc,
9783                                              /*MutableLoc=*/NoLoc,
9784                                              EST_None,
9785                                              /*ESpecLoc=*/NoLoc,
9786                                              /*Exceptions=*/0,
9787                                              /*ExceptionRanges=*/0,
9788                                              /*NumExceptions=*/0,
9789                                              /*NoexceptExpr=*/0,
9790                                              Loc, Loc, D),
9791                 DS.getAttributes(),
9792                 SourceLocation());
9793   D.SetIdentifier(&II, Loc);
9794 
9795   // Insert this function into translation-unit scope.
9796 
9797   DeclContext *PrevDC = CurContext;
9798   CurContext = Context.getTranslationUnitDecl();
9799 
9800   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
9801   FD->setImplicit();
9802 
9803   CurContext = PrevDC;
9804 
9805   AddKnownFunctionAttributes(FD);
9806 
9807   return FD;
9808 }
9809 
9810 /// \brief Adds any function attributes that we know a priori based on
9811 /// the declaration of this function.
9812 ///
9813 /// These attributes can apply both to implicitly-declared builtins
9814 /// (like __builtin___printf_chk) or to library-declared functions
9815 /// like NSLog or printf.
9816 ///
9817 /// We need to check for duplicate attributes both here and where user-written
9818 /// attributes are applied to declarations.
9819 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9820   if (FD->isInvalidDecl())
9821     return;
9822 
9823   // If this is a built-in function, map its builtin attributes to
9824   // actual attributes.
9825   if (unsigned BuiltinID = FD->getBuiltinID()) {
9826     // Handle printf-formatting attributes.
9827     unsigned FormatIdx;
9828     bool HasVAListArg;
9829     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
9830       if (!FD->getAttr<FormatAttr>()) {
9831         const char *fmt = "printf";
9832         unsigned int NumParams = FD->getNumParams();
9833         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
9834             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
9835           fmt = "NSString";
9836         FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9837                                                &Context.Idents.get(fmt),
9838                                                FormatIdx+1,
9839                                                HasVAListArg ? 0 : FormatIdx+2));
9840       }
9841     }
9842     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
9843                                              HasVAListArg)) {
9844      if (!FD->getAttr<FormatAttr>())
9845        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9846                                               &Context.Idents.get("scanf"),
9847                                               FormatIdx+1,
9848                                               HasVAListArg ? 0 : FormatIdx+2));
9849     }
9850 
9851     // Mark const if we don't care about errno and that is the only
9852     // thing preventing the function from being const. This allows
9853     // IRgen to use LLVM intrinsics for such functions.
9854     if (!getLangOpts().MathErrno &&
9855         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
9856       if (!FD->getAttr<ConstAttr>())
9857         FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
9858     }
9859 
9860     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
9861         !FD->getAttr<ReturnsTwiceAttr>())
9862       FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
9863     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
9864       FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
9865     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
9866       FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
9867   }
9868 
9869   IdentifierInfo *Name = FD->getIdentifier();
9870   if (!Name)
9871     return;
9872   if ((!getLangOpts().CPlusPlus &&
9873        FD->getDeclContext()->isTranslationUnit()) ||
9874       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
9875        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
9876        LinkageSpecDecl::lang_c)) {
9877     // Okay: this could be a libc/libm/Objective-C function we know
9878     // about.
9879   } else
9880     return;
9881 
9882   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
9883     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
9884     // target-specific builtins, perhaps?
9885     if (!FD->getAttr<FormatAttr>())
9886       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9887                                              &Context.Idents.get("printf"), 2,
9888                                              Name->isStr("vasprintf") ? 0 : 3));
9889   }
9890 
9891   if (Name->isStr("__CFStringMakeConstantString")) {
9892     // We already have a __builtin___CFStringMakeConstantString,
9893     // but builds that use -fno-constant-cfstrings don't go through that.
9894     if (!FD->getAttr<FormatArgAttr>())
9895       FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
9896   }
9897 }
9898 
9899 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
9900                                     TypeSourceInfo *TInfo) {
9901   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
9902   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
9903 
9904   if (!TInfo) {
9905     assert(D.isInvalidType() && "no declarator info for valid type");
9906     TInfo = Context.getTrivialTypeSourceInfo(T);
9907   }
9908 
9909   // Scope manipulation handled by caller.
9910   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
9911                                            D.getLocStart(),
9912                                            D.getIdentifierLoc(),
9913                                            D.getIdentifier(),
9914                                            TInfo);
9915 
9916   // Bail out immediately if we have an invalid declaration.
9917   if (D.isInvalidType()) {
9918     NewTD->setInvalidDecl();
9919     return NewTD;
9920   }
9921 
9922   if (D.getDeclSpec().isModulePrivateSpecified()) {
9923     if (CurContext->isFunctionOrMethod())
9924       Diag(NewTD->getLocation(), diag::err_module_private_local)
9925         << 2 << NewTD->getDeclName()
9926         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9927         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9928     else
9929       NewTD->setModulePrivate();
9930   }
9931 
9932   // C++ [dcl.typedef]p8:
9933   //   If the typedef declaration defines an unnamed class (or
9934   //   enum), the first typedef-name declared by the declaration
9935   //   to be that class type (or enum type) is used to denote the
9936   //   class type (or enum type) for linkage purposes only.
9937   // We need to check whether the type was declared in the declaration.
9938   switch (D.getDeclSpec().getTypeSpecType()) {
9939   case TST_enum:
9940   case TST_struct:
9941   case TST_interface:
9942   case TST_union:
9943   case TST_class: {
9944     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
9945 
9946     // Do nothing if the tag is not anonymous or already has an
9947     // associated typedef (from an earlier typedef in this decl group).
9948     if (tagFromDeclSpec->getIdentifier()) break;
9949     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
9950 
9951     // A well-formed anonymous tag must always be a TUK_Definition.
9952     assert(tagFromDeclSpec->isThisDeclarationADefinition());
9953 
9954     // The type must match the tag exactly;  no qualifiers allowed.
9955     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
9956       break;
9957 
9958     // Otherwise, set this is the anon-decl typedef for the tag.
9959     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
9960     break;
9961   }
9962 
9963   default:
9964     break;
9965   }
9966 
9967   return NewTD;
9968 }
9969 
9970 
9971 /// \brief Check that this is a valid underlying type for an enum declaration.
9972 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
9973   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
9974   QualType T = TI->getType();
9975 
9976   if (T->isDependentType())
9977     return false;
9978 
9979   if (const BuiltinType *BT = T->getAs<BuiltinType>())
9980     if (BT->isInteger())
9981       return false;
9982 
9983   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
9984   return true;
9985 }
9986 
9987 /// Check whether this is a valid redeclaration of a previous enumeration.
9988 /// \return true if the redeclaration was invalid.
9989 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
9990                                   QualType EnumUnderlyingTy,
9991                                   const EnumDecl *Prev) {
9992   bool IsFixed = !EnumUnderlyingTy.isNull();
9993 
9994   if (IsScoped != Prev->isScoped()) {
9995     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
9996       << Prev->isScoped();
9997     Diag(Prev->getLocation(), diag::note_previous_use);
9998     return true;
9999   }
10000 
10001   if (IsFixed && Prev->isFixed()) {
10002     if (!EnumUnderlyingTy->isDependentType() &&
10003         !Prev->getIntegerType()->isDependentType() &&
10004         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10005                                         Prev->getIntegerType())) {
10006       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10007         << EnumUnderlyingTy << Prev->getIntegerType();
10008       Diag(Prev->getLocation(), diag::note_previous_use);
10009       return true;
10010     }
10011   } else if (IsFixed != Prev->isFixed()) {
10012     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10013       << Prev->isFixed();
10014     Diag(Prev->getLocation(), diag::note_previous_use);
10015     return true;
10016   }
10017 
10018   return false;
10019 }
10020 
10021 /// \brief Get diagnostic %select index for tag kind for
10022 /// redeclaration diagnostic message.
10023 /// WARNING: Indexes apply to particular diagnostics only!
10024 ///
10025 /// \returns diagnostic %select index.
10026 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10027   switch (Tag) {
10028   case TTK_Struct: return 0;
10029   case TTK_Interface: return 1;
10030   case TTK_Class:  return 2;
10031   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10032   }
10033 }
10034 
10035 /// \brief Determine if tag kind is a class-key compatible with
10036 /// class for redeclaration (class, struct, or __interface).
10037 ///
10038 /// \returns true iff the tag kind is compatible.
10039 static bool isClassCompatTagKind(TagTypeKind Tag)
10040 {
10041   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10042 }
10043 
10044 /// \brief Determine whether a tag with a given kind is acceptable
10045 /// as a redeclaration of the given tag declaration.
10046 ///
10047 /// \returns true if the new tag kind is acceptable, false otherwise.
10048 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10049                                         TagTypeKind NewTag, bool isDefinition,
10050                                         SourceLocation NewTagLoc,
10051                                         const IdentifierInfo &Name) {
10052   // C++ [dcl.type.elab]p3:
10053   //   The class-key or enum keyword present in the
10054   //   elaborated-type-specifier shall agree in kind with the
10055   //   declaration to which the name in the elaborated-type-specifier
10056   //   refers. This rule also applies to the form of
10057   //   elaborated-type-specifier that declares a class-name or
10058   //   friend class since it can be construed as referring to the
10059   //   definition of the class. Thus, in any
10060   //   elaborated-type-specifier, the enum keyword shall be used to
10061   //   refer to an enumeration (7.2), the union class-key shall be
10062   //   used to refer to a union (clause 9), and either the class or
10063   //   struct class-key shall be used to refer to a class (clause 9)
10064   //   declared using the class or struct class-key.
10065   TagTypeKind OldTag = Previous->getTagKind();
10066   if (!isDefinition || !isClassCompatTagKind(NewTag))
10067     if (OldTag == NewTag)
10068       return true;
10069 
10070   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10071     // Warn about the struct/class tag mismatch.
10072     bool isTemplate = false;
10073     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10074       isTemplate = Record->getDescribedClassTemplate();
10075 
10076     if (!ActiveTemplateInstantiations.empty()) {
10077       // In a template instantiation, do not offer fix-its for tag mismatches
10078       // since they usually mess up the template instead of fixing the problem.
10079       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10080         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10081         << getRedeclDiagFromTagKind(OldTag);
10082       return true;
10083     }
10084 
10085     if (isDefinition) {
10086       // On definitions, check previous tags and issue a fix-it for each
10087       // one that doesn't match the current tag.
10088       if (Previous->getDefinition()) {
10089         // Don't suggest fix-its for redefinitions.
10090         return true;
10091       }
10092 
10093       bool previousMismatch = false;
10094       for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10095            E(Previous->redecls_end()); I != E; ++I) {
10096         if (I->getTagKind() != NewTag) {
10097           if (!previousMismatch) {
10098             previousMismatch = true;
10099             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10100               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10101               << getRedeclDiagFromTagKind(I->getTagKind());
10102           }
10103           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10104             << getRedeclDiagFromTagKind(NewTag)
10105             << FixItHint::CreateReplacement(I->getInnerLocStart(),
10106                  TypeWithKeyword::getTagTypeKindName(NewTag));
10107         }
10108       }
10109       return true;
10110     }
10111 
10112     // Check for a previous definition.  If current tag and definition
10113     // are same type, do nothing.  If no definition, but disagree with
10114     // with previous tag type, give a warning, but no fix-it.
10115     const TagDecl *Redecl = Previous->getDefinition() ?
10116                             Previous->getDefinition() : Previous;
10117     if (Redecl->getTagKind() == NewTag) {
10118       return true;
10119     }
10120 
10121     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10122       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10123       << getRedeclDiagFromTagKind(OldTag);
10124     Diag(Redecl->getLocation(), diag::note_previous_use);
10125 
10126     // If there is a previous defintion, suggest a fix-it.
10127     if (Previous->getDefinition()) {
10128         Diag(NewTagLoc, diag::note_struct_class_suggestion)
10129           << getRedeclDiagFromTagKind(Redecl->getTagKind())
10130           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10131                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10132     }
10133 
10134     return true;
10135   }
10136   return false;
10137 }
10138 
10139 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10140 /// former case, Name will be non-null.  In the later case, Name will be null.
10141 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10142 /// reference/declaration/definition of a tag.
10143 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10144                      SourceLocation KWLoc, CXXScopeSpec &SS,
10145                      IdentifierInfo *Name, SourceLocation NameLoc,
10146                      AttributeList *Attr, AccessSpecifier AS,
10147                      SourceLocation ModulePrivateLoc,
10148                      MultiTemplateParamsArg TemplateParameterLists,
10149                      bool &OwnedDecl, bool &IsDependent,
10150                      SourceLocation ScopedEnumKWLoc,
10151                      bool ScopedEnumUsesClassTag,
10152                      TypeResult UnderlyingType) {
10153   // If this is not a definition, it must have a name.
10154   IdentifierInfo *OrigName = Name;
10155   assert((Name != 0 || TUK == TUK_Definition) &&
10156          "Nameless record must be a definition!");
10157   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10158 
10159   OwnedDecl = false;
10160   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10161   bool ScopedEnum = ScopedEnumKWLoc.isValid();
10162 
10163   // FIXME: Check explicit specializations more carefully.
10164   bool isExplicitSpecialization = false;
10165   bool Invalid = false;
10166 
10167   // We only need to do this matching if we have template parameters
10168   // or a scope specifier, which also conveniently avoids this work
10169   // for non-C++ cases.
10170   if (TemplateParameterLists.size() > 0 ||
10171       (SS.isNotEmpty() && TUK != TUK_Reference)) {
10172     if (TemplateParameterList *TemplateParams =
10173             MatchTemplateParametersToScopeSpecifier(
10174                 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10175                 isExplicitSpecialization, Invalid)) {
10176       if (Kind == TTK_Enum) {
10177         Diag(KWLoc, diag::err_enum_template);
10178         return 0;
10179       }
10180 
10181       if (TemplateParams->size() > 0) {
10182         // This is a declaration or definition of a class template (which may
10183         // be a member of another template).
10184 
10185         if (Invalid)
10186           return 0;
10187 
10188         OwnedDecl = false;
10189         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
10190                                                SS, Name, NameLoc, Attr,
10191                                                TemplateParams, AS,
10192                                                ModulePrivateLoc,
10193                                                TemplateParameterLists.size()-1,
10194                                                TemplateParameterLists.data());
10195         return Result.get();
10196       } else {
10197         // The "template<>" header is extraneous.
10198         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10199           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10200         isExplicitSpecialization = true;
10201       }
10202     }
10203   }
10204 
10205   // Figure out the underlying type if this a enum declaration. We need to do
10206   // this early, because it's needed to detect if this is an incompatible
10207   // redeclaration.
10208   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10209 
10210   if (Kind == TTK_Enum) {
10211     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10212       // No underlying type explicitly specified, or we failed to parse the
10213       // type, default to int.
10214       EnumUnderlying = Context.IntTy.getTypePtr();
10215     else if (UnderlyingType.get()) {
10216       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10217       // integral type; any cv-qualification is ignored.
10218       TypeSourceInfo *TI = 0;
10219       GetTypeFromParser(UnderlyingType.get(), &TI);
10220       EnumUnderlying = TI;
10221 
10222       if (CheckEnumUnderlyingType(TI))
10223         // Recover by falling back to int.
10224         EnumUnderlying = Context.IntTy.getTypePtr();
10225 
10226       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
10227                                           UPPC_FixedUnderlyingType))
10228         EnumUnderlying = Context.IntTy.getTypePtr();
10229 
10230     } else if (getLangOpts().MicrosoftMode)
10231       // Microsoft enums are always of int type.
10232       EnumUnderlying = Context.IntTy.getTypePtr();
10233   }
10234 
10235   DeclContext *SearchDC = CurContext;
10236   DeclContext *DC = CurContext;
10237   bool isStdBadAlloc = false;
10238 
10239   RedeclarationKind Redecl = ForRedeclaration;
10240   if (TUK == TUK_Friend || TUK == TUK_Reference)
10241     Redecl = NotForRedeclaration;
10242 
10243   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
10244   bool FriendSawTagOutsideEnclosingNamespace = false;
10245   if (Name && SS.isNotEmpty()) {
10246     // We have a nested-name tag ('struct foo::bar').
10247 
10248     // Check for invalid 'foo::'.
10249     if (SS.isInvalid()) {
10250       Name = 0;
10251       goto CreateNewDecl;
10252     }
10253 
10254     // If this is a friend or a reference to a class in a dependent
10255     // context, don't try to make a decl for it.
10256     if (TUK == TUK_Friend || TUK == TUK_Reference) {
10257       DC = computeDeclContext(SS, false);
10258       if (!DC) {
10259         IsDependent = true;
10260         return 0;
10261       }
10262     } else {
10263       DC = computeDeclContext(SS, true);
10264       if (!DC) {
10265         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10266           << SS.getRange();
10267         return 0;
10268       }
10269     }
10270 
10271     if (RequireCompleteDeclContext(SS, DC))
10272       return 0;
10273 
10274     SearchDC = DC;
10275     // Look-up name inside 'foo::'.
10276     LookupQualifiedName(Previous, DC);
10277 
10278     if (Previous.isAmbiguous())
10279       return 0;
10280 
10281     if (Previous.empty()) {
10282       // Name lookup did not find anything. However, if the
10283       // nested-name-specifier refers to the current instantiation,
10284       // and that current instantiation has any dependent base
10285       // classes, we might find something at instantiation time: treat
10286       // this as a dependent elaborated-type-specifier.
10287       // But this only makes any sense for reference-like lookups.
10288       if (Previous.wasNotFoundInCurrentInstantiation() &&
10289           (TUK == TUK_Reference || TUK == TUK_Friend)) {
10290         IsDependent = true;
10291         return 0;
10292       }
10293 
10294       // A tag 'foo::bar' must already exist.
10295       Diag(NameLoc, diag::err_not_tag_in_scope)
10296         << Kind << Name << DC << SS.getRange();
10297       Name = 0;
10298       Invalid = true;
10299       goto CreateNewDecl;
10300     }
10301   } else if (Name) {
10302     // If this is a named struct, check to see if there was a previous forward
10303     // declaration or definition.
10304     // FIXME: We're looking into outer scopes here, even when we
10305     // shouldn't be. Doing so can result in ambiguities that we
10306     // shouldn't be diagnosing.
10307     LookupName(Previous, S);
10308 
10309     // When declaring or defining a tag, ignore ambiguities introduced
10310     // by types using'ed into this scope.
10311     if (Previous.isAmbiguous() &&
10312         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
10313       LookupResult::Filter F = Previous.makeFilter();
10314       while (F.hasNext()) {
10315         NamedDecl *ND = F.next();
10316         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10317           F.erase();
10318       }
10319       F.done();
10320     }
10321 
10322     // C++11 [namespace.memdef]p3:
10323     //   If the name in a friend declaration is neither qualified nor
10324     //   a template-id and the declaration is a function or an
10325     //   elaborated-type-specifier, the lookup to determine whether
10326     //   the entity has been previously declared shall not consider
10327     //   any scopes outside the innermost enclosing namespace.
10328     //
10329     // Does it matter that this should be by scope instead of by
10330     // semantic context?
10331     if (!Previous.empty() && TUK == TUK_Friend) {
10332       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10333       LookupResult::Filter F = Previous.makeFilter();
10334       while (F.hasNext()) {
10335         NamedDecl *ND = F.next();
10336         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10337         if (DC->isFileContext() &&
10338             !EnclosingNS->Encloses(ND->getDeclContext())) {
10339           F.erase();
10340           FriendSawTagOutsideEnclosingNamespace = true;
10341         }
10342       }
10343       F.done();
10344     }
10345 
10346     // Note:  there used to be some attempt at recovery here.
10347     if (Previous.isAmbiguous())
10348       return 0;
10349 
10350     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
10351       // FIXME: This makes sure that we ignore the contexts associated
10352       // with C structs, unions, and enums when looking for a matching
10353       // tag declaration or definition. See the similar lookup tweak
10354       // in Sema::LookupName; is there a better way to deal with this?
10355       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10356         SearchDC = SearchDC->getParent();
10357     }
10358   } else if (S->isFunctionPrototypeScope()) {
10359     // If this is an enum declaration in function prototype scope, set its
10360     // initial context to the translation unit.
10361     // FIXME: [citation needed]
10362     SearchDC = Context.getTranslationUnitDecl();
10363   }
10364 
10365   if (Previous.isSingleResult() &&
10366       Previous.getFoundDecl()->isTemplateParameter()) {
10367     // Maybe we will complain about the shadowed template parameter.
10368     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
10369     // Just pretend that we didn't see the previous declaration.
10370     Previous.clear();
10371   }
10372 
10373   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
10374       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
10375     // This is a declaration of or a reference to "std::bad_alloc".
10376     isStdBadAlloc = true;
10377 
10378     if (Previous.empty() && StdBadAlloc) {
10379       // std::bad_alloc has been implicitly declared (but made invisible to
10380       // name lookup). Fill in this implicit declaration as the previous
10381       // declaration, so that the declarations get chained appropriately.
10382       Previous.addDecl(getStdBadAlloc());
10383     }
10384   }
10385 
10386   // If we didn't find a previous declaration, and this is a reference
10387   // (or friend reference), move to the correct scope.  In C++, we
10388   // also need to do a redeclaration lookup there, just in case
10389   // there's a shadow friend decl.
10390   if (Name && Previous.empty() &&
10391       (TUK == TUK_Reference || TUK == TUK_Friend)) {
10392     if (Invalid) goto CreateNewDecl;
10393     assert(SS.isEmpty());
10394 
10395     if (TUK == TUK_Reference) {
10396       // C++ [basic.scope.pdecl]p5:
10397       //   -- for an elaborated-type-specifier of the form
10398       //
10399       //          class-key identifier
10400       //
10401       //      if the elaborated-type-specifier is used in the
10402       //      decl-specifier-seq or parameter-declaration-clause of a
10403       //      function defined in namespace scope, the identifier is
10404       //      declared as a class-name in the namespace that contains
10405       //      the declaration; otherwise, except as a friend
10406       //      declaration, the identifier is declared in the smallest
10407       //      non-class, non-function-prototype scope that contains the
10408       //      declaration.
10409       //
10410       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10411       // C structs and unions.
10412       //
10413       // It is an error in C++ to declare (rather than define) an enum
10414       // type, including via an elaborated type specifier.  We'll
10415       // diagnose that later; for now, declare the enum in the same
10416       // scope as we would have picked for any other tag type.
10417       //
10418       // GNU C also supports this behavior as part of its incomplete
10419       // enum types extension, while GNU C++ does not.
10420       //
10421       // Find the context where we'll be declaring the tag.
10422       // FIXME: We would like to maintain the current DeclContext as the
10423       // lexical context,
10424       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
10425         SearchDC = SearchDC->getParent();
10426 
10427       // Find the scope where we'll be declaring the tag.
10428       while (S->isClassScope() ||
10429              (getLangOpts().CPlusPlus &&
10430               S->isFunctionPrototypeScope()) ||
10431              ((S->getFlags() & Scope::DeclScope) == 0) ||
10432              (S->getEntity() &&
10433               ((DeclContext *)S->getEntity())->isTransparentContext()))
10434         S = S->getParent();
10435     } else {
10436       assert(TUK == TUK_Friend);
10437       // C++ [namespace.memdef]p3:
10438       //   If a friend declaration in a non-local class first declares a
10439       //   class or function, the friend class or function is a member of
10440       //   the innermost enclosing namespace.
10441       SearchDC = SearchDC->getEnclosingNamespaceContext();
10442     }
10443 
10444     // In C++, we need to do a redeclaration lookup to properly
10445     // diagnose some problems.
10446     if (getLangOpts().CPlusPlus) {
10447       Previous.setRedeclarationKind(ForRedeclaration);
10448       LookupQualifiedName(Previous, SearchDC);
10449     }
10450   }
10451 
10452   if (!Previous.empty()) {
10453     NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
10454 
10455     // It's okay to have a tag decl in the same scope as a typedef
10456     // which hides a tag decl in the same scope.  Finding this
10457     // insanity with a redeclaration lookup can only actually happen
10458     // in C++.
10459     //
10460     // This is also okay for elaborated-type-specifiers, which is
10461     // technically forbidden by the current standard but which is
10462     // okay according to the likely resolution of an open issue;
10463     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
10464     if (getLangOpts().CPlusPlus) {
10465       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10466         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10467           TagDecl *Tag = TT->getDecl();
10468           if (Tag->getDeclName() == Name &&
10469               Tag->getDeclContext()->getRedeclContext()
10470                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
10471             PrevDecl = Tag;
10472             Previous.clear();
10473             Previous.addDecl(Tag);
10474             Previous.resolveKind();
10475           }
10476         }
10477       }
10478     }
10479 
10480     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
10481       // If this is a use of a previous tag, or if the tag is already declared
10482       // in the same scope (so that the definition/declaration completes or
10483       // rementions the tag), reuse the decl.
10484       if (TUK == TUK_Reference || TUK == TUK_Friend ||
10485           isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
10486         // Make sure that this wasn't declared as an enum and now used as a
10487         // struct or something similar.
10488         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10489                                           TUK == TUK_Definition, KWLoc,
10490                                           *Name)) {
10491           bool SafeToContinue
10492             = (PrevTagDecl->getTagKind() != TTK_Enum &&
10493                Kind != TTK_Enum);
10494           if (SafeToContinue)
10495             Diag(KWLoc, diag::err_use_with_wrong_tag)
10496               << Name
10497               << FixItHint::CreateReplacement(SourceRange(KWLoc),
10498                                               PrevTagDecl->getKindName());
10499           else
10500             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
10501           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
10502 
10503           if (SafeToContinue)
10504             Kind = PrevTagDecl->getTagKind();
10505           else {
10506             // Recover by making this an anonymous redefinition.
10507             Name = 0;
10508             Previous.clear();
10509             Invalid = true;
10510           }
10511         }
10512 
10513         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10514           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10515 
10516           // If this is an elaborated-type-specifier for a scoped enumeration,
10517           // the 'class' keyword is not necessary and not permitted.
10518           if (TUK == TUK_Reference || TUK == TUK_Friend) {
10519             if (ScopedEnum)
10520               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10521                 << PrevEnum->isScoped()
10522                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10523             return PrevTagDecl;
10524           }
10525 
10526           QualType EnumUnderlyingTy;
10527           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10528             EnumUnderlyingTy = TI->getType();
10529           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10530             EnumUnderlyingTy = QualType(T, 0);
10531 
10532           // All conflicts with previous declarations are recovered by
10533           // returning the previous declaration, unless this is a definition,
10534           // in which case we want the caller to bail out.
10535           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10536                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
10537             return TUK == TUK_Declaration ? PrevTagDecl : 0;
10538         }
10539 
10540         // C++11 [class.mem]p1:
10541         //   A member shall not be declared twice in the member-specification,
10542         //   except that a nested class or member class template can be declared
10543         //   and then later defined.
10544         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10545             S->isDeclScope(PrevDecl)) {
10546           Diag(NameLoc, diag::ext_member_redeclared);
10547           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10548         }
10549 
10550         if (!Invalid) {
10551           // If this is a use, just return the declaration we found.
10552 
10553           // FIXME: In the future, return a variant or some other clue
10554           // for the consumer of this Decl to know it doesn't own it.
10555           // For our current ASTs this shouldn't be a problem, but will
10556           // need to be changed with DeclGroups.
10557           if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
10558                getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
10559             return PrevTagDecl;
10560 
10561           // Diagnose attempts to redefine a tag.
10562           if (TUK == TUK_Definition) {
10563             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
10564               // If we're defining a specialization and the previous definition
10565               // is from an implicit instantiation, don't emit an error
10566               // here; we'll catch this in the general case below.
10567               bool IsExplicitSpecializationAfterInstantiation = false;
10568               if (isExplicitSpecialization) {
10569                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10570                   IsExplicitSpecializationAfterInstantiation =
10571                     RD->getTemplateSpecializationKind() !=
10572                     TSK_ExplicitSpecialization;
10573                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10574                   IsExplicitSpecializationAfterInstantiation =
10575                     ED->getTemplateSpecializationKind() !=
10576                     TSK_ExplicitSpecialization;
10577               }
10578 
10579               if (!IsExplicitSpecializationAfterInstantiation) {
10580                 // A redeclaration in function prototype scope in C isn't
10581                 // visible elsewhere, so merely issue a warning.
10582                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
10583                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10584                 else
10585                   Diag(NameLoc, diag::err_redefinition) << Name;
10586                 Diag(Def->getLocation(), diag::note_previous_definition);
10587                 // If this is a redefinition, recover by making this
10588                 // struct be anonymous, which will make any later
10589                 // references get the previous definition.
10590                 Name = 0;
10591                 Previous.clear();
10592                 Invalid = true;
10593               }
10594             } else {
10595               // If the type is currently being defined, complain
10596               // about a nested redefinition.
10597               const TagType *Tag
10598                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
10599               if (Tag->isBeingDefined()) {
10600                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
10601                 Diag(PrevTagDecl->getLocation(),
10602                      diag::note_previous_definition);
10603                 Name = 0;
10604                 Previous.clear();
10605                 Invalid = true;
10606               }
10607             }
10608 
10609             // Okay, this is definition of a previously declared or referenced
10610             // tag PrevDecl. We're going to create a new Decl for it.
10611           }
10612         }
10613         // If we get here we have (another) forward declaration or we
10614         // have a definition.  Just create a new decl.
10615 
10616       } else {
10617         // If we get here, this is a definition of a new tag type in a nested
10618         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
10619         // new decl/type.  We set PrevDecl to NULL so that the entities
10620         // have distinct types.
10621         Previous.clear();
10622       }
10623       // If we get here, we're going to create a new Decl. If PrevDecl
10624       // is non-NULL, it's a definition of the tag declared by
10625       // PrevDecl. If it's NULL, we have a new definition.
10626 
10627 
10628     // Otherwise, PrevDecl is not a tag, but was found with tag
10629     // lookup.  This is only actually possible in C++, where a few
10630     // things like templates still live in the tag namespace.
10631     } else {
10632       // Use a better diagnostic if an elaborated-type-specifier
10633       // found the wrong kind of type on the first
10634       // (non-redeclaration) lookup.
10635       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10636           !Previous.isForRedeclaration()) {
10637         unsigned Kind = 0;
10638         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10639         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10640         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10641         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10642         Diag(PrevDecl->getLocation(), diag::note_declared_at);
10643         Invalid = true;
10644 
10645       // Otherwise, only diagnose if the declaration is in scope.
10646       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10647                                 isExplicitSpecialization)) {
10648         // do nothing
10649 
10650       // Diagnose implicit declarations introduced by elaborated types.
10651       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10652         unsigned Kind = 0;
10653         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10654         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10655         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10656         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10657         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10658         Invalid = true;
10659 
10660       // Otherwise it's a declaration.  Call out a particularly common
10661       // case here.
10662       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10663         unsigned Kind = 0;
10664         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
10665         Diag(NameLoc, diag::err_tag_definition_of_typedef)
10666           << Name << Kind << TND->getUnderlyingType();
10667         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10668         Invalid = true;
10669 
10670       // Otherwise, diagnose.
10671       } else {
10672         // The tag name clashes with something else in the target scope,
10673         // issue an error and recover by making this tag be anonymous.
10674         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
10675         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10676         Name = 0;
10677         Invalid = true;
10678       }
10679 
10680       // The existing declaration isn't relevant to us; we're in a
10681       // new scope, so clear out the previous declaration.
10682       Previous.clear();
10683     }
10684   }
10685 
10686 CreateNewDecl:
10687 
10688   TagDecl *PrevDecl = 0;
10689   if (Previous.isSingleResult())
10690     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10691 
10692   // If there is an identifier, use the location of the identifier as the
10693   // location of the decl, otherwise use the location of the struct/union
10694   // keyword.
10695   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
10696 
10697   // Otherwise, create a new declaration. If there is a previous
10698   // declaration of the same entity, the two will be linked via
10699   // PrevDecl.
10700   TagDecl *New;
10701 
10702   bool IsForwardReference = false;
10703   if (Kind == TTK_Enum) {
10704     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10705     // enum X { A, B, C } D;    D should chain to X.
10706     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
10707                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
10708                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
10709     // If this is an undefined enum, warn.
10710     if (TUK != TUK_Definition && !Invalid) {
10711       TagDecl *Def;
10712       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10713           cast<EnumDecl>(New)->isFixed()) {
10714         // C++0x: 7.2p2: opaque-enum-declaration.
10715         // Conflicts are diagnosed above. Do nothing.
10716       }
10717       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
10718         Diag(Loc, diag::ext_forward_ref_enum_def)
10719           << New;
10720         Diag(Def->getLocation(), diag::note_previous_definition);
10721       } else {
10722         unsigned DiagID = diag::ext_forward_ref_enum;
10723         if (getLangOpts().MicrosoftMode)
10724           DiagID = diag::ext_ms_forward_ref_enum;
10725         else if (getLangOpts().CPlusPlus)
10726           DiagID = diag::err_forward_ref_enum;
10727         Diag(Loc, DiagID);
10728 
10729         // If this is a forward-declared reference to an enumeration, make a
10730         // note of it; we won't actually be introducing the declaration into
10731         // the declaration context.
10732         if (TUK == TUK_Reference)
10733           IsForwardReference = true;
10734       }
10735     }
10736 
10737     if (EnumUnderlying) {
10738       EnumDecl *ED = cast<EnumDecl>(New);
10739       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10740         ED->setIntegerTypeSourceInfo(TI);
10741       else
10742         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10743       ED->setPromotionType(ED->getIntegerType());
10744     }
10745 
10746   } else {
10747     // struct/union/class
10748 
10749     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10750     // struct X { int A; } D;    D should chain to X.
10751     if (getLangOpts().CPlusPlus) {
10752       // FIXME: Look for a way to use RecordDecl for simple structs.
10753       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10754                                   cast_or_null<CXXRecordDecl>(PrevDecl));
10755 
10756       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
10757         StdBadAlloc = cast<CXXRecordDecl>(New);
10758     } else
10759       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10760                                cast_or_null<RecordDecl>(PrevDecl));
10761   }
10762 
10763   // Maybe add qualifier info.
10764   if (SS.isNotEmpty()) {
10765     if (SS.isSet()) {
10766       // If this is either a declaration or a definition, check the
10767       // nested-name-specifier against the current context. We don't do this
10768       // for explicit specializations, because they have similar checking
10769       // (with more specific diagnostics) in the call to
10770       // CheckMemberSpecialization, below.
10771       if (!isExplicitSpecialization &&
10772           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10773           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10774         Invalid = true;
10775 
10776       New->setQualifierInfo(SS.getWithLocInContext(Context));
10777       if (TemplateParameterLists.size() > 0) {
10778         New->setTemplateParameterListsInfo(Context,
10779                                            TemplateParameterLists.size(),
10780                                            TemplateParameterLists.data());
10781       }
10782     }
10783     else
10784       Invalid = true;
10785   }
10786 
10787   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10788     // Add alignment attributes if necessary; these attributes are checked when
10789     // the ASTContext lays out the structure.
10790     //
10791     // It is important for implementing the correct semantics that this
10792     // happen here (in act on tag decl). The #pragma pack stack is
10793     // maintained as a result of parser callbacks which can occur at
10794     // many points during the parsing of a struct declaration (because
10795     // the #pragma tokens are effectively skipped over during the
10796     // parsing of the struct).
10797     if (TUK == TUK_Definition) {
10798       AddAlignmentAttributesForRecord(RD);
10799       AddMsStructLayoutForRecord(RD);
10800     }
10801   }
10802 
10803   if (ModulePrivateLoc.isValid()) {
10804     if (isExplicitSpecialization)
10805       Diag(New->getLocation(), diag::err_module_private_specialization)
10806         << 2
10807         << FixItHint::CreateRemoval(ModulePrivateLoc);
10808     // __module_private__ does not apply to local classes. However, we only
10809     // diagnose this as an error when the declaration specifiers are
10810     // freestanding. Here, we just ignore the __module_private__.
10811     else if (!SearchDC->isFunctionOrMethod())
10812       New->setModulePrivate();
10813   }
10814 
10815   // If this is a specialization of a member class (of a class template),
10816   // check the specialization.
10817   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
10818     Invalid = true;
10819 
10820   if (Invalid)
10821     New->setInvalidDecl();
10822 
10823   if (Attr)
10824     ProcessDeclAttributeList(S, New, Attr);
10825 
10826   // If we're declaring or defining a tag in function prototype scope
10827   // in C, note that this type can only be used within the function.
10828   if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
10829     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
10830 
10831   // Set the lexical context. If the tag has a C++ scope specifier, the
10832   // lexical context will be different from the semantic context.
10833   New->setLexicalDeclContext(CurContext);
10834 
10835   // Mark this as a friend decl if applicable.
10836   // In Microsoft mode, a friend declaration also acts as a forward
10837   // declaration so we always pass true to setObjectOfFriendDecl to make
10838   // the tag name visible.
10839   if (TUK == TUK_Friend)
10840     New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
10841                                getLangOpts().MicrosoftExt);
10842 
10843   // Set the access specifier.
10844   if (!Invalid && SearchDC->isRecord())
10845     SetMemberAccessSpecifier(New, PrevDecl, AS);
10846 
10847   if (TUK == TUK_Definition)
10848     New->startDefinition();
10849 
10850   // If this has an identifier, add it to the scope stack.
10851   if (TUK == TUK_Friend) {
10852     // We might be replacing an existing declaration in the lookup tables;
10853     // if so, borrow its access specifier.
10854     if (PrevDecl)
10855       New->setAccess(PrevDecl->getAccess());
10856 
10857     DeclContext *DC = New->getDeclContext()->getRedeclContext();
10858     DC->makeDeclVisibleInContext(New);
10859     if (Name) // can be null along some error paths
10860       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10861         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
10862   } else if (Name) {
10863     S = getNonFieldDeclScope(S);
10864     PushOnScopeChains(New, S, !IsForwardReference);
10865     if (IsForwardReference)
10866       SearchDC->makeDeclVisibleInContext(New);
10867 
10868   } else {
10869     CurContext->addDecl(New);
10870   }
10871 
10872   // If this is the C FILE type, notify the AST context.
10873   if (IdentifierInfo *II = New->getIdentifier())
10874     if (!New->isInvalidDecl() &&
10875         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
10876         II->isStr("FILE"))
10877       Context.setFILEDecl(New);
10878 
10879   // If we were in function prototype scope (and not in C++ mode), add this
10880   // tag to the list of decls to inject into the function definition scope.
10881   if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
10882       InFunctionDeclarator && Name)
10883     DeclsInPrototypeScope.push_back(New);
10884 
10885   if (PrevDecl)
10886     mergeDeclAttributes(New, PrevDecl);
10887 
10888   // If there's a #pragma GCC visibility in scope, set the visibility of this
10889   // record.
10890   AddPushedVisibilityAttribute(New);
10891 
10892   OwnedDecl = true;
10893   // In C++, don't return an invalid declaration. We can't recover well from
10894   // the cases where we make the type anonymous.
10895   return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
10896 }
10897 
10898 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
10899   AdjustDeclIfTemplate(TagD);
10900   TagDecl *Tag = cast<TagDecl>(TagD);
10901 
10902   // Enter the tag context.
10903   PushDeclContext(S, Tag);
10904 
10905   ActOnDocumentableDecl(TagD);
10906 
10907   // If there's a #pragma GCC visibility in scope, set the visibility of this
10908   // record.
10909   AddPushedVisibilityAttribute(Tag);
10910 }
10911 
10912 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
10913   assert(isa<ObjCContainerDecl>(IDecl) &&
10914          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
10915   DeclContext *OCD = cast<DeclContext>(IDecl);
10916   assert(getContainingDC(OCD) == CurContext &&
10917       "The next DeclContext should be lexically contained in the current one.");
10918   CurContext = OCD;
10919   return IDecl;
10920 }
10921 
10922 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
10923                                            SourceLocation FinalLoc,
10924                                            SourceLocation LBraceLoc) {
10925   AdjustDeclIfTemplate(TagD);
10926   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
10927 
10928   FieldCollector->StartClass();
10929 
10930   if (!Record->getIdentifier())
10931     return;
10932 
10933   if (FinalLoc.isValid())
10934     Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
10935 
10936   // C++ [class]p2:
10937   //   [...] The class-name is also inserted into the scope of the
10938   //   class itself; this is known as the injected-class-name. For
10939   //   purposes of access checking, the injected-class-name is treated
10940   //   as if it were a public member name.
10941   CXXRecordDecl *InjectedClassName
10942     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
10943                             Record->getLocStart(), Record->getLocation(),
10944                             Record->getIdentifier(),
10945                             /*PrevDecl=*/0,
10946                             /*DelayTypeCreation=*/true);
10947   Context.getTypeDeclType(InjectedClassName, Record);
10948   InjectedClassName->setImplicit();
10949   InjectedClassName->setAccess(AS_public);
10950   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
10951       InjectedClassName->setDescribedClassTemplate(Template);
10952   PushOnScopeChains(InjectedClassName, S);
10953   assert(InjectedClassName->isInjectedClassName() &&
10954          "Broken injected-class-name");
10955 }
10956 
10957 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
10958                                     SourceLocation RBraceLoc) {
10959   AdjustDeclIfTemplate(TagD);
10960   TagDecl *Tag = cast<TagDecl>(TagD);
10961   Tag->setRBraceLoc(RBraceLoc);
10962 
10963   // Make sure we "complete" the definition even it is invalid.
10964   if (Tag->isBeingDefined()) {
10965     assert(Tag->isInvalidDecl() && "We should already have completed it");
10966     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
10967       RD->completeDefinition();
10968   }
10969 
10970   if (isa<CXXRecordDecl>(Tag))
10971     FieldCollector->FinishClass();
10972 
10973   // Exit this scope of this tag's definition.
10974   PopDeclContext();
10975 
10976   if (getCurLexicalContext()->isObjCContainer() &&
10977       Tag->getDeclContext()->isFileContext())
10978     Tag->setTopLevelDeclInObjCContainer();
10979 
10980   // Notify the consumer that we've defined a tag.
10981   if (!Tag->isInvalidDecl())
10982     Consumer.HandleTagDeclDefinition(Tag);
10983 }
10984 
10985 void Sema::ActOnObjCContainerFinishDefinition() {
10986   // Exit this scope of this interface definition.
10987   PopDeclContext();
10988 }
10989 
10990 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
10991   assert(DC == CurContext && "Mismatch of container contexts");
10992   OriginalLexicalContext = DC;
10993   ActOnObjCContainerFinishDefinition();
10994 }
10995 
10996 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
10997   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
10998   OriginalLexicalContext = 0;
10999 }
11000 
11001 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11002   AdjustDeclIfTemplate(TagD);
11003   TagDecl *Tag = cast<TagDecl>(TagD);
11004   Tag->setInvalidDecl();
11005 
11006   // Make sure we "complete" the definition even it is invalid.
11007   if (Tag->isBeingDefined()) {
11008     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11009       RD->completeDefinition();
11010   }
11011 
11012   // We're undoing ActOnTagStartDefinition here, not
11013   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11014   // the FieldCollector.
11015 
11016   PopDeclContext();
11017 }
11018 
11019 // Note that FieldName may be null for anonymous bitfields.
11020 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11021                                 IdentifierInfo *FieldName,
11022                                 QualType FieldTy, bool IsMsStruct,
11023                                 Expr *BitWidth, bool *ZeroWidth) {
11024   // Default to true; that shouldn't confuse checks for emptiness
11025   if (ZeroWidth)
11026     *ZeroWidth = true;
11027 
11028   // C99 6.7.2.1p4 - verify the field type.
11029   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11030   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11031     // Handle incomplete types with specific error.
11032     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11033       return ExprError();
11034     if (FieldName)
11035       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11036         << FieldName << FieldTy << BitWidth->getSourceRange();
11037     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11038       << FieldTy << BitWidth->getSourceRange();
11039   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11040                                              UPPC_BitFieldWidth))
11041     return ExprError();
11042 
11043   // If the bit-width is type- or value-dependent, don't try to check
11044   // it now.
11045   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11046     return Owned(BitWidth);
11047 
11048   llvm::APSInt Value;
11049   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11050   if (ICE.isInvalid())
11051     return ICE;
11052   BitWidth = ICE.take();
11053 
11054   if (Value != 0 && ZeroWidth)
11055     *ZeroWidth = false;
11056 
11057   // Zero-width bitfield is ok for anonymous field.
11058   if (Value == 0 && FieldName)
11059     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11060 
11061   if (Value.isSigned() && Value.isNegative()) {
11062     if (FieldName)
11063       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11064                << FieldName << Value.toString(10);
11065     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11066       << Value.toString(10);
11067   }
11068 
11069   if (!FieldTy->isDependentType()) {
11070     uint64_t TypeSize = Context.getTypeSize(FieldTy);
11071     if (Value.getZExtValue() > TypeSize) {
11072       if (!getLangOpts().CPlusPlus || IsMsStruct) {
11073         if (FieldName)
11074           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11075             << FieldName << (unsigned)Value.getZExtValue()
11076             << (unsigned)TypeSize;
11077 
11078         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11079           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11080       }
11081 
11082       if (FieldName)
11083         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11084           << FieldName << (unsigned)Value.getZExtValue()
11085           << (unsigned)TypeSize;
11086       else
11087         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11088           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11089     }
11090   }
11091 
11092   return Owned(BitWidth);
11093 }
11094 
11095 /// ActOnField - Each field of a C struct/union is passed into this in order
11096 /// to create a FieldDecl object for it.
11097 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11098                        Declarator &D, Expr *BitfieldWidth) {
11099   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11100                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11101                                /*InitStyle=*/ICIS_NoInit, AS_public);
11102   return Res;
11103 }
11104 
11105 /// HandleField - Analyze a field of a C struct or a C++ data member.
11106 ///
11107 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11108                              SourceLocation DeclStart,
11109                              Declarator &D, Expr *BitWidth,
11110                              InClassInitStyle InitStyle,
11111                              AccessSpecifier AS) {
11112   IdentifierInfo *II = D.getIdentifier();
11113   SourceLocation Loc = DeclStart;
11114   if (II) Loc = D.getIdentifierLoc();
11115 
11116   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11117   QualType T = TInfo->getType();
11118   if (getLangOpts().CPlusPlus) {
11119     CheckExtraCXXDefaultArguments(D);
11120 
11121     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11122                                         UPPC_DataMemberType)) {
11123       D.setInvalidType();
11124       T = Context.IntTy;
11125       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11126     }
11127   }
11128 
11129   // TR 18037 does not allow fields to be declared with address spaces.
11130   if (T.getQualifiers().hasAddressSpace()) {
11131     Diag(Loc, diag::err_field_with_address_space);
11132     D.setInvalidType();
11133   }
11134 
11135   // OpenCL 1.2 spec, s6.9 r:
11136   // The event type cannot be used to declare a structure or union field.
11137   if (LangOpts.OpenCL && T->isEventT()) {
11138     Diag(Loc, diag::err_event_t_struct_field);
11139     D.setInvalidType();
11140   }
11141 
11142   DiagnoseFunctionSpecifiers(D.getDeclSpec());
11143 
11144   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11145     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11146          diag::err_invalid_thread)
11147       << DeclSpec::getSpecifierName(TSCS);
11148 
11149   // Check to see if this name was declared as a member previously
11150   NamedDecl *PrevDecl = 0;
11151   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11152   LookupName(Previous, S);
11153   switch (Previous.getResultKind()) {
11154     case LookupResult::Found:
11155     case LookupResult::FoundUnresolvedValue:
11156       PrevDecl = Previous.getAsSingle<NamedDecl>();
11157       break;
11158 
11159     case LookupResult::FoundOverloaded:
11160       PrevDecl = Previous.getRepresentativeDecl();
11161       break;
11162 
11163     case LookupResult::NotFound:
11164     case LookupResult::NotFoundInCurrentInstantiation:
11165     case LookupResult::Ambiguous:
11166       break;
11167   }
11168   Previous.suppressDiagnostics();
11169 
11170   if (PrevDecl && PrevDecl->isTemplateParameter()) {
11171     // Maybe we will complain about the shadowed template parameter.
11172     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11173     // Just pretend that we didn't see the previous declaration.
11174     PrevDecl = 0;
11175   }
11176 
11177   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11178     PrevDecl = 0;
11179 
11180   bool Mutable
11181     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
11182   SourceLocation TSSL = D.getLocStart();
11183   FieldDecl *NewFD
11184     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
11185                      TSSL, AS, PrevDecl, &D);
11186 
11187   if (NewFD->isInvalidDecl())
11188     Record->setInvalidDecl();
11189 
11190   if (D.getDeclSpec().isModulePrivateSpecified())
11191     NewFD->setModulePrivate();
11192 
11193   if (NewFD->isInvalidDecl() && PrevDecl) {
11194     // Don't introduce NewFD into scope; there's already something
11195     // with the same name in the same scope.
11196   } else if (II) {
11197     PushOnScopeChains(NewFD, S);
11198   } else
11199     Record->addDecl(NewFD);
11200 
11201   return NewFD;
11202 }
11203 
11204 /// \brief Build a new FieldDecl and check its well-formedness.
11205 ///
11206 /// This routine builds a new FieldDecl given the fields name, type,
11207 /// record, etc. \p PrevDecl should refer to any previous declaration
11208 /// with the same name and in the same scope as the field to be
11209 /// created.
11210 ///
11211 /// \returns a new FieldDecl.
11212 ///
11213 /// \todo The Declarator argument is a hack. It will be removed once
11214 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
11215                                 TypeSourceInfo *TInfo,
11216                                 RecordDecl *Record, SourceLocation Loc,
11217                                 bool Mutable, Expr *BitWidth,
11218                                 InClassInitStyle InitStyle,
11219                                 SourceLocation TSSL,
11220                                 AccessSpecifier AS, NamedDecl *PrevDecl,
11221                                 Declarator *D) {
11222   IdentifierInfo *II = Name.getAsIdentifierInfo();
11223   bool InvalidDecl = false;
11224   if (D) InvalidDecl = D->isInvalidType();
11225 
11226   // If we receive a broken type, recover by assuming 'int' and
11227   // marking this declaration as invalid.
11228   if (T.isNull()) {
11229     InvalidDecl = true;
11230     T = Context.IntTy;
11231   }
11232 
11233   QualType EltTy = Context.getBaseElementType(T);
11234   if (!EltTy->isDependentType()) {
11235     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11236       // Fields of incomplete type force their record to be invalid.
11237       Record->setInvalidDecl();
11238       InvalidDecl = true;
11239     } else {
11240       NamedDecl *Def;
11241       EltTy->isIncompleteType(&Def);
11242       if (Def && Def->isInvalidDecl()) {
11243         Record->setInvalidDecl();
11244         InvalidDecl = true;
11245       }
11246     }
11247   }
11248 
11249   // OpenCL v1.2 s6.9.c: bitfields are not supported.
11250   if (BitWidth && getLangOpts().OpenCL) {
11251     Diag(Loc, diag::err_opencl_bitfields);
11252     InvalidDecl = true;
11253   }
11254 
11255   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11256   // than a variably modified type.
11257   if (!InvalidDecl && T->isVariablyModifiedType()) {
11258     bool SizeIsNegative;
11259     llvm::APSInt Oversized;
11260 
11261     TypeSourceInfo *FixedTInfo =
11262       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11263                                                     SizeIsNegative,
11264                                                     Oversized);
11265     if (FixedTInfo) {
11266       Diag(Loc, diag::warn_illegal_constant_array_size);
11267       TInfo = FixedTInfo;
11268       T = FixedTInfo->getType();
11269     } else {
11270       if (SizeIsNegative)
11271         Diag(Loc, diag::err_typecheck_negative_array_size);
11272       else if (Oversized.getBoolValue())
11273         Diag(Loc, diag::err_array_too_large)
11274           << Oversized.toString(10);
11275       else
11276         Diag(Loc, diag::err_typecheck_field_variable_size);
11277       InvalidDecl = true;
11278     }
11279   }
11280 
11281   // Fields can not have abstract class types
11282   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11283                                              diag::err_abstract_type_in_decl,
11284                                              AbstractFieldType))
11285     InvalidDecl = true;
11286 
11287   bool ZeroWidth = false;
11288   // If this is declared as a bit-field, check the bit-field.
11289   if (!InvalidDecl && BitWidth) {
11290     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11291                               &ZeroWidth).take();
11292     if (!BitWidth) {
11293       InvalidDecl = true;
11294       BitWidth = 0;
11295       ZeroWidth = false;
11296     }
11297   }
11298 
11299   // Check that 'mutable' is consistent with the type of the declaration.
11300   if (!InvalidDecl && Mutable) {
11301     unsigned DiagID = 0;
11302     if (T->isReferenceType())
11303       DiagID = diag::err_mutable_reference;
11304     else if (T.isConstQualified())
11305       DiagID = diag::err_mutable_const;
11306 
11307     if (DiagID) {
11308       SourceLocation ErrLoc = Loc;
11309       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11310         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11311       Diag(ErrLoc, DiagID);
11312       Mutable = false;
11313       InvalidDecl = true;
11314     }
11315   }
11316 
11317   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
11318                                        BitWidth, Mutable, InitStyle);
11319   if (InvalidDecl)
11320     NewFD->setInvalidDecl();
11321 
11322   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11323     Diag(Loc, diag::err_duplicate_member) << II;
11324     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11325     NewFD->setInvalidDecl();
11326   }
11327 
11328   if (!InvalidDecl && getLangOpts().CPlusPlus) {
11329     if (Record->isUnion()) {
11330       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11331         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11332         if (RDecl->getDefinition()) {
11333           // C++ [class.union]p1: An object of a class with a non-trivial
11334           // constructor, a non-trivial copy constructor, a non-trivial
11335           // destructor, or a non-trivial copy assignment operator
11336           // cannot be a member of a union, nor can an array of such
11337           // objects.
11338           if (CheckNontrivialField(NewFD))
11339             NewFD->setInvalidDecl();
11340         }
11341       }
11342 
11343       // C++ [class.union]p1: If a union contains a member of reference type,
11344       // the program is ill-formed, except when compiling with MSVC extensions
11345       // enabled.
11346       if (EltTy->isReferenceType()) {
11347         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11348                                     diag::ext_union_member_of_reference_type :
11349                                     diag::err_union_member_of_reference_type)
11350           << NewFD->getDeclName() << EltTy;
11351         if (!getLangOpts().MicrosoftExt)
11352           NewFD->setInvalidDecl();
11353       }
11354     }
11355   }
11356 
11357   // FIXME: We need to pass in the attributes given an AST
11358   // representation, not a parser representation.
11359   if (D) {
11360     // FIXME: The current scope is almost... but not entirely... correct here.
11361     ProcessDeclAttributes(getCurScope(), NewFD, *D);
11362 
11363     if (NewFD->hasAttrs())
11364       CheckAlignasUnderalignment(NewFD);
11365   }
11366 
11367   // In auto-retain/release, infer strong retension for fields of
11368   // retainable type.
11369   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
11370     NewFD->setInvalidDecl();
11371 
11372   if (T.isObjCGCWeak())
11373     Diag(Loc, diag::warn_attribute_weak_on_field);
11374 
11375   NewFD->setAccess(AS);
11376   return NewFD;
11377 }
11378 
11379 bool Sema::CheckNontrivialField(FieldDecl *FD) {
11380   assert(FD);
11381   assert(getLangOpts().CPlusPlus && "valid check only for C++");
11382 
11383   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11384     return false;
11385 
11386   QualType EltTy = Context.getBaseElementType(FD->getType());
11387   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11388     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
11389     if (RDecl->getDefinition()) {
11390       // We check for copy constructors before constructors
11391       // because otherwise we'll never get complaints about
11392       // copy constructors.
11393 
11394       CXXSpecialMember member = CXXInvalid;
11395       // We're required to check for any non-trivial constructors. Since the
11396       // implicit default constructor is suppressed if there are any
11397       // user-declared constructors, we just need to check that there is a
11398       // trivial default constructor and a trivial copy constructor. (We don't
11399       // worry about move constructors here, since this is a C++98 check.)
11400       if (RDecl->hasNonTrivialCopyConstructor())
11401         member = CXXCopyConstructor;
11402       else if (!RDecl->hasTrivialDefaultConstructor())
11403         member = CXXDefaultConstructor;
11404       else if (RDecl->hasNonTrivialCopyAssignment())
11405         member = CXXCopyAssignment;
11406       else if (RDecl->hasNonTrivialDestructor())
11407         member = CXXDestructor;
11408 
11409       if (member != CXXInvalid) {
11410         if (!getLangOpts().CPlusPlus11 &&
11411             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
11412           // Objective-C++ ARC: it is an error to have a non-trivial field of
11413           // a union. However, system headers in Objective-C programs
11414           // occasionally have Objective-C lifetime objects within unions,
11415           // and rather than cause the program to fail, we make those
11416           // members unavailable.
11417           SourceLocation Loc = FD->getLocation();
11418           if (getSourceManager().isInSystemHeader(Loc)) {
11419             if (!FD->hasAttr<UnavailableAttr>())
11420               FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
11421                                   "this system field has retaining ownership"));
11422             return false;
11423           }
11424         }
11425 
11426         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
11427                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11428                diag::err_illegal_union_or_anon_struct_member)
11429           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
11430         DiagnoseNontrivial(RDecl, member);
11431         return !getLangOpts().CPlusPlus11;
11432       }
11433     }
11434   }
11435 
11436   return false;
11437 }
11438 
11439 /// TranslateIvarVisibility - Translate visibility from a token ID to an
11440 ///  AST enum value.
11441 static ObjCIvarDecl::AccessControl
11442 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
11443   switch (ivarVisibility) {
11444   default: llvm_unreachable("Unknown visitibility kind");
11445   case tok::objc_private: return ObjCIvarDecl::Private;
11446   case tok::objc_public: return ObjCIvarDecl::Public;
11447   case tok::objc_protected: return ObjCIvarDecl::Protected;
11448   case tok::objc_package: return ObjCIvarDecl::Package;
11449   }
11450 }
11451 
11452 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
11453 /// in order to create an IvarDecl object for it.
11454 Decl *Sema::ActOnIvar(Scope *S,
11455                                 SourceLocation DeclStart,
11456                                 Declarator &D, Expr *BitfieldWidth,
11457                                 tok::ObjCKeywordKind Visibility) {
11458 
11459   IdentifierInfo *II = D.getIdentifier();
11460   Expr *BitWidth = (Expr*)BitfieldWidth;
11461   SourceLocation Loc = DeclStart;
11462   if (II) Loc = D.getIdentifierLoc();
11463 
11464   // FIXME: Unnamed fields can be handled in various different ways, for
11465   // example, unnamed unions inject all members into the struct namespace!
11466 
11467   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11468   QualType T = TInfo->getType();
11469 
11470   if (BitWidth) {
11471     // 6.7.2.1p3, 6.7.2.1p4
11472     BitWidth =
11473         VerifyBitField(Loc, II, T, /*IsMsStruct=*/false, BitWidth).take();
11474     if (!BitWidth)
11475       D.setInvalidType();
11476   } else {
11477     // Not a bitfield.
11478 
11479     // validate II.
11480 
11481   }
11482   if (T->isReferenceType()) {
11483     Diag(Loc, diag::err_ivar_reference_type);
11484     D.setInvalidType();
11485   }
11486   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11487   // than a variably modified type.
11488   else if (T->isVariablyModifiedType()) {
11489     Diag(Loc, diag::err_typecheck_ivar_variable_size);
11490     D.setInvalidType();
11491   }
11492 
11493   // Get the visibility (access control) for this ivar.
11494   ObjCIvarDecl::AccessControl ac =
11495     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11496                                         : ObjCIvarDecl::None;
11497   // Must set ivar's DeclContext to its enclosing interface.
11498   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
11499   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11500     return 0;
11501   ObjCContainerDecl *EnclosingContext;
11502   if (ObjCImplementationDecl *IMPDecl =
11503       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11504     if (LangOpts.ObjCRuntime.isFragile()) {
11505     // Case of ivar declared in an implementation. Context is that of its class.
11506       EnclosingContext = IMPDecl->getClassInterface();
11507       assert(EnclosingContext && "Implementation has no class interface!");
11508     }
11509     else
11510       EnclosingContext = EnclosingDecl;
11511   } else {
11512     if (ObjCCategoryDecl *CDecl =
11513         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11514       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
11515         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
11516         return 0;
11517       }
11518     }
11519     EnclosingContext = EnclosingDecl;
11520   }
11521 
11522   // Construct the decl.
11523   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11524                                              DeclStart, Loc, II, T,
11525                                              TInfo, ac, (Expr *)BitfieldWidth);
11526 
11527   if (II) {
11528     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
11529                                            ForRedeclaration);
11530     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
11531         && !isa<TagDecl>(PrevDecl)) {
11532       Diag(Loc, diag::err_duplicate_member) << II;
11533       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11534       NewID->setInvalidDecl();
11535     }
11536   }
11537 
11538   // Process attributes attached to the ivar.
11539   ProcessDeclAttributes(S, NewID, D);
11540 
11541   if (D.isInvalidType())
11542     NewID->setInvalidDecl();
11543 
11544   // In ARC, infer 'retaining' for ivars of retainable type.
11545   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
11546     NewID->setInvalidDecl();
11547 
11548   if (D.getDeclSpec().isModulePrivateSpecified())
11549     NewID->setModulePrivate();
11550 
11551   if (II) {
11552     // FIXME: When interfaces are DeclContexts, we'll need to add
11553     // these to the interface.
11554     S->AddDecl(NewID);
11555     IdResolver.AddDecl(NewID);
11556   }
11557 
11558   if (LangOpts.ObjCRuntime.isNonFragile() &&
11559       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
11560     Diag(Loc, diag::warn_ivars_in_interface);
11561 
11562   return NewID;
11563 }
11564 
11565 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
11566 /// class and class extensions. For every class \@interface and class
11567 /// extension \@interface, if the last ivar is a bitfield of any type,
11568 /// then add an implicit `char :0` ivar to the end of that interface.
11569 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
11570                              SmallVectorImpl<Decl *> &AllIvarDecls) {
11571   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
11572     return;
11573 
11574   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11575   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11576 
11577   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
11578     return;
11579   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
11580   if (!ID) {
11581     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
11582       if (!CD->IsClassExtension())
11583         return;
11584     }
11585     // No need to add this to end of @implementation.
11586     else
11587       return;
11588   }
11589   // All conditions are met. Add a new bitfield to the tail end of ivars.
11590   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11591   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
11592 
11593   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
11594                               DeclLoc, DeclLoc, 0,
11595                               Context.CharTy,
11596                               Context.getTrivialTypeSourceInfo(Context.CharTy,
11597                                                                DeclLoc),
11598                               ObjCIvarDecl::Private, BW,
11599                               true);
11600   AllIvarDecls.push_back(Ivar);
11601 }
11602 
11603 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11604                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
11605                        SourceLocation RBrac, AttributeList *Attr) {
11606   assert(EnclosingDecl && "missing record or interface decl");
11607 
11608   // If this is an Objective-C @implementation or category and we have
11609   // new fields here we should reset the layout of the interface since
11610   // it will now change.
11611   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11612     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11613     switch (DC->getKind()) {
11614     default: break;
11615     case Decl::ObjCCategory:
11616       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11617       break;
11618     case Decl::ObjCImplementation:
11619       Context.
11620         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11621       break;
11622     }
11623   }
11624 
11625   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11626 
11627   // Start counting up the number of named members; make sure to include
11628   // members of anonymous structs and unions in the total.
11629   unsigned NumNamedMembers = 0;
11630   if (Record) {
11631     for (RecordDecl::decl_iterator i = Record->decls_begin(),
11632                                    e = Record->decls_end(); i != e; i++) {
11633       if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11634         if (IFD->getDeclName())
11635           ++NumNamedMembers;
11636     }
11637   }
11638 
11639   // Verify that all the fields are okay.
11640   SmallVector<FieldDecl*, 32> RecFields;
11641 
11642   bool ARCErrReported = false;
11643   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
11644        i != end; ++i) {
11645     FieldDecl *FD = cast<FieldDecl>(*i);
11646 
11647     // Get the type for the field.
11648     const Type *FDTy = FD->getType().getTypePtr();
11649 
11650     if (!FD->isAnonymousStructOrUnion()) {
11651       // Remember all fields written by the user.
11652       RecFields.push_back(FD);
11653     }
11654 
11655     // If the field is already invalid for some reason, don't emit more
11656     // diagnostics about it.
11657     if (FD->isInvalidDecl()) {
11658       EnclosingDecl->setInvalidDecl();
11659       continue;
11660     }
11661 
11662     // C99 6.7.2.1p2:
11663     //   A structure or union shall not contain a member with
11664     //   incomplete or function type (hence, a structure shall not
11665     //   contain an instance of itself, but may contain a pointer to
11666     //   an instance of itself), except that the last member of a
11667     //   structure with more than one named member may have incomplete
11668     //   array type; such a structure (and any union containing,
11669     //   possibly recursively, a member that is such a structure)
11670     //   shall not be a member of a structure or an element of an
11671     //   array.
11672     if (FDTy->isFunctionType()) {
11673       // Field declared as a function.
11674       Diag(FD->getLocation(), diag::err_field_declared_as_function)
11675         << FD->getDeclName();
11676       FD->setInvalidDecl();
11677       EnclosingDecl->setInvalidDecl();
11678       continue;
11679     } else if (FDTy->isIncompleteArrayType() && Record &&
11680                ((i + 1 == Fields.end() && !Record->isUnion()) ||
11681                 ((getLangOpts().MicrosoftExt ||
11682                   getLangOpts().CPlusPlus) &&
11683                  (i + 1 == Fields.end() || Record->isUnion())))) {
11684       // Flexible array member.
11685       // Microsoft and g++ is more permissive regarding flexible array.
11686       // It will accept flexible array in union and also
11687       // as the sole element of a struct/class.
11688       if (getLangOpts().MicrosoftExt) {
11689         if (Record->isUnion())
11690           Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
11691             << FD->getDeclName();
11692         else if (Fields.size() == 1)
11693           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
11694             << FD->getDeclName() << Record->getTagKind();
11695       } else if (getLangOpts().CPlusPlus) {
11696         if (Record->isUnion())
11697           Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11698             << FD->getDeclName();
11699         else if (Fields.size() == 1)
11700           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
11701             << FD->getDeclName() << Record->getTagKind();
11702       } else if (!getLangOpts().C99) {
11703       if (Record->isUnion())
11704         Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11705           << FD->getDeclName();
11706       else
11707         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11708           << FD->getDeclName() << Record->getTagKind();
11709       } else if (NumNamedMembers < 1) {
11710         Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
11711           << FD->getDeclName();
11712         FD->setInvalidDecl();
11713         EnclosingDecl->setInvalidDecl();
11714         continue;
11715       }
11716       if (!FD->getType()->isDependentType() &&
11717           !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
11718         Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
11719           << FD->getDeclName() << FD->getType();
11720         FD->setInvalidDecl();
11721         EnclosingDecl->setInvalidDecl();
11722         continue;
11723       }
11724       // Okay, we have a legal flexible array member at the end of the struct.
11725       if (Record)
11726         Record->setHasFlexibleArrayMember(true);
11727     } else if (!FDTy->isDependentType() &&
11728                RequireCompleteType(FD->getLocation(), FD->getType(),
11729                                    diag::err_field_incomplete)) {
11730       // Incomplete type
11731       FD->setInvalidDecl();
11732       EnclosingDecl->setInvalidDecl();
11733       continue;
11734     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
11735       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11736         // If this is a member of a union, then entire union becomes "flexible".
11737         if (Record && Record->isUnion()) {
11738           Record->setHasFlexibleArrayMember(true);
11739         } else {
11740           // If this is a struct/class and this is not the last element, reject
11741           // it.  Note that GCC supports variable sized arrays in the middle of
11742           // structures.
11743           if (i + 1 != Fields.end())
11744             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
11745               << FD->getDeclName() << FD->getType();
11746           else {
11747             // We support flexible arrays at the end of structs in
11748             // other structs as an extension.
11749             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11750               << FD->getDeclName();
11751             if (Record)
11752               Record->setHasFlexibleArrayMember(true);
11753           }
11754         }
11755       }
11756       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11757           RequireNonAbstractType(FD->getLocation(), FD->getType(),
11758                                  diag::err_abstract_type_in_decl,
11759                                  AbstractIvarType)) {
11760         // Ivars can not have abstract class types
11761         FD->setInvalidDecl();
11762       }
11763       if (Record && FDTTy->getDecl()->hasObjectMember())
11764         Record->setHasObjectMember(true);
11765       if (Record && FDTTy->getDecl()->hasVolatileMember())
11766         Record->setHasVolatileMember(true);
11767     } else if (FDTy->isObjCObjectType()) {
11768       /// A field cannot be an Objective-c object
11769       Diag(FD->getLocation(), diag::err_statically_allocated_object)
11770         << FixItHint::CreateInsertion(FD->getLocation(), "*");
11771       QualType T = Context.getObjCObjectPointerType(FD->getType());
11772       FD->setType(T);
11773     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11774                (!getLangOpts().CPlusPlus || Record->isUnion())) {
11775       // It's an error in ARC if a field has lifetime.
11776       // We don't want to report this in a system header, though,
11777       // so we just make the field unavailable.
11778       // FIXME: that's really not sufficient; we need to make the type
11779       // itself invalid to, say, initialize or copy.
11780       QualType T = FD->getType();
11781       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11782       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11783         SourceLocation loc = FD->getLocation();
11784         if (getSourceManager().isInSystemHeader(loc)) {
11785           if (!FD->hasAttr<UnavailableAttr>()) {
11786             FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11787                               "this system field has retaining ownership"));
11788           }
11789         } else {
11790           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
11791             << T->isBlockPointerType() << Record->getTagKind();
11792         }
11793         ARCErrReported = true;
11794       }
11795     } else if (getLangOpts().ObjC1 &&
11796                getLangOpts().getGC() != LangOptions::NonGC &&
11797                Record && !Record->hasObjectMember()) {
11798       if (FD->getType()->isObjCObjectPointerType() ||
11799           FD->getType().isObjCGCStrong())
11800         Record->setHasObjectMember(true);
11801       else if (Context.getAsArrayType(FD->getType())) {
11802         QualType BaseType = Context.getBaseElementType(FD->getType());
11803         if (BaseType->isRecordType() &&
11804             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
11805           Record->setHasObjectMember(true);
11806         else if (BaseType->isObjCObjectPointerType() ||
11807                  BaseType.isObjCGCStrong())
11808                Record->setHasObjectMember(true);
11809       }
11810     }
11811     if (Record && FD->getType().isVolatileQualified())
11812       Record->setHasVolatileMember(true);
11813     // Keep track of the number of named members.
11814     if (FD->getIdentifier())
11815       ++NumNamedMembers;
11816   }
11817 
11818   // Okay, we successfully defined 'Record'.
11819   if (Record) {
11820     bool Completed = false;
11821     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
11822       if (!CXXRecord->isInvalidDecl()) {
11823         // Set access bits correctly on the directly-declared conversions.
11824         for (CXXRecordDecl::conversion_iterator
11825                I = CXXRecord->conversion_begin(),
11826                E = CXXRecord->conversion_end(); I != E; ++I)
11827           I.setAccess((*I)->getAccess());
11828 
11829         if (!CXXRecord->isDependentType()) {
11830           if (CXXRecord->hasUserDeclaredDestructor()) {
11831             // Adjust user-defined destructor exception spec.
11832             if (getLangOpts().CPlusPlus11)
11833               AdjustDestructorExceptionSpec(CXXRecord,
11834                                             CXXRecord->getDestructor());
11835 
11836             // The Microsoft ABI requires that we perform the destructor body
11837             // checks (i.e. operator delete() lookup) at every declaration, as
11838             // any translation unit may need to emit a deleting destructor.
11839             if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11840               CheckDestructor(CXXRecord->getDestructor());
11841           }
11842 
11843           // Add any implicitly-declared members to this class.
11844           AddImplicitlyDeclaredMembersToClass(CXXRecord);
11845 
11846           // If we have virtual base classes, we may end up finding multiple
11847           // final overriders for a given virtual function. Check for this
11848           // problem now.
11849           if (CXXRecord->getNumVBases()) {
11850             CXXFinalOverriderMap FinalOverriders;
11851             CXXRecord->getFinalOverriders(FinalOverriders);
11852 
11853             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
11854                                              MEnd = FinalOverriders.end();
11855                  M != MEnd; ++M) {
11856               for (OverridingMethods::iterator SO = M->second.begin(),
11857                                             SOEnd = M->second.end();
11858                    SO != SOEnd; ++SO) {
11859                 assert(SO->second.size() > 0 &&
11860                        "Virtual function without overridding functions?");
11861                 if (SO->second.size() == 1)
11862                   continue;
11863 
11864                 // C++ [class.virtual]p2:
11865                 //   In a derived class, if a virtual member function of a base
11866                 //   class subobject has more than one final overrider the
11867                 //   program is ill-formed.
11868                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
11869                   << (const NamedDecl *)M->first << Record;
11870                 Diag(M->first->getLocation(),
11871                      diag::note_overridden_virtual_function);
11872                 for (OverridingMethods::overriding_iterator
11873                           OM = SO->second.begin(),
11874                        OMEnd = SO->second.end();
11875                      OM != OMEnd; ++OM)
11876                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
11877                     << (const NamedDecl *)M->first << OM->Method->getParent();
11878 
11879                 Record->setInvalidDecl();
11880               }
11881             }
11882             CXXRecord->completeDefinition(&FinalOverriders);
11883             Completed = true;
11884           }
11885         }
11886       }
11887     }
11888 
11889     if (!Completed)
11890       Record->completeDefinition();
11891 
11892     if (Record->hasAttrs())
11893       CheckAlignasUnderalignment(Record);
11894 
11895     // Check if the structure/union declaration is a language extension.
11896     if (!getLangOpts().CPlusPlus) {
11897       bool ZeroSize = true;
11898       bool IsEmpty = true;
11899       unsigned NonBitFields = 0;
11900       for (RecordDecl::field_iterator I = Record->field_begin(),
11901                                       E = Record->field_end();
11902            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
11903         IsEmpty = false;
11904         if (I->isUnnamedBitfield()) {
11905           if (I->getBitWidthValue(Context) > 0)
11906             ZeroSize = false;
11907         } else {
11908           ++NonBitFields;
11909           QualType FieldType = I->getType();
11910           if (FieldType->isIncompleteType() ||
11911               !Context.getTypeSizeInChars(FieldType).isZero())
11912             ZeroSize = false;
11913         }
11914       }
11915 
11916       // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
11917       // C++.
11918       if (ZeroSize)
11919         Diag(RecLoc, diag::warn_zero_size_struct_union_compat) << IsEmpty
11920             << Record->isUnion() << (NonBitFields > 1);
11921 
11922       // Structs without named members are extension in C (C99 6.7.2.1p7), but
11923       // are accepted by GCC.
11924       if (NonBitFields == 0) {
11925         if (IsEmpty)
11926           Diag(RecLoc, diag::ext_empty_struct_union) << Record->isUnion();
11927         else
11928           Diag(RecLoc, diag::ext_no_named_members_in_struct_union) << Record->isUnion();
11929       }
11930     }
11931   } else {
11932     ObjCIvarDecl **ClsFields =
11933       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
11934     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
11935       ID->setEndOfDefinitionLoc(RBrac);
11936       // Add ivar's to class's DeclContext.
11937       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
11938         ClsFields[i]->setLexicalDeclContext(ID);
11939         ID->addDecl(ClsFields[i]);
11940       }
11941       // Must enforce the rule that ivars in the base classes may not be
11942       // duplicates.
11943       if (ID->getSuperClass())
11944         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
11945     } else if (ObjCImplementationDecl *IMPDecl =
11946                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11947       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
11948       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
11949         // Ivar declared in @implementation never belongs to the implementation.
11950         // Only it is in implementation's lexical context.
11951         ClsFields[I]->setLexicalDeclContext(IMPDecl);
11952       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
11953       IMPDecl->setIvarLBraceLoc(LBrac);
11954       IMPDecl->setIvarRBraceLoc(RBrac);
11955     } else if (ObjCCategoryDecl *CDecl =
11956                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11957       // case of ivars in class extension; all other cases have been
11958       // reported as errors elsewhere.
11959       // FIXME. Class extension does not have a LocEnd field.
11960       // CDecl->setLocEnd(RBrac);
11961       // Add ivar's to class extension's DeclContext.
11962       // Diagnose redeclaration of private ivars.
11963       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
11964       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
11965         if (IDecl) {
11966           if (const ObjCIvarDecl *ClsIvar =
11967               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
11968             Diag(ClsFields[i]->getLocation(),
11969                  diag::err_duplicate_ivar_declaration);
11970             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
11971             continue;
11972           }
11973           for (ObjCInterfaceDecl::known_extensions_iterator
11974                  Ext = IDecl->known_extensions_begin(),
11975                  ExtEnd = IDecl->known_extensions_end();
11976                Ext != ExtEnd; ++Ext) {
11977             if (const ObjCIvarDecl *ClsExtIvar
11978                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
11979               Diag(ClsFields[i]->getLocation(),
11980                    diag::err_duplicate_ivar_declaration);
11981               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
11982               continue;
11983             }
11984           }
11985         }
11986         ClsFields[i]->setLexicalDeclContext(CDecl);
11987         CDecl->addDecl(ClsFields[i]);
11988       }
11989       CDecl->setIvarLBraceLoc(LBrac);
11990       CDecl->setIvarRBraceLoc(RBrac);
11991     }
11992   }
11993 
11994   if (Attr)
11995     ProcessDeclAttributeList(S, Record, Attr);
11996 }
11997 
11998 /// \brief Determine whether the given integral value is representable within
11999 /// the given type T.
12000 static bool isRepresentableIntegerValue(ASTContext &Context,
12001                                         llvm::APSInt &Value,
12002                                         QualType T) {
12003   assert(T->isIntegralType(Context) && "Integral type required!");
12004   unsigned BitWidth = Context.getIntWidth(T);
12005 
12006   if (Value.isUnsigned() || Value.isNonNegative()) {
12007     if (T->isSignedIntegerOrEnumerationType())
12008       --BitWidth;
12009     return Value.getActiveBits() <= BitWidth;
12010   }
12011   return Value.getMinSignedBits() <= BitWidth;
12012 }
12013 
12014 // \brief Given an integral type, return the next larger integral type
12015 // (or a NULL type of no such type exists).
12016 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12017   // FIXME: Int128/UInt128 support, which also needs to be introduced into
12018   // enum checking below.
12019   assert(T->isIntegralType(Context) && "Integral type required!");
12020   const unsigned NumTypes = 4;
12021   QualType SignedIntegralTypes[NumTypes] = {
12022     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12023   };
12024   QualType UnsignedIntegralTypes[NumTypes] = {
12025     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12026     Context.UnsignedLongLongTy
12027   };
12028 
12029   unsigned BitWidth = Context.getTypeSize(T);
12030   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12031                                                         : UnsignedIntegralTypes;
12032   for (unsigned I = 0; I != NumTypes; ++I)
12033     if (Context.getTypeSize(Types[I]) > BitWidth)
12034       return Types[I];
12035 
12036   return QualType();
12037 }
12038 
12039 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12040                                           EnumConstantDecl *LastEnumConst,
12041                                           SourceLocation IdLoc,
12042                                           IdentifierInfo *Id,
12043                                           Expr *Val) {
12044   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12045   llvm::APSInt EnumVal(IntWidth);
12046   QualType EltTy;
12047 
12048   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12049     Val = 0;
12050 
12051   if (Val)
12052     Val = DefaultLvalueConversion(Val).take();
12053 
12054   if (Val) {
12055     if (Enum->isDependentType() || Val->isTypeDependent())
12056       EltTy = Context.DependentTy;
12057     else {
12058       SourceLocation ExpLoc;
12059       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12060           !getLangOpts().MicrosoftMode) {
12061         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12062         // constant-expression in the enumerator-definition shall be a converted
12063         // constant expression of the underlying type.
12064         EltTy = Enum->getIntegerType();
12065         ExprResult Converted =
12066           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12067                                            CCEK_Enumerator);
12068         if (Converted.isInvalid())
12069           Val = 0;
12070         else
12071           Val = Converted.take();
12072       } else if (!Val->isValueDependent() &&
12073                  !(Val = VerifyIntegerConstantExpression(Val,
12074                                                          &EnumVal).take())) {
12075         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12076       } else {
12077         if (Enum->isFixed()) {
12078           EltTy = Enum->getIntegerType();
12079 
12080           // In Obj-C and Microsoft mode, require the enumeration value to be
12081           // representable in the underlying type of the enumeration. In C++11,
12082           // we perform a non-narrowing conversion as part of converted constant
12083           // expression checking.
12084           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12085             if (getLangOpts().MicrosoftMode) {
12086               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12087               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12088             } else
12089               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12090           } else
12091             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12092         } else if (getLangOpts().CPlusPlus) {
12093           // C++11 [dcl.enum]p5:
12094           //   If the underlying type is not fixed, the type of each enumerator
12095           //   is the type of its initializing value:
12096           //     - If an initializer is specified for an enumerator, the
12097           //       initializing value has the same type as the expression.
12098           EltTy = Val->getType();
12099         } else {
12100           // C99 6.7.2.2p2:
12101           //   The expression that defines the value of an enumeration constant
12102           //   shall be an integer constant expression that has a value
12103           //   representable as an int.
12104 
12105           // Complain if the value is not representable in an int.
12106           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12107             Diag(IdLoc, diag::ext_enum_value_not_int)
12108               << EnumVal.toString(10) << Val->getSourceRange()
12109               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12110           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12111             // Force the type of the expression to 'int'.
12112             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12113           }
12114           EltTy = Val->getType();
12115         }
12116       }
12117     }
12118   }
12119 
12120   if (!Val) {
12121     if (Enum->isDependentType())
12122       EltTy = Context.DependentTy;
12123     else if (!LastEnumConst) {
12124       // C++0x [dcl.enum]p5:
12125       //   If the underlying type is not fixed, the type of each enumerator
12126       //   is the type of its initializing value:
12127       //     - If no initializer is specified for the first enumerator, the
12128       //       initializing value has an unspecified integral type.
12129       //
12130       // GCC uses 'int' for its unspecified integral type, as does
12131       // C99 6.7.2.2p3.
12132       if (Enum->isFixed()) {
12133         EltTy = Enum->getIntegerType();
12134       }
12135       else {
12136         EltTy = Context.IntTy;
12137       }
12138     } else {
12139       // Assign the last value + 1.
12140       EnumVal = LastEnumConst->getInitVal();
12141       ++EnumVal;
12142       EltTy = LastEnumConst->getType();
12143 
12144       // Check for overflow on increment.
12145       if (EnumVal < LastEnumConst->getInitVal()) {
12146         // C++0x [dcl.enum]p5:
12147         //   If the underlying type is not fixed, the type of each enumerator
12148         //   is the type of its initializing value:
12149         //
12150         //     - Otherwise the type of the initializing value is the same as
12151         //       the type of the initializing value of the preceding enumerator
12152         //       unless the incremented value is not representable in that type,
12153         //       in which case the type is an unspecified integral type
12154         //       sufficient to contain the incremented value. If no such type
12155         //       exists, the program is ill-formed.
12156         QualType T = getNextLargerIntegralType(Context, EltTy);
12157         if (T.isNull() || Enum->isFixed()) {
12158           // There is no integral type larger enough to represent this
12159           // value. Complain, then allow the value to wrap around.
12160           EnumVal = LastEnumConst->getInitVal();
12161           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
12162           ++EnumVal;
12163           if (Enum->isFixed())
12164             // When the underlying type is fixed, this is ill-formed.
12165             Diag(IdLoc, diag::err_enumerator_wrapped)
12166               << EnumVal.toString(10)
12167               << EltTy;
12168           else
12169             Diag(IdLoc, diag::warn_enumerator_too_large)
12170               << EnumVal.toString(10);
12171         } else {
12172           EltTy = T;
12173         }
12174 
12175         // Retrieve the last enumerator's value, extent that type to the
12176         // type that is supposed to be large enough to represent the incremented
12177         // value, then increment.
12178         EnumVal = LastEnumConst->getInitVal();
12179         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12180         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
12181         ++EnumVal;
12182 
12183         // If we're not in C++, diagnose the overflow of enumerator values,
12184         // which in C99 means that the enumerator value is not representable in
12185         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12186         // permits enumerator values that are representable in some larger
12187         // integral type.
12188         if (!getLangOpts().CPlusPlus && !T.isNull())
12189           Diag(IdLoc, diag::warn_enum_value_overflow);
12190       } else if (!getLangOpts().CPlusPlus &&
12191                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12192         // Enforce C99 6.7.2.2p2 even when we compute the next value.
12193         Diag(IdLoc, diag::ext_enum_value_not_int)
12194           << EnumVal.toString(10) << 1;
12195       }
12196     }
12197   }
12198 
12199   if (!EltTy->isDependentType()) {
12200     // Make the enumerator value match the signedness and size of the
12201     // enumerator's type.
12202     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
12203     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12204   }
12205 
12206   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
12207                                   Val, EnumVal);
12208 }
12209 
12210 
12211 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12212                               SourceLocation IdLoc, IdentifierInfo *Id,
12213                               AttributeList *Attr,
12214                               SourceLocation EqualLoc, Expr *Val) {
12215   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
12216   EnumConstantDecl *LastEnumConst =
12217     cast_or_null<EnumConstantDecl>(lastEnumConst);
12218 
12219   // The scope passed in may not be a decl scope.  Zip up the scope tree until
12220   // we find one that is.
12221   S = getNonFieldDeclScope(S);
12222 
12223   // Verify that there isn't already something declared with this name in this
12224   // scope.
12225   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
12226                                          ForRedeclaration);
12227   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12228     // Maybe we will complain about the shadowed template parameter.
12229     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12230     // Just pretend that we didn't see the previous declaration.
12231     PrevDecl = 0;
12232   }
12233 
12234   if (PrevDecl) {
12235     // When in C++, we may get a TagDecl with the same name; in this case the
12236     // enum constant will 'hide' the tag.
12237     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
12238            "Received TagDecl when not in C++!");
12239     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
12240       if (isa<EnumConstantDecl>(PrevDecl))
12241         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
12242       else
12243         Diag(IdLoc, diag::err_redefinition) << Id;
12244       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12245       return 0;
12246     }
12247   }
12248 
12249   // C++ [class.mem]p15:
12250   // If T is the name of a class, then each of the following shall have a name
12251   // different from T:
12252   // - every enumerator of every member of class T that is an unscoped
12253   // enumerated type
12254   if (CXXRecordDecl *Record
12255                       = dyn_cast<CXXRecordDecl>(
12256                              TheEnumDecl->getDeclContext()->getRedeclContext()))
12257     if (!TheEnumDecl->isScoped() &&
12258         Record->getIdentifier() && Record->getIdentifier() == Id)
12259       Diag(IdLoc, diag::err_member_name_of_class) << Id;
12260 
12261   EnumConstantDecl *New =
12262     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
12263 
12264   if (New) {
12265     // Process attributes.
12266     if (Attr) ProcessDeclAttributeList(S, New, Attr);
12267 
12268     // Register this decl in the current scope stack.
12269     New->setAccess(TheEnumDecl->getAccess());
12270     PushOnScopeChains(New, S);
12271   }
12272 
12273   ActOnDocumentableDecl(New);
12274 
12275   return New;
12276 }
12277 
12278 // Returns true when the enum initial expression does not trigger the
12279 // duplicate enum warning.  A few common cases are exempted as follows:
12280 // Element2 = Element1
12281 // Element2 = Element1 + 1
12282 // Element2 = Element1 - 1
12283 // Where Element2 and Element1 are from the same enum.
12284 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12285   Expr *InitExpr = ECD->getInitExpr();
12286   if (!InitExpr)
12287     return true;
12288   InitExpr = InitExpr->IgnoreImpCasts();
12289 
12290   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12291     if (!BO->isAdditiveOp())
12292       return true;
12293     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12294     if (!IL)
12295       return true;
12296     if (IL->getValue() != 1)
12297       return true;
12298 
12299     InitExpr = BO->getLHS();
12300   }
12301 
12302   // This checks if the elements are from the same enum.
12303   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12304   if (!DRE)
12305     return true;
12306 
12307   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12308   if (!EnumConstant)
12309     return true;
12310 
12311   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12312       Enum)
12313     return true;
12314 
12315   return false;
12316 }
12317 
12318 struct DupKey {
12319   int64_t val;
12320   bool isTombstoneOrEmptyKey;
12321   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12322     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12323 };
12324 
12325 static DupKey GetDupKey(const llvm::APSInt& Val) {
12326   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12327                 false);
12328 }
12329 
12330 struct DenseMapInfoDupKey {
12331   static DupKey getEmptyKey() { return DupKey(0, true); }
12332   static DupKey getTombstoneKey() { return DupKey(1, true); }
12333   static unsigned getHashValue(const DupKey Key) {
12334     return (unsigned)(Key.val * 37);
12335   }
12336   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12337     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12338            LHS.val == RHS.val;
12339   }
12340 };
12341 
12342 // Emits a warning when an element is implicitly set a value that
12343 // a previous element has already been set to.
12344 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12345                                         EnumDecl *Enum,
12346                                         QualType EnumType) {
12347   if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12348                                  Enum->getLocation()) ==
12349       DiagnosticsEngine::Ignored)
12350     return;
12351   // Avoid anonymous enums
12352   if (!Enum->getIdentifier())
12353     return;
12354 
12355   // Only check for small enums.
12356   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12357     return;
12358 
12359   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12360   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
12361 
12362   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12363   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12364           ValueToVectorMap;
12365 
12366   DuplicatesVector DupVector;
12367   ValueToVectorMap EnumMap;
12368 
12369   // Populate the EnumMap with all values represented by enum constants without
12370   // an initialier.
12371   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12372     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12373 
12374     // Null EnumConstantDecl means a previous diagnostic has been emitted for
12375     // this constant.  Skip this enum since it may be ill-formed.
12376     if (!ECD) {
12377       return;
12378     }
12379 
12380     if (ECD->getInitExpr())
12381       continue;
12382 
12383     DupKey Key = GetDupKey(ECD->getInitVal());
12384     DeclOrVector &Entry = EnumMap[Key];
12385 
12386     // First time encountering this value.
12387     if (Entry.isNull())
12388       Entry = ECD;
12389   }
12390 
12391   // Create vectors for any values that has duplicates.
12392   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12393     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12394     if (!ValidDuplicateEnum(ECD, Enum))
12395       continue;
12396 
12397     DupKey Key = GetDupKey(ECD->getInitVal());
12398 
12399     DeclOrVector& Entry = EnumMap[Key];
12400     if (Entry.isNull())
12401       continue;
12402 
12403     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12404       // Ensure constants are different.
12405       if (D == ECD)
12406         continue;
12407 
12408       // Create new vector and push values onto it.
12409       ECDVector *Vec = new ECDVector();
12410       Vec->push_back(D);
12411       Vec->push_back(ECD);
12412 
12413       // Update entry to point to the duplicates vector.
12414       Entry = Vec;
12415 
12416       // Store the vector somewhere we can consult later for quick emission of
12417       // diagnostics.
12418       DupVector.push_back(Vec);
12419       continue;
12420     }
12421 
12422     ECDVector *Vec = Entry.get<ECDVector*>();
12423     // Make sure constants are not added more than once.
12424     if (*Vec->begin() == ECD)
12425       continue;
12426 
12427     Vec->push_back(ECD);
12428   }
12429 
12430   // Emit diagnostics.
12431   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12432                                   DupVectorEnd = DupVector.end();
12433        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12434     ECDVector *Vec = *DupVectorIter;
12435     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12436 
12437     // Emit warning for one enum constant.
12438     ECDVector::iterator I = Vec->begin();
12439     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12440       << (*I)->getName() << (*I)->getInitVal().toString(10)
12441       << (*I)->getSourceRange();
12442     ++I;
12443 
12444     // Emit one note for each of the remaining enum constants with
12445     // the same value.
12446     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12447       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12448         << (*I)->getName() << (*I)->getInitVal().toString(10)
12449         << (*I)->getSourceRange();
12450     delete Vec;
12451   }
12452 }
12453 
12454 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
12455                          SourceLocation RBraceLoc, Decl *EnumDeclX,
12456                          ArrayRef<Decl *> Elements,
12457                          Scope *S, AttributeList *Attr) {
12458   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
12459   QualType EnumType = Context.getTypeDeclType(Enum);
12460 
12461   if (Attr)
12462     ProcessDeclAttributeList(S, Enum, Attr);
12463 
12464   if (Enum->isDependentType()) {
12465     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12466       EnumConstantDecl *ECD =
12467         cast_or_null<EnumConstantDecl>(Elements[i]);
12468       if (!ECD) continue;
12469 
12470       ECD->setType(EnumType);
12471     }
12472 
12473     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
12474     return;
12475   }
12476 
12477   // TODO: If the result value doesn't fit in an int, it must be a long or long
12478   // long value.  ISO C does not support this, but GCC does as an extension,
12479   // emit a warning.
12480   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12481   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12482   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
12483 
12484   // Verify that all the values are okay, compute the size of the values, and
12485   // reverse the list.
12486   unsigned NumNegativeBits = 0;
12487   unsigned NumPositiveBits = 0;
12488 
12489   // Keep track of whether all elements have type int.
12490   bool AllElementsInt = true;
12491 
12492   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12493     EnumConstantDecl *ECD =
12494       cast_or_null<EnumConstantDecl>(Elements[i]);
12495     if (!ECD) continue;  // Already issued a diagnostic.
12496 
12497     const llvm::APSInt &InitVal = ECD->getInitVal();
12498 
12499     // Keep track of the size of positive and negative values.
12500     if (InitVal.isUnsigned() || InitVal.isNonNegative())
12501       NumPositiveBits = std::max(NumPositiveBits,
12502                                  (unsigned)InitVal.getActiveBits());
12503     else
12504       NumNegativeBits = std::max(NumNegativeBits,
12505                                  (unsigned)InitVal.getMinSignedBits());
12506 
12507     // Keep track of whether every enum element has type int (very commmon).
12508     if (AllElementsInt)
12509       AllElementsInt = ECD->getType() == Context.IntTy;
12510   }
12511 
12512   // Figure out the type that should be used for this enum.
12513   QualType BestType;
12514   unsigned BestWidth;
12515 
12516   // C++0x N3000 [conv.prom]p3:
12517   //   An rvalue of an unscoped enumeration type whose underlying
12518   //   type is not fixed can be converted to an rvalue of the first
12519   //   of the following types that can represent all the values of
12520   //   the enumeration: int, unsigned int, long int, unsigned long
12521   //   int, long long int, or unsigned long long int.
12522   // C99 6.4.4.3p2:
12523   //   An identifier declared as an enumeration constant has type int.
12524   // The C99 rule is modified by a gcc extension
12525   QualType BestPromotionType;
12526 
12527   bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
12528   // -fshort-enums is the equivalent to specifying the packed attribute on all
12529   // enum definitions.
12530   if (LangOpts.ShortEnums)
12531     Packed = true;
12532 
12533   if (Enum->isFixed()) {
12534     BestType = Enum->getIntegerType();
12535     if (BestType->isPromotableIntegerType())
12536       BestPromotionType = Context.getPromotedIntegerType(BestType);
12537     else
12538       BestPromotionType = BestType;
12539     // We don't need to set BestWidth, because BestType is going to be the type
12540     // of the enumerators, but we do anyway because otherwise some compilers
12541     // warn that it might be used uninitialized.
12542     BestWidth = CharWidth;
12543   }
12544   else if (NumNegativeBits) {
12545     // If there is a negative value, figure out the smallest integer type (of
12546     // int/long/longlong) that fits.
12547     // If it's packed, check also if it fits a char or a short.
12548     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
12549       BestType = Context.SignedCharTy;
12550       BestWidth = CharWidth;
12551     } else if (Packed && NumNegativeBits <= ShortWidth &&
12552                NumPositiveBits < ShortWidth) {
12553       BestType = Context.ShortTy;
12554       BestWidth = ShortWidth;
12555     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
12556       BestType = Context.IntTy;
12557       BestWidth = IntWidth;
12558     } else {
12559       BestWidth = Context.getTargetInfo().getLongWidth();
12560 
12561       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
12562         BestType = Context.LongTy;
12563       } else {
12564         BestWidth = Context.getTargetInfo().getLongLongWidth();
12565 
12566         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
12567           Diag(Enum->getLocation(), diag::warn_enum_too_large);
12568         BestType = Context.LongLongTy;
12569       }
12570     }
12571     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
12572   } else {
12573     // If there is no negative value, figure out the smallest type that fits
12574     // all of the enumerator values.
12575     // If it's packed, check also if it fits a char or a short.
12576     if (Packed && NumPositiveBits <= CharWidth) {
12577       BestType = Context.UnsignedCharTy;
12578       BestPromotionType = Context.IntTy;
12579       BestWidth = CharWidth;
12580     } else if (Packed && NumPositiveBits <= ShortWidth) {
12581       BestType = Context.UnsignedShortTy;
12582       BestPromotionType = Context.IntTy;
12583       BestWidth = ShortWidth;
12584     } else if (NumPositiveBits <= IntWidth) {
12585       BestType = Context.UnsignedIntTy;
12586       BestWidth = IntWidth;
12587       BestPromotionType
12588         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12589                            ? Context.UnsignedIntTy : Context.IntTy;
12590     } else if (NumPositiveBits <=
12591                (BestWidth = Context.getTargetInfo().getLongWidth())) {
12592       BestType = Context.UnsignedLongTy;
12593       BestPromotionType
12594         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12595                            ? Context.UnsignedLongTy : Context.LongTy;
12596     } else {
12597       BestWidth = Context.getTargetInfo().getLongLongWidth();
12598       assert(NumPositiveBits <= BestWidth &&
12599              "How could an initializer get larger than ULL?");
12600       BestType = Context.UnsignedLongLongTy;
12601       BestPromotionType
12602         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12603                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
12604     }
12605   }
12606 
12607   // Loop over all of the enumerator constants, changing their types to match
12608   // the type of the enum if needed.
12609   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12610     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12611     if (!ECD) continue;  // Already issued a diagnostic.
12612 
12613     // Standard C says the enumerators have int type, but we allow, as an
12614     // extension, the enumerators to be larger than int size.  If each
12615     // enumerator value fits in an int, type it as an int, otherwise type it the
12616     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
12617     // that X has type 'int', not 'unsigned'.
12618 
12619     // Determine whether the value fits into an int.
12620     llvm::APSInt InitVal = ECD->getInitVal();
12621 
12622     // If it fits into an integer type, force it.  Otherwise force it to match
12623     // the enum decl type.
12624     QualType NewTy;
12625     unsigned NewWidth;
12626     bool NewSign;
12627     if (!getLangOpts().CPlusPlus &&
12628         !Enum->isFixed() &&
12629         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
12630       NewTy = Context.IntTy;
12631       NewWidth = IntWidth;
12632       NewSign = true;
12633     } else if (ECD->getType() == BestType) {
12634       // Already the right type!
12635       if (getLangOpts().CPlusPlus)
12636         // C++ [dcl.enum]p4: Following the closing brace of an
12637         // enum-specifier, each enumerator has the type of its
12638         // enumeration.
12639         ECD->setType(EnumType);
12640       continue;
12641     } else {
12642       NewTy = BestType;
12643       NewWidth = BestWidth;
12644       NewSign = BestType->isSignedIntegerOrEnumerationType();
12645     }
12646 
12647     // Adjust the APSInt value.
12648     InitVal = InitVal.extOrTrunc(NewWidth);
12649     InitVal.setIsSigned(NewSign);
12650     ECD->setInitVal(InitVal);
12651 
12652     // Adjust the Expr initializer and type.
12653     if (ECD->getInitExpr() &&
12654         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
12655       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
12656                                                 CK_IntegralCast,
12657                                                 ECD->getInitExpr(),
12658                                                 /*base paths*/ 0,
12659                                                 VK_RValue));
12660     if (getLangOpts().CPlusPlus)
12661       // C++ [dcl.enum]p4: Following the closing brace of an
12662       // enum-specifier, each enumerator has the type of its
12663       // enumeration.
12664       ECD->setType(EnumType);
12665     else
12666       ECD->setType(NewTy);
12667   }
12668 
12669   Enum->completeDefinition(BestType, BestPromotionType,
12670                            NumPositiveBits, NumNegativeBits);
12671 
12672   // If we're declaring a function, ensure this decl isn't forgotten about -
12673   // it needs to go into the function scope.
12674   if (InFunctionDeclarator)
12675     DeclsInPrototypeScope.push_back(Enum);
12676 
12677   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
12678 
12679   // Now that the enum type is defined, ensure it's not been underaligned.
12680   if (Enum->hasAttrs())
12681     CheckAlignasUnderalignment(Enum);
12682 }
12683 
12684 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12685                                   SourceLocation StartLoc,
12686                                   SourceLocation EndLoc) {
12687   StringLiteral *AsmString = cast<StringLiteral>(expr);
12688 
12689   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
12690                                                    AsmString, StartLoc,
12691                                                    EndLoc);
12692   CurContext->addDecl(New);
12693   return New;
12694 }
12695 
12696 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12697                                    SourceLocation ImportLoc,
12698                                    ModuleIdPath Path) {
12699   Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
12700                                                 Module::AllVisible,
12701                                                 /*IsIncludeDirective=*/false);
12702   if (!Mod)
12703     return true;
12704 
12705   SmallVector<SourceLocation, 2> IdentifierLocs;
12706   Module *ModCheck = Mod;
12707   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12708     // If we've run out of module parents, just drop the remaining identifiers.
12709     // We need the length to be consistent.
12710     if (!ModCheck)
12711       break;
12712     ModCheck = ModCheck->Parent;
12713 
12714     IdentifierLocs.push_back(Path[I].second);
12715   }
12716 
12717   ImportDecl *Import = ImportDecl::Create(Context,
12718                                           Context.getTranslationUnitDecl(),
12719                                           AtLoc.isValid()? AtLoc : ImportLoc,
12720                                           Mod, IdentifierLocs);
12721   Context.getTranslationUnitDecl()->addDecl(Import);
12722   return Import;
12723 }
12724 
12725 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12726   // Create the implicit import declaration.
12727   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12728   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12729                                                    Loc, Mod, Loc);
12730   TU->addDecl(ImportD);
12731   Consumer.HandleImplicitImportDecl(ImportD);
12732 
12733   // Make the module visible.
12734   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12735                                          /*Complain=*/false);
12736 }
12737 
12738 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12739                                       IdentifierInfo* AliasName,
12740                                       SourceLocation PragmaLoc,
12741                                       SourceLocation NameLoc,
12742                                       SourceLocation AliasNameLoc) {
12743   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12744                                     LookupOrdinaryName);
12745   AsmLabelAttr *Attr =
12746      ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
12747 
12748   if (PrevDecl)
12749     PrevDecl->addAttr(Attr);
12750   else
12751     (void)ExtnameUndeclaredIdentifiers.insert(
12752       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12753 }
12754 
12755 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12756                              SourceLocation PragmaLoc,
12757                              SourceLocation NameLoc) {
12758   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
12759 
12760   if (PrevDecl) {
12761     PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
12762   } else {
12763     (void)WeakUndeclaredIdentifiers.insert(
12764       std::pair<IdentifierInfo*,WeakInfo>
12765         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
12766   }
12767 }
12768 
12769 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12770                                 IdentifierInfo* AliasName,
12771                                 SourceLocation PragmaLoc,
12772                                 SourceLocation NameLoc,
12773                                 SourceLocation AliasNameLoc) {
12774   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12775                                     LookupOrdinaryName);
12776   WeakInfo W = WeakInfo(Name, NameLoc);
12777 
12778   if (PrevDecl) {
12779     if (!PrevDecl->hasAttr<AliasAttr>())
12780       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
12781         DeclApplyPragmaWeak(TUScope, ND, W);
12782   } else {
12783     (void)WeakUndeclaredIdentifiers.insert(
12784       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
12785   }
12786 }
12787 
12788 Decl *Sema::getObjCDeclContext() const {
12789   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12790 }
12791 
12792 AvailabilityResult Sema::getCurContextAvailability() const {
12793   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
12794   return D->getAvailability();
12795 }
12796