1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
32 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
34 #include "clang/Parse/ParseDiagnostic.h"
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/Triple.h"
45 #include <algorithm>
46 #include <cstring>
47 #include <functional>
48 using namespace clang;
49 using namespace sema;
50 
51 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
52   if (OwnedType) {
53     Decl *Group[2] = { OwnedType, Ptr };
54     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
55   }
56 
57   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
58 }
59 
60 namespace {
61 
62 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
63  public:
64   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
65       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
66     WantExpressionKeywords = false;
67     WantCXXNamedCasts = false;
68     WantRemainingKeywords = false;
69   }
70 
71   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
72     if (NamedDecl *ND = candidate.getCorrectionDecl())
73       return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
74           (AllowInvalidDecl || !ND->isInvalidDecl());
75     else
76       return !WantClassName && candidate.isKeyword();
77   }
78 
79  private:
80   bool AllowInvalidDecl;
81   bool WantClassName;
82 };
83 
84 }
85 
86 /// \brief Determine whether the token kind starts a simple-type-specifier.
87 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
88   switch (Kind) {
89   // FIXME: Take into account the current language when deciding whether a
90   // token kind is a valid type specifier
91   case tok::kw_short:
92   case tok::kw_long:
93   case tok::kw___int64:
94   case tok::kw___int128:
95   case tok::kw_signed:
96   case tok::kw_unsigned:
97   case tok::kw_void:
98   case tok::kw_char:
99   case tok::kw_int:
100   case tok::kw_half:
101   case tok::kw_float:
102   case tok::kw_double:
103   case tok::kw_wchar_t:
104   case tok::kw_bool:
105   case tok::kw___underlying_type:
106     return true;
107 
108   case tok::annot_typename:
109   case tok::kw_char16_t:
110   case tok::kw_char32_t:
111   case tok::kw_typeof:
112   case tok::annot_decltype:
113   case tok::kw_decltype:
114     return getLangOpts().CPlusPlus;
115 
116   default:
117     break;
118   }
119 
120   return false;
121 }
122 
123 /// \brief If the identifier refers to a type name within this scope,
124 /// return the declaration of that type.
125 ///
126 /// This routine performs ordinary name lookup of the identifier II
127 /// within the given scope, with optional C++ scope specifier SS, to
128 /// determine whether the name refers to a type. If so, returns an
129 /// opaque pointer (actually a QualType) corresponding to that
130 /// type. Otherwise, returns NULL.
131 ///
132 /// If name lookup results in an ambiguity, this routine will complain
133 /// and then return NULL.
134 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
135                              Scope *S, CXXScopeSpec *SS,
136                              bool isClassName, bool HasTrailingDot,
137                              ParsedType ObjectTypePtr,
138                              bool IsCtorOrDtorName,
139                              bool WantNontrivialTypeSourceInfo,
140                              IdentifierInfo **CorrectedII) {
141   // Determine where we will perform name lookup.
142   DeclContext *LookupCtx = 0;
143   if (ObjectTypePtr) {
144     QualType ObjectType = ObjectTypePtr.get();
145     if (ObjectType->isRecordType())
146       LookupCtx = computeDeclContext(ObjectType);
147   } else if (SS && SS->isNotEmpty()) {
148     LookupCtx = computeDeclContext(*SS, false);
149 
150     if (!LookupCtx) {
151       if (isDependentScopeSpecifier(*SS)) {
152         // C++ [temp.res]p3:
153         //   A qualified-id that refers to a type and in which the
154         //   nested-name-specifier depends on a template-parameter (14.6.2)
155         //   shall be prefixed by the keyword typename to indicate that the
156         //   qualified-id denotes a type, forming an
157         //   elaborated-type-specifier (7.1.5.3).
158         //
159         // We therefore do not perform any name lookup if the result would
160         // refer to a member of an unknown specialization.
161         if (!isClassName && !IsCtorOrDtorName)
162           return ParsedType();
163 
164         // We know from the grammar that this name refers to a type,
165         // so build a dependent node to describe the type.
166         if (WantNontrivialTypeSourceInfo)
167           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
168 
169         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
170         QualType T =
171           CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
172                             II, NameLoc);
173 
174           return ParsedType::make(T);
175       }
176 
177       return ParsedType();
178     }
179 
180     if (!LookupCtx->isDependentContext() &&
181         RequireCompleteDeclContext(*SS, LookupCtx))
182       return ParsedType();
183   }
184 
185   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
186   // lookup for class-names.
187   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
188                                       LookupOrdinaryName;
189   LookupResult Result(*this, &II, NameLoc, Kind);
190   if (LookupCtx) {
191     // Perform "qualified" name lookup into the declaration context we
192     // computed, which is either the type of the base of a member access
193     // expression or the declaration context associated with a prior
194     // nested-name-specifier.
195     LookupQualifiedName(Result, LookupCtx);
196 
197     if (ObjectTypePtr && Result.empty()) {
198       // C++ [basic.lookup.classref]p3:
199       //   If the unqualified-id is ~type-name, the type-name is looked up
200       //   in the context of the entire postfix-expression. If the type T of
201       //   the object expression is of a class type C, the type-name is also
202       //   looked up in the scope of class C. At least one of the lookups shall
203       //   find a name that refers to (possibly cv-qualified) T.
204       LookupName(Result, S);
205     }
206   } else {
207     // Perform unqualified name lookup.
208     LookupName(Result, S);
209   }
210 
211   NamedDecl *IIDecl = 0;
212   switch (Result.getResultKind()) {
213   case LookupResult::NotFound:
214   case LookupResult::NotFoundInCurrentInstantiation:
215     if (CorrectedII) {
216       TypeNameValidatorCCC Validator(true, isClassName);
217       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
218                                               Kind, S, SS, Validator);
219       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
220       TemplateTy Template;
221       bool MemberOfUnknownSpecialization;
222       UnqualifiedId TemplateName;
223       TemplateName.setIdentifier(NewII, NameLoc);
224       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
225       CXXScopeSpec NewSS, *NewSSPtr = SS;
226       if (SS && NNS) {
227         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
228         NewSSPtr = &NewSS;
229       }
230       if (Correction && (NNS || NewII != &II) &&
231           // Ignore a correction to a template type as the to-be-corrected
232           // identifier is not a template (typo correction for template names
233           // is handled elsewhere).
234           !(getLangOpts().CPlusPlus && NewSSPtr &&
235             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
236                            false, Template, MemberOfUnknownSpecialization))) {
237         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
238                                     isClassName, HasTrailingDot, ObjectTypePtr,
239                                     IsCtorOrDtorName,
240                                     WantNontrivialTypeSourceInfo);
241         if (Ty) {
242           diagnoseTypo(Correction,
243                        PDiag(diag::err_unknown_type_or_class_name_suggest)
244                          << Result.getLookupName() << isClassName);
245           if (SS && NNS)
246             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
247           *CorrectedII = NewII;
248           return Ty;
249         }
250       }
251     }
252     // If typo correction failed or was not performed, fall through
253   case LookupResult::FoundOverloaded:
254   case LookupResult::FoundUnresolvedValue:
255     Result.suppressDiagnostics();
256     return ParsedType();
257 
258   case LookupResult::Ambiguous:
259     // Recover from type-hiding ambiguities by hiding the type.  We'll
260     // do the lookup again when looking for an object, and we can
261     // diagnose the error then.  If we don't do this, then the error
262     // about hiding the type will be immediately followed by an error
263     // that only makes sense if the identifier was treated like a type.
264     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
265       Result.suppressDiagnostics();
266       return ParsedType();
267     }
268 
269     // Look to see if we have a type anywhere in the list of results.
270     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
271          Res != ResEnd; ++Res) {
272       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
273         if (!IIDecl ||
274             (*Res)->getLocation().getRawEncoding() <
275               IIDecl->getLocation().getRawEncoding())
276           IIDecl = *Res;
277       }
278     }
279 
280     if (!IIDecl) {
281       // None of the entities we found is a type, so there is no way
282       // to even assume that the result is a type. In this case, don't
283       // complain about the ambiguity. The parser will either try to
284       // perform this lookup again (e.g., as an object name), which
285       // will produce the ambiguity, or will complain that it expected
286       // a type name.
287       Result.suppressDiagnostics();
288       return ParsedType();
289     }
290 
291     // We found a type within the ambiguous lookup; diagnose the
292     // ambiguity and then return that type. This might be the right
293     // answer, or it might not be, but it suppresses any attempt to
294     // perform the name lookup again.
295     break;
296 
297   case LookupResult::Found:
298     IIDecl = Result.getFoundDecl();
299     break;
300   }
301 
302   assert(IIDecl && "Didn't find decl");
303 
304   QualType T;
305   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
306     DiagnoseUseOfDecl(IIDecl, NameLoc);
307 
308     if (T.isNull())
309       T = Context.getTypeDeclType(TD);
310 
311     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
312     // constructor or destructor name (in such a case, the scope specifier
313     // will be attached to the enclosing Expr or Decl node).
314     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
315       if (WantNontrivialTypeSourceInfo) {
316         // Construct a type with type-source information.
317         TypeLocBuilder Builder;
318         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
319 
320         T = getElaboratedType(ETK_None, *SS, T);
321         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
322         ElabTL.setElaboratedKeywordLoc(SourceLocation());
323         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
324         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
325       } else {
326         T = getElaboratedType(ETK_None, *SS, T);
327       }
328     }
329   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
330     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
331     if (!HasTrailingDot)
332       T = Context.getObjCInterfaceType(IDecl);
333   }
334 
335   if (T.isNull()) {
336     // If it's not plausibly a type, suppress diagnostics.
337     Result.suppressDiagnostics();
338     return ParsedType();
339   }
340   return ParsedType::make(T);
341 }
342 
343 /// isTagName() - This method is called *for error recovery purposes only*
344 /// to determine if the specified name is a valid tag name ("struct foo").  If
345 /// so, this returns the TST for the tag corresponding to it (TST_enum,
346 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
347 /// cases in C where the user forgot to specify the tag.
348 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
349   // Do a tag name lookup in this scope.
350   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
351   LookupName(R, S, false);
352   R.suppressDiagnostics();
353   if (R.getResultKind() == LookupResult::Found)
354     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
355       switch (TD->getTagKind()) {
356       case TTK_Struct: return DeclSpec::TST_struct;
357       case TTK_Interface: return DeclSpec::TST_interface;
358       case TTK_Union:  return DeclSpec::TST_union;
359       case TTK_Class:  return DeclSpec::TST_class;
360       case TTK_Enum:   return DeclSpec::TST_enum;
361       }
362     }
363 
364   return DeclSpec::TST_unspecified;
365 }
366 
367 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
368 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
369 /// then downgrade the missing typename error to a warning.
370 /// This is needed for MSVC compatibility; Example:
371 /// @code
372 /// template<class T> class A {
373 /// public:
374 ///   typedef int TYPE;
375 /// };
376 /// template<class T> class B : public A<T> {
377 /// public:
378 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
379 /// };
380 /// @endcode
381 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
382   if (CurContext->isRecord()) {
383     const Type *Ty = SS->getScopeRep()->getAsType();
384 
385     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
386     for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
387           BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
388       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
389         return true;
390     return S->isFunctionPrototypeScope();
391   }
392   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
393 }
394 
395 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
396                                    SourceLocation IILoc,
397                                    Scope *S,
398                                    CXXScopeSpec *SS,
399                                    ParsedType &SuggestedType) {
400   // We don't have anything to suggest (yet).
401   SuggestedType = ParsedType();
402 
403   // There may have been a typo in the name of the type. Look up typo
404   // results, in case we have something that we can suggest.
405   TypeNameValidatorCCC Validator(false);
406   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
407                                              LookupOrdinaryName, S, SS,
408                                              Validator)) {
409     if (Corrected.isKeyword()) {
410       // We corrected to a keyword.
411       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
412       II = Corrected.getCorrectionAsIdentifierInfo();
413     } else {
414       // We found a similarly-named type or interface; suggest that.
415       if (!SS || !SS->isSet()) {
416         diagnoseTypo(Corrected,
417                      PDiag(diag::err_unknown_typename_suggest) << II);
418       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
419         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
420         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
421                                 II->getName().equals(CorrectedStr);
422         diagnoseTypo(Corrected,
423                      PDiag(diag::err_unknown_nested_typename_suggest)
424                        << II << DC << DroppedSpecifier << SS->getRange());
425       } else {
426         llvm_unreachable("could not have corrected a typo here");
427       }
428 
429       CXXScopeSpec tmpSS;
430       if (Corrected.getCorrectionSpecifier())
431         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
432                           SourceRange(IILoc));
433       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
434                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
435                                   false, ParsedType(),
436                                   /*IsCtorOrDtorName=*/false,
437                                   /*NonTrivialTypeSourceInfo=*/true);
438     }
439     return true;
440   }
441 
442   if (getLangOpts().CPlusPlus) {
443     // See if II is a class template that the user forgot to pass arguments to.
444     UnqualifiedId Name;
445     Name.setIdentifier(II, IILoc);
446     CXXScopeSpec EmptySS;
447     TemplateTy TemplateResult;
448     bool MemberOfUnknownSpecialization;
449     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
450                        Name, ParsedType(), true, TemplateResult,
451                        MemberOfUnknownSpecialization) == TNK_Type_template) {
452       TemplateName TplName = TemplateResult.get();
453       Diag(IILoc, diag::err_template_missing_args) << TplName;
454       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
455         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
456           << TplDecl->getTemplateParameters()->getSourceRange();
457       }
458       return true;
459     }
460   }
461 
462   // FIXME: Should we move the logic that tries to recover from a missing tag
463   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
464 
465   if (!SS || (!SS->isSet() && !SS->isInvalid()))
466     Diag(IILoc, diag::err_unknown_typename) << II;
467   else if (DeclContext *DC = computeDeclContext(*SS, false))
468     Diag(IILoc, diag::err_typename_nested_not_found)
469       << II << DC << SS->getRange();
470   else if (isDependentScopeSpecifier(*SS)) {
471     unsigned DiagID = diag::err_typename_missing;
472     if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
473       DiagID = diag::warn_typename_missing;
474 
475     Diag(SS->getRange().getBegin(), DiagID)
476       << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
477       << SourceRange(SS->getRange().getBegin(), IILoc)
478       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
479     SuggestedType = ActOnTypenameType(S, SourceLocation(),
480                                       *SS, *II, IILoc).get();
481   } else {
482     assert(SS && SS->isInvalid() &&
483            "Invalid scope specifier has already been diagnosed");
484   }
485 
486   return true;
487 }
488 
489 /// \brief Determine whether the given result set contains either a type name
490 /// or
491 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
492   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
493                        NextToken.is(tok::less);
494 
495   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
496     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
497       return true;
498 
499     if (CheckTemplate && isa<TemplateDecl>(*I))
500       return true;
501   }
502 
503   return false;
504 }
505 
506 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
507                                     Scope *S, CXXScopeSpec &SS,
508                                     IdentifierInfo *&Name,
509                                     SourceLocation NameLoc) {
510   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
511   SemaRef.LookupParsedName(R, S, &SS);
512   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
513     const char *TagName = 0;
514     const char *FixItTagName = 0;
515     switch (Tag->getTagKind()) {
516       case TTK_Class:
517         TagName = "class";
518         FixItTagName = "class ";
519         break;
520 
521       case TTK_Enum:
522         TagName = "enum";
523         FixItTagName = "enum ";
524         break;
525 
526       case TTK_Struct:
527         TagName = "struct";
528         FixItTagName = "struct ";
529         break;
530 
531       case TTK_Interface:
532         TagName = "__interface";
533         FixItTagName = "__interface ";
534         break;
535 
536       case TTK_Union:
537         TagName = "union";
538         FixItTagName = "union ";
539         break;
540     }
541 
542     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
543       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
544       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
545 
546     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
547          I != IEnd; ++I)
548       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
549         << Name << TagName;
550 
551     // Replace lookup results with just the tag decl.
552     Result.clear(Sema::LookupTagName);
553     SemaRef.LookupParsedName(Result, S, &SS);
554     return true;
555   }
556 
557   return false;
558 }
559 
560 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
561 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
562                                   QualType T, SourceLocation NameLoc) {
563   ASTContext &Context = S.Context;
564 
565   TypeLocBuilder Builder;
566   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
567 
568   T = S.getElaboratedType(ETK_None, SS, T);
569   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
570   ElabTL.setElaboratedKeywordLoc(SourceLocation());
571   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
572   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
573 }
574 
575 Sema::NameClassification Sema::ClassifyName(Scope *S,
576                                             CXXScopeSpec &SS,
577                                             IdentifierInfo *&Name,
578                                             SourceLocation NameLoc,
579                                             const Token &NextToken,
580                                             bool IsAddressOfOperand,
581                                             CorrectionCandidateCallback *CCC) {
582   DeclarationNameInfo NameInfo(Name, NameLoc);
583   ObjCMethodDecl *CurMethod = getCurMethodDecl();
584 
585   if (NextToken.is(tok::coloncolon)) {
586     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
587                                 QualType(), false, SS, 0, false);
588 
589   }
590 
591   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
592   LookupParsedName(Result, S, &SS, !CurMethod);
593 
594   // Perform lookup for Objective-C instance variables (including automatically
595   // synthesized instance variables), if we're in an Objective-C method.
596   // FIXME: This lookup really, really needs to be folded in to the normal
597   // unqualified lookup mechanism.
598   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
599     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
600     if (E.get() || E.isInvalid())
601       return E;
602   }
603 
604   bool SecondTry = false;
605   bool IsFilteredTemplateName = false;
606 
607 Corrected:
608   switch (Result.getResultKind()) {
609   case LookupResult::NotFound:
610     // If an unqualified-id is followed by a '(', then we have a function
611     // call.
612     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
613       // In C++, this is an ADL-only call.
614       // FIXME: Reference?
615       if (getLangOpts().CPlusPlus)
616         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
617 
618       // C90 6.3.2.2:
619       //   If the expression that precedes the parenthesized argument list in a
620       //   function call consists solely of an identifier, and if no
621       //   declaration is visible for this identifier, the identifier is
622       //   implicitly declared exactly as if, in the innermost block containing
623       //   the function call, the declaration
624       //
625       //     extern int identifier ();
626       //
627       //   appeared.
628       //
629       // We also allow this in C99 as an extension.
630       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
631         Result.addDecl(D);
632         Result.resolveKind();
633         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
634       }
635     }
636 
637     // In C, we first see whether there is a tag type by the same name, in
638     // which case it's likely that the user just forget to write "enum",
639     // "struct", or "union".
640     if (!getLangOpts().CPlusPlus && !SecondTry &&
641         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
642       break;
643     }
644 
645     // Perform typo correction to determine if there is another name that is
646     // close to this name.
647     if (!SecondTry && CCC) {
648       SecondTry = true;
649       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
650                                                  Result.getLookupKind(), S,
651                                                  &SS, *CCC)) {
652         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
653         unsigned QualifiedDiag = diag::err_no_member_suggest;
654 
655         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
656         NamedDecl *UnderlyingFirstDecl
657           = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
658         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
659             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
660           UnqualifiedDiag = diag::err_no_template_suggest;
661           QualifiedDiag = diag::err_no_member_template_suggest;
662         } else if (UnderlyingFirstDecl &&
663                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
664                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
665                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
666           UnqualifiedDiag = diag::err_unknown_typename_suggest;
667           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
668         }
669 
670         if (SS.isEmpty()) {
671           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
672         } else {// FIXME: is this even reachable? Test it.
673           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
674           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
675                                   Name->getName().equals(CorrectedStr);
676           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
677                                     << Name << computeDeclContext(SS, false)
678                                     << DroppedSpecifier << SS.getRange());
679         }
680 
681         // Update the name, so that the caller has the new name.
682         Name = Corrected.getCorrectionAsIdentifierInfo();
683 
684         // Typo correction corrected to a keyword.
685         if (Corrected.isKeyword())
686           return Name;
687 
688         // Also update the LookupResult...
689         // FIXME: This should probably go away at some point
690         Result.clear();
691         Result.setLookupName(Corrected.getCorrection());
692         if (FirstDecl)
693           Result.addDecl(FirstDecl);
694 
695         // If we found an Objective-C instance variable, let
696         // LookupInObjCMethod build the appropriate expression to
697         // reference the ivar.
698         // FIXME: This is a gross hack.
699         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
700           Result.clear();
701           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
702           return E;
703         }
704 
705         goto Corrected;
706       }
707     }
708 
709     // We failed to correct; just fall through and let the parser deal with it.
710     Result.suppressDiagnostics();
711     return NameClassification::Unknown();
712 
713   case LookupResult::NotFoundInCurrentInstantiation: {
714     // We performed name lookup into the current instantiation, and there were
715     // dependent bases, so we treat this result the same way as any other
716     // dependent nested-name-specifier.
717 
718     // C++ [temp.res]p2:
719     //   A name used in a template declaration or definition and that is
720     //   dependent on a template-parameter is assumed not to name a type
721     //   unless the applicable name lookup finds a type name or the name is
722     //   qualified by the keyword typename.
723     //
724     // FIXME: If the next token is '<', we might want to ask the parser to
725     // perform some heroics to see if we actually have a
726     // template-argument-list, which would indicate a missing 'template'
727     // keyword here.
728     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
729                                       NameInfo, IsAddressOfOperand,
730                                       /*TemplateArgs=*/0);
731   }
732 
733   case LookupResult::Found:
734   case LookupResult::FoundOverloaded:
735   case LookupResult::FoundUnresolvedValue:
736     break;
737 
738   case LookupResult::Ambiguous:
739     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
740         hasAnyAcceptableTemplateNames(Result)) {
741       // C++ [temp.local]p3:
742       //   A lookup that finds an injected-class-name (10.2) can result in an
743       //   ambiguity in certain cases (for example, if it is found in more than
744       //   one base class). If all of the injected-class-names that are found
745       //   refer to specializations of the same class template, and if the name
746       //   is followed by a template-argument-list, the reference refers to the
747       //   class template itself and not a specialization thereof, and is not
748       //   ambiguous.
749       //
750       // This filtering can make an ambiguous result into an unambiguous one,
751       // so try again after filtering out template names.
752       FilterAcceptableTemplateNames(Result);
753       if (!Result.isAmbiguous()) {
754         IsFilteredTemplateName = true;
755         break;
756       }
757     }
758 
759     // Diagnose the ambiguity and return an error.
760     return NameClassification::Error();
761   }
762 
763   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
764       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
765     // C++ [temp.names]p3:
766     //   After name lookup (3.4) finds that a name is a template-name or that
767     //   an operator-function-id or a literal- operator-id refers to a set of
768     //   overloaded functions any member of which is a function template if
769     //   this is followed by a <, the < is always taken as the delimiter of a
770     //   template-argument-list and never as the less-than operator.
771     if (!IsFilteredTemplateName)
772       FilterAcceptableTemplateNames(Result);
773 
774     if (!Result.empty()) {
775       bool IsFunctionTemplate;
776       bool IsVarTemplate;
777       TemplateName Template;
778       if (Result.end() - Result.begin() > 1) {
779         IsFunctionTemplate = true;
780         Template = Context.getOverloadedTemplateName(Result.begin(),
781                                                      Result.end());
782       } else {
783         TemplateDecl *TD
784           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
785         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
786         IsVarTemplate = isa<VarTemplateDecl>(TD);
787 
788         if (SS.isSet() && !SS.isInvalid())
789           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
790                                                     /*TemplateKeyword=*/false,
791                                                       TD);
792         else
793           Template = TemplateName(TD);
794       }
795 
796       if (IsFunctionTemplate) {
797         // Function templates always go through overload resolution, at which
798         // point we'll perform the various checks (e.g., accessibility) we need
799         // to based on which function we selected.
800         Result.suppressDiagnostics();
801 
802         return NameClassification::FunctionTemplate(Template);
803       }
804 
805       return IsVarTemplate ? NameClassification::VarTemplate(Template)
806                            : NameClassification::TypeTemplate(Template);
807     }
808   }
809 
810   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
811   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
812     DiagnoseUseOfDecl(Type, NameLoc);
813     QualType T = Context.getTypeDeclType(Type);
814     if (SS.isNotEmpty())
815       return buildNestedType(*this, SS, T, NameLoc);
816     return ParsedType::make(T);
817   }
818 
819   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
820   if (!Class) {
821     // FIXME: It's unfortunate that we don't have a Type node for handling this.
822     if (ObjCCompatibleAliasDecl *Alias
823                                 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
824       Class = Alias->getClassInterface();
825   }
826 
827   if (Class) {
828     DiagnoseUseOfDecl(Class, NameLoc);
829 
830     if (NextToken.is(tok::period)) {
831       // Interface. <something> is parsed as a property reference expression.
832       // Just return "unknown" as a fall-through for now.
833       Result.suppressDiagnostics();
834       return NameClassification::Unknown();
835     }
836 
837     QualType T = Context.getObjCInterfaceType(Class);
838     return ParsedType::make(T);
839   }
840 
841   // We can have a type template here if we're classifying a template argument.
842   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
843     return NameClassification::TypeTemplate(
844         TemplateName(cast<TemplateDecl>(FirstDecl)));
845 
846   // Check for a tag type hidden by a non-type decl in a few cases where it
847   // seems likely a type is wanted instead of the non-type that was found.
848   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
849   if ((NextToken.is(tok::identifier) ||
850        (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
851       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
852     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
853     DiagnoseUseOfDecl(Type, NameLoc);
854     QualType T = Context.getTypeDeclType(Type);
855     if (SS.isNotEmpty())
856       return buildNestedType(*this, SS, T, NameLoc);
857     return ParsedType::make(T);
858   }
859 
860   if (FirstDecl->isCXXClassMember())
861     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
862 
863   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
864   return BuildDeclarationNameExpr(SS, Result, ADL);
865 }
866 
867 // Determines the context to return to after temporarily entering a
868 // context.  This depends in an unnecessarily complicated way on the
869 // exact ordering of callbacks from the parser.
870 DeclContext *Sema::getContainingDC(DeclContext *DC) {
871 
872   // Functions defined inline within classes aren't parsed until we've
873   // finished parsing the top-level class, so the top-level class is
874   // the context we'll need to return to.
875   if (isa<FunctionDecl>(DC)) {
876     DC = DC->getLexicalParent();
877 
878     // A function not defined within a class will always return to its
879     // lexical context.
880     if (!isa<CXXRecordDecl>(DC))
881       return DC;
882 
883     // A C++ inline method/friend is parsed *after* the topmost class
884     // it was declared in is fully parsed ("complete");  the topmost
885     // class is the context we need to return to.
886     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
887       DC = RD;
888 
889     // Return the declaration context of the topmost class the inline method is
890     // declared in.
891     return DC;
892   }
893 
894   return DC->getLexicalParent();
895 }
896 
897 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
898   assert(getContainingDC(DC) == CurContext &&
899       "The next DeclContext should be lexically contained in the current one.");
900   CurContext = DC;
901   S->setEntity(DC);
902 }
903 
904 void Sema::PopDeclContext() {
905   assert(CurContext && "DeclContext imbalance!");
906 
907   CurContext = getContainingDC(CurContext);
908   assert(CurContext && "Popped translation unit!");
909 }
910 
911 /// EnterDeclaratorContext - Used when we must lookup names in the context
912 /// of a declarator's nested name specifier.
913 ///
914 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
915   // C++0x [basic.lookup.unqual]p13:
916   //   A name used in the definition of a static data member of class
917   //   X (after the qualified-id of the static member) is looked up as
918   //   if the name was used in a member function of X.
919   // C++0x [basic.lookup.unqual]p14:
920   //   If a variable member of a namespace is defined outside of the
921   //   scope of its namespace then any name used in the definition of
922   //   the variable member (after the declarator-id) is looked up as
923   //   if the definition of the variable member occurred in its
924   //   namespace.
925   // Both of these imply that we should push a scope whose context
926   // is the semantic context of the declaration.  We can't use
927   // PushDeclContext here because that context is not necessarily
928   // lexically contained in the current context.  Fortunately,
929   // the containing scope should have the appropriate information.
930 
931   assert(!S->getEntity() && "scope already has entity");
932 
933 #ifndef NDEBUG
934   Scope *Ancestor = S->getParent();
935   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
936   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
937 #endif
938 
939   CurContext = DC;
940   S->setEntity(DC);
941 }
942 
943 void Sema::ExitDeclaratorContext(Scope *S) {
944   assert(S->getEntity() == CurContext && "Context imbalance!");
945 
946   // Switch back to the lexical context.  The safety of this is
947   // enforced by an assert in EnterDeclaratorContext.
948   Scope *Ancestor = S->getParent();
949   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
950   CurContext = Ancestor->getEntity();
951 
952   // We don't need to do anything with the scope, which is going to
953   // disappear.
954 }
955 
956 
957 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
958   FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
959   if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
960     // We assume that the caller has already called
961     // ActOnReenterTemplateScope
962     FD = TFD->getTemplatedDecl();
963   }
964   if (!FD)
965     return;
966 
967   // Same implementation as PushDeclContext, but enters the context
968   // from the lexical parent, rather than the top-level class.
969   assert(CurContext == FD->getLexicalParent() &&
970     "The next DeclContext should be lexically contained in the current one.");
971   CurContext = FD;
972   S->setEntity(CurContext);
973 
974   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
975     ParmVarDecl *Param = FD->getParamDecl(P);
976     // If the parameter has an identifier, then add it to the scope
977     if (Param->getIdentifier()) {
978       S->AddDecl(Param);
979       IdResolver.AddDecl(Param);
980     }
981   }
982 }
983 
984 
985 void Sema::ActOnExitFunctionContext() {
986   // Same implementation as PopDeclContext, but returns to the lexical parent,
987   // rather than the top-level class.
988   assert(CurContext && "DeclContext imbalance!");
989   CurContext = CurContext->getLexicalParent();
990   assert(CurContext && "Popped translation unit!");
991 }
992 
993 
994 /// \brief Determine whether we allow overloading of the function
995 /// PrevDecl with another declaration.
996 ///
997 /// This routine determines whether overloading is possible, not
998 /// whether some new function is actually an overload. It will return
999 /// true in C++ (where we can always provide overloads) or, as an
1000 /// extension, in C when the previous function is already an
1001 /// overloaded function declaration or has the "overloadable"
1002 /// attribute.
1003 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1004                                        ASTContext &Context) {
1005   if (Context.getLangOpts().CPlusPlus)
1006     return true;
1007 
1008   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1009     return true;
1010 
1011   return (Previous.getResultKind() == LookupResult::Found
1012           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1013 }
1014 
1015 /// Add this decl to the scope shadowed decl chains.
1016 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1017   // Move up the scope chain until we find the nearest enclosing
1018   // non-transparent context. The declaration will be introduced into this
1019   // scope.
1020   while (S->getEntity() && S->getEntity()->isTransparentContext())
1021     S = S->getParent();
1022 
1023   // Add scoped declarations into their context, so that they can be
1024   // found later. Declarations without a context won't be inserted
1025   // into any context.
1026   if (AddToContext)
1027     CurContext->addDecl(D);
1028 
1029   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1030   // are function-local declarations.
1031   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1032       !D->getDeclContext()->getRedeclContext()->Equals(
1033         D->getLexicalDeclContext()->getRedeclContext()) &&
1034       !D->getLexicalDeclContext()->isFunctionOrMethod())
1035     return;
1036 
1037   // Template instantiations should also not be pushed into scope.
1038   if (isa<FunctionDecl>(D) &&
1039       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1040     return;
1041 
1042   // If this replaces anything in the current scope,
1043   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1044                                IEnd = IdResolver.end();
1045   for (; I != IEnd; ++I) {
1046     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1047       S->RemoveDecl(*I);
1048       IdResolver.RemoveDecl(*I);
1049 
1050       // Should only need to replace one decl.
1051       break;
1052     }
1053   }
1054 
1055   S->AddDecl(D);
1056 
1057   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1058     // Implicitly-generated labels may end up getting generated in an order that
1059     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1060     // the label at the appropriate place in the identifier chain.
1061     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1062       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1063       if (IDC == CurContext) {
1064         if (!S->isDeclScope(*I))
1065           continue;
1066       } else if (IDC->Encloses(CurContext))
1067         break;
1068     }
1069 
1070     IdResolver.InsertDeclAfter(I, D);
1071   } else {
1072     IdResolver.AddDecl(D);
1073   }
1074 }
1075 
1076 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1077   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1078     TUScope->AddDecl(D);
1079 }
1080 
1081 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1082                          bool ExplicitInstantiationOrSpecialization) {
1083   return IdResolver.isDeclInScope(D, Ctx, S,
1084                                   ExplicitInstantiationOrSpecialization);
1085 }
1086 
1087 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1088   DeclContext *TargetDC = DC->getPrimaryContext();
1089   do {
1090     if (DeclContext *ScopeDC = S->getEntity())
1091       if (ScopeDC->getPrimaryContext() == TargetDC)
1092         return S;
1093   } while ((S = S->getParent()));
1094 
1095   return 0;
1096 }
1097 
1098 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1099                                             DeclContext*,
1100                                             ASTContext&);
1101 
1102 /// Filters out lookup results that don't fall within the given scope
1103 /// as determined by isDeclInScope.
1104 void Sema::FilterLookupForScope(LookupResult &R,
1105                                 DeclContext *Ctx, Scope *S,
1106                                 bool ConsiderLinkage,
1107                                 bool ExplicitInstantiationOrSpecialization) {
1108   LookupResult::Filter F = R.makeFilter();
1109   while (F.hasNext()) {
1110     NamedDecl *D = F.next();
1111 
1112     if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1113       continue;
1114 
1115     if (ConsiderLinkage &&
1116         isOutOfScopePreviousDeclaration(D, Ctx, Context))
1117       continue;
1118 
1119     F.erase();
1120   }
1121 
1122   F.done();
1123 }
1124 
1125 static bool isUsingDecl(NamedDecl *D) {
1126   return isa<UsingShadowDecl>(D) ||
1127          isa<UnresolvedUsingTypenameDecl>(D) ||
1128          isa<UnresolvedUsingValueDecl>(D);
1129 }
1130 
1131 /// Removes using shadow declarations from the lookup results.
1132 static void RemoveUsingDecls(LookupResult &R) {
1133   LookupResult::Filter F = R.makeFilter();
1134   while (F.hasNext())
1135     if (isUsingDecl(F.next()))
1136       F.erase();
1137 
1138   F.done();
1139 }
1140 
1141 /// \brief Check for this common pattern:
1142 /// @code
1143 /// class S {
1144 ///   S(const S&); // DO NOT IMPLEMENT
1145 ///   void operator=(const S&); // DO NOT IMPLEMENT
1146 /// };
1147 /// @endcode
1148 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1149   // FIXME: Should check for private access too but access is set after we get
1150   // the decl here.
1151   if (D->doesThisDeclarationHaveABody())
1152     return false;
1153 
1154   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1155     return CD->isCopyConstructor();
1156   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1157     return Method->isCopyAssignmentOperator();
1158   return false;
1159 }
1160 
1161 // We need this to handle
1162 //
1163 // typedef struct {
1164 //   void *foo() { return 0; }
1165 // } A;
1166 //
1167 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1168 // for example. If 'A', foo will have external linkage. If we have '*A',
1169 // foo will have no linkage. Since we can't know untill we get to the end
1170 // of the typedef, this function finds out if D might have non external linkage.
1171 // Callers should verify at the end of the TU if it D has external linkage or
1172 // not.
1173 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1174   const DeclContext *DC = D->getDeclContext();
1175   while (!DC->isTranslationUnit()) {
1176     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1177       if (!RD->hasNameForLinkage())
1178         return true;
1179     }
1180     DC = DC->getParent();
1181   }
1182 
1183   return !D->isExternallyVisible();
1184 }
1185 
1186 // FIXME: This needs to be refactored; some other isInMainFile users want
1187 // these semantics.
1188 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1189   if (S.TUKind != TU_Complete)
1190     return false;
1191   return S.SourceMgr.isInMainFile(Loc);
1192 }
1193 
1194 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1195   assert(D);
1196 
1197   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1198     return false;
1199 
1200   // Ignore class templates.
1201   if (D->getDeclContext()->isDependentContext() ||
1202       D->getLexicalDeclContext()->isDependentContext())
1203     return false;
1204 
1205   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1206     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1207       return false;
1208 
1209     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1210       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1211         return false;
1212     } else {
1213       // 'static inline' functions are defined in headers; don't warn.
1214       if (FD->isInlineSpecified() &&
1215           !isMainFileLoc(*this, FD->getLocation()))
1216         return false;
1217     }
1218 
1219     if (FD->doesThisDeclarationHaveABody() &&
1220         Context.DeclMustBeEmitted(FD))
1221       return false;
1222   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1223     // Constants and utility variables are defined in headers with internal
1224     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1225     // like "inline".)
1226     if (!isMainFileLoc(*this, VD->getLocation()))
1227       return false;
1228 
1229     if (Context.DeclMustBeEmitted(VD))
1230       return false;
1231 
1232     if (VD->isStaticDataMember() &&
1233         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1234       return false;
1235   } else {
1236     return false;
1237   }
1238 
1239   // Only warn for unused decls internal to the translation unit.
1240   return mightHaveNonExternalLinkage(D);
1241 }
1242 
1243 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1244   if (!D)
1245     return;
1246 
1247   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1248     const FunctionDecl *First = FD->getFirstDecl();
1249     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1250       return; // First should already be in the vector.
1251   }
1252 
1253   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1254     const VarDecl *First = VD->getFirstDecl();
1255     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1256       return; // First should already be in the vector.
1257   }
1258 
1259   if (ShouldWarnIfUnusedFileScopedDecl(D))
1260     UnusedFileScopedDecls.push_back(D);
1261 }
1262 
1263 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1264   if (D->isInvalidDecl())
1265     return false;
1266 
1267   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1268     return false;
1269 
1270   if (isa<LabelDecl>(D))
1271     return true;
1272 
1273   // White-list anything that isn't a local variable.
1274   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1275       !D->getDeclContext()->isFunctionOrMethod())
1276     return false;
1277 
1278   // Types of valid local variables should be complete, so this should succeed.
1279   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1280 
1281     // White-list anything with an __attribute__((unused)) type.
1282     QualType Ty = VD->getType();
1283 
1284     // Only look at the outermost level of typedef.
1285     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1286       if (TT->getDecl()->hasAttr<UnusedAttr>())
1287         return false;
1288     }
1289 
1290     // If we failed to complete the type for some reason, or if the type is
1291     // dependent, don't diagnose the variable.
1292     if (Ty->isIncompleteType() || Ty->isDependentType())
1293       return false;
1294 
1295     if (const TagType *TT = Ty->getAs<TagType>()) {
1296       const TagDecl *Tag = TT->getDecl();
1297       if (Tag->hasAttr<UnusedAttr>())
1298         return false;
1299 
1300       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1301         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1302           return false;
1303 
1304         if (const Expr *Init = VD->getInit()) {
1305           if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1306             Init = Cleanups->getSubExpr();
1307           const CXXConstructExpr *Construct =
1308             dyn_cast<CXXConstructExpr>(Init);
1309           if (Construct && !Construct->isElidable()) {
1310             CXXConstructorDecl *CD = Construct->getConstructor();
1311             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1312               return false;
1313           }
1314         }
1315       }
1316     }
1317 
1318     // TODO: __attribute__((unused)) templates?
1319   }
1320 
1321   return true;
1322 }
1323 
1324 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1325                                      FixItHint &Hint) {
1326   if (isa<LabelDecl>(D)) {
1327     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1328                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1329     if (AfterColon.isInvalid())
1330       return;
1331     Hint = FixItHint::CreateRemoval(CharSourceRange::
1332                                     getCharRange(D->getLocStart(), AfterColon));
1333   }
1334   return;
1335 }
1336 
1337 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1338 /// unless they are marked attr(unused).
1339 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1340   FixItHint Hint;
1341   if (!ShouldDiagnoseUnusedDecl(D))
1342     return;
1343 
1344   GenerateFixForUnusedDecl(D, Context, Hint);
1345 
1346   unsigned DiagID;
1347   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1348     DiagID = diag::warn_unused_exception_param;
1349   else if (isa<LabelDecl>(D))
1350     DiagID = diag::warn_unused_label;
1351   else
1352     DiagID = diag::warn_unused_variable;
1353 
1354   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1355 }
1356 
1357 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1358   // Verify that we have no forward references left.  If so, there was a goto
1359   // or address of a label taken, but no definition of it.  Label fwd
1360   // definitions are indicated with a null substmt.
1361   if (L->getStmt() == 0)
1362     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1363 }
1364 
1365 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1366   if (S->decl_empty()) return;
1367   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1368          "Scope shouldn't contain decls!");
1369 
1370   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1371        I != E; ++I) {
1372     Decl *TmpD = (*I);
1373     assert(TmpD && "This decl didn't get pushed??");
1374 
1375     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1376     NamedDecl *D = cast<NamedDecl>(TmpD);
1377 
1378     if (!D->getDeclName()) continue;
1379 
1380     // Diagnose unused variables in this scope.
1381     if (!S->hasUnrecoverableErrorOccurred())
1382       DiagnoseUnusedDecl(D);
1383 
1384     // If this was a forward reference to a label, verify it was defined.
1385     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1386       CheckPoppedLabel(LD, *this);
1387 
1388     // Remove this name from our lexical scope.
1389     IdResolver.RemoveDecl(D);
1390   }
1391   DiagnoseUnusedBackingIvarInAccessor(S);
1392 }
1393 
1394 void Sema::ActOnStartFunctionDeclarator() {
1395   ++InFunctionDeclarator;
1396 }
1397 
1398 void Sema::ActOnEndFunctionDeclarator() {
1399   assert(InFunctionDeclarator);
1400   --InFunctionDeclarator;
1401 }
1402 
1403 /// \brief Look for an Objective-C class in the translation unit.
1404 ///
1405 /// \param Id The name of the Objective-C class we're looking for. If
1406 /// typo-correction fixes this name, the Id will be updated
1407 /// to the fixed name.
1408 ///
1409 /// \param IdLoc The location of the name in the translation unit.
1410 ///
1411 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1412 /// if there is no class with the given name.
1413 ///
1414 /// \returns The declaration of the named Objective-C class, or NULL if the
1415 /// class could not be found.
1416 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1417                                               SourceLocation IdLoc,
1418                                               bool DoTypoCorrection) {
1419   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1420   // creation from this context.
1421   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1422 
1423   if (!IDecl && DoTypoCorrection) {
1424     // Perform typo correction at the given location, but only if we
1425     // find an Objective-C class name.
1426     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1427     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1428                                        LookupOrdinaryName, TUScope, NULL,
1429                                        Validator)) {
1430       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1431       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1432       Id = IDecl->getIdentifier();
1433     }
1434   }
1435   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1436   // This routine must always return a class definition, if any.
1437   if (Def && Def->getDefinition())
1438       Def = Def->getDefinition();
1439   return Def;
1440 }
1441 
1442 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1443 /// from S, where a non-field would be declared. This routine copes
1444 /// with the difference between C and C++ scoping rules in structs and
1445 /// unions. For example, the following code is well-formed in C but
1446 /// ill-formed in C++:
1447 /// @code
1448 /// struct S6 {
1449 ///   enum { BAR } e;
1450 /// };
1451 ///
1452 /// void test_S6() {
1453 ///   struct S6 a;
1454 ///   a.e = BAR;
1455 /// }
1456 /// @endcode
1457 /// For the declaration of BAR, this routine will return a different
1458 /// scope. The scope S will be the scope of the unnamed enumeration
1459 /// within S6. In C++, this routine will return the scope associated
1460 /// with S6, because the enumeration's scope is a transparent
1461 /// context but structures can contain non-field names. In C, this
1462 /// routine will return the translation unit scope, since the
1463 /// enumeration's scope is a transparent context and structures cannot
1464 /// contain non-field names.
1465 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1466   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1467          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1468          (S->isClassScope() && !getLangOpts().CPlusPlus))
1469     S = S->getParent();
1470   return S;
1471 }
1472 
1473 /// \brief Looks up the declaration of "struct objc_super" and
1474 /// saves it for later use in building builtin declaration of
1475 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1476 /// pre-existing declaration exists no action takes place.
1477 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1478                                         IdentifierInfo *II) {
1479   if (!II->isStr("objc_msgSendSuper"))
1480     return;
1481   ASTContext &Context = ThisSema.Context;
1482 
1483   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1484                       SourceLocation(), Sema::LookupTagName);
1485   ThisSema.LookupName(Result, S);
1486   if (Result.getResultKind() == LookupResult::Found)
1487     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1488       Context.setObjCSuperType(Context.getTagDeclType(TD));
1489 }
1490 
1491 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1492 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1493 /// if we're creating this built-in in anticipation of redeclaring the
1494 /// built-in.
1495 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1496                                      Scope *S, bool ForRedeclaration,
1497                                      SourceLocation Loc) {
1498   LookupPredefedObjCSuperType(*this, S, II);
1499 
1500   Builtin::ID BID = (Builtin::ID)bid;
1501 
1502   ASTContext::GetBuiltinTypeError Error;
1503   QualType R = Context.GetBuiltinType(BID, Error);
1504   switch (Error) {
1505   case ASTContext::GE_None:
1506     // Okay
1507     break;
1508 
1509   case ASTContext::GE_Missing_stdio:
1510     if (ForRedeclaration)
1511       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1512         << Context.BuiltinInfo.GetName(BID);
1513     return 0;
1514 
1515   case ASTContext::GE_Missing_setjmp:
1516     if (ForRedeclaration)
1517       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1518         << Context.BuiltinInfo.GetName(BID);
1519     return 0;
1520 
1521   case ASTContext::GE_Missing_ucontext:
1522     if (ForRedeclaration)
1523       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1524         << Context.BuiltinInfo.GetName(BID);
1525     return 0;
1526   }
1527 
1528   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1529     Diag(Loc, diag::ext_implicit_lib_function_decl)
1530       << Context.BuiltinInfo.GetName(BID)
1531       << R;
1532     if (Context.BuiltinInfo.getHeaderName(BID) &&
1533         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1534           != DiagnosticsEngine::Ignored)
1535       Diag(Loc, diag::note_please_include_header)
1536         << Context.BuiltinInfo.getHeaderName(BID)
1537         << Context.BuiltinInfo.GetName(BID);
1538   }
1539 
1540   FunctionDecl *New = FunctionDecl::Create(Context,
1541                                            Context.getTranslationUnitDecl(),
1542                                            Loc, Loc, II, R, /*TInfo=*/0,
1543                                            SC_Extern,
1544                                            false,
1545                                            /*hasPrototype=*/true);
1546   New->setImplicit();
1547 
1548   // Create Decl objects for each parameter, adding them to the
1549   // FunctionDecl.
1550   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1551     SmallVector<ParmVarDecl*, 16> Params;
1552     for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1553       ParmVarDecl *parm =
1554         ParmVarDecl::Create(Context, New, SourceLocation(),
1555                             SourceLocation(), 0,
1556                             FT->getArgType(i), /*TInfo=*/0,
1557                             SC_None, 0);
1558       parm->setScopeInfo(0, i);
1559       Params.push_back(parm);
1560     }
1561     New->setParams(Params);
1562   }
1563 
1564   AddKnownFunctionAttributes(New);
1565 
1566   // TUScope is the translation-unit scope to insert this function into.
1567   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1568   // relate Scopes to DeclContexts, and probably eliminate CurContext
1569   // entirely, but we're not there yet.
1570   DeclContext *SavedContext = CurContext;
1571   CurContext = Context.getTranslationUnitDecl();
1572   PushOnScopeChains(New, TUScope);
1573   CurContext = SavedContext;
1574   return New;
1575 }
1576 
1577 /// \brief Filter out any previous declarations that the given declaration
1578 /// should not consider because they are not permitted to conflict, e.g.,
1579 /// because they come from hidden sub-modules and do not refer to the same
1580 /// entity.
1581 static void filterNonConflictingPreviousDecls(ASTContext &context,
1582                                               NamedDecl *decl,
1583                                               LookupResult &previous){
1584   // This is only interesting when modules are enabled.
1585   if (!context.getLangOpts().Modules)
1586     return;
1587 
1588   // Empty sets are uninteresting.
1589   if (previous.empty())
1590     return;
1591 
1592   LookupResult::Filter filter = previous.makeFilter();
1593   while (filter.hasNext()) {
1594     NamedDecl *old = filter.next();
1595 
1596     // Non-hidden declarations are never ignored.
1597     if (!old->isHidden())
1598       continue;
1599 
1600     if (!old->isExternallyVisible())
1601       filter.erase();
1602   }
1603 
1604   filter.done();
1605 }
1606 
1607 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1608   QualType OldType;
1609   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1610     OldType = OldTypedef->getUnderlyingType();
1611   else
1612     OldType = Context.getTypeDeclType(Old);
1613   QualType NewType = New->getUnderlyingType();
1614 
1615   if (NewType->isVariablyModifiedType()) {
1616     // Must not redefine a typedef with a variably-modified type.
1617     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1618     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1619       << Kind << NewType;
1620     if (Old->getLocation().isValid())
1621       Diag(Old->getLocation(), diag::note_previous_definition);
1622     New->setInvalidDecl();
1623     return true;
1624   }
1625 
1626   if (OldType != NewType &&
1627       !OldType->isDependentType() &&
1628       !NewType->isDependentType() &&
1629       !Context.hasSameType(OldType, NewType)) {
1630     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1631     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1632       << Kind << NewType << OldType;
1633     if (Old->getLocation().isValid())
1634       Diag(Old->getLocation(), diag::note_previous_definition);
1635     New->setInvalidDecl();
1636     return true;
1637   }
1638   return false;
1639 }
1640 
1641 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1642 /// same name and scope as a previous declaration 'Old'.  Figure out
1643 /// how to resolve this situation, merging decls or emitting
1644 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1645 ///
1646 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1647   // If the new decl is known invalid already, don't bother doing any
1648   // merging checks.
1649   if (New->isInvalidDecl()) return;
1650 
1651   // Allow multiple definitions for ObjC built-in typedefs.
1652   // FIXME: Verify the underlying types are equivalent!
1653   if (getLangOpts().ObjC1) {
1654     const IdentifierInfo *TypeID = New->getIdentifier();
1655     switch (TypeID->getLength()) {
1656     default: break;
1657     case 2:
1658       {
1659         if (!TypeID->isStr("id"))
1660           break;
1661         QualType T = New->getUnderlyingType();
1662         if (!T->isPointerType())
1663           break;
1664         if (!T->isVoidPointerType()) {
1665           QualType PT = T->getAs<PointerType>()->getPointeeType();
1666           if (!PT->isStructureType())
1667             break;
1668         }
1669         Context.setObjCIdRedefinitionType(T);
1670         // Install the built-in type for 'id', ignoring the current definition.
1671         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1672         return;
1673       }
1674     case 5:
1675       if (!TypeID->isStr("Class"))
1676         break;
1677       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1678       // Install the built-in type for 'Class', ignoring the current definition.
1679       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1680       return;
1681     case 3:
1682       if (!TypeID->isStr("SEL"))
1683         break;
1684       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1685       // Install the built-in type for 'SEL', ignoring the current definition.
1686       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1687       return;
1688     }
1689     // Fall through - the typedef name was not a builtin type.
1690   }
1691 
1692   // Verify the old decl was also a type.
1693   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1694   if (!Old) {
1695     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1696       << New->getDeclName();
1697 
1698     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1699     if (OldD->getLocation().isValid())
1700       Diag(OldD->getLocation(), diag::note_previous_definition);
1701 
1702     return New->setInvalidDecl();
1703   }
1704 
1705   // If the old declaration is invalid, just give up here.
1706   if (Old->isInvalidDecl())
1707     return New->setInvalidDecl();
1708 
1709   // If the typedef types are not identical, reject them in all languages and
1710   // with any extensions enabled.
1711   if (isIncompatibleTypedef(Old, New))
1712     return;
1713 
1714   // The types match.  Link up the redeclaration chain and merge attributes if
1715   // the old declaration was a typedef.
1716   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1717     New->setPreviousDecl(Typedef);
1718     mergeDeclAttributes(New, Old);
1719   }
1720 
1721   if (getLangOpts().MicrosoftExt)
1722     return;
1723 
1724   if (getLangOpts().CPlusPlus) {
1725     // C++ [dcl.typedef]p2:
1726     //   In a given non-class scope, a typedef specifier can be used to
1727     //   redefine the name of any type declared in that scope to refer
1728     //   to the type to which it already refers.
1729     if (!isa<CXXRecordDecl>(CurContext))
1730       return;
1731 
1732     // C++0x [dcl.typedef]p4:
1733     //   In a given class scope, a typedef specifier can be used to redefine
1734     //   any class-name declared in that scope that is not also a typedef-name
1735     //   to refer to the type to which it already refers.
1736     //
1737     // This wording came in via DR424, which was a correction to the
1738     // wording in DR56, which accidentally banned code like:
1739     //
1740     //   struct S {
1741     //     typedef struct A { } A;
1742     //   };
1743     //
1744     // in the C++03 standard. We implement the C++0x semantics, which
1745     // allow the above but disallow
1746     //
1747     //   struct S {
1748     //     typedef int I;
1749     //     typedef int I;
1750     //   };
1751     //
1752     // since that was the intent of DR56.
1753     if (!isa<TypedefNameDecl>(Old))
1754       return;
1755 
1756     Diag(New->getLocation(), diag::err_redefinition)
1757       << New->getDeclName();
1758     Diag(Old->getLocation(), diag::note_previous_definition);
1759     return New->setInvalidDecl();
1760   }
1761 
1762   // Modules always permit redefinition of typedefs, as does C11.
1763   if (getLangOpts().Modules || getLangOpts().C11)
1764     return;
1765 
1766   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1767   // is normally mapped to an error, but can be controlled with
1768   // -Wtypedef-redefinition.  If either the original or the redefinition is
1769   // in a system header, don't emit this for compatibility with GCC.
1770   if (getDiagnostics().getSuppressSystemWarnings() &&
1771       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1772        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1773     return;
1774 
1775   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1776     << New->getDeclName();
1777   Diag(Old->getLocation(), diag::note_previous_definition);
1778   return;
1779 }
1780 
1781 /// DeclhasAttr - returns true if decl Declaration already has the target
1782 /// attribute.
1783 static bool
1784 DeclHasAttr(const Decl *D, const Attr *A) {
1785   // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1786   // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1787   // responsible for making sure they are consistent.
1788   const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1789   if (AA)
1790     return false;
1791 
1792   // The following thread safety attributes can also be duplicated.
1793   switch (A->getKind()) {
1794     case attr::ExclusiveLocksRequired:
1795     case attr::SharedLocksRequired:
1796     case attr::LocksExcluded:
1797     case attr::ExclusiveLockFunction:
1798     case attr::SharedLockFunction:
1799     case attr::UnlockFunction:
1800     case attr::ExclusiveTrylockFunction:
1801     case attr::SharedTrylockFunction:
1802     case attr::GuardedBy:
1803     case attr::PtGuardedBy:
1804     case attr::AcquiredBefore:
1805     case attr::AcquiredAfter:
1806       return false;
1807     default:
1808       ;
1809   }
1810 
1811   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1812   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1813   for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1814     if ((*i)->getKind() == A->getKind()) {
1815       if (Ann) {
1816         if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1817           return true;
1818         continue;
1819       }
1820       // FIXME: Don't hardcode this check
1821       if (OA && isa<OwnershipAttr>(*i))
1822         return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1823       return true;
1824     }
1825 
1826   return false;
1827 }
1828 
1829 static bool isAttributeTargetADefinition(Decl *D) {
1830   if (VarDecl *VD = dyn_cast<VarDecl>(D))
1831     return VD->isThisDeclarationADefinition();
1832   if (TagDecl *TD = dyn_cast<TagDecl>(D))
1833     return TD->isCompleteDefinition() || TD->isBeingDefined();
1834   return true;
1835 }
1836 
1837 /// Merge alignment attributes from \p Old to \p New, taking into account the
1838 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1839 ///
1840 /// \return \c true if any attributes were added to \p New.
1841 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1842   // Look for alignas attributes on Old, and pick out whichever attribute
1843   // specifies the strictest alignment requirement.
1844   AlignedAttr *OldAlignasAttr = 0;
1845   AlignedAttr *OldStrictestAlignAttr = 0;
1846   unsigned OldAlign = 0;
1847   for (specific_attr_iterator<AlignedAttr>
1848          I = Old->specific_attr_begin<AlignedAttr>(),
1849          E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1850     // FIXME: We have no way of representing inherited dependent alignments
1851     // in a case like:
1852     //   template<int A, int B> struct alignas(A) X;
1853     //   template<int A, int B> struct alignas(B) X {};
1854     // For now, we just ignore any alignas attributes which are not on the
1855     // definition in such a case.
1856     if (I->isAlignmentDependent())
1857       return false;
1858 
1859     if (I->isAlignas())
1860       OldAlignasAttr = *I;
1861 
1862     unsigned Align = I->getAlignment(S.Context);
1863     if (Align > OldAlign) {
1864       OldAlign = Align;
1865       OldStrictestAlignAttr = *I;
1866     }
1867   }
1868 
1869   // Look for alignas attributes on New.
1870   AlignedAttr *NewAlignasAttr = 0;
1871   unsigned NewAlign = 0;
1872   for (specific_attr_iterator<AlignedAttr>
1873          I = New->specific_attr_begin<AlignedAttr>(),
1874          E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1875     if (I->isAlignmentDependent())
1876       return false;
1877 
1878     if (I->isAlignas())
1879       NewAlignasAttr = *I;
1880 
1881     unsigned Align = I->getAlignment(S.Context);
1882     if (Align > NewAlign)
1883       NewAlign = Align;
1884   }
1885 
1886   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1887     // Both declarations have 'alignas' attributes. We require them to match.
1888     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1889     // fall short. (If two declarations both have alignas, they must both match
1890     // every definition, and so must match each other if there is a definition.)
1891 
1892     // If either declaration only contains 'alignas(0)' specifiers, then it
1893     // specifies the natural alignment for the type.
1894     if (OldAlign == 0 || NewAlign == 0) {
1895       QualType Ty;
1896       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1897         Ty = VD->getType();
1898       else
1899         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1900 
1901       if (OldAlign == 0)
1902         OldAlign = S.Context.getTypeAlign(Ty);
1903       if (NewAlign == 0)
1904         NewAlign = S.Context.getTypeAlign(Ty);
1905     }
1906 
1907     if (OldAlign != NewAlign) {
1908       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1909         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1910         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1911       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1912     }
1913   }
1914 
1915   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1916     // C++11 [dcl.align]p6:
1917     //   if any declaration of an entity has an alignment-specifier,
1918     //   every defining declaration of that entity shall specify an
1919     //   equivalent alignment.
1920     // C11 6.7.5/7:
1921     //   If the definition of an object does not have an alignment
1922     //   specifier, any other declaration of that object shall also
1923     //   have no alignment specifier.
1924     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1925       << OldAlignasAttr->isC11();
1926     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1927       << OldAlignasAttr->isC11();
1928   }
1929 
1930   bool AnyAdded = false;
1931 
1932   // Ensure we have an attribute representing the strictest alignment.
1933   if (OldAlign > NewAlign) {
1934     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1935     Clone->setInherited(true);
1936     New->addAttr(Clone);
1937     AnyAdded = true;
1938   }
1939 
1940   // Ensure we have an alignas attribute if the old declaration had one.
1941   if (OldAlignasAttr && !NewAlignasAttr &&
1942       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1943     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1944     Clone->setInherited(true);
1945     New->addAttr(Clone);
1946     AnyAdded = true;
1947   }
1948 
1949   return AnyAdded;
1950 }
1951 
1952 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1953                                bool Override) {
1954   InheritableAttr *NewAttr = NULL;
1955   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1956   if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1957     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1958                                       AA->getIntroduced(), AA->getDeprecated(),
1959                                       AA->getObsoleted(), AA->getUnavailable(),
1960                                       AA->getMessage(), Override,
1961                                       AttrSpellingListIndex);
1962   else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1963     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1964                                     AttrSpellingListIndex);
1965   else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1966     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1967                                         AttrSpellingListIndex);
1968   else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1969     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1970                                    AttrSpellingListIndex);
1971   else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1972     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1973                                    AttrSpellingListIndex);
1974   else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1975     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1976                                 FA->getFormatIdx(), FA->getFirstArg(),
1977                                 AttrSpellingListIndex);
1978   else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1979     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1980                                  AttrSpellingListIndex);
1981   else if (isa<AlignedAttr>(Attr))
1982     // AlignedAttrs are handled separately, because we need to handle all
1983     // such attributes on a declaration at the same time.
1984     NewAttr = 0;
1985   else if (!DeclHasAttr(D, Attr))
1986     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
1987 
1988   if (NewAttr) {
1989     NewAttr->setInherited(true);
1990     D->addAttr(NewAttr);
1991     return true;
1992   }
1993 
1994   return false;
1995 }
1996 
1997 static const Decl *getDefinition(const Decl *D) {
1998   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
1999     return TD->getDefinition();
2000   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2001     const VarDecl *Def = VD->getDefinition();
2002     if (Def)
2003       return Def;
2004     return VD->getActingDefinition();
2005   }
2006   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2007     const FunctionDecl* Def;
2008     if (FD->isDefined(Def))
2009       return Def;
2010   }
2011   return NULL;
2012 }
2013 
2014 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2015   for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2016        I != E; ++I) {
2017     Attr *Attribute = *I;
2018     if (Attribute->getKind() == Kind)
2019       return true;
2020   }
2021   return false;
2022 }
2023 
2024 /// checkNewAttributesAfterDef - If we already have a definition, check that
2025 /// there are no new attributes in this declaration.
2026 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2027   if (!New->hasAttrs())
2028     return;
2029 
2030   const Decl *Def = getDefinition(Old);
2031   if (!Def || Def == New)
2032     return;
2033 
2034   AttrVec &NewAttributes = New->getAttrs();
2035   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2036     const Attr *NewAttribute = NewAttributes[I];
2037 
2038     if (isa<AliasAttr>(NewAttribute)) {
2039       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2040         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2041       else {
2042         VarDecl *VD = cast<VarDecl>(New);
2043         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2044                                 VarDecl::TentativeDefinition
2045                             ? diag::err_alias_after_tentative
2046                             : diag::err_redefinition;
2047         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2048         S.Diag(Def->getLocation(), diag::note_previous_definition);
2049         VD->setInvalidDecl();
2050       }
2051       ++I;
2052       continue;
2053     }
2054 
2055     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2056       // Tentative definitions are only interesting for the alias check above.
2057       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2058         ++I;
2059         continue;
2060       }
2061     }
2062 
2063     if (hasAttribute(Def, NewAttribute->getKind())) {
2064       ++I;
2065       continue; // regular attr merging will take care of validating this.
2066     }
2067 
2068     if (isa<C11NoReturnAttr>(NewAttribute)) {
2069       // C's _Noreturn is allowed to be added to a function after it is defined.
2070       ++I;
2071       continue;
2072     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2073       if (AA->isAlignas()) {
2074         // C++11 [dcl.align]p6:
2075         //   if any declaration of an entity has an alignment-specifier,
2076         //   every defining declaration of that entity shall specify an
2077         //   equivalent alignment.
2078         // C11 6.7.5/7:
2079         //   If the definition of an object does not have an alignment
2080         //   specifier, any other declaration of that object shall also
2081         //   have no alignment specifier.
2082         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2083           << AA->isC11();
2084         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2085           << AA->isC11();
2086         NewAttributes.erase(NewAttributes.begin() + I);
2087         --E;
2088         continue;
2089       }
2090     }
2091 
2092     S.Diag(NewAttribute->getLocation(),
2093            diag::warn_attribute_precede_definition);
2094     S.Diag(Def->getLocation(), diag::note_previous_definition);
2095     NewAttributes.erase(NewAttributes.begin() + I);
2096     --E;
2097   }
2098 }
2099 
2100 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2101 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2102                                AvailabilityMergeKind AMK) {
2103   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2104     UsedAttr *NewAttr = OldAttr->clone(Context);
2105     NewAttr->setInherited(true);
2106     New->addAttr(NewAttr);
2107   }
2108 
2109   if (!Old->hasAttrs() && !New->hasAttrs())
2110     return;
2111 
2112   // attributes declared post-definition are currently ignored
2113   checkNewAttributesAfterDef(*this, New, Old);
2114 
2115   if (!Old->hasAttrs())
2116     return;
2117 
2118   bool foundAny = New->hasAttrs();
2119 
2120   // Ensure that any moving of objects within the allocated map is done before
2121   // we process them.
2122   if (!foundAny) New->setAttrs(AttrVec());
2123 
2124   for (specific_attr_iterator<InheritableAttr>
2125          i = Old->specific_attr_begin<InheritableAttr>(),
2126          e = Old->specific_attr_end<InheritableAttr>();
2127        i != e; ++i) {
2128     bool Override = false;
2129     // Ignore deprecated/unavailable/availability attributes if requested.
2130     if (isa<DeprecatedAttr>(*i) ||
2131         isa<UnavailableAttr>(*i) ||
2132         isa<AvailabilityAttr>(*i)) {
2133       switch (AMK) {
2134       case AMK_None:
2135         continue;
2136 
2137       case AMK_Redeclaration:
2138         break;
2139 
2140       case AMK_Override:
2141         Override = true;
2142         break;
2143       }
2144     }
2145 
2146     // Already handled.
2147     if (isa<UsedAttr>(*i))
2148       continue;
2149 
2150     if (mergeDeclAttribute(*this, New, *i, Override))
2151       foundAny = true;
2152   }
2153 
2154   if (mergeAlignedAttrs(*this, New, Old))
2155     foundAny = true;
2156 
2157   if (!foundAny) New->dropAttrs();
2158 }
2159 
2160 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2161 /// to the new one.
2162 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2163                                      const ParmVarDecl *oldDecl,
2164                                      Sema &S) {
2165   // C++11 [dcl.attr.depend]p2:
2166   //   The first declaration of a function shall specify the
2167   //   carries_dependency attribute for its declarator-id if any declaration
2168   //   of the function specifies the carries_dependency attribute.
2169   if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2170       !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2171     S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2172            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2173     // Find the first declaration of the parameter.
2174     // FIXME: Should we build redeclaration chains for function parameters?
2175     const FunctionDecl *FirstFD =
2176       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2177     const ParmVarDecl *FirstVD =
2178       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2179     S.Diag(FirstVD->getLocation(),
2180            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2181   }
2182 
2183   if (!oldDecl->hasAttrs())
2184     return;
2185 
2186   bool foundAny = newDecl->hasAttrs();
2187 
2188   // Ensure that any moving of objects within the allocated map is
2189   // done before we process them.
2190   if (!foundAny) newDecl->setAttrs(AttrVec());
2191 
2192   for (specific_attr_iterator<InheritableParamAttr>
2193        i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2194        e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2195     if (!DeclHasAttr(newDecl, *i)) {
2196       InheritableAttr *newAttr =
2197         cast<InheritableParamAttr>((*i)->clone(S.Context));
2198       newAttr->setInherited(true);
2199       newDecl->addAttr(newAttr);
2200       foundAny = true;
2201     }
2202   }
2203 
2204   if (!foundAny) newDecl->dropAttrs();
2205 }
2206 
2207 namespace {
2208 
2209 /// Used in MergeFunctionDecl to keep track of function parameters in
2210 /// C.
2211 struct GNUCompatibleParamWarning {
2212   ParmVarDecl *OldParm;
2213   ParmVarDecl *NewParm;
2214   QualType PromotedType;
2215 };
2216 
2217 }
2218 
2219 /// getSpecialMember - get the special member enum for a method.
2220 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2221   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2222     if (Ctor->isDefaultConstructor())
2223       return Sema::CXXDefaultConstructor;
2224 
2225     if (Ctor->isCopyConstructor())
2226       return Sema::CXXCopyConstructor;
2227 
2228     if (Ctor->isMoveConstructor())
2229       return Sema::CXXMoveConstructor;
2230   } else if (isa<CXXDestructorDecl>(MD)) {
2231     return Sema::CXXDestructor;
2232   } else if (MD->isCopyAssignmentOperator()) {
2233     return Sema::CXXCopyAssignment;
2234   } else if (MD->isMoveAssignmentOperator()) {
2235     return Sema::CXXMoveAssignment;
2236   }
2237 
2238   return Sema::CXXInvalid;
2239 }
2240 
2241 /// canRedefineFunction - checks if a function can be redefined. Currently,
2242 /// only extern inline functions can be redefined, and even then only in
2243 /// GNU89 mode.
2244 static bool canRedefineFunction(const FunctionDecl *FD,
2245                                 const LangOptions& LangOpts) {
2246   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2247           !LangOpts.CPlusPlus &&
2248           FD->isInlineSpecified() &&
2249           FD->getStorageClass() == SC_Extern);
2250 }
2251 
2252 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2253   const AttributedType *AT = T->getAs<AttributedType>();
2254   while (AT && !AT->isCallingConv())
2255     AT = AT->getModifiedType()->getAs<AttributedType>();
2256   return AT;
2257 }
2258 
2259 template <typename T>
2260 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2261   const DeclContext *DC = Old->getDeclContext();
2262   if (DC->isRecord())
2263     return false;
2264 
2265   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2266   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2267     return true;
2268   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2269     return true;
2270   return false;
2271 }
2272 
2273 /// MergeFunctionDecl - We just parsed a function 'New' from
2274 /// declarator D which has the same name and scope as a previous
2275 /// declaration 'Old'.  Figure out how to resolve this situation,
2276 /// merging decls or emitting diagnostics as appropriate.
2277 ///
2278 /// In C++, New and Old must be declarations that are not
2279 /// overloaded. Use IsOverload to determine whether New and Old are
2280 /// overloaded, and to select the Old declaration that New should be
2281 /// merged with.
2282 ///
2283 /// Returns true if there was an error, false otherwise.
2284 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2285                              bool MergeTypeWithOld) {
2286   // Verify the old decl was also a function.
2287   FunctionDecl *Old = 0;
2288   if (FunctionTemplateDecl *OldFunctionTemplate
2289         = dyn_cast<FunctionTemplateDecl>(OldD))
2290     Old = OldFunctionTemplate->getTemplatedDecl();
2291   else
2292     Old = dyn_cast<FunctionDecl>(OldD);
2293   if (!Old) {
2294     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2295       if (New->getFriendObjectKind()) {
2296         Diag(New->getLocation(), diag::err_using_decl_friend);
2297         Diag(Shadow->getTargetDecl()->getLocation(),
2298              diag::note_using_decl_target);
2299         Diag(Shadow->getUsingDecl()->getLocation(),
2300              diag::note_using_decl) << 0;
2301         return true;
2302       }
2303 
2304       Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2305       Diag(Shadow->getTargetDecl()->getLocation(),
2306            diag::note_using_decl_target);
2307       Diag(Shadow->getUsingDecl()->getLocation(),
2308            diag::note_using_decl) << 0;
2309       return true;
2310     }
2311 
2312     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2313       << New->getDeclName();
2314     Diag(OldD->getLocation(), diag::note_previous_definition);
2315     return true;
2316   }
2317 
2318   // If the old declaration is invalid, just give up here.
2319   if (Old->isInvalidDecl())
2320     return true;
2321 
2322   // Determine whether the previous declaration was a definition,
2323   // implicit declaration, or a declaration.
2324   diag::kind PrevDiag;
2325   if (Old->isThisDeclarationADefinition())
2326     PrevDiag = diag::note_previous_definition;
2327   else if (Old->isImplicit())
2328     PrevDiag = diag::note_previous_implicit_declaration;
2329   else
2330     PrevDiag = diag::note_previous_declaration;
2331 
2332   // Don't complain about this if we're in GNU89 mode and the old function
2333   // is an extern inline function.
2334   // Don't complain about specializations. They are not supposed to have
2335   // storage classes.
2336   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2337       New->getStorageClass() == SC_Static &&
2338       Old->hasExternalFormalLinkage() &&
2339       !New->getTemplateSpecializationInfo() &&
2340       !canRedefineFunction(Old, getLangOpts())) {
2341     if (getLangOpts().MicrosoftExt) {
2342       Diag(New->getLocation(), diag::warn_static_non_static) << New;
2343       Diag(Old->getLocation(), PrevDiag);
2344     } else {
2345       Diag(New->getLocation(), diag::err_static_non_static) << New;
2346       Diag(Old->getLocation(), PrevDiag);
2347       return true;
2348     }
2349   }
2350 
2351 
2352   // If a function is first declared with a calling convention, but is later
2353   // declared or defined without one, all following decls assume the calling
2354   // convention of the first.
2355   //
2356   // It's OK if a function is first declared without a calling convention,
2357   // but is later declared or defined with the default calling convention.
2358   //
2359   // To test if either decl has an explicit calling convention, we look for
2360   // AttributedType sugar nodes on the type as written.  If they are missing or
2361   // were canonicalized away, we assume the calling convention was implicit.
2362   //
2363   // Note also that we DO NOT return at this point, because we still have
2364   // other tests to run.
2365   QualType OldQType = Context.getCanonicalType(Old->getType());
2366   QualType NewQType = Context.getCanonicalType(New->getType());
2367   const FunctionType *OldType = cast<FunctionType>(OldQType);
2368   const FunctionType *NewType = cast<FunctionType>(NewQType);
2369   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2370   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2371   bool RequiresAdjustment = false;
2372 
2373   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2374     FunctionDecl *First = Old->getFirstDecl();
2375     const FunctionType *FT =
2376         First->getType().getCanonicalType()->castAs<FunctionType>();
2377     FunctionType::ExtInfo FI = FT->getExtInfo();
2378     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2379     if (!NewCCExplicit) {
2380       // Inherit the CC from the previous declaration if it was specified
2381       // there but not here.
2382       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2383       RequiresAdjustment = true;
2384     } else {
2385       // Calling conventions aren't compatible, so complain.
2386       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2387       Diag(New->getLocation(), diag::err_cconv_change)
2388         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2389         << !FirstCCExplicit
2390         << (!FirstCCExplicit ? "" :
2391             FunctionType::getNameForCallConv(FI.getCC()));
2392 
2393       // Put the note on the first decl, since it is the one that matters.
2394       Diag(First->getLocation(), diag::note_previous_declaration);
2395       return true;
2396     }
2397   }
2398 
2399   // FIXME: diagnose the other way around?
2400   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2401     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2402     RequiresAdjustment = true;
2403   }
2404 
2405   // Merge regparm attribute.
2406   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2407       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2408     if (NewTypeInfo.getHasRegParm()) {
2409       Diag(New->getLocation(), diag::err_regparm_mismatch)
2410         << NewType->getRegParmType()
2411         << OldType->getRegParmType();
2412       Diag(Old->getLocation(), diag::note_previous_declaration);
2413       return true;
2414     }
2415 
2416     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2417     RequiresAdjustment = true;
2418   }
2419 
2420   // Merge ns_returns_retained attribute.
2421   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2422     if (NewTypeInfo.getProducesResult()) {
2423       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2424       Diag(Old->getLocation(), diag::note_previous_declaration);
2425       return true;
2426     }
2427 
2428     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2429     RequiresAdjustment = true;
2430   }
2431 
2432   if (RequiresAdjustment) {
2433     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2434     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2435     New->setType(QualType(AdjustedType, 0));
2436     NewQType = Context.getCanonicalType(New->getType());
2437     NewType = cast<FunctionType>(NewQType);
2438   }
2439 
2440   // If this redeclaration makes the function inline, we may need to add it to
2441   // UndefinedButUsed.
2442   if (!Old->isInlined() && New->isInlined() &&
2443       !New->hasAttr<GNUInlineAttr>() &&
2444       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2445       Old->isUsed(false) &&
2446       !Old->isDefined() && !New->isThisDeclarationADefinition())
2447     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2448                                            SourceLocation()));
2449 
2450   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2451   // about it.
2452   if (New->hasAttr<GNUInlineAttr>() &&
2453       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2454     UndefinedButUsed.erase(Old->getCanonicalDecl());
2455   }
2456 
2457   if (getLangOpts().CPlusPlus) {
2458     // (C++98 13.1p2):
2459     //   Certain function declarations cannot be overloaded:
2460     //     -- Function declarations that differ only in the return type
2461     //        cannot be overloaded.
2462 
2463     // Go back to the type source info to compare the declared return types,
2464     // per C++1y [dcl.type.auto]p13:
2465     //   Redeclarations or specializations of a function or function template
2466     //   with a declared return type that uses a placeholder type shall also
2467     //   use that placeholder, not a deduced type.
2468     QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2469       ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2470       : OldType)->getResultType();
2471     QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2472       ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2473       : NewType)->getResultType();
2474     QualType ResQT;
2475     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2476         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2477           New->isLocalExternDecl())) {
2478       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2479           OldDeclaredReturnType->isObjCObjectPointerType())
2480         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2481       if (ResQT.isNull()) {
2482         if (New->isCXXClassMember() && New->isOutOfLine())
2483           Diag(New->getLocation(),
2484                diag::err_member_def_does_not_match_ret_type) << New;
2485         else
2486           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2487         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2488         return true;
2489       }
2490       else
2491         NewQType = ResQT;
2492     }
2493 
2494     QualType OldReturnType = OldType->getResultType();
2495     QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2496     if (OldReturnType != NewReturnType) {
2497       // If this function has a deduced return type and has already been
2498       // defined, copy the deduced value from the old declaration.
2499       AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2500       if (OldAT && OldAT->isDeduced()) {
2501         New->setType(
2502             SubstAutoType(New->getType(),
2503                           OldAT->isDependentType() ? Context.DependentTy
2504                                                    : OldAT->getDeducedType()));
2505         NewQType = Context.getCanonicalType(
2506             SubstAutoType(NewQType,
2507                           OldAT->isDependentType() ? Context.DependentTy
2508                                                    : OldAT->getDeducedType()));
2509       }
2510     }
2511 
2512     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2513     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2514     if (OldMethod && NewMethod) {
2515       // Preserve triviality.
2516       NewMethod->setTrivial(OldMethod->isTrivial());
2517 
2518       // MSVC allows explicit template specialization at class scope:
2519       // 2 CXMethodDecls referring to the same function will be injected.
2520       // We don't want a redeclartion error.
2521       bool IsClassScopeExplicitSpecialization =
2522                               OldMethod->isFunctionTemplateSpecialization() &&
2523                               NewMethod->isFunctionTemplateSpecialization();
2524       bool isFriend = NewMethod->getFriendObjectKind();
2525 
2526       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2527           !IsClassScopeExplicitSpecialization) {
2528         //    -- Member function declarations with the same name and the
2529         //       same parameter types cannot be overloaded if any of them
2530         //       is a static member function declaration.
2531         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2532           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2533           Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2534           return true;
2535         }
2536 
2537         // C++ [class.mem]p1:
2538         //   [...] A member shall not be declared twice in the
2539         //   member-specification, except that a nested class or member
2540         //   class template can be declared and then later defined.
2541         if (ActiveTemplateInstantiations.empty()) {
2542           unsigned NewDiag;
2543           if (isa<CXXConstructorDecl>(OldMethod))
2544             NewDiag = diag::err_constructor_redeclared;
2545           else if (isa<CXXDestructorDecl>(NewMethod))
2546             NewDiag = diag::err_destructor_redeclared;
2547           else if (isa<CXXConversionDecl>(NewMethod))
2548             NewDiag = diag::err_conv_function_redeclared;
2549           else
2550             NewDiag = diag::err_member_redeclared;
2551 
2552           Diag(New->getLocation(), NewDiag);
2553         } else {
2554           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2555             << New << New->getType();
2556         }
2557         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2558 
2559       // Complain if this is an explicit declaration of a special
2560       // member that was initially declared implicitly.
2561       //
2562       // As an exception, it's okay to befriend such methods in order
2563       // to permit the implicit constructor/destructor/operator calls.
2564       } else if (OldMethod->isImplicit()) {
2565         if (isFriend) {
2566           NewMethod->setImplicit();
2567         } else {
2568           Diag(NewMethod->getLocation(),
2569                diag::err_definition_of_implicitly_declared_member)
2570             << New << getSpecialMember(OldMethod);
2571           return true;
2572         }
2573       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2574         Diag(NewMethod->getLocation(),
2575              diag::err_definition_of_explicitly_defaulted_member)
2576           << getSpecialMember(OldMethod);
2577         return true;
2578       }
2579     }
2580 
2581     // C++11 [dcl.attr.noreturn]p1:
2582     //   The first declaration of a function shall specify the noreturn
2583     //   attribute if any declaration of that function specifies the noreturn
2584     //   attribute.
2585     if (New->hasAttr<CXX11NoReturnAttr>() &&
2586         !Old->hasAttr<CXX11NoReturnAttr>()) {
2587       Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2588            diag::err_noreturn_missing_on_first_decl);
2589       Diag(Old->getFirstDecl()->getLocation(),
2590            diag::note_noreturn_missing_first_decl);
2591     }
2592 
2593     // C++11 [dcl.attr.depend]p2:
2594     //   The first declaration of a function shall specify the
2595     //   carries_dependency attribute for its declarator-id if any declaration
2596     //   of the function specifies the carries_dependency attribute.
2597     if (New->hasAttr<CarriesDependencyAttr>() &&
2598         !Old->hasAttr<CarriesDependencyAttr>()) {
2599       Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2600            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2601       Diag(Old->getFirstDecl()->getLocation(),
2602            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2603     }
2604 
2605     // (C++98 8.3.5p3):
2606     //   All declarations for a function shall agree exactly in both the
2607     //   return type and the parameter-type-list.
2608     // We also want to respect all the extended bits except noreturn.
2609 
2610     // noreturn should now match unless the old type info didn't have it.
2611     QualType OldQTypeForComparison = OldQType;
2612     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2613       assert(OldQType == QualType(OldType, 0));
2614       const FunctionType *OldTypeForComparison
2615         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2616       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2617       assert(OldQTypeForComparison.isCanonical());
2618     }
2619 
2620     if (haveIncompatibleLanguageLinkages(Old, New)) {
2621       // As a special case, retain the language linkage from previous
2622       // declarations of a friend function as an extension.
2623       //
2624       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2625       // and is useful because there's otherwise no way to specify language
2626       // linkage within class scope.
2627       //
2628       // Check cautiously as the friend object kind isn't yet complete.
2629       if (New->getFriendObjectKind() != Decl::FOK_None) {
2630         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2631         Diag(Old->getLocation(), PrevDiag);
2632       } else {
2633         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2634         Diag(Old->getLocation(), PrevDiag);
2635         return true;
2636       }
2637     }
2638 
2639     if (OldQTypeForComparison == NewQType)
2640       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2641 
2642     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2643         New->isLocalExternDecl()) {
2644       // It's OK if we couldn't merge types for a local function declaraton
2645       // if either the old or new type is dependent. We'll merge the types
2646       // when we instantiate the function.
2647       return false;
2648     }
2649 
2650     // Fall through for conflicting redeclarations and redefinitions.
2651   }
2652 
2653   // C: Function types need to be compatible, not identical. This handles
2654   // duplicate function decls like "void f(int); void f(enum X);" properly.
2655   if (!getLangOpts().CPlusPlus &&
2656       Context.typesAreCompatible(OldQType, NewQType)) {
2657     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2658     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2659     const FunctionProtoType *OldProto = 0;
2660     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2661         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2662       // The old declaration provided a function prototype, but the
2663       // new declaration does not. Merge in the prototype.
2664       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2665       SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2666                                                  OldProto->arg_type_end());
2667       NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2668                                          ParamTypes,
2669                                          OldProto->getExtProtoInfo());
2670       New->setType(NewQType);
2671       New->setHasInheritedPrototype();
2672 
2673       // Synthesize a parameter for each argument type.
2674       SmallVector<ParmVarDecl*, 16> Params;
2675       for (FunctionProtoType::arg_type_iterator
2676              ParamType = OldProto->arg_type_begin(),
2677              ParamEnd = OldProto->arg_type_end();
2678            ParamType != ParamEnd; ++ParamType) {
2679         ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2680                                                  SourceLocation(),
2681                                                  SourceLocation(), 0,
2682                                                  *ParamType, /*TInfo=*/0,
2683                                                  SC_None,
2684                                                  0);
2685         Param->setScopeInfo(0, Params.size());
2686         Param->setImplicit();
2687         Params.push_back(Param);
2688       }
2689 
2690       New->setParams(Params);
2691     }
2692 
2693     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2694   }
2695 
2696   // GNU C permits a K&R definition to follow a prototype declaration
2697   // if the declared types of the parameters in the K&R definition
2698   // match the types in the prototype declaration, even when the
2699   // promoted types of the parameters from the K&R definition differ
2700   // from the types in the prototype. GCC then keeps the types from
2701   // the prototype.
2702   //
2703   // If a variadic prototype is followed by a non-variadic K&R definition,
2704   // the K&R definition becomes variadic.  This is sort of an edge case, but
2705   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2706   // C99 6.9.1p8.
2707   if (!getLangOpts().CPlusPlus &&
2708       Old->hasPrototype() && !New->hasPrototype() &&
2709       New->getType()->getAs<FunctionProtoType>() &&
2710       Old->getNumParams() == New->getNumParams()) {
2711     SmallVector<QualType, 16> ArgTypes;
2712     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2713     const FunctionProtoType *OldProto
2714       = Old->getType()->getAs<FunctionProtoType>();
2715     const FunctionProtoType *NewProto
2716       = New->getType()->getAs<FunctionProtoType>();
2717 
2718     // Determine whether this is the GNU C extension.
2719     QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2720                                                NewProto->getResultType());
2721     bool LooseCompatible = !MergedReturn.isNull();
2722     for (unsigned Idx = 0, End = Old->getNumParams();
2723          LooseCompatible && Idx != End; ++Idx) {
2724       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2725       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2726       if (Context.typesAreCompatible(OldParm->getType(),
2727                                      NewProto->getArgType(Idx))) {
2728         ArgTypes.push_back(NewParm->getType());
2729       } else if (Context.typesAreCompatible(OldParm->getType(),
2730                                             NewParm->getType(),
2731                                             /*CompareUnqualified=*/true)) {
2732         GNUCompatibleParamWarning Warn
2733           = { OldParm, NewParm, NewProto->getArgType(Idx) };
2734         Warnings.push_back(Warn);
2735         ArgTypes.push_back(NewParm->getType());
2736       } else
2737         LooseCompatible = false;
2738     }
2739 
2740     if (LooseCompatible) {
2741       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2742         Diag(Warnings[Warn].NewParm->getLocation(),
2743              diag::ext_param_promoted_not_compatible_with_prototype)
2744           << Warnings[Warn].PromotedType
2745           << Warnings[Warn].OldParm->getType();
2746         if (Warnings[Warn].OldParm->getLocation().isValid())
2747           Diag(Warnings[Warn].OldParm->getLocation(),
2748                diag::note_previous_declaration);
2749       }
2750 
2751       if (MergeTypeWithOld)
2752         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2753                                              OldProto->getExtProtoInfo()));
2754       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2755     }
2756 
2757     // Fall through to diagnose conflicting types.
2758   }
2759 
2760   // A function that has already been declared has been redeclared or
2761   // defined with a different type; show an appropriate diagnostic.
2762 
2763   // If the previous declaration was an implicitly-generated builtin
2764   // declaration, then at the very least we should use a specialized note.
2765   unsigned BuiltinID;
2766   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2767     // If it's actually a library-defined builtin function like 'malloc'
2768     // or 'printf', just warn about the incompatible redeclaration.
2769     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2770       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2771       Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2772         << Old << Old->getType();
2773 
2774       // If this is a global redeclaration, just forget hereafter
2775       // about the "builtin-ness" of the function.
2776       //
2777       // Doing this for local extern declarations is problematic.  If
2778       // the builtin declaration remains visible, a second invalid
2779       // local declaration will produce a hard error; if it doesn't
2780       // remain visible, a single bogus local redeclaration (which is
2781       // actually only a warning) could break all the downstream code.
2782       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2783         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2784 
2785       return false;
2786     }
2787 
2788     PrevDiag = diag::note_previous_builtin_declaration;
2789   }
2790 
2791   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2792   Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2793   return true;
2794 }
2795 
2796 /// \brief Completes the merge of two function declarations that are
2797 /// known to be compatible.
2798 ///
2799 /// This routine handles the merging of attributes and other
2800 /// properties of function declarations from the old declaration to
2801 /// the new declaration, once we know that New is in fact a
2802 /// redeclaration of Old.
2803 ///
2804 /// \returns false
2805 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2806                                         Scope *S, bool MergeTypeWithOld) {
2807   // Merge the attributes
2808   mergeDeclAttributes(New, Old);
2809 
2810   // Merge "pure" flag.
2811   if (Old->isPure())
2812     New->setPure();
2813 
2814   // Merge "used" flag.
2815   if (Old->getMostRecentDecl()->isUsed(false))
2816     New->setIsUsed();
2817 
2818   // Merge attributes from the parameters.  These can mismatch with K&R
2819   // declarations.
2820   if (New->getNumParams() == Old->getNumParams())
2821     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2822       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2823                                *this);
2824 
2825   if (getLangOpts().CPlusPlus)
2826     return MergeCXXFunctionDecl(New, Old, S);
2827 
2828   // Merge the function types so the we get the composite types for the return
2829   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2830   // was visible.
2831   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2832   if (!Merged.isNull() && MergeTypeWithOld)
2833     New->setType(Merged);
2834 
2835   return false;
2836 }
2837 
2838 
2839 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2840                                 ObjCMethodDecl *oldMethod) {
2841 
2842   // Merge the attributes, including deprecated/unavailable
2843   AvailabilityMergeKind MergeKind =
2844     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2845                                                    : AMK_Override;
2846   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
2847 
2848   // Merge attributes from the parameters.
2849   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2850                                        oe = oldMethod->param_end();
2851   for (ObjCMethodDecl::param_iterator
2852          ni = newMethod->param_begin(), ne = newMethod->param_end();
2853        ni != ne && oi != oe; ++ni, ++oi)
2854     mergeParamDeclAttributes(*ni, *oi, *this);
2855 
2856   CheckObjCMethodOverride(newMethod, oldMethod);
2857 }
2858 
2859 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2860 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2861 /// emitting diagnostics as appropriate.
2862 ///
2863 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2864 /// to here in AddInitializerToDecl. We can't check them before the initializer
2865 /// is attached.
2866 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2867                              bool MergeTypeWithOld) {
2868   if (New->isInvalidDecl() || Old->isInvalidDecl())
2869     return;
2870 
2871   QualType MergedT;
2872   if (getLangOpts().CPlusPlus) {
2873     if (New->getType()->isUndeducedType()) {
2874       // We don't know what the new type is until the initializer is attached.
2875       return;
2876     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2877       // These could still be something that needs exception specs checked.
2878       return MergeVarDeclExceptionSpecs(New, Old);
2879     }
2880     // C++ [basic.link]p10:
2881     //   [...] the types specified by all declarations referring to a given
2882     //   object or function shall be identical, except that declarations for an
2883     //   array object can specify array types that differ by the presence or
2884     //   absence of a major array bound (8.3.4).
2885     else if (Old->getType()->isIncompleteArrayType() &&
2886              New->getType()->isArrayType()) {
2887       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2888       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2889       if (Context.hasSameType(OldArray->getElementType(),
2890                               NewArray->getElementType()))
2891         MergedT = New->getType();
2892     } else if (Old->getType()->isArrayType() &&
2893                New->getType()->isIncompleteArrayType()) {
2894       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2895       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2896       if (Context.hasSameType(OldArray->getElementType(),
2897                               NewArray->getElementType()))
2898         MergedT = Old->getType();
2899     } else if (New->getType()->isObjCObjectPointerType() &&
2900                Old->getType()->isObjCObjectPointerType()) {
2901       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2902                                               Old->getType());
2903     }
2904   } else {
2905     // C 6.2.7p2:
2906     //   All declarations that refer to the same object or function shall have
2907     //   compatible type.
2908     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2909   }
2910   if (MergedT.isNull()) {
2911     // It's OK if we couldn't merge types if either type is dependent, for a
2912     // block-scope variable. In other cases (static data members of class
2913     // templates, variable templates, ...), we require the types to be
2914     // equivalent.
2915     // FIXME: The C++ standard doesn't say anything about this.
2916     if ((New->getType()->isDependentType() ||
2917          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2918       // If the old type was dependent, we can't merge with it, so the new type
2919       // becomes dependent for now. We'll reproduce the original type when we
2920       // instantiate the TypeSourceInfo for the variable.
2921       if (!New->getType()->isDependentType() && MergeTypeWithOld)
2922         New->setType(Context.DependentTy);
2923       return;
2924     }
2925 
2926     // FIXME: Even if this merging succeeds, some other non-visible declaration
2927     // of this variable might have an incompatible type. For instance:
2928     //
2929     //   extern int arr[];
2930     //   void f() { extern int arr[2]; }
2931     //   void g() { extern int arr[3]; }
2932     //
2933     // Neither C nor C++ requires a diagnostic for this, but we should still try
2934     // to diagnose it.
2935     Diag(New->getLocation(), diag::err_redefinition_different_type)
2936       << New->getDeclName() << New->getType() << Old->getType();
2937     Diag(Old->getLocation(), diag::note_previous_definition);
2938     return New->setInvalidDecl();
2939   }
2940 
2941   // Don't actually update the type on the new declaration if the old
2942   // declaration was an extern declaration in a different scope.
2943   if (MergeTypeWithOld)
2944     New->setType(MergedT);
2945 }
2946 
2947 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2948                                   LookupResult &Previous) {
2949   // C11 6.2.7p4:
2950   //   For an identifier with internal or external linkage declared
2951   //   in a scope in which a prior declaration of that identifier is
2952   //   visible, if the prior declaration specifies internal or
2953   //   external linkage, the type of the identifier at the later
2954   //   declaration becomes the composite type.
2955   //
2956   // If the variable isn't visible, we do not merge with its type.
2957   if (Previous.isShadowed())
2958     return false;
2959 
2960   if (S.getLangOpts().CPlusPlus) {
2961     // C++11 [dcl.array]p3:
2962     //   If there is a preceding declaration of the entity in the same
2963     //   scope in which the bound was specified, an omitted array bound
2964     //   is taken to be the same as in that earlier declaration.
2965     return NewVD->isPreviousDeclInSameBlockScope() ||
2966            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2967             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2968   } else {
2969     // If the old declaration was function-local, don't merge with its
2970     // type unless we're in the same function.
2971     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2972            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2973   }
2974 }
2975 
2976 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2977 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2978 /// situation, merging decls or emitting diagnostics as appropriate.
2979 ///
2980 /// Tentative definition rules (C99 6.9.2p2) are checked by
2981 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2982 /// definitions here, since the initializer hasn't been attached.
2983 ///
2984 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2985   // If the new decl is already invalid, don't do any other checking.
2986   if (New->isInvalidDecl())
2987     return;
2988 
2989   // Verify the old decl was also a variable or variable template.
2990   VarDecl *Old = 0;
2991   if (Previous.isSingleResult() &&
2992       (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2993     if (New->getDescribedVarTemplate())
2994       Old = Old->getDescribedVarTemplate() ? Old : 0;
2995     else
2996       Old = Old->getDescribedVarTemplate() ? 0 : Old;
2997   }
2998   if (!Old) {
2999     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3000       << New->getDeclName();
3001     Diag(Previous.getRepresentativeDecl()->getLocation(),
3002          diag::note_previous_definition);
3003     return New->setInvalidDecl();
3004   }
3005 
3006   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3007     return;
3008 
3009   // C++ [class.mem]p1:
3010   //   A member shall not be declared twice in the member-specification [...]
3011   //
3012   // Here, we need only consider static data members.
3013   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3014     Diag(New->getLocation(), diag::err_duplicate_member)
3015       << New->getIdentifier();
3016     Diag(Old->getLocation(), diag::note_previous_declaration);
3017     New->setInvalidDecl();
3018   }
3019 
3020   mergeDeclAttributes(New, Old);
3021   // Warn if an already-declared variable is made a weak_import in a subsequent
3022   // declaration
3023   if (New->getAttr<WeakImportAttr>() &&
3024       Old->getStorageClass() == SC_None &&
3025       !Old->getAttr<WeakImportAttr>()) {
3026     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3027     Diag(Old->getLocation(), diag::note_previous_definition);
3028     // Remove weak_import attribute on new declaration.
3029     New->dropAttr<WeakImportAttr>();
3030   }
3031 
3032   // Merge the types.
3033   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3034 
3035   if (New->isInvalidDecl())
3036     return;
3037 
3038   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3039   if (New->getStorageClass() == SC_Static &&
3040       !New->isStaticDataMember() &&
3041       Old->hasExternalFormalLinkage()) {
3042     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
3043     Diag(Old->getLocation(), diag::note_previous_definition);
3044     return New->setInvalidDecl();
3045   }
3046   // C99 6.2.2p4:
3047   //   For an identifier declared with the storage-class specifier
3048   //   extern in a scope in which a prior declaration of that
3049   //   identifier is visible,23) if the prior declaration specifies
3050   //   internal or external linkage, the linkage of the identifier at
3051   //   the later declaration is the same as the linkage specified at
3052   //   the prior declaration. If no prior declaration is visible, or
3053   //   if the prior declaration specifies no linkage, then the
3054   //   identifier has external linkage.
3055   if (New->hasExternalStorage() && Old->hasLinkage())
3056     /* Okay */;
3057   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3058            !New->isStaticDataMember() &&
3059            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3060     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3061     Diag(Old->getLocation(), diag::note_previous_definition);
3062     return New->setInvalidDecl();
3063   }
3064 
3065   // Check if extern is followed by non-extern and vice-versa.
3066   if (New->hasExternalStorage() &&
3067       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3068     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3069     Diag(Old->getLocation(), diag::note_previous_definition);
3070     return New->setInvalidDecl();
3071   }
3072   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3073       !New->hasExternalStorage()) {
3074     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3075     Diag(Old->getLocation(), diag::note_previous_definition);
3076     return New->setInvalidDecl();
3077   }
3078 
3079   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3080 
3081   // FIXME: The test for external storage here seems wrong? We still
3082   // need to check for mismatches.
3083   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3084       // Don't complain about out-of-line definitions of static members.
3085       !(Old->getLexicalDeclContext()->isRecord() &&
3086         !New->getLexicalDeclContext()->isRecord())) {
3087     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3088     Diag(Old->getLocation(), diag::note_previous_definition);
3089     return New->setInvalidDecl();
3090   }
3091 
3092   if (New->getTLSKind() != Old->getTLSKind()) {
3093     if (!Old->getTLSKind()) {
3094       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3095       Diag(Old->getLocation(), diag::note_previous_declaration);
3096     } else if (!New->getTLSKind()) {
3097       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3098       Diag(Old->getLocation(), diag::note_previous_declaration);
3099     } else {
3100       // Do not allow redeclaration to change the variable between requiring
3101       // static and dynamic initialization.
3102       // FIXME: GCC allows this, but uses the TLS keyword on the first
3103       // declaration to determine the kind. Do we need to be compatible here?
3104       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3105         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3106       Diag(Old->getLocation(), diag::note_previous_declaration);
3107     }
3108   }
3109 
3110   // C++ doesn't have tentative definitions, so go right ahead and check here.
3111   const VarDecl *Def;
3112   if (getLangOpts().CPlusPlus &&
3113       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3114       (Def = Old->getDefinition())) {
3115     Diag(New->getLocation(), diag::err_redefinition) << New;
3116     Diag(Def->getLocation(), diag::note_previous_definition);
3117     New->setInvalidDecl();
3118     return;
3119   }
3120 
3121   if (haveIncompatibleLanguageLinkages(Old, New)) {
3122     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3123     Diag(Old->getLocation(), diag::note_previous_definition);
3124     New->setInvalidDecl();
3125     return;
3126   }
3127 
3128   // Merge "used" flag.
3129   if (Old->getMostRecentDecl()->isUsed(false))
3130     New->setIsUsed();
3131 
3132   // Keep a chain of previous declarations.
3133   New->setPreviousDecl(Old);
3134 
3135   // Inherit access appropriately.
3136   New->setAccess(Old->getAccess());
3137 
3138   if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3139     if (New->isStaticDataMember() && New->isOutOfLine())
3140       VTD->setAccess(New->getAccess());
3141   }
3142 }
3143 
3144 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3145 /// no declarator (e.g. "struct foo;") is parsed.
3146 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3147                                        DeclSpec &DS) {
3148   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3149 }
3150 
3151 static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
3152   if (!S.Context.getLangOpts().CPlusPlus)
3153     return;
3154 
3155   if (isa<CXXRecordDecl>(Tag->getParent())) {
3156     // If this tag is the direct child of a class, number it if
3157     // it is anonymous.
3158     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3159       return;
3160     MangleNumberingContext &MCtx =
3161         S.Context.getManglingNumberContext(Tag->getParent());
3162     S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3163     return;
3164   }
3165 
3166   // If this tag isn't a direct child of a class, number it if it is local.
3167   Decl *ManglingContextDecl;
3168   if (MangleNumberingContext *MCtx =
3169           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3170                                           ManglingContextDecl)) {
3171     S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3172   }
3173 }
3174 
3175 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3176 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3177 /// parameters to cope with template friend declarations.
3178 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3179                                        DeclSpec &DS,
3180                                        MultiTemplateParamsArg TemplateParams,
3181                                        bool IsExplicitInstantiation) {
3182   Decl *TagD = 0;
3183   TagDecl *Tag = 0;
3184   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3185       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3186       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3187       DS.getTypeSpecType() == DeclSpec::TST_union ||
3188       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3189     TagD = DS.getRepAsDecl();
3190 
3191     if (!TagD) // We probably had an error
3192       return 0;
3193 
3194     // Note that the above type specs guarantee that the
3195     // type rep is a Decl, whereas in many of the others
3196     // it's a Type.
3197     if (isa<TagDecl>(TagD))
3198       Tag = cast<TagDecl>(TagD);
3199     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3200       Tag = CTD->getTemplatedDecl();
3201   }
3202 
3203   if (Tag) {
3204     HandleTagNumbering(*this, Tag);
3205     Tag->setFreeStanding();
3206     if (Tag->isInvalidDecl())
3207       return Tag;
3208   }
3209 
3210   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3211     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3212     // or incomplete types shall not be restrict-qualified."
3213     if (TypeQuals & DeclSpec::TQ_restrict)
3214       Diag(DS.getRestrictSpecLoc(),
3215            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3216            << DS.getSourceRange();
3217   }
3218 
3219   if (DS.isConstexprSpecified()) {
3220     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3221     // and definitions of functions and variables.
3222     if (Tag)
3223       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3224         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3225             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3226             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3227             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3228     else
3229       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3230     // Don't emit warnings after this error.
3231     return TagD;
3232   }
3233 
3234   DiagnoseFunctionSpecifiers(DS);
3235 
3236   if (DS.isFriendSpecified()) {
3237     // If we're dealing with a decl but not a TagDecl, assume that
3238     // whatever routines created it handled the friendship aspect.
3239     if (TagD && !Tag)
3240       return 0;
3241     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3242   }
3243 
3244   CXXScopeSpec &SS = DS.getTypeSpecScope();
3245   bool IsExplicitSpecialization =
3246     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3247   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3248       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3249     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3250     // nested-name-specifier unless it is an explicit instantiation
3251     // or an explicit specialization.
3252     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3253     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3254       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3255           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3256           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3257           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3258       << SS.getRange();
3259     return 0;
3260   }
3261 
3262   // Track whether this decl-specifier declares anything.
3263   bool DeclaresAnything = true;
3264 
3265   // Handle anonymous struct definitions.
3266   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3267     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3268         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3269       if (getLangOpts().CPlusPlus ||
3270           Record->getDeclContext()->isRecord())
3271         return BuildAnonymousStructOrUnion(S, DS, AS, Record);
3272 
3273       DeclaresAnything = false;
3274     }
3275   }
3276 
3277   // Check for Microsoft C extension: anonymous struct member.
3278   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3279       CurContext->isRecord() &&
3280       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3281     // Handle 2 kinds of anonymous struct:
3282     //   struct STRUCT;
3283     // and
3284     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3285     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3286     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3287         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3288          DS.getRepAsType().get()->isStructureType())) {
3289       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3290         << DS.getSourceRange();
3291       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3292     }
3293   }
3294 
3295   // Skip all the checks below if we have a type error.
3296   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3297       (TagD && TagD->isInvalidDecl()))
3298     return TagD;
3299 
3300   if (getLangOpts().CPlusPlus &&
3301       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3302     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3303       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3304           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3305         DeclaresAnything = false;
3306 
3307   if (!DS.isMissingDeclaratorOk()) {
3308     // Customize diagnostic for a typedef missing a name.
3309     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3310       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3311         << DS.getSourceRange();
3312     else
3313       DeclaresAnything = false;
3314   }
3315 
3316   if (DS.isModulePrivateSpecified() &&
3317       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3318     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3319       << Tag->getTagKind()
3320       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3321 
3322   ActOnDocumentableDecl(TagD);
3323 
3324   // C 6.7/2:
3325   //   A declaration [...] shall declare at least a declarator [...], a tag,
3326   //   or the members of an enumeration.
3327   // C++ [dcl.dcl]p3:
3328   //   [If there are no declarators], and except for the declaration of an
3329   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3330   //   names into the program, or shall redeclare a name introduced by a
3331   //   previous declaration.
3332   if (!DeclaresAnything) {
3333     // In C, we allow this as a (popular) extension / bug. Don't bother
3334     // producing further diagnostics for redundant qualifiers after this.
3335     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3336     return TagD;
3337   }
3338 
3339   // C++ [dcl.stc]p1:
3340   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3341   //   init-declarator-list of the declaration shall not be empty.
3342   // C++ [dcl.fct.spec]p1:
3343   //   If a cv-qualifier appears in a decl-specifier-seq, the
3344   //   init-declarator-list of the declaration shall not be empty.
3345   //
3346   // Spurious qualifiers here appear to be valid in C.
3347   unsigned DiagID = diag::warn_standalone_specifier;
3348   if (getLangOpts().CPlusPlus)
3349     DiagID = diag::ext_standalone_specifier;
3350 
3351   // Note that a linkage-specification sets a storage class, but
3352   // 'extern "C" struct foo;' is actually valid and not theoretically
3353   // useless.
3354   if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3355     if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3356       Diag(DS.getStorageClassSpecLoc(), DiagID)
3357         << DeclSpec::getSpecifierName(SCS);
3358 
3359   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3360     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3361       << DeclSpec::getSpecifierName(TSCS);
3362   if (DS.getTypeQualifiers()) {
3363     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3364       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3365     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3366       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3367     // Restrict is covered above.
3368     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3369       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3370   }
3371 
3372   // Warn about ignored type attributes, for example:
3373   // __attribute__((aligned)) struct A;
3374   // Attributes should be placed after tag to apply to type declaration.
3375   if (!DS.getAttributes().empty()) {
3376     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3377     if (TypeSpecType == DeclSpec::TST_class ||
3378         TypeSpecType == DeclSpec::TST_struct ||
3379         TypeSpecType == DeclSpec::TST_interface ||
3380         TypeSpecType == DeclSpec::TST_union ||
3381         TypeSpecType == DeclSpec::TST_enum) {
3382       AttributeList* attrs = DS.getAttributes().getList();
3383       while (attrs) {
3384         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3385         << attrs->getName()
3386         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3387             TypeSpecType == DeclSpec::TST_struct ? 1 :
3388             TypeSpecType == DeclSpec::TST_union ? 2 :
3389             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3390         attrs = attrs->getNext();
3391       }
3392     }
3393   }
3394 
3395   return TagD;
3396 }
3397 
3398 /// We are trying to inject an anonymous member into the given scope;
3399 /// check if there's an existing declaration that can't be overloaded.
3400 ///
3401 /// \return true if this is a forbidden redeclaration
3402 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3403                                          Scope *S,
3404                                          DeclContext *Owner,
3405                                          DeclarationName Name,
3406                                          SourceLocation NameLoc,
3407                                          unsigned diagnostic) {
3408   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3409                  Sema::ForRedeclaration);
3410   if (!SemaRef.LookupName(R, S)) return false;
3411 
3412   if (R.getAsSingle<TagDecl>())
3413     return false;
3414 
3415   // Pick a representative declaration.
3416   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3417   assert(PrevDecl && "Expected a non-null Decl");
3418 
3419   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3420     return false;
3421 
3422   SemaRef.Diag(NameLoc, diagnostic) << Name;
3423   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3424 
3425   return true;
3426 }
3427 
3428 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3429 /// anonymous struct or union AnonRecord into the owning context Owner
3430 /// and scope S. This routine will be invoked just after we realize
3431 /// that an unnamed union or struct is actually an anonymous union or
3432 /// struct, e.g.,
3433 ///
3434 /// @code
3435 /// union {
3436 ///   int i;
3437 ///   float f;
3438 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3439 ///    // f into the surrounding scope.x
3440 /// @endcode
3441 ///
3442 /// This routine is recursive, injecting the names of nested anonymous
3443 /// structs/unions into the owning context and scope as well.
3444 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3445                                          DeclContext *Owner,
3446                                          RecordDecl *AnonRecord,
3447                                          AccessSpecifier AS,
3448                                          SmallVectorImpl<NamedDecl *> &Chaining,
3449                                          bool MSAnonStruct) {
3450   unsigned diagKind
3451     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3452                             : diag::err_anonymous_struct_member_redecl;
3453 
3454   bool Invalid = false;
3455 
3456   // Look every FieldDecl and IndirectFieldDecl with a name.
3457   for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3458                                DEnd = AnonRecord->decls_end();
3459        D != DEnd; ++D) {
3460     if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3461         cast<NamedDecl>(*D)->getDeclName()) {
3462       ValueDecl *VD = cast<ValueDecl>(*D);
3463       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3464                                        VD->getLocation(), diagKind)) {
3465         // C++ [class.union]p2:
3466         //   The names of the members of an anonymous union shall be
3467         //   distinct from the names of any other entity in the
3468         //   scope in which the anonymous union is declared.
3469         Invalid = true;
3470       } else {
3471         // C++ [class.union]p2:
3472         //   For the purpose of name lookup, after the anonymous union
3473         //   definition, the members of the anonymous union are
3474         //   considered to have been defined in the scope in which the
3475         //   anonymous union is declared.
3476         unsigned OldChainingSize = Chaining.size();
3477         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3478           for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3479                PE = IF->chain_end(); PI != PE; ++PI)
3480             Chaining.push_back(*PI);
3481         else
3482           Chaining.push_back(VD);
3483 
3484         assert(Chaining.size() >= 2);
3485         NamedDecl **NamedChain =
3486           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3487         for (unsigned i = 0; i < Chaining.size(); i++)
3488           NamedChain[i] = Chaining[i];
3489 
3490         IndirectFieldDecl* IndirectField =
3491           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3492                                     VD->getIdentifier(), VD->getType(),
3493                                     NamedChain, Chaining.size());
3494 
3495         IndirectField->setAccess(AS);
3496         IndirectField->setImplicit();
3497         SemaRef.PushOnScopeChains(IndirectField, S);
3498 
3499         // That includes picking up the appropriate access specifier.
3500         if (AS != AS_none) IndirectField->setAccess(AS);
3501 
3502         Chaining.resize(OldChainingSize);
3503       }
3504     }
3505   }
3506 
3507   return Invalid;
3508 }
3509 
3510 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3511 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3512 /// illegal input values are mapped to SC_None.
3513 static StorageClass
3514 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3515   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3516   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3517          "Parser allowed 'typedef' as storage class VarDecl.");
3518   switch (StorageClassSpec) {
3519   case DeclSpec::SCS_unspecified:    return SC_None;
3520   case DeclSpec::SCS_extern:
3521     if (DS.isExternInLinkageSpec())
3522       return SC_None;
3523     return SC_Extern;
3524   case DeclSpec::SCS_static:         return SC_Static;
3525   case DeclSpec::SCS_auto:           return SC_Auto;
3526   case DeclSpec::SCS_register:       return SC_Register;
3527   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3528     // Illegal SCSs map to None: error reporting is up to the caller.
3529   case DeclSpec::SCS_mutable:        // Fall through.
3530   case DeclSpec::SCS_typedef:        return SC_None;
3531   }
3532   llvm_unreachable("unknown storage class specifier");
3533 }
3534 
3535 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3536 /// anonymous structure or union. Anonymous unions are a C++ feature
3537 /// (C++ [class.union]) and a C11 feature; anonymous structures
3538 /// are a C11 feature and GNU C++ extension.
3539 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3540                                              AccessSpecifier AS,
3541                                              RecordDecl *Record) {
3542   DeclContext *Owner = Record->getDeclContext();
3543 
3544   // Diagnose whether this anonymous struct/union is an extension.
3545   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3546     Diag(Record->getLocation(), diag::ext_anonymous_union);
3547   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3548     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3549   else if (!Record->isUnion() && !getLangOpts().C11)
3550     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3551 
3552   // C and C++ require different kinds of checks for anonymous
3553   // structs/unions.
3554   bool Invalid = false;
3555   if (getLangOpts().CPlusPlus) {
3556     const char* PrevSpec = 0;
3557     unsigned DiagID;
3558     if (Record->isUnion()) {
3559       // C++ [class.union]p6:
3560       //   Anonymous unions declared in a named namespace or in the
3561       //   global namespace shall be declared static.
3562       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3563           (isa<TranslationUnitDecl>(Owner) ||
3564            (isa<NamespaceDecl>(Owner) &&
3565             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3566         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3567           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3568 
3569         // Recover by adding 'static'.
3570         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3571                                PrevSpec, DiagID);
3572       }
3573       // C++ [class.union]p6:
3574       //   A storage class is not allowed in a declaration of an
3575       //   anonymous union in a class scope.
3576       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3577                isa<RecordDecl>(Owner)) {
3578         Diag(DS.getStorageClassSpecLoc(),
3579              diag::err_anonymous_union_with_storage_spec)
3580           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3581 
3582         // Recover by removing the storage specifier.
3583         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3584                                SourceLocation(),
3585                                PrevSpec, DiagID);
3586       }
3587     }
3588 
3589     // Ignore const/volatile/restrict qualifiers.
3590     if (DS.getTypeQualifiers()) {
3591       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3592         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3593           << Record->isUnion() << "const"
3594           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3595       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3596         Diag(DS.getVolatileSpecLoc(),
3597              diag::ext_anonymous_struct_union_qualified)
3598           << Record->isUnion() << "volatile"
3599           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3600       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3601         Diag(DS.getRestrictSpecLoc(),
3602              diag::ext_anonymous_struct_union_qualified)
3603           << Record->isUnion() << "restrict"
3604           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3605       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3606         Diag(DS.getAtomicSpecLoc(),
3607              diag::ext_anonymous_struct_union_qualified)
3608           << Record->isUnion() << "_Atomic"
3609           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3610 
3611       DS.ClearTypeQualifiers();
3612     }
3613 
3614     // C++ [class.union]p2:
3615     //   The member-specification of an anonymous union shall only
3616     //   define non-static data members. [Note: nested types and
3617     //   functions cannot be declared within an anonymous union. ]
3618     for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3619                                  MemEnd = Record->decls_end();
3620          Mem != MemEnd; ++Mem) {
3621       if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3622         // C++ [class.union]p3:
3623         //   An anonymous union shall not have private or protected
3624         //   members (clause 11).
3625         assert(FD->getAccess() != AS_none);
3626         if (FD->getAccess() != AS_public) {
3627           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3628             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3629           Invalid = true;
3630         }
3631 
3632         // C++ [class.union]p1
3633         //   An object of a class with a non-trivial constructor, a non-trivial
3634         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3635         //   assignment operator cannot be a member of a union, nor can an
3636         //   array of such objects.
3637         if (CheckNontrivialField(FD))
3638           Invalid = true;
3639       } else if ((*Mem)->isImplicit()) {
3640         // Any implicit members are fine.
3641       } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3642         // This is a type that showed up in an
3643         // elaborated-type-specifier inside the anonymous struct or
3644         // union, but which actually declares a type outside of the
3645         // anonymous struct or union. It's okay.
3646       } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3647         if (!MemRecord->isAnonymousStructOrUnion() &&
3648             MemRecord->getDeclName()) {
3649           // Visual C++ allows type definition in anonymous struct or union.
3650           if (getLangOpts().MicrosoftExt)
3651             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3652               << (int)Record->isUnion();
3653           else {
3654             // This is a nested type declaration.
3655             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3656               << (int)Record->isUnion();
3657             Invalid = true;
3658           }
3659         } else {
3660           // This is an anonymous type definition within another anonymous type.
3661           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3662           // not part of standard C++.
3663           Diag(MemRecord->getLocation(),
3664                diag::ext_anonymous_record_with_anonymous_type)
3665             << (int)Record->isUnion();
3666         }
3667       } else if (isa<AccessSpecDecl>(*Mem)) {
3668         // Any access specifier is fine.
3669       } else {
3670         // We have something that isn't a non-static data
3671         // member. Complain about it.
3672         unsigned DK = diag::err_anonymous_record_bad_member;
3673         if (isa<TypeDecl>(*Mem))
3674           DK = diag::err_anonymous_record_with_type;
3675         else if (isa<FunctionDecl>(*Mem))
3676           DK = diag::err_anonymous_record_with_function;
3677         else if (isa<VarDecl>(*Mem))
3678           DK = diag::err_anonymous_record_with_static;
3679 
3680         // Visual C++ allows type definition in anonymous struct or union.
3681         if (getLangOpts().MicrosoftExt &&
3682             DK == diag::err_anonymous_record_with_type)
3683           Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3684             << (int)Record->isUnion();
3685         else {
3686           Diag((*Mem)->getLocation(), DK)
3687               << (int)Record->isUnion();
3688           Invalid = true;
3689         }
3690       }
3691     }
3692   }
3693 
3694   if (!Record->isUnion() && !Owner->isRecord()) {
3695     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3696       << (int)getLangOpts().CPlusPlus;
3697     Invalid = true;
3698   }
3699 
3700   // Mock up a declarator.
3701   Declarator Dc(DS, Declarator::MemberContext);
3702   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3703   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3704 
3705   // Create a declaration for this anonymous struct/union.
3706   NamedDecl *Anon = 0;
3707   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3708     Anon = FieldDecl::Create(Context, OwningClass,
3709                              DS.getLocStart(),
3710                              Record->getLocation(),
3711                              /*IdentifierInfo=*/0,
3712                              Context.getTypeDeclType(Record),
3713                              TInfo,
3714                              /*BitWidth=*/0, /*Mutable=*/false,
3715                              /*InitStyle=*/ICIS_NoInit);
3716     Anon->setAccess(AS);
3717     if (getLangOpts().CPlusPlus)
3718       FieldCollector->Add(cast<FieldDecl>(Anon));
3719   } else {
3720     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3721     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3722     if (SCSpec == DeclSpec::SCS_mutable) {
3723       // mutable can only appear on non-static class members, so it's always
3724       // an error here
3725       Diag(Record->getLocation(), diag::err_mutable_nonmember);
3726       Invalid = true;
3727       SC = SC_None;
3728     }
3729 
3730     Anon = VarDecl::Create(Context, Owner,
3731                            DS.getLocStart(),
3732                            Record->getLocation(), /*IdentifierInfo=*/0,
3733                            Context.getTypeDeclType(Record),
3734                            TInfo, SC);
3735 
3736     // Default-initialize the implicit variable. This initialization will be
3737     // trivial in almost all cases, except if a union member has an in-class
3738     // initializer:
3739     //   union { int n = 0; };
3740     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3741   }
3742   Anon->setImplicit();
3743 
3744   // Add the anonymous struct/union object to the current
3745   // context. We'll be referencing this object when we refer to one of
3746   // its members.
3747   Owner->addDecl(Anon);
3748 
3749   // Inject the members of the anonymous struct/union into the owning
3750   // context and into the identifier resolver chain for name lookup
3751   // purposes.
3752   SmallVector<NamedDecl*, 2> Chain;
3753   Chain.push_back(Anon);
3754 
3755   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3756                                           Chain, false))
3757     Invalid = true;
3758 
3759   // Mark this as an anonymous struct/union type. Note that we do not
3760   // do this until after we have already checked and injected the
3761   // members of this anonymous struct/union type, because otherwise
3762   // the members could be injected twice: once by DeclContext when it
3763   // builds its lookup table, and once by
3764   // InjectAnonymousStructOrUnionMembers.
3765   Record->setAnonymousStructOrUnion(true);
3766 
3767   if (Invalid)
3768     Anon->setInvalidDecl();
3769 
3770   return Anon;
3771 }
3772 
3773 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3774 /// Microsoft C anonymous structure.
3775 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3776 /// Example:
3777 ///
3778 /// struct A { int a; };
3779 /// struct B { struct A; int b; };
3780 ///
3781 /// void foo() {
3782 ///   B var;
3783 ///   var.a = 3;
3784 /// }
3785 ///
3786 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3787                                            RecordDecl *Record) {
3788 
3789   // If there is no Record, get the record via the typedef.
3790   if (!Record)
3791     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3792 
3793   // Mock up a declarator.
3794   Declarator Dc(DS, Declarator::TypeNameContext);
3795   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3796   assert(TInfo && "couldn't build declarator info for anonymous struct");
3797 
3798   // Create a declaration for this anonymous struct.
3799   NamedDecl* Anon = FieldDecl::Create(Context,
3800                              cast<RecordDecl>(CurContext),
3801                              DS.getLocStart(),
3802                              DS.getLocStart(),
3803                              /*IdentifierInfo=*/0,
3804                              Context.getTypeDeclType(Record),
3805                              TInfo,
3806                              /*BitWidth=*/0, /*Mutable=*/false,
3807                              /*InitStyle=*/ICIS_NoInit);
3808   Anon->setImplicit();
3809 
3810   // Add the anonymous struct object to the current context.
3811   CurContext->addDecl(Anon);
3812 
3813   // Inject the members of the anonymous struct into the current
3814   // context and into the identifier resolver chain for name lookup
3815   // purposes.
3816   SmallVector<NamedDecl*, 2> Chain;
3817   Chain.push_back(Anon);
3818 
3819   RecordDecl *RecordDef = Record->getDefinition();
3820   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3821                                                         RecordDef, AS_none,
3822                                                         Chain, true))
3823     Anon->setInvalidDecl();
3824 
3825   return Anon;
3826 }
3827 
3828 /// GetNameForDeclarator - Determine the full declaration name for the
3829 /// given Declarator.
3830 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3831   return GetNameFromUnqualifiedId(D.getName());
3832 }
3833 
3834 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3835 DeclarationNameInfo
3836 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3837   DeclarationNameInfo NameInfo;
3838   NameInfo.setLoc(Name.StartLocation);
3839 
3840   switch (Name.getKind()) {
3841 
3842   case UnqualifiedId::IK_ImplicitSelfParam:
3843   case UnqualifiedId::IK_Identifier:
3844     NameInfo.setName(Name.Identifier);
3845     NameInfo.setLoc(Name.StartLocation);
3846     return NameInfo;
3847 
3848   case UnqualifiedId::IK_OperatorFunctionId:
3849     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3850                                            Name.OperatorFunctionId.Operator));
3851     NameInfo.setLoc(Name.StartLocation);
3852     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3853       = Name.OperatorFunctionId.SymbolLocations[0];
3854     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3855       = Name.EndLocation.getRawEncoding();
3856     return NameInfo;
3857 
3858   case UnqualifiedId::IK_LiteralOperatorId:
3859     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3860                                                            Name.Identifier));
3861     NameInfo.setLoc(Name.StartLocation);
3862     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3863     return NameInfo;
3864 
3865   case UnqualifiedId::IK_ConversionFunctionId: {
3866     TypeSourceInfo *TInfo;
3867     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3868     if (Ty.isNull())
3869       return DeclarationNameInfo();
3870     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3871                                                Context.getCanonicalType(Ty)));
3872     NameInfo.setLoc(Name.StartLocation);
3873     NameInfo.setNamedTypeInfo(TInfo);
3874     return NameInfo;
3875   }
3876 
3877   case UnqualifiedId::IK_ConstructorName: {
3878     TypeSourceInfo *TInfo;
3879     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3880     if (Ty.isNull())
3881       return DeclarationNameInfo();
3882     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3883                                               Context.getCanonicalType(Ty)));
3884     NameInfo.setLoc(Name.StartLocation);
3885     NameInfo.setNamedTypeInfo(TInfo);
3886     return NameInfo;
3887   }
3888 
3889   case UnqualifiedId::IK_ConstructorTemplateId: {
3890     // In well-formed code, we can only have a constructor
3891     // template-id that refers to the current context, so go there
3892     // to find the actual type being constructed.
3893     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3894     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3895       return DeclarationNameInfo();
3896 
3897     // Determine the type of the class being constructed.
3898     QualType CurClassType = Context.getTypeDeclType(CurClass);
3899 
3900     // FIXME: Check two things: that the template-id names the same type as
3901     // CurClassType, and that the template-id does not occur when the name
3902     // was qualified.
3903 
3904     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3905                                     Context.getCanonicalType(CurClassType)));
3906     NameInfo.setLoc(Name.StartLocation);
3907     // FIXME: should we retrieve TypeSourceInfo?
3908     NameInfo.setNamedTypeInfo(0);
3909     return NameInfo;
3910   }
3911 
3912   case UnqualifiedId::IK_DestructorName: {
3913     TypeSourceInfo *TInfo;
3914     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3915     if (Ty.isNull())
3916       return DeclarationNameInfo();
3917     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3918                                               Context.getCanonicalType(Ty)));
3919     NameInfo.setLoc(Name.StartLocation);
3920     NameInfo.setNamedTypeInfo(TInfo);
3921     return NameInfo;
3922   }
3923 
3924   case UnqualifiedId::IK_TemplateId: {
3925     TemplateName TName = Name.TemplateId->Template.get();
3926     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3927     return Context.getNameForTemplate(TName, TNameLoc);
3928   }
3929 
3930   } // switch (Name.getKind())
3931 
3932   llvm_unreachable("Unknown name kind");
3933 }
3934 
3935 static QualType getCoreType(QualType Ty) {
3936   do {
3937     if (Ty->isPointerType() || Ty->isReferenceType())
3938       Ty = Ty->getPointeeType();
3939     else if (Ty->isArrayType())
3940       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3941     else
3942       return Ty.withoutLocalFastQualifiers();
3943   } while (true);
3944 }
3945 
3946 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3947 /// and Definition have "nearly" matching parameters. This heuristic is
3948 /// used to improve diagnostics in the case where an out-of-line function
3949 /// definition doesn't match any declaration within the class or namespace.
3950 /// Also sets Params to the list of indices to the parameters that differ
3951 /// between the declaration and the definition. If hasSimilarParameters
3952 /// returns true and Params is empty, then all of the parameters match.
3953 static bool hasSimilarParameters(ASTContext &Context,
3954                                      FunctionDecl *Declaration,
3955                                      FunctionDecl *Definition,
3956                                      SmallVectorImpl<unsigned> &Params) {
3957   Params.clear();
3958   if (Declaration->param_size() != Definition->param_size())
3959     return false;
3960   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3961     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3962     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3963 
3964     // The parameter types are identical
3965     if (Context.hasSameType(DefParamTy, DeclParamTy))
3966       continue;
3967 
3968     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3969     QualType DefParamBaseTy = getCoreType(DefParamTy);
3970     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3971     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3972 
3973     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3974         (DeclTyName && DeclTyName == DefTyName))
3975       Params.push_back(Idx);
3976     else  // The two parameters aren't even close
3977       return false;
3978   }
3979 
3980   return true;
3981 }
3982 
3983 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3984 /// declarator needs to be rebuilt in the current instantiation.
3985 /// Any bits of declarator which appear before the name are valid for
3986 /// consideration here.  That's specifically the type in the decl spec
3987 /// and the base type in any member-pointer chunks.
3988 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3989                                                     DeclarationName Name) {
3990   // The types we specifically need to rebuild are:
3991   //   - typenames, typeofs, and decltypes
3992   //   - types which will become injected class names
3993   // Of course, we also need to rebuild any type referencing such a
3994   // type.  It's safest to just say "dependent", but we call out a
3995   // few cases here.
3996 
3997   DeclSpec &DS = D.getMutableDeclSpec();
3998   switch (DS.getTypeSpecType()) {
3999   case DeclSpec::TST_typename:
4000   case DeclSpec::TST_typeofType:
4001   case DeclSpec::TST_underlyingType:
4002   case DeclSpec::TST_atomic: {
4003     // Grab the type from the parser.
4004     TypeSourceInfo *TSI = 0;
4005     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4006     if (T.isNull() || !T->isDependentType()) break;
4007 
4008     // Make sure there's a type source info.  This isn't really much
4009     // of a waste; most dependent types should have type source info
4010     // attached already.
4011     if (!TSI)
4012       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4013 
4014     // Rebuild the type in the current instantiation.
4015     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4016     if (!TSI) return true;
4017 
4018     // Store the new type back in the decl spec.
4019     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4020     DS.UpdateTypeRep(LocType);
4021     break;
4022   }
4023 
4024   case DeclSpec::TST_decltype:
4025   case DeclSpec::TST_typeofExpr: {
4026     Expr *E = DS.getRepAsExpr();
4027     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4028     if (Result.isInvalid()) return true;
4029     DS.UpdateExprRep(Result.get());
4030     break;
4031   }
4032 
4033   default:
4034     // Nothing to do for these decl specs.
4035     break;
4036   }
4037 
4038   // It doesn't matter what order we do this in.
4039   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4040     DeclaratorChunk &Chunk = D.getTypeObject(I);
4041 
4042     // The only type information in the declarator which can come
4043     // before the declaration name is the base type of a member
4044     // pointer.
4045     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4046       continue;
4047 
4048     // Rebuild the scope specifier in-place.
4049     CXXScopeSpec &SS = Chunk.Mem.Scope();
4050     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4051       return true;
4052   }
4053 
4054   return false;
4055 }
4056 
4057 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4058   D.setFunctionDefinitionKind(FDK_Declaration);
4059   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4060 
4061   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4062       Dcl && Dcl->getDeclContext()->isFileContext())
4063     Dcl->setTopLevelDeclInObjCContainer();
4064 
4065   return Dcl;
4066 }
4067 
4068 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4069 ///   If T is the name of a class, then each of the following shall have a
4070 ///   name different from T:
4071 ///     - every static data member of class T;
4072 ///     - every member function of class T
4073 ///     - every member of class T that is itself a type;
4074 /// \returns true if the declaration name violates these rules.
4075 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4076                                    DeclarationNameInfo NameInfo) {
4077   DeclarationName Name = NameInfo.getName();
4078 
4079   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4080     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4081       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4082       return true;
4083     }
4084 
4085   return false;
4086 }
4087 
4088 /// \brief Diagnose a declaration whose declarator-id has the given
4089 /// nested-name-specifier.
4090 ///
4091 /// \param SS The nested-name-specifier of the declarator-id.
4092 ///
4093 /// \param DC The declaration context to which the nested-name-specifier
4094 /// resolves.
4095 ///
4096 /// \param Name The name of the entity being declared.
4097 ///
4098 /// \param Loc The location of the name of the entity being declared.
4099 ///
4100 /// \returns true if we cannot safely recover from this error, false otherwise.
4101 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4102                                         DeclarationName Name,
4103                                       SourceLocation Loc) {
4104   DeclContext *Cur = CurContext;
4105   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4106     Cur = Cur->getParent();
4107 
4108   // C++ [dcl.meaning]p1:
4109   //   A declarator-id shall not be qualified except for the definition
4110   //   of a member function (9.3) or static data member (9.4) outside of
4111   //   its class, the definition or explicit instantiation of a function
4112   //   or variable member of a namespace outside of its namespace, or the
4113   //   definition of an explicit specialization outside of its namespace,
4114   //   or the declaration of a friend function that is a member of
4115   //   another class or namespace (11.3). [...]
4116 
4117   // The user provided a superfluous scope specifier that refers back to the
4118   // class or namespaces in which the entity is already declared.
4119   //
4120   // class X {
4121   //   void X::f();
4122   // };
4123   if (Cur->Equals(DC)) {
4124     Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4125                                    : diag::err_member_extra_qualification)
4126       << Name << FixItHint::CreateRemoval(SS.getRange());
4127     SS.clear();
4128     return false;
4129   }
4130 
4131   // Check whether the qualifying scope encloses the scope of the original
4132   // declaration.
4133   if (!Cur->Encloses(DC)) {
4134     if (Cur->isRecord())
4135       Diag(Loc, diag::err_member_qualification)
4136         << Name << SS.getRange();
4137     else if (isa<TranslationUnitDecl>(DC))
4138       Diag(Loc, diag::err_invalid_declarator_global_scope)
4139         << Name << SS.getRange();
4140     else if (isa<FunctionDecl>(Cur))
4141       Diag(Loc, diag::err_invalid_declarator_in_function)
4142         << Name << SS.getRange();
4143     else if (isa<BlockDecl>(Cur))
4144       Diag(Loc, diag::err_invalid_declarator_in_block)
4145         << Name << SS.getRange();
4146     else
4147       Diag(Loc, diag::err_invalid_declarator_scope)
4148       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4149 
4150     return true;
4151   }
4152 
4153   if (Cur->isRecord()) {
4154     // Cannot qualify members within a class.
4155     Diag(Loc, diag::err_member_qualification)
4156       << Name << SS.getRange();
4157     SS.clear();
4158 
4159     // C++ constructors and destructors with incorrect scopes can break
4160     // our AST invariants by having the wrong underlying types. If
4161     // that's the case, then drop this declaration entirely.
4162     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4163          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4164         !Context.hasSameType(Name.getCXXNameType(),
4165                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4166       return true;
4167 
4168     return false;
4169   }
4170 
4171   // C++11 [dcl.meaning]p1:
4172   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4173   //   not begin with a decltype-specifer"
4174   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4175   while (SpecLoc.getPrefix())
4176     SpecLoc = SpecLoc.getPrefix();
4177   if (dyn_cast_or_null<DecltypeType>(
4178         SpecLoc.getNestedNameSpecifier()->getAsType()))
4179     Diag(Loc, diag::err_decltype_in_declarator)
4180       << SpecLoc.getTypeLoc().getSourceRange();
4181 
4182   return false;
4183 }
4184 
4185 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4186                                   MultiTemplateParamsArg TemplateParamLists) {
4187   // TODO: consider using NameInfo for diagnostic.
4188   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4189   DeclarationName Name = NameInfo.getName();
4190 
4191   // All of these full declarators require an identifier.  If it doesn't have
4192   // one, the ParsedFreeStandingDeclSpec action should be used.
4193   if (!Name) {
4194     if (!D.isInvalidType())  // Reject this if we think it is valid.
4195       Diag(D.getDeclSpec().getLocStart(),
4196            diag::err_declarator_need_ident)
4197         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4198     return 0;
4199   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4200     return 0;
4201 
4202   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4203   // we find one that is.
4204   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4205          (S->getFlags() & Scope::TemplateParamScope) != 0)
4206     S = S->getParent();
4207 
4208   DeclContext *DC = CurContext;
4209   if (D.getCXXScopeSpec().isInvalid())
4210     D.setInvalidType();
4211   else if (D.getCXXScopeSpec().isSet()) {
4212     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4213                                         UPPC_DeclarationQualifier))
4214       return 0;
4215 
4216     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4217     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4218     if (!DC) {
4219       // If we could not compute the declaration context, it's because the
4220       // declaration context is dependent but does not refer to a class,
4221       // class template, or class template partial specialization. Complain
4222       // and return early, to avoid the coming semantic disaster.
4223       Diag(D.getIdentifierLoc(),
4224            diag::err_template_qualified_declarator_no_match)
4225         << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4226         << D.getCXXScopeSpec().getRange();
4227       return 0;
4228     }
4229     bool IsDependentContext = DC->isDependentContext();
4230 
4231     if (!IsDependentContext &&
4232         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4233       return 0;
4234 
4235     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4236       Diag(D.getIdentifierLoc(),
4237            diag::err_member_def_undefined_record)
4238         << Name << DC << D.getCXXScopeSpec().getRange();
4239       D.setInvalidType();
4240     } else if (!D.getDeclSpec().isFriendSpecified()) {
4241       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4242                                       Name, D.getIdentifierLoc())) {
4243         if (DC->isRecord())
4244           return 0;
4245 
4246         D.setInvalidType();
4247       }
4248     }
4249 
4250     // Check whether we need to rebuild the type of the given
4251     // declaration in the current instantiation.
4252     if (EnteringContext && IsDependentContext &&
4253         TemplateParamLists.size() != 0) {
4254       ContextRAII SavedContext(*this, DC);
4255       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4256         D.setInvalidType();
4257     }
4258   }
4259 
4260   if (DiagnoseClassNameShadow(DC, NameInfo))
4261     // If this is a typedef, we'll end up spewing multiple diagnostics.
4262     // Just return early; it's safer.
4263     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4264       return 0;
4265 
4266   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4267   QualType R = TInfo->getType();
4268 
4269   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4270                                       UPPC_DeclarationType))
4271     D.setInvalidType();
4272 
4273   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4274                         ForRedeclaration);
4275 
4276   // See if this is a redefinition of a variable in the same scope.
4277   if (!D.getCXXScopeSpec().isSet()) {
4278     bool IsLinkageLookup = false;
4279     bool CreateBuiltins = false;
4280 
4281     // If the declaration we're planning to build will be a function
4282     // or object with linkage, then look for another declaration with
4283     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4284     //
4285     // If the declaration we're planning to build will be declared with
4286     // external linkage in the translation unit, create any builtin with
4287     // the same name.
4288     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4289       /* Do nothing*/;
4290     else if (CurContext->isFunctionOrMethod() &&
4291              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4292               R->isFunctionType())) {
4293       IsLinkageLookup = true;
4294       CreateBuiltins =
4295           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4296     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4297                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4298       CreateBuiltins = true;
4299 
4300     if (IsLinkageLookup)
4301       Previous.clear(LookupRedeclarationWithLinkage);
4302 
4303     LookupName(Previous, S, CreateBuiltins);
4304   } else { // Something like "int foo::x;"
4305     LookupQualifiedName(Previous, DC);
4306 
4307     // C++ [dcl.meaning]p1:
4308     //   When the declarator-id is qualified, the declaration shall refer to a
4309     //  previously declared member of the class or namespace to which the
4310     //  qualifier refers (or, in the case of a namespace, of an element of the
4311     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4312     //  thereof; [...]
4313     //
4314     // Note that we already checked the context above, and that we do not have
4315     // enough information to make sure that Previous contains the declaration
4316     // we want to match. For example, given:
4317     //
4318     //   class X {
4319     //     void f();
4320     //     void f(float);
4321     //   };
4322     //
4323     //   void X::f(int) { } // ill-formed
4324     //
4325     // In this case, Previous will point to the overload set
4326     // containing the two f's declared in X, but neither of them
4327     // matches.
4328 
4329     // C++ [dcl.meaning]p1:
4330     //   [...] the member shall not merely have been introduced by a
4331     //   using-declaration in the scope of the class or namespace nominated by
4332     //   the nested-name-specifier of the declarator-id.
4333     RemoveUsingDecls(Previous);
4334   }
4335 
4336   if (Previous.isSingleResult() &&
4337       Previous.getFoundDecl()->isTemplateParameter()) {
4338     // Maybe we will complain about the shadowed template parameter.
4339     if (!D.isInvalidType())
4340       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4341                                       Previous.getFoundDecl());
4342 
4343     // Just pretend that we didn't see the previous declaration.
4344     Previous.clear();
4345   }
4346 
4347   // In C++, the previous declaration we find might be a tag type
4348   // (class or enum). In this case, the new declaration will hide the
4349   // tag type. Note that this does does not apply if we're declaring a
4350   // typedef (C++ [dcl.typedef]p4).
4351   if (Previous.isSingleTagDecl() &&
4352       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4353     Previous.clear();
4354 
4355   // Check that there are no default arguments other than in the parameters
4356   // of a function declaration (C++ only).
4357   if (getLangOpts().CPlusPlus)
4358     CheckExtraCXXDefaultArguments(D);
4359 
4360   NamedDecl *New;
4361 
4362   bool AddToScope = true;
4363   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4364     if (TemplateParamLists.size()) {
4365       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4366       return 0;
4367     }
4368 
4369     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4370   } else if (R->isFunctionType()) {
4371     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4372                                   TemplateParamLists,
4373                                   AddToScope);
4374   } else {
4375     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4376                                   AddToScope);
4377   }
4378 
4379   if (New == 0)
4380     return 0;
4381 
4382   // If this has an identifier and is not an invalid redeclaration or
4383   // function template specialization, add it to the scope stack.
4384   if (New->getDeclName() && AddToScope &&
4385        !(D.isRedeclaration() && New->isInvalidDecl())) {
4386     // Only make a locally-scoped extern declaration visible if it is the first
4387     // declaration of this entity. Qualified lookup for such an entity should
4388     // only find this declaration if there is no visible declaration of it.
4389     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4390     PushOnScopeChains(New, S, AddToContext);
4391     if (!AddToContext)
4392       CurContext->addHiddenDecl(New);
4393   }
4394 
4395   return New;
4396 }
4397 
4398 /// Helper method to turn variable array types into constant array
4399 /// types in certain situations which would otherwise be errors (for
4400 /// GCC compatibility).
4401 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4402                                                     ASTContext &Context,
4403                                                     bool &SizeIsNegative,
4404                                                     llvm::APSInt &Oversized) {
4405   // This method tries to turn a variable array into a constant
4406   // array even when the size isn't an ICE.  This is necessary
4407   // for compatibility with code that depends on gcc's buggy
4408   // constant expression folding, like struct {char x[(int)(char*)2];}
4409   SizeIsNegative = false;
4410   Oversized = 0;
4411 
4412   if (T->isDependentType())
4413     return QualType();
4414 
4415   QualifierCollector Qs;
4416   const Type *Ty = Qs.strip(T);
4417 
4418   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4419     QualType Pointee = PTy->getPointeeType();
4420     QualType FixedType =
4421         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4422                                             Oversized);
4423     if (FixedType.isNull()) return FixedType;
4424     FixedType = Context.getPointerType(FixedType);
4425     return Qs.apply(Context, FixedType);
4426   }
4427   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4428     QualType Inner = PTy->getInnerType();
4429     QualType FixedType =
4430         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4431                                             Oversized);
4432     if (FixedType.isNull()) return FixedType;
4433     FixedType = Context.getParenType(FixedType);
4434     return Qs.apply(Context, FixedType);
4435   }
4436 
4437   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4438   if (!VLATy)
4439     return QualType();
4440   // FIXME: We should probably handle this case
4441   if (VLATy->getElementType()->isVariablyModifiedType())
4442     return QualType();
4443 
4444   llvm::APSInt Res;
4445   if (!VLATy->getSizeExpr() ||
4446       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4447     return QualType();
4448 
4449   // Check whether the array size is negative.
4450   if (Res.isSigned() && Res.isNegative()) {
4451     SizeIsNegative = true;
4452     return QualType();
4453   }
4454 
4455   // Check whether the array is too large to be addressed.
4456   unsigned ActiveSizeBits
4457     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4458                                               Res);
4459   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4460     Oversized = Res;
4461     return QualType();
4462   }
4463 
4464   return Context.getConstantArrayType(VLATy->getElementType(),
4465                                       Res, ArrayType::Normal, 0);
4466 }
4467 
4468 static void
4469 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4470   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4471     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4472     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4473                                       DstPTL.getPointeeLoc());
4474     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4475     return;
4476   }
4477   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4478     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4479     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4480                                       DstPTL.getInnerLoc());
4481     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4482     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4483     return;
4484   }
4485   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4486   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4487   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4488   TypeLoc DstElemTL = DstATL.getElementLoc();
4489   DstElemTL.initializeFullCopy(SrcElemTL);
4490   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4491   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4492   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4493 }
4494 
4495 /// Helper method to turn variable array types into constant array
4496 /// types in certain situations which would otherwise be errors (for
4497 /// GCC compatibility).
4498 static TypeSourceInfo*
4499 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4500                                               ASTContext &Context,
4501                                               bool &SizeIsNegative,
4502                                               llvm::APSInt &Oversized) {
4503   QualType FixedTy
4504     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4505                                           SizeIsNegative, Oversized);
4506   if (FixedTy.isNull())
4507     return 0;
4508   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4509   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4510                                     FixedTInfo->getTypeLoc());
4511   return FixedTInfo;
4512 }
4513 
4514 /// \brief Register the given locally-scoped extern "C" declaration so
4515 /// that it can be found later for redeclarations. We include any extern "C"
4516 /// declaration that is not visible in the translation unit here, not just
4517 /// function-scope declarations.
4518 void
4519 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4520   if (!getLangOpts().CPlusPlus &&
4521       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4522     // Don't need to track declarations in the TU in C.
4523     return;
4524 
4525   // Note that we have a locally-scoped external with this name.
4526   // FIXME: There can be multiple such declarations if they are functions marked
4527   // __attribute__((overloadable)) declared in function scope in C.
4528   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4529 }
4530 
4531 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4532   if (ExternalSource) {
4533     // Load locally-scoped external decls from the external source.
4534     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4535     SmallVector<NamedDecl *, 4> Decls;
4536     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4537     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4538       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4539         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4540       if (Pos == LocallyScopedExternCDecls.end())
4541         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4542     }
4543   }
4544 
4545   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4546   return D ? D->getMostRecentDecl() : 0;
4547 }
4548 
4549 /// \brief Diagnose function specifiers on a declaration of an identifier that
4550 /// does not identify a function.
4551 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4552   // FIXME: We should probably indicate the identifier in question to avoid
4553   // confusion for constructs like "inline int a(), b;"
4554   if (DS.isInlineSpecified())
4555     Diag(DS.getInlineSpecLoc(),
4556          diag::err_inline_non_function);
4557 
4558   if (DS.isVirtualSpecified())
4559     Diag(DS.getVirtualSpecLoc(),
4560          diag::err_virtual_non_function);
4561 
4562   if (DS.isExplicitSpecified())
4563     Diag(DS.getExplicitSpecLoc(),
4564          diag::err_explicit_non_function);
4565 
4566   if (DS.isNoreturnSpecified())
4567     Diag(DS.getNoreturnSpecLoc(),
4568          diag::err_noreturn_non_function);
4569 }
4570 
4571 NamedDecl*
4572 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4573                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4574   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4575   if (D.getCXXScopeSpec().isSet()) {
4576     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4577       << D.getCXXScopeSpec().getRange();
4578     D.setInvalidType();
4579     // Pretend we didn't see the scope specifier.
4580     DC = CurContext;
4581     Previous.clear();
4582   }
4583 
4584   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4585 
4586   if (D.getDeclSpec().isConstexprSpecified())
4587     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4588       << 1;
4589 
4590   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4591     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4592       << D.getName().getSourceRange();
4593     return 0;
4594   }
4595 
4596   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4597   if (!NewTD) return 0;
4598 
4599   // Handle attributes prior to checking for duplicates in MergeVarDecl
4600   ProcessDeclAttributes(S, NewTD, D);
4601 
4602   CheckTypedefForVariablyModifiedType(S, NewTD);
4603 
4604   bool Redeclaration = D.isRedeclaration();
4605   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4606   D.setRedeclaration(Redeclaration);
4607   return ND;
4608 }
4609 
4610 void
4611 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4612   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4613   // then it shall have block scope.
4614   // Note that variably modified types must be fixed before merging the decl so
4615   // that redeclarations will match.
4616   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4617   QualType T = TInfo->getType();
4618   if (T->isVariablyModifiedType()) {
4619     getCurFunction()->setHasBranchProtectedScope();
4620 
4621     if (S->getFnParent() == 0) {
4622       bool SizeIsNegative;
4623       llvm::APSInt Oversized;
4624       TypeSourceInfo *FixedTInfo =
4625         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4626                                                       SizeIsNegative,
4627                                                       Oversized);
4628       if (FixedTInfo) {
4629         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4630         NewTD->setTypeSourceInfo(FixedTInfo);
4631       } else {
4632         if (SizeIsNegative)
4633           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4634         else if (T->isVariableArrayType())
4635           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4636         else if (Oversized.getBoolValue())
4637           Diag(NewTD->getLocation(), diag::err_array_too_large)
4638             << Oversized.toString(10);
4639         else
4640           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4641         NewTD->setInvalidDecl();
4642       }
4643     }
4644   }
4645 }
4646 
4647 
4648 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4649 /// declares a typedef-name, either using the 'typedef' type specifier or via
4650 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4651 NamedDecl*
4652 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4653                            LookupResult &Previous, bool &Redeclaration) {
4654   // Merge the decl with the existing one if appropriate. If the decl is
4655   // in an outer scope, it isn't the same thing.
4656   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
4657                        /*ExplicitInstantiationOrSpecialization=*/false);
4658   filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4659   if (!Previous.empty()) {
4660     Redeclaration = true;
4661     MergeTypedefNameDecl(NewTD, Previous);
4662   }
4663 
4664   // If this is the C FILE type, notify the AST context.
4665   if (IdentifierInfo *II = NewTD->getIdentifier())
4666     if (!NewTD->isInvalidDecl() &&
4667         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4668       if (II->isStr("FILE"))
4669         Context.setFILEDecl(NewTD);
4670       else if (II->isStr("jmp_buf"))
4671         Context.setjmp_bufDecl(NewTD);
4672       else if (II->isStr("sigjmp_buf"))
4673         Context.setsigjmp_bufDecl(NewTD);
4674       else if (II->isStr("ucontext_t"))
4675         Context.setucontext_tDecl(NewTD);
4676     }
4677 
4678   return NewTD;
4679 }
4680 
4681 /// \brief Determines whether the given declaration is an out-of-scope
4682 /// previous declaration.
4683 ///
4684 /// This routine should be invoked when name lookup has found a
4685 /// previous declaration (PrevDecl) that is not in the scope where a
4686 /// new declaration by the same name is being introduced. If the new
4687 /// declaration occurs in a local scope, previous declarations with
4688 /// linkage may still be considered previous declarations (C99
4689 /// 6.2.2p4-5, C++ [basic.link]p6).
4690 ///
4691 /// \param PrevDecl the previous declaration found by name
4692 /// lookup
4693 ///
4694 /// \param DC the context in which the new declaration is being
4695 /// declared.
4696 ///
4697 /// \returns true if PrevDecl is an out-of-scope previous declaration
4698 /// for a new delcaration with the same name.
4699 static bool
4700 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4701                                 ASTContext &Context) {
4702   if (!PrevDecl)
4703     return false;
4704 
4705   if (!PrevDecl->hasLinkage())
4706     return false;
4707 
4708   if (Context.getLangOpts().CPlusPlus) {
4709     // C++ [basic.link]p6:
4710     //   If there is a visible declaration of an entity with linkage
4711     //   having the same name and type, ignoring entities declared
4712     //   outside the innermost enclosing namespace scope, the block
4713     //   scope declaration declares that same entity and receives the
4714     //   linkage of the previous declaration.
4715     DeclContext *OuterContext = DC->getRedeclContext();
4716     if (!OuterContext->isFunctionOrMethod())
4717       // This rule only applies to block-scope declarations.
4718       return false;
4719 
4720     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4721     if (PrevOuterContext->isRecord())
4722       // We found a member function: ignore it.
4723       return false;
4724 
4725     // Find the innermost enclosing namespace for the new and
4726     // previous declarations.
4727     OuterContext = OuterContext->getEnclosingNamespaceContext();
4728     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4729 
4730     // The previous declaration is in a different namespace, so it
4731     // isn't the same function.
4732     if (!OuterContext->Equals(PrevOuterContext))
4733       return false;
4734   }
4735 
4736   return true;
4737 }
4738 
4739 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4740   CXXScopeSpec &SS = D.getCXXScopeSpec();
4741   if (!SS.isSet()) return;
4742   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4743 }
4744 
4745 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4746   QualType type = decl->getType();
4747   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4748   if (lifetime == Qualifiers::OCL_Autoreleasing) {
4749     // Various kinds of declaration aren't allowed to be __autoreleasing.
4750     unsigned kind = -1U;
4751     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4752       if (var->hasAttr<BlocksAttr>())
4753         kind = 0; // __block
4754       else if (!var->hasLocalStorage())
4755         kind = 1; // global
4756     } else if (isa<ObjCIvarDecl>(decl)) {
4757       kind = 3; // ivar
4758     } else if (isa<FieldDecl>(decl)) {
4759       kind = 2; // field
4760     }
4761 
4762     if (kind != -1U) {
4763       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4764         << kind;
4765     }
4766   } else if (lifetime == Qualifiers::OCL_None) {
4767     // Try to infer lifetime.
4768     if (!type->isObjCLifetimeType())
4769       return false;
4770 
4771     lifetime = type->getObjCARCImplicitLifetime();
4772     type = Context.getLifetimeQualifiedType(type, lifetime);
4773     decl->setType(type);
4774   }
4775 
4776   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4777     // Thread-local variables cannot have lifetime.
4778     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4779         var->getTLSKind()) {
4780       Diag(var->getLocation(), diag::err_arc_thread_ownership)
4781         << var->getType();
4782       return true;
4783     }
4784   }
4785 
4786   return false;
4787 }
4788 
4789 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4790   // 'weak' only applies to declarations with external linkage.
4791   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4792     if (!ND.isExternallyVisible()) {
4793       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4794       ND.dropAttr<WeakAttr>();
4795     }
4796   }
4797   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4798     if (ND.isExternallyVisible()) {
4799       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4800       ND.dropAttr<WeakRefAttr>();
4801     }
4802   }
4803 
4804   // 'selectany' only applies to externally visible varable declarations.
4805   // It does not apply to functions.
4806   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4807     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4808       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4809       ND.dropAttr<SelectAnyAttr>();
4810     }
4811   }
4812 }
4813 
4814 /// Given that we are within the definition of the given function,
4815 /// will that definition behave like C99's 'inline', where the
4816 /// definition is discarded except for optimization purposes?
4817 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4818   // Try to avoid calling GetGVALinkageForFunction.
4819 
4820   // All cases of this require the 'inline' keyword.
4821   if (!FD->isInlined()) return false;
4822 
4823   // This is only possible in C++ with the gnu_inline attribute.
4824   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4825     return false;
4826 
4827   // Okay, go ahead and call the relatively-more-expensive function.
4828 
4829 #ifndef NDEBUG
4830   // AST quite reasonably asserts that it's working on a function
4831   // definition.  We don't really have a way to tell it that we're
4832   // currently defining the function, so just lie to it in +Asserts
4833   // builds.  This is an awful hack.
4834   FD->setLazyBody(1);
4835 #endif
4836 
4837   bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4838 
4839 #ifndef NDEBUG
4840   FD->setLazyBody(0);
4841 #endif
4842 
4843   return isC99Inline;
4844 }
4845 
4846 /// Determine whether a variable is extern "C" prior to attaching
4847 /// an initializer. We can't just call isExternC() here, because that
4848 /// will also compute and cache whether the declaration is externally
4849 /// visible, which might change when we attach the initializer.
4850 ///
4851 /// This can only be used if the declaration is known to not be a
4852 /// redeclaration of an internal linkage declaration.
4853 ///
4854 /// For instance:
4855 ///
4856 ///   auto x = []{};
4857 ///
4858 /// Attaching the initializer here makes this declaration not externally
4859 /// visible, because its type has internal linkage.
4860 ///
4861 /// FIXME: This is a hack.
4862 template<typename T>
4863 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4864   if (S.getLangOpts().CPlusPlus) {
4865     // In C++, the overloadable attribute negates the effects of extern "C".
4866     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4867       return false;
4868   }
4869   return D->isExternC();
4870 }
4871 
4872 static bool shouldConsiderLinkage(const VarDecl *VD) {
4873   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4874   if (DC->isFunctionOrMethod())
4875     return VD->hasExternalStorage();
4876   if (DC->isFileContext())
4877     return true;
4878   if (DC->isRecord())
4879     return false;
4880   llvm_unreachable("Unexpected context");
4881 }
4882 
4883 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4884   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4885   if (DC->isFileContext() || DC->isFunctionOrMethod())
4886     return true;
4887   if (DC->isRecord())
4888     return false;
4889   llvm_unreachable("Unexpected context");
4890 }
4891 
4892 /// Adjust the \c DeclContext for a function or variable that might be a
4893 /// function-local external declaration.
4894 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4895   if (!DC->isFunctionOrMethod())
4896     return false;
4897 
4898   // If this is a local extern function or variable declared within a function
4899   // template, don't add it into the enclosing namespace scope until it is
4900   // instantiated; it might have a dependent type right now.
4901   if (DC->isDependentContext())
4902     return true;
4903 
4904   // C++11 [basic.link]p7:
4905   //   When a block scope declaration of an entity with linkage is not found to
4906   //   refer to some other declaration, then that entity is a member of the
4907   //   innermost enclosing namespace.
4908   //
4909   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4910   // semantically-enclosing namespace, not a lexically-enclosing one.
4911   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4912     DC = DC->getParent();
4913   return true;
4914 }
4915 
4916 NamedDecl *
4917 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4918                               TypeSourceInfo *TInfo, LookupResult &Previous,
4919                               MultiTemplateParamsArg TemplateParamLists,
4920                               bool &AddToScope) {
4921   QualType R = TInfo->getType();
4922   DeclarationName Name = GetNameForDeclarator(D).getName();
4923 
4924   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4925   VarDecl::StorageClass SC =
4926     StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
4927 
4928   DeclContext *OriginalDC = DC;
4929   bool IsLocalExternDecl = SC == SC_Extern &&
4930                            adjustContextForLocalExternDecl(DC);
4931 
4932   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
4933     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4934     // half array type (unless the cl_khr_fp16 extension is enabled).
4935     if (Context.getBaseElementType(R)->isHalfType()) {
4936       Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4937       D.setInvalidType();
4938     }
4939   }
4940 
4941   if (SCSpec == DeclSpec::SCS_mutable) {
4942     // mutable can only appear on non-static class members, so it's always
4943     // an error here
4944     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
4945     D.setInvalidType();
4946     SC = SC_None;
4947   }
4948 
4949   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4950       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4951                               D.getDeclSpec().getStorageClassSpecLoc())) {
4952     // In C++11, the 'register' storage class specifier is deprecated.
4953     // Suppress the warning in system macros, it's used in macros in some
4954     // popular C system headers, such as in glibc's htonl() macro.
4955     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4956          diag::warn_deprecated_register)
4957       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4958   }
4959 
4960   IdentifierInfo *II = Name.getAsIdentifierInfo();
4961   if (!II) {
4962     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
4963       << Name;
4964     return 0;
4965   }
4966 
4967   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4968 
4969   if (!DC->isRecord() && S->getFnParent() == 0) {
4970     // C99 6.9p2: The storage-class specifiers auto and register shall not
4971     // appear in the declaration specifiers in an external declaration.
4972     if (SC == SC_Auto || SC == SC_Register) {
4973       // If this is a register variable with an asm label specified, then this
4974       // is a GNU extension.
4975       if (SC == SC_Register && D.getAsmLabel())
4976         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4977       else
4978         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
4979       D.setInvalidType();
4980     }
4981   }
4982 
4983   if (getLangOpts().OpenCL) {
4984     // Set up the special work-group-local storage class for variables in the
4985     // OpenCL __local address space.
4986     if (R.getAddressSpace() == LangAS::opencl_local) {
4987       SC = SC_OpenCLWorkGroupLocal;
4988     }
4989 
4990     // OpenCL v1.2 s6.9.b p4:
4991     // The sampler type cannot be used with the __local and __global address
4992     // space qualifiers.
4993     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
4994       R.getAddressSpace() == LangAS::opencl_global)) {
4995       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
4996     }
4997 
4998     // OpenCL 1.2 spec, p6.9 r:
4999     // The event type cannot be used to declare a program scope variable.
5000     // The event type cannot be used with the __local, __constant and __global
5001     // address space qualifiers.
5002     if (R->isEventT()) {
5003       if (S->getParent() == 0) {
5004         Diag(D.getLocStart(), diag::err_event_t_global_var);
5005         D.setInvalidType();
5006       }
5007 
5008       if (R.getAddressSpace()) {
5009         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5010         D.setInvalidType();
5011       }
5012     }
5013   }
5014 
5015   bool IsExplicitSpecialization = false;
5016   bool IsVariableTemplateSpecialization = false;
5017   bool IsPartialSpecialization = false;
5018   bool IsVariableTemplate = false;
5019   VarTemplateDecl *PrevVarTemplate = 0;
5020   VarDecl *NewVD = 0;
5021   VarTemplateDecl *NewTemplate = 0;
5022   if (!getLangOpts().CPlusPlus) {
5023     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5024                             D.getIdentifierLoc(), II,
5025                             R, TInfo, SC);
5026 
5027     if (D.isInvalidType())
5028       NewVD->setInvalidDecl();
5029   } else {
5030     bool Invalid = false;
5031 
5032     if (DC->isRecord() && !CurContext->isRecord()) {
5033       // This is an out-of-line definition of a static data member.
5034       switch (SC) {
5035       case SC_None:
5036         break;
5037       case SC_Static:
5038         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5039              diag::err_static_out_of_line)
5040           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5041         break;
5042       case SC_Auto:
5043       case SC_Register:
5044       case SC_Extern:
5045         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5046         // to names of variables declared in a block or to function parameters.
5047         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5048         // of class members
5049 
5050         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5051              diag::err_storage_class_for_static_member)
5052           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5053         break;
5054       case SC_PrivateExtern:
5055         llvm_unreachable("C storage class in c++!");
5056       case SC_OpenCLWorkGroupLocal:
5057         llvm_unreachable("OpenCL storage class in c++!");
5058       }
5059     }
5060 
5061     if (SC == SC_Static && CurContext->isRecord()) {
5062       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5063         if (RD->isLocalClass())
5064           Diag(D.getIdentifierLoc(),
5065                diag::err_static_data_member_not_allowed_in_local_class)
5066             << Name << RD->getDeclName();
5067 
5068         // C++98 [class.union]p1: If a union contains a static data member,
5069         // the program is ill-formed. C++11 drops this restriction.
5070         if (RD->isUnion())
5071           Diag(D.getIdentifierLoc(),
5072                getLangOpts().CPlusPlus11
5073                  ? diag::warn_cxx98_compat_static_data_member_in_union
5074                  : diag::ext_static_data_member_in_union) << Name;
5075         // We conservatively disallow static data members in anonymous structs.
5076         else if (!RD->getDeclName())
5077           Diag(D.getIdentifierLoc(),
5078                diag::err_static_data_member_not_allowed_in_anon_struct)
5079             << Name << RD->isUnion();
5080       }
5081     }
5082 
5083     NamedDecl *PrevDecl = 0;
5084     if (Previous.begin() != Previous.end())
5085       PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5086     PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5087 
5088     // Match up the template parameter lists with the scope specifier, then
5089     // determine whether we have a template or a template specialization.
5090     TemplateParameterList *TemplateParams =
5091         MatchTemplateParametersToScopeSpecifier(
5092             D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5093             D.getCXXScopeSpec(), TemplateParamLists,
5094             /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5095     if (TemplateParams) {
5096       if (!TemplateParams->size() &&
5097           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5098         // There is an extraneous 'template<>' for this variable. Complain
5099         // about it, but allow the declaration of the variable.
5100         Diag(TemplateParams->getTemplateLoc(),
5101              diag::err_template_variable_noparams)
5102           << II
5103           << SourceRange(TemplateParams->getTemplateLoc(),
5104                          TemplateParams->getRAngleLoc());
5105       } else {
5106         // Only C++1y supports variable templates (N3651).
5107         Diag(D.getIdentifierLoc(),
5108              getLangOpts().CPlusPlus1y
5109                  ? diag::warn_cxx11_compat_variable_template
5110                  : diag::ext_variable_template);
5111 
5112         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5113           // This is an explicit specialization or a partial specialization.
5114           // Check that we can declare a specialization here
5115 
5116           IsVariableTemplateSpecialization = true;
5117           IsPartialSpecialization = TemplateParams->size() > 0;
5118 
5119         } else { // if (TemplateParams->size() > 0)
5120           // This is a template declaration.
5121           IsVariableTemplate = true;
5122 
5123           // Check that we can declare a template here.
5124           if (CheckTemplateDeclScope(S, TemplateParams))
5125             return 0;
5126 
5127           // If there is a previous declaration with the same name, check
5128           // whether this is a valid redeclaration.
5129           if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5130             PrevDecl = PrevVarTemplate = 0;
5131 
5132           if (PrevVarTemplate) {
5133             // Ensure that the template parameter lists are compatible.
5134             if (!TemplateParameterListsAreEqual(
5135                     TemplateParams, PrevVarTemplate->getTemplateParameters(),
5136                     /*Complain=*/true, TPL_TemplateMatch))
5137               return 0;
5138           } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5139             // Maybe we will complain about the shadowed template parameter.
5140             DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5141 
5142             // Just pretend that we didn't see the previous declaration.
5143             PrevDecl = 0;
5144           } else if (PrevDecl) {
5145             // C++ [temp]p5:
5146             // ... a template name declared in namespace scope or in class
5147             // scope shall be unique in that scope.
5148             Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5149                 << Name;
5150             Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5151             return 0;
5152           }
5153 
5154           // Check the template parameter list of this declaration, possibly
5155           // merging in the template parameter list from the previous variable
5156           // template declaration.
5157           if (CheckTemplateParameterList(
5158                   TemplateParams,
5159                   PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5160                                   : 0,
5161                   (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5162                    DC->isDependentContext())
5163                       ? TPC_ClassTemplateMember
5164                       : TPC_VarTemplate))
5165             Invalid = true;
5166 
5167           if (D.getCXXScopeSpec().isSet()) {
5168             // If the name of the template was qualified, we must be defining
5169             // the template out-of-line.
5170             if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5171                 !PrevVarTemplate) {
5172               Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5173                   << Name << DC << /*IsDefinition*/true
5174                   << D.getCXXScopeSpec().getRange();
5175               Invalid = true;
5176             }
5177           }
5178         }
5179       }
5180     } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5181       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5182 
5183       // We have encountered something that the user meant to be a
5184       // specialization (because it has explicitly-specified template
5185       // arguments) but that was not introduced with a "template<>" (or had
5186       // too few of them).
5187       // FIXME: Differentiate between attempts for explicit instantiations
5188       // (starting with "template") and the rest.
5189       Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5190           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5191           << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5192                                         "template<> ");
5193       IsVariableTemplateSpecialization = true;
5194     }
5195 
5196     if (IsVariableTemplateSpecialization) {
5197       if (!PrevVarTemplate) {
5198         Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5199             << IsPartialSpecialization;
5200         return 0;
5201       }
5202 
5203       SourceLocation TemplateKWLoc =
5204           TemplateParamLists.size() > 0
5205               ? TemplateParamLists[0]->getTemplateLoc()
5206               : SourceLocation();
5207       DeclResult Res = ActOnVarTemplateSpecialization(
5208           S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5209           IsPartialSpecialization);
5210       if (Res.isInvalid())
5211         return 0;
5212       NewVD = cast<VarDecl>(Res.get());
5213       AddToScope = false;
5214     } else
5215       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5216                               D.getIdentifierLoc(), II, R, TInfo, SC);
5217 
5218     // If this is supposed to be a variable template, create it as such.
5219     if (IsVariableTemplate) {
5220       NewTemplate =
5221           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5222                                   TemplateParams, NewVD, PrevVarTemplate);
5223       NewVD->setDescribedVarTemplate(NewTemplate);
5224     }
5225 
5226     // If this decl has an auto type in need of deduction, make a note of the
5227     // Decl so we can diagnose uses of it in its own initializer.
5228     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5229       ParsingInitForAutoVars.insert(NewVD);
5230 
5231     if (D.isInvalidType() || Invalid) {
5232       NewVD->setInvalidDecl();
5233       if (NewTemplate)
5234         NewTemplate->setInvalidDecl();
5235     }
5236 
5237     SetNestedNameSpecifier(NewVD, D);
5238 
5239     // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5240     if (TemplateParams && TemplateParamLists.size() > 1 &&
5241         (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5242       NewVD->setTemplateParameterListsInfo(
5243           Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5244     } else if (IsVariableTemplateSpecialization ||
5245                (!TemplateParams && TemplateParamLists.size() > 0 &&
5246                 (D.getCXXScopeSpec().isSet()))) {
5247       NewVD->setTemplateParameterListsInfo(Context,
5248                                            TemplateParamLists.size(),
5249                                            TemplateParamLists.data());
5250     }
5251 
5252     if (D.getDeclSpec().isConstexprSpecified())
5253       NewVD->setConstexpr(true);
5254   }
5255 
5256   // Set the lexical context. If the declarator has a C++ scope specifier, the
5257   // lexical context will be different from the semantic context.
5258   NewVD->setLexicalDeclContext(CurContext);
5259   if (NewTemplate)
5260     NewTemplate->setLexicalDeclContext(CurContext);
5261 
5262   if (IsLocalExternDecl)
5263     NewVD->setLocalExternDecl();
5264 
5265   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5266     if (NewVD->hasLocalStorage()) {
5267       // C++11 [dcl.stc]p4:
5268       //   When thread_local is applied to a variable of block scope the
5269       //   storage-class-specifier static is implied if it does not appear
5270       //   explicitly.
5271       // Core issue: 'static' is not implied if the variable is declared
5272       //   'extern'.
5273       if (SCSpec == DeclSpec::SCS_unspecified &&
5274           TSCS == DeclSpec::TSCS_thread_local &&
5275           DC->isFunctionOrMethod())
5276         NewVD->setTSCSpec(TSCS);
5277       else
5278         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5279              diag::err_thread_non_global)
5280           << DeclSpec::getSpecifierName(TSCS);
5281     } else if (!Context.getTargetInfo().isTLSSupported())
5282       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5283            diag::err_thread_unsupported);
5284     else
5285       NewVD->setTSCSpec(TSCS);
5286   }
5287 
5288   // C99 6.7.4p3
5289   //   An inline definition of a function with external linkage shall
5290   //   not contain a definition of a modifiable object with static or
5291   //   thread storage duration...
5292   // We only apply this when the function is required to be defined
5293   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5294   // that a local variable with thread storage duration still has to
5295   // be marked 'static'.  Also note that it's possible to get these
5296   // semantics in C++ using __attribute__((gnu_inline)).
5297   if (SC == SC_Static && S->getFnParent() != 0 &&
5298       !NewVD->getType().isConstQualified()) {
5299     FunctionDecl *CurFD = getCurFunctionDecl();
5300     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5301       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5302            diag::warn_static_local_in_extern_inline);
5303       MaybeSuggestAddingStaticToDecl(CurFD);
5304     }
5305   }
5306 
5307   if (D.getDeclSpec().isModulePrivateSpecified()) {
5308     if (IsVariableTemplateSpecialization)
5309       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5310           << (IsPartialSpecialization ? 1 : 0)
5311           << FixItHint::CreateRemoval(
5312                  D.getDeclSpec().getModulePrivateSpecLoc());
5313     else if (IsExplicitSpecialization)
5314       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5315         << 2
5316         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5317     else if (NewVD->hasLocalStorage())
5318       Diag(NewVD->getLocation(), diag::err_module_private_local)
5319         << 0 << NewVD->getDeclName()
5320         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5321         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5322     else {
5323       NewVD->setModulePrivate();
5324       if (NewTemplate)
5325         NewTemplate->setModulePrivate();
5326     }
5327   }
5328 
5329   // Handle attributes prior to checking for duplicates in MergeVarDecl
5330   ProcessDeclAttributes(S, NewVD, D);
5331 
5332   if (NewVD->hasAttrs())
5333     CheckAlignasUnderalignment(NewVD);
5334 
5335   if (getLangOpts().CUDA) {
5336     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5337     // storage [duration]."
5338     if (SC == SC_None && S->getFnParent() != 0 &&
5339         (NewVD->hasAttr<CUDASharedAttr>() ||
5340          NewVD->hasAttr<CUDAConstantAttr>())) {
5341       NewVD->setStorageClass(SC_Static);
5342     }
5343   }
5344 
5345   // In auto-retain/release, infer strong retension for variables of
5346   // retainable type.
5347   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5348     NewVD->setInvalidDecl();
5349 
5350   // Handle GNU asm-label extension (encoded as an attribute).
5351   if (Expr *E = (Expr*)D.getAsmLabel()) {
5352     // The parser guarantees this is a string.
5353     StringLiteral *SE = cast<StringLiteral>(E);
5354     StringRef Label = SE->getString();
5355     if (S->getFnParent() != 0) {
5356       switch (SC) {
5357       case SC_None:
5358       case SC_Auto:
5359         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5360         break;
5361       case SC_Register:
5362         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5363           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5364         break;
5365       case SC_Static:
5366       case SC_Extern:
5367       case SC_PrivateExtern:
5368       case SC_OpenCLWorkGroupLocal:
5369         break;
5370       }
5371     }
5372 
5373     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5374                                                 Context, Label));
5375   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5376     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5377       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5378     if (I != ExtnameUndeclaredIdentifiers.end()) {
5379       NewVD->addAttr(I->second);
5380       ExtnameUndeclaredIdentifiers.erase(I);
5381     }
5382   }
5383 
5384   // Diagnose shadowed variables before filtering for scope.
5385   if (!D.getCXXScopeSpec().isSet())
5386     CheckShadow(S, NewVD, Previous);
5387 
5388   // Don't consider existing declarations that are in a different
5389   // scope and are out-of-semantic-context declarations (if the new
5390   // declaration has linkage).
5391   FilterLookupForScope(
5392       Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5393       IsExplicitSpecialization || IsVariableTemplateSpecialization);
5394 
5395   // Check whether the previous declaration is in the same block scope. This
5396   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5397   if (getLangOpts().CPlusPlus &&
5398       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5399     NewVD->setPreviousDeclInSameBlockScope(
5400         Previous.isSingleResult() && !Previous.isShadowed() &&
5401         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5402 
5403   if (!getLangOpts().CPlusPlus) {
5404     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5405   } else {
5406     // Merge the decl with the existing one if appropriate.
5407     if (!Previous.empty()) {
5408       if (Previous.isSingleResult() &&
5409           isa<FieldDecl>(Previous.getFoundDecl()) &&
5410           D.getCXXScopeSpec().isSet()) {
5411         // The user tried to define a non-static data member
5412         // out-of-line (C++ [dcl.meaning]p1).
5413         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5414           << D.getCXXScopeSpec().getRange();
5415         Previous.clear();
5416         NewVD->setInvalidDecl();
5417       }
5418     } else if (D.getCXXScopeSpec().isSet()) {
5419       // No previous declaration in the qualifying scope.
5420       Diag(D.getIdentifierLoc(), diag::err_no_member)
5421         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5422         << D.getCXXScopeSpec().getRange();
5423       NewVD->setInvalidDecl();
5424     }
5425 
5426     if (!IsVariableTemplateSpecialization) {
5427       if (PrevVarTemplate) {
5428         LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5429                               LookupOrdinaryName, ForRedeclaration);
5430         PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
5431         D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
5432       } else
5433         D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5434     }
5435 
5436     // This is an explicit specialization of a static data member. Check it.
5437     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5438         CheckMemberSpecialization(NewVD, Previous))
5439       NewVD->setInvalidDecl();
5440   }
5441 
5442   ProcessPragmaWeak(S, NewVD);
5443   checkAttributesAfterMerging(*this, *NewVD);
5444 
5445   // If this is the first declaration of an extern C variable, update
5446   // the map of such variables.
5447   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5448       isIncompleteDeclExternC(*this, NewVD))
5449     RegisterLocallyScopedExternCDecl(NewVD, S);
5450 
5451   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5452     Decl *ManglingContextDecl;
5453     if (MangleNumberingContext *MCtx =
5454             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5455                                           ManglingContextDecl)) {
5456       Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5457     }
5458   }
5459 
5460   // If we are providing an explicit specialization of a static variable
5461   // template, make a note of that.
5462   if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
5463     PrevVarTemplate->setMemberSpecialization();
5464 
5465   if (NewTemplate) {
5466     ActOnDocumentableDecl(NewTemplate);
5467     return NewTemplate;
5468   }
5469 
5470   return NewVD;
5471 }
5472 
5473 /// \brief Diagnose variable or built-in function shadowing.  Implements
5474 /// -Wshadow.
5475 ///
5476 /// This method is called whenever a VarDecl is added to a "useful"
5477 /// scope.
5478 ///
5479 /// \param S the scope in which the shadowing name is being declared
5480 /// \param R the lookup of the name
5481 ///
5482 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5483   // Return if warning is ignored.
5484   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
5485         DiagnosticsEngine::Ignored)
5486     return;
5487 
5488   // Don't diagnose declarations at file scope.
5489   if (D->hasGlobalStorage())
5490     return;
5491 
5492   DeclContext *NewDC = D->getDeclContext();
5493 
5494   // Only diagnose if we're shadowing an unambiguous field or variable.
5495   if (R.getResultKind() != LookupResult::Found)
5496     return;
5497 
5498   NamedDecl* ShadowedDecl = R.getFoundDecl();
5499   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5500     return;
5501 
5502   // Fields are not shadowed by variables in C++ static methods.
5503   if (isa<FieldDecl>(ShadowedDecl))
5504     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5505       if (MD->isStatic())
5506         return;
5507 
5508   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5509     if (shadowedVar->isExternC()) {
5510       // For shadowing external vars, make sure that we point to the global
5511       // declaration, not a locally scoped extern declaration.
5512       for (VarDecl::redecl_iterator
5513              I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5514            I != E; ++I)
5515         if (I->isFileVarDecl()) {
5516           ShadowedDecl = *I;
5517           break;
5518         }
5519     }
5520 
5521   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5522 
5523   // Only warn about certain kinds of shadowing for class members.
5524   if (NewDC && NewDC->isRecord()) {
5525     // In particular, don't warn about shadowing non-class members.
5526     if (!OldDC->isRecord())
5527       return;
5528 
5529     // TODO: should we warn about static data members shadowing
5530     // static data members from base classes?
5531 
5532     // TODO: don't diagnose for inaccessible shadowed members.
5533     // This is hard to do perfectly because we might friend the
5534     // shadowing context, but that's just a false negative.
5535   }
5536 
5537   // Determine what kind of declaration we're shadowing.
5538   unsigned Kind;
5539   if (isa<RecordDecl>(OldDC)) {
5540     if (isa<FieldDecl>(ShadowedDecl))
5541       Kind = 3; // field
5542     else
5543       Kind = 2; // static data member
5544   } else if (OldDC->isFileContext())
5545     Kind = 1; // global
5546   else
5547     Kind = 0; // local
5548 
5549   DeclarationName Name = R.getLookupName();
5550 
5551   // Emit warning and note.
5552   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5553   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5554 }
5555 
5556 /// \brief Check -Wshadow without the advantage of a previous lookup.
5557 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5558   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
5559         DiagnosticsEngine::Ignored)
5560     return;
5561 
5562   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5563                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5564   LookupName(R, S);
5565   CheckShadow(S, D, R);
5566 }
5567 
5568 /// Check for conflict between this global or extern "C" declaration and
5569 /// previous global or extern "C" declarations. This is only used in C++.
5570 template<typename T>
5571 static bool checkGlobalOrExternCConflict(
5572     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5573   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5574   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5575 
5576   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5577     // The common case: this global doesn't conflict with any extern "C"
5578     // declaration.
5579     return false;
5580   }
5581 
5582   if (Prev) {
5583     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5584       // Both the old and new declarations have C language linkage. This is a
5585       // redeclaration.
5586       Previous.clear();
5587       Previous.addDecl(Prev);
5588       return true;
5589     }
5590 
5591     // This is a global, non-extern "C" declaration, and there is a previous
5592     // non-global extern "C" declaration. Diagnose if this is a variable
5593     // declaration.
5594     if (!isa<VarDecl>(ND))
5595       return false;
5596   } else {
5597     // The declaration is extern "C". Check for any declaration in the
5598     // translation unit which might conflict.
5599     if (IsGlobal) {
5600       // We have already performed the lookup into the translation unit.
5601       IsGlobal = false;
5602       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5603            I != E; ++I) {
5604         if (isa<VarDecl>(*I)) {
5605           Prev = *I;
5606           break;
5607         }
5608       }
5609     } else {
5610       DeclContext::lookup_result R =
5611           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5612       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5613            I != E; ++I) {
5614         if (isa<VarDecl>(*I)) {
5615           Prev = *I;
5616           break;
5617         }
5618         // FIXME: If we have any other entity with this name in global scope,
5619         // the declaration is ill-formed, but that is a defect: it breaks the
5620         // 'stat' hack, for instance. Only variables can have mangled name
5621         // clashes with extern "C" declarations, so only they deserve a
5622         // diagnostic.
5623       }
5624     }
5625 
5626     if (!Prev)
5627       return false;
5628   }
5629 
5630   // Use the first declaration's location to ensure we point at something which
5631   // is lexically inside an extern "C" linkage-spec.
5632   assert(Prev && "should have found a previous declaration to diagnose");
5633   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5634     Prev = FD->getFirstDecl();
5635   else
5636     Prev = cast<VarDecl>(Prev)->getFirstDecl();
5637 
5638   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5639     << IsGlobal << ND;
5640   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5641     << IsGlobal;
5642   return false;
5643 }
5644 
5645 /// Apply special rules for handling extern "C" declarations. Returns \c true
5646 /// if we have found that this is a redeclaration of some prior entity.
5647 ///
5648 /// Per C++ [dcl.link]p6:
5649 ///   Two declarations [for a function or variable] with C language linkage
5650 ///   with the same name that appear in different scopes refer to the same
5651 ///   [entity]. An entity with C language linkage shall not be declared with
5652 ///   the same name as an entity in global scope.
5653 template<typename T>
5654 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5655                                                   LookupResult &Previous) {
5656   if (!S.getLangOpts().CPlusPlus) {
5657     // In C, when declaring a global variable, look for a corresponding 'extern'
5658     // variable declared in function scope. We don't need this in C++, because
5659     // we find local extern decls in the surrounding file-scope DeclContext.
5660     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5661       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5662         Previous.clear();
5663         Previous.addDecl(Prev);
5664         return true;
5665       }
5666     }
5667     return false;
5668   }
5669 
5670   // A declaration in the translation unit can conflict with an extern "C"
5671   // declaration.
5672   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5673     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5674 
5675   // An extern "C" declaration can conflict with a declaration in the
5676   // translation unit or can be a redeclaration of an extern "C" declaration
5677   // in another scope.
5678   if (isIncompleteDeclExternC(S,ND))
5679     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5680 
5681   // Neither global nor extern "C": nothing to do.
5682   return false;
5683 }
5684 
5685 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
5686   // If the decl is already known invalid, don't check it.
5687   if (NewVD->isInvalidDecl())
5688     return;
5689 
5690   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5691   QualType T = TInfo->getType();
5692 
5693   // Defer checking an 'auto' type until its initializer is attached.
5694   if (T->isUndeducedType())
5695     return;
5696 
5697   if (T->isObjCObjectType()) {
5698     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5699       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5700     T = Context.getObjCObjectPointerType(T);
5701     NewVD->setType(T);
5702   }
5703 
5704   // Emit an error if an address space was applied to decl with local storage.
5705   // This includes arrays of objects with address space qualifiers, but not
5706   // automatic variables that point to other address spaces.
5707   // ISO/IEC TR 18037 S5.1.2
5708   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5709     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5710     NewVD->setInvalidDecl();
5711     return;
5712   }
5713 
5714   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5715   // __constant address space.
5716   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5717       && T.getAddressSpace() != LangAS::opencl_constant
5718       && !T->isSamplerT()){
5719     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5720     NewVD->setInvalidDecl();
5721     return;
5722   }
5723 
5724   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5725   // scope.
5726   if ((getLangOpts().OpenCLVersion >= 120)
5727       && NewVD->isStaticLocal()) {
5728     Diag(NewVD->getLocation(), diag::err_static_function_scope);
5729     NewVD->setInvalidDecl();
5730     return;
5731   }
5732 
5733   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5734       && !NewVD->hasAttr<BlocksAttr>()) {
5735     if (getLangOpts().getGC() != LangOptions::NonGC)
5736       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5737     else {
5738       assert(!getLangOpts().ObjCAutoRefCount);
5739       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5740     }
5741   }
5742 
5743   bool isVM = T->isVariablyModifiedType();
5744   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5745       NewVD->hasAttr<BlocksAttr>())
5746     getCurFunction()->setHasBranchProtectedScope();
5747 
5748   if ((isVM && NewVD->hasLinkage()) ||
5749       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5750     bool SizeIsNegative;
5751     llvm::APSInt Oversized;
5752     TypeSourceInfo *FixedTInfo =
5753       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5754                                                     SizeIsNegative, Oversized);
5755     if (FixedTInfo == 0 && T->isVariableArrayType()) {
5756       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5757       // FIXME: This won't give the correct result for
5758       // int a[10][n];
5759       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5760 
5761       if (NewVD->isFileVarDecl())
5762         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5763         << SizeRange;
5764       else if (NewVD->isStaticLocal())
5765         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5766         << SizeRange;
5767       else
5768         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5769         << SizeRange;
5770       NewVD->setInvalidDecl();
5771       return;
5772     }
5773 
5774     if (FixedTInfo == 0) {
5775       if (NewVD->isFileVarDecl())
5776         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5777       else
5778         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5779       NewVD->setInvalidDecl();
5780       return;
5781     }
5782 
5783     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5784     NewVD->setType(FixedTInfo->getType());
5785     NewVD->setTypeSourceInfo(FixedTInfo);
5786   }
5787 
5788   if (T->isVoidType()) {
5789     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5790     //                    of objects and functions.
5791     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5792       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5793         << T;
5794       NewVD->setInvalidDecl();
5795       return;
5796     }
5797   }
5798 
5799   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5800     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5801     NewVD->setInvalidDecl();
5802     return;
5803   }
5804 
5805   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5806     Diag(NewVD->getLocation(), diag::err_block_on_vm);
5807     NewVD->setInvalidDecl();
5808     return;
5809   }
5810 
5811   if (NewVD->isConstexpr() && !T->isDependentType() &&
5812       RequireLiteralType(NewVD->getLocation(), T,
5813                          diag::err_constexpr_var_non_literal)) {
5814     // Can't perform this check until the type is deduced.
5815     NewVD->setInvalidDecl();
5816     return;
5817   }
5818 }
5819 
5820 /// \brief Perform semantic checking on a newly-created variable
5821 /// declaration.
5822 ///
5823 /// This routine performs all of the type-checking required for a
5824 /// variable declaration once it has been built. It is used both to
5825 /// check variables after they have been parsed and their declarators
5826 /// have been translated into a declaration, and to check variables
5827 /// that have been instantiated from a template.
5828 ///
5829 /// Sets NewVD->isInvalidDecl() if an error was encountered.
5830 ///
5831 /// Returns true if the variable declaration is a redeclaration.
5832 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
5833   CheckVariableDeclarationType(NewVD);
5834 
5835   // If the decl is already known invalid, don't check it.
5836   if (NewVD->isInvalidDecl())
5837     return false;
5838 
5839   // If we did not find anything by this name, look for a non-visible
5840   // extern "C" declaration with the same name.
5841   if (Previous.empty() &&
5842       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
5843     Previous.setShadowed();
5844 
5845   // Filter out any non-conflicting previous declarations.
5846   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5847 
5848   if (!Previous.empty()) {
5849     MergeVarDecl(NewVD, Previous);
5850     return true;
5851   }
5852   return false;
5853 }
5854 
5855 /// \brief Data used with FindOverriddenMethod
5856 struct FindOverriddenMethodData {
5857   Sema *S;
5858   CXXMethodDecl *Method;
5859 };
5860 
5861 /// \brief Member lookup function that determines whether a given C++
5862 /// method overrides a method in a base class, to be used with
5863 /// CXXRecordDecl::lookupInBases().
5864 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
5865                                  CXXBasePath &Path,
5866                                  void *UserData) {
5867   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5868 
5869   FindOverriddenMethodData *Data
5870     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
5871 
5872   DeclarationName Name = Data->Method->getDeclName();
5873 
5874   // FIXME: Do we care about other names here too?
5875   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5876     // We really want to find the base class destructor here.
5877     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5878     CanQualType CT = Data->S->Context.getCanonicalType(T);
5879 
5880     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
5881   }
5882 
5883   for (Path.Decls = BaseRecord->lookup(Name);
5884        !Path.Decls.empty();
5885        Path.Decls = Path.Decls.slice(1)) {
5886     NamedDecl *D = Path.Decls.front();
5887     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5888       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
5889         return true;
5890     }
5891   }
5892 
5893   return false;
5894 }
5895 
5896 namespace {
5897   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5898 }
5899 /// \brief Report an error regarding overriding, along with any relevant
5900 /// overriden methods.
5901 ///
5902 /// \param DiagID the primary error to report.
5903 /// \param MD the overriding method.
5904 /// \param OEK which overrides to include as notes.
5905 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5906                             OverrideErrorKind OEK = OEK_All) {
5907   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5908   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5909                                       E = MD->end_overridden_methods();
5910        I != E; ++I) {
5911     // This check (& the OEK parameter) could be replaced by a predicate, but
5912     // without lambdas that would be overkill. This is still nicer than writing
5913     // out the diag loop 3 times.
5914     if ((OEK == OEK_All) ||
5915         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5916         (OEK == OEK_Deleted && (*I)->isDeleted()))
5917       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5918   }
5919 }
5920 
5921 /// AddOverriddenMethods - See if a method overrides any in the base classes,
5922 /// and if so, check that it's a valid override and remember it.
5923 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5924   // Look for virtual methods in base classes that this method might override.
5925   CXXBasePaths Paths;
5926   FindOverriddenMethodData Data;
5927   Data.Method = MD;
5928   Data.S = this;
5929   bool hasDeletedOverridenMethods = false;
5930   bool hasNonDeletedOverridenMethods = false;
5931   bool AddedAny = false;
5932   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5933     for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5934          E = Paths.found_decls_end(); I != E; ++I) {
5935       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
5936         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
5937         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
5938             !CheckOverridingFunctionAttributes(MD, OldMD) &&
5939             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
5940             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
5941           hasDeletedOverridenMethods |= OldMD->isDeleted();
5942           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
5943           AddedAny = true;
5944         }
5945       }
5946     }
5947   }
5948 
5949   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5950     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5951   }
5952   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5953     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5954   }
5955 
5956   return AddedAny;
5957 }
5958 
5959 namespace {
5960   // Struct for holding all of the extra arguments needed by
5961   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5962   struct ActOnFDArgs {
5963     Scope *S;
5964     Declarator &D;
5965     MultiTemplateParamsArg TemplateParamLists;
5966     bool AddToScope;
5967   };
5968 }
5969 
5970 namespace {
5971 
5972 // Callback to only accept typo corrections that have a non-zero edit distance.
5973 // Also only accept corrections that have the same parent decl.
5974 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5975  public:
5976   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5977                             CXXRecordDecl *Parent)
5978       : Context(Context), OriginalFD(TypoFD),
5979         ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
5980 
5981   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5982     if (candidate.getEditDistance() == 0)
5983       return false;
5984 
5985     SmallVector<unsigned, 1> MismatchedParams;
5986     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5987                                           CDeclEnd = candidate.end();
5988          CDecl != CDeclEnd; ++CDecl) {
5989       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5990 
5991       if (FD && !FD->hasBody() &&
5992           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
5993         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5994           CXXRecordDecl *Parent = MD->getParent();
5995           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
5996             return true;
5997         } else if (!ExpectedParent) {
5998           return true;
5999         }
6000       }
6001     }
6002 
6003     return false;
6004   }
6005 
6006  private:
6007   ASTContext &Context;
6008   FunctionDecl *OriginalFD;
6009   CXXRecordDecl *ExpectedParent;
6010 };
6011 
6012 }
6013 
6014 /// \brief Generate diagnostics for an invalid function redeclaration.
6015 ///
6016 /// This routine handles generating the diagnostic messages for an invalid
6017 /// function redeclaration, including finding possible similar declarations
6018 /// or performing typo correction if there are no previous declarations with
6019 /// the same name.
6020 ///
6021 /// Returns a NamedDecl iff typo correction was performed and substituting in
6022 /// the new declaration name does not cause new errors.
6023 static NamedDecl *DiagnoseInvalidRedeclaration(
6024     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6025     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6026   DeclarationName Name = NewFD->getDeclName();
6027   DeclContext *NewDC = NewFD->getDeclContext();
6028   SmallVector<unsigned, 1> MismatchedParams;
6029   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6030   TypoCorrection Correction;
6031   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6032   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6033                                    : diag::err_member_decl_does_not_match;
6034   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6035                     IsLocalFriend ? Sema::LookupLocalFriendName
6036                                   : Sema::LookupOrdinaryName,
6037                     Sema::ForRedeclaration);
6038 
6039   NewFD->setInvalidDecl();
6040   if (IsLocalFriend)
6041     SemaRef.LookupName(Prev, S);
6042   else
6043     SemaRef.LookupQualifiedName(Prev, NewDC);
6044   assert(!Prev.isAmbiguous() &&
6045          "Cannot have an ambiguity in previous-declaration lookup");
6046   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6047   DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6048                                       MD ? MD->getParent() : 0);
6049   if (!Prev.empty()) {
6050     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6051          Func != FuncEnd; ++Func) {
6052       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6053       if (FD &&
6054           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6055         // Add 1 to the index so that 0 can mean the mismatch didn't
6056         // involve a parameter
6057         unsigned ParamNum =
6058             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6059         NearMatches.push_back(std::make_pair(FD, ParamNum));
6060       }
6061     }
6062   // If the qualified name lookup yielded nothing, try typo correction
6063   } else if ((Correction = SemaRef.CorrectTypo(
6064                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6065                  &ExtraArgs.D.getCXXScopeSpec(), Validator,
6066                  IsLocalFriend ? 0 : NewDC))) {
6067     // Set up everything for the call to ActOnFunctionDeclarator
6068     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6069                               ExtraArgs.D.getIdentifierLoc());
6070     Previous.clear();
6071     Previous.setLookupName(Correction.getCorrection());
6072     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6073                                     CDeclEnd = Correction.end();
6074          CDecl != CDeclEnd; ++CDecl) {
6075       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6076       if (FD && !FD->hasBody() &&
6077           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6078         Previous.addDecl(FD);
6079       }
6080     }
6081     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6082 
6083     NamedDecl *Result;
6084     // Retry building the function declaration with the new previous
6085     // declarations, and with errors suppressed.
6086     {
6087       // Trap errors.
6088       Sema::SFINAETrap Trap(SemaRef);
6089 
6090       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6091       // pieces need to verify the typo-corrected C++ declaration and hopefully
6092       // eliminate the need for the parameter pack ExtraArgs.
6093       Result = SemaRef.ActOnFunctionDeclarator(
6094           ExtraArgs.S, ExtraArgs.D,
6095           Correction.getCorrectionDecl()->getDeclContext(),
6096           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6097           ExtraArgs.AddToScope);
6098 
6099       if (Trap.hasErrorOccurred())
6100         Result = 0;
6101     }
6102 
6103     if (Result) {
6104       // Determine which correction we picked.
6105       Decl *Canonical = Result->getCanonicalDecl();
6106       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6107            I != E; ++I)
6108         if ((*I)->getCanonicalDecl() == Canonical)
6109           Correction.setCorrectionDecl(*I);
6110 
6111       SemaRef.diagnoseTypo(
6112           Correction,
6113           SemaRef.PDiag(IsLocalFriend
6114                           ? diag::err_no_matching_local_friend_suggest
6115                           : diag::err_member_decl_does_not_match_suggest)
6116             << Name << NewDC << IsDefinition);
6117       return Result;
6118     }
6119 
6120     // Pretend the typo correction never occurred
6121     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6122                               ExtraArgs.D.getIdentifierLoc());
6123     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6124     Previous.clear();
6125     Previous.setLookupName(Name);
6126   }
6127 
6128   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6129       << Name << NewDC << IsDefinition << NewFD->getLocation();
6130 
6131   bool NewFDisConst = false;
6132   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6133     NewFDisConst = NewMD->isConst();
6134 
6135   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6136        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6137        NearMatch != NearMatchEnd; ++NearMatch) {
6138     FunctionDecl *FD = NearMatch->first;
6139     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6140     bool FDisConst = MD && MD->isConst();
6141     bool IsMember = MD || !IsLocalFriend;
6142 
6143     // FIXME: These notes are poorly worded for the local friend case.
6144     if (unsigned Idx = NearMatch->second) {
6145       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6146       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6147       if (Loc.isInvalid()) Loc = FD->getLocation();
6148       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6149                                  : diag::note_local_decl_close_param_match)
6150         << Idx << FDParam->getType()
6151         << NewFD->getParamDecl(Idx - 1)->getType();
6152     } else if (FDisConst != NewFDisConst) {
6153       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6154           << NewFDisConst << FD->getSourceRange().getEnd();
6155     } else
6156       SemaRef.Diag(FD->getLocation(),
6157                    IsMember ? diag::note_member_def_close_match
6158                             : diag::note_local_decl_close_match);
6159   }
6160   return 0;
6161 }
6162 
6163 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6164                                                           Declarator &D) {
6165   switch (D.getDeclSpec().getStorageClassSpec()) {
6166   default: llvm_unreachable("Unknown storage class!");
6167   case DeclSpec::SCS_auto:
6168   case DeclSpec::SCS_register:
6169   case DeclSpec::SCS_mutable:
6170     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6171                  diag::err_typecheck_sclass_func);
6172     D.setInvalidType();
6173     break;
6174   case DeclSpec::SCS_unspecified: break;
6175   case DeclSpec::SCS_extern:
6176     if (D.getDeclSpec().isExternInLinkageSpec())
6177       return SC_None;
6178     return SC_Extern;
6179   case DeclSpec::SCS_static: {
6180     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6181       // C99 6.7.1p5:
6182       //   The declaration of an identifier for a function that has
6183       //   block scope shall have no explicit storage-class specifier
6184       //   other than extern
6185       // See also (C++ [dcl.stc]p4).
6186       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6187                    diag::err_static_block_func);
6188       break;
6189     } else
6190       return SC_Static;
6191   }
6192   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6193   }
6194 
6195   // No explicit storage class has already been returned
6196   return SC_None;
6197 }
6198 
6199 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6200                                            DeclContext *DC, QualType &R,
6201                                            TypeSourceInfo *TInfo,
6202                                            FunctionDecl::StorageClass SC,
6203                                            bool &IsVirtualOkay) {
6204   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6205   DeclarationName Name = NameInfo.getName();
6206 
6207   FunctionDecl *NewFD = 0;
6208   bool isInline = D.getDeclSpec().isInlineSpecified();
6209 
6210   if (!SemaRef.getLangOpts().CPlusPlus) {
6211     // Determine whether the function was written with a
6212     // prototype. This true when:
6213     //   - there is a prototype in the declarator, or
6214     //   - the type R of the function is some kind of typedef or other reference
6215     //     to a type name (which eventually refers to a function type).
6216     bool HasPrototype =
6217       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6218       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6219 
6220     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6221                                  D.getLocStart(), NameInfo, R,
6222                                  TInfo, SC, isInline,
6223                                  HasPrototype, false);
6224     if (D.isInvalidType())
6225       NewFD->setInvalidDecl();
6226 
6227     // Set the lexical context.
6228     NewFD->setLexicalDeclContext(SemaRef.CurContext);
6229 
6230     return NewFD;
6231   }
6232 
6233   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6234   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6235 
6236   // Check that the return type is not an abstract class type.
6237   // For record types, this is done by the AbstractClassUsageDiagnoser once
6238   // the class has been completely parsed.
6239   if (!DC->isRecord() &&
6240       SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6241                                      R->getAs<FunctionType>()->getResultType(),
6242                                      diag::err_abstract_type_in_decl,
6243                                      SemaRef.AbstractReturnType))
6244     D.setInvalidType();
6245 
6246   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6247     // This is a C++ constructor declaration.
6248     assert(DC->isRecord() &&
6249            "Constructors can only be declared in a member context");
6250 
6251     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6252     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6253                                       D.getLocStart(), NameInfo,
6254                                       R, TInfo, isExplicit, isInline,
6255                                       /*isImplicitlyDeclared=*/false,
6256                                       isConstexpr);
6257 
6258   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6259     // This is a C++ destructor declaration.
6260     if (DC->isRecord()) {
6261       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6262       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6263       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6264                                         SemaRef.Context, Record,
6265                                         D.getLocStart(),
6266                                         NameInfo, R, TInfo, isInline,
6267                                         /*isImplicitlyDeclared=*/false);
6268 
6269       // If the class is complete, then we now create the implicit exception
6270       // specification. If the class is incomplete or dependent, we can't do
6271       // it yet.
6272       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6273           Record->getDefinition() && !Record->isBeingDefined() &&
6274           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6275         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6276       }
6277 
6278       // The Microsoft ABI requires that we perform the destructor body
6279       // checks (i.e. operator delete() lookup) at every declaration, as
6280       // any translation unit may need to emit a deleting destructor.
6281       if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6282           !Record->isDependentType() && Record->getDefinition() &&
6283           !Record->isBeingDefined()) {
6284         SemaRef.CheckDestructor(NewDD);
6285       }
6286 
6287       IsVirtualOkay = true;
6288       return NewDD;
6289 
6290     } else {
6291       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6292       D.setInvalidType();
6293 
6294       // Create a FunctionDecl to satisfy the function definition parsing
6295       // code path.
6296       return FunctionDecl::Create(SemaRef.Context, DC,
6297                                   D.getLocStart(),
6298                                   D.getIdentifierLoc(), Name, R, TInfo,
6299                                   SC, isInline,
6300                                   /*hasPrototype=*/true, isConstexpr);
6301     }
6302 
6303   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6304     if (!DC->isRecord()) {
6305       SemaRef.Diag(D.getIdentifierLoc(),
6306            diag::err_conv_function_not_member);
6307       return 0;
6308     }
6309 
6310     SemaRef.CheckConversionDeclarator(D, R, SC);
6311     IsVirtualOkay = true;
6312     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6313                                      D.getLocStart(), NameInfo,
6314                                      R, TInfo, isInline, isExplicit,
6315                                      isConstexpr, SourceLocation());
6316 
6317   } else if (DC->isRecord()) {
6318     // If the name of the function is the same as the name of the record,
6319     // then this must be an invalid constructor that has a return type.
6320     // (The parser checks for a return type and makes the declarator a
6321     // constructor if it has no return type).
6322     if (Name.getAsIdentifierInfo() &&
6323         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6324       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6325         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6326         << SourceRange(D.getIdentifierLoc());
6327       return 0;
6328     }
6329 
6330     // This is a C++ method declaration.
6331     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6332                                                cast<CXXRecordDecl>(DC),
6333                                                D.getLocStart(), NameInfo, R,
6334                                                TInfo, SC, isInline,
6335                                                isConstexpr, SourceLocation());
6336     IsVirtualOkay = !Ret->isStatic();
6337     return Ret;
6338   } else {
6339     // Determine whether the function was written with a
6340     // prototype. This true when:
6341     //   - we're in C++ (where every function has a prototype),
6342     return FunctionDecl::Create(SemaRef.Context, DC,
6343                                 D.getLocStart(),
6344                                 NameInfo, R, TInfo, SC, isInline,
6345                                 true/*HasPrototype*/, isConstexpr);
6346   }
6347 }
6348 
6349 void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6350   // In C++, the empty parameter-type-list must be spelled "void"; a
6351   // typedef of void is not permitted.
6352   if (getLangOpts().CPlusPlus &&
6353       Param->getType().getUnqualifiedType() != Context.VoidTy) {
6354     bool IsTypeAlias = false;
6355     if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6356       IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6357     else if (const TemplateSpecializationType *TST =
6358                Param->getType()->getAs<TemplateSpecializationType>())
6359       IsTypeAlias = TST->isTypeAlias();
6360     Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6361       << IsTypeAlias;
6362   }
6363 }
6364 
6365 enum OpenCLParamType {
6366   ValidKernelParam,
6367   PtrPtrKernelParam,
6368   PtrKernelParam,
6369   InvalidKernelParam,
6370   RecordKernelParam
6371 };
6372 
6373 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6374   if (PT->isPointerType()) {
6375     QualType PointeeType = PT->getPointeeType();
6376     return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6377   }
6378 
6379   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6380   // be used as builtin types.
6381 
6382   if (PT->isImageType())
6383     return PtrKernelParam;
6384 
6385   if (PT->isBooleanType())
6386     return InvalidKernelParam;
6387 
6388   if (PT->isEventT())
6389     return InvalidKernelParam;
6390 
6391   if (PT->isHalfType())
6392     return InvalidKernelParam;
6393 
6394   if (PT->isRecordType())
6395     return RecordKernelParam;
6396 
6397   return ValidKernelParam;
6398 }
6399 
6400 static void checkIsValidOpenCLKernelParameter(
6401   Sema &S,
6402   Declarator &D,
6403   ParmVarDecl *Param,
6404   llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6405   QualType PT = Param->getType();
6406 
6407   // Cache the valid types we encounter to avoid rechecking structs that are
6408   // used again
6409   if (ValidTypes.count(PT.getTypePtr()))
6410     return;
6411 
6412   switch (getOpenCLKernelParameterType(PT)) {
6413   case PtrPtrKernelParam:
6414     // OpenCL v1.2 s6.9.a:
6415     // A kernel function argument cannot be declared as a
6416     // pointer to a pointer type.
6417     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6418     D.setInvalidType();
6419     return;
6420 
6421     // OpenCL v1.2 s6.9.k:
6422     // Arguments to kernel functions in a program cannot be declared with the
6423     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6424     // uintptr_t or a struct and/or union that contain fields declared to be
6425     // one of these built-in scalar types.
6426 
6427   case InvalidKernelParam:
6428     // OpenCL v1.2 s6.8 n:
6429     // A kernel function argument cannot be declared
6430     // of event_t type.
6431     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6432     D.setInvalidType();
6433     return;
6434 
6435   case PtrKernelParam:
6436   case ValidKernelParam:
6437     ValidTypes.insert(PT.getTypePtr());
6438     return;
6439 
6440   case RecordKernelParam:
6441     break;
6442   }
6443 
6444   // Track nested structs we will inspect
6445   SmallVector<const Decl *, 4> VisitStack;
6446 
6447   // Track where we are in the nested structs. Items will migrate from
6448   // VisitStack to HistoryStack as we do the DFS for bad field.
6449   SmallVector<const FieldDecl *, 4> HistoryStack;
6450   HistoryStack.push_back((const FieldDecl *) 0);
6451 
6452   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6453   VisitStack.push_back(PD);
6454 
6455   assert(VisitStack.back() && "First decl null?");
6456 
6457   do {
6458     const Decl *Next = VisitStack.pop_back_val();
6459     if (!Next) {
6460       assert(!HistoryStack.empty());
6461       // Found a marker, we have gone up a level
6462       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6463         ValidTypes.insert(Hist->getType().getTypePtr());
6464 
6465       continue;
6466     }
6467 
6468     // Adds everything except the original parameter declaration (which is not a
6469     // field itself) to the history stack.
6470     const RecordDecl *RD;
6471     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6472       HistoryStack.push_back(Field);
6473       RD = Field->getType()->castAs<RecordType>()->getDecl();
6474     } else {
6475       RD = cast<RecordDecl>(Next);
6476     }
6477 
6478     // Add a null marker so we know when we've gone back up a level
6479     VisitStack.push_back((const Decl *) 0);
6480 
6481     for (RecordDecl::field_iterator I = RD->field_begin(),
6482            E = RD->field_end(); I != E; ++I) {
6483       const FieldDecl *FD = *I;
6484       QualType QT = FD->getType();
6485 
6486       if (ValidTypes.count(QT.getTypePtr()))
6487         continue;
6488 
6489       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6490       if (ParamType == ValidKernelParam)
6491         continue;
6492 
6493       if (ParamType == RecordKernelParam) {
6494         VisitStack.push_back(FD);
6495         continue;
6496       }
6497 
6498       // OpenCL v1.2 s6.9.p:
6499       // Arguments to kernel functions that are declared to be a struct or union
6500       // do not allow OpenCL objects to be passed as elements of the struct or
6501       // union.
6502       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6503         S.Diag(Param->getLocation(),
6504                diag::err_record_with_pointers_kernel_param)
6505           << PT->isUnionType()
6506           << PT;
6507       } else {
6508         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6509       }
6510 
6511       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6512         << PD->getDeclName();
6513 
6514       // We have an error, now let's go back up through history and show where
6515       // the offending field came from
6516       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6517              E = HistoryStack.end(); I != E; ++I) {
6518         const FieldDecl *OuterField = *I;
6519         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6520           << OuterField->getType();
6521       }
6522 
6523       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6524         << QT->isPointerType()
6525         << QT;
6526       D.setInvalidType();
6527       return;
6528     }
6529   } while (!VisitStack.empty());
6530 }
6531 
6532 NamedDecl*
6533 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6534                               TypeSourceInfo *TInfo, LookupResult &Previous,
6535                               MultiTemplateParamsArg TemplateParamLists,
6536                               bool &AddToScope) {
6537   QualType R = TInfo->getType();
6538 
6539   assert(R.getTypePtr()->isFunctionType());
6540 
6541   // TODO: consider using NameInfo for diagnostic.
6542   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6543   DeclarationName Name = NameInfo.getName();
6544   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6545 
6546   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6547     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6548          diag::err_invalid_thread)
6549       << DeclSpec::getSpecifierName(TSCS);
6550 
6551   if (D.isFirstDeclarationOfMember())
6552     adjustMemberFunctionCC(R, D.isStaticMember());
6553 
6554   bool isFriend = false;
6555   FunctionTemplateDecl *FunctionTemplate = 0;
6556   bool isExplicitSpecialization = false;
6557   bool isFunctionTemplateSpecialization = false;
6558 
6559   bool isDependentClassScopeExplicitSpecialization = false;
6560   bool HasExplicitTemplateArgs = false;
6561   TemplateArgumentListInfo TemplateArgs;
6562 
6563   bool isVirtualOkay = false;
6564 
6565   DeclContext *OriginalDC = DC;
6566   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6567 
6568   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6569                                               isVirtualOkay);
6570   if (!NewFD) return 0;
6571 
6572   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6573     NewFD->setTopLevelDeclInObjCContainer();
6574 
6575   // Set the lexical context. If this is a function-scope declaration, or has a
6576   // C++ scope specifier, or is the object of a friend declaration, the lexical
6577   // context will be different from the semantic context.
6578   NewFD->setLexicalDeclContext(CurContext);
6579 
6580   if (IsLocalExternDecl)
6581     NewFD->setLocalExternDecl();
6582 
6583   if (getLangOpts().CPlusPlus) {
6584     bool isInline = D.getDeclSpec().isInlineSpecified();
6585     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6586     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6587     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6588     isFriend = D.getDeclSpec().isFriendSpecified();
6589     if (isFriend && !isInline && D.isFunctionDefinition()) {
6590       // C++ [class.friend]p5
6591       //   A function can be defined in a friend declaration of a
6592       //   class . . . . Such a function is implicitly inline.
6593       NewFD->setImplicitlyInline();
6594     }
6595 
6596     // If this is a method defined in an __interface, and is not a constructor
6597     // or an overloaded operator, then set the pure flag (isVirtual will already
6598     // return true).
6599     if (const CXXRecordDecl *Parent =
6600           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6601       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6602         NewFD->setPure(true);
6603     }
6604 
6605     SetNestedNameSpecifier(NewFD, D);
6606     isExplicitSpecialization = false;
6607     isFunctionTemplateSpecialization = false;
6608     if (D.isInvalidType())
6609       NewFD->setInvalidDecl();
6610 
6611     // Match up the template parameter lists with the scope specifier, then
6612     // determine whether we have a template or a template specialization.
6613     bool Invalid = false;
6614     if (TemplateParameterList *TemplateParams =
6615             MatchTemplateParametersToScopeSpecifier(
6616                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6617                 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6618                 isExplicitSpecialization, Invalid)) {
6619       if (TemplateParams->size() > 0) {
6620         // This is a function template
6621 
6622         // Check that we can declare a template here.
6623         if (CheckTemplateDeclScope(S, TemplateParams))
6624           return 0;
6625 
6626         // A destructor cannot be a template.
6627         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6628           Diag(NewFD->getLocation(), diag::err_destructor_template);
6629           return 0;
6630         }
6631 
6632         // If we're adding a template to a dependent context, we may need to
6633         // rebuilding some of the types used within the template parameter list,
6634         // now that we know what the current instantiation is.
6635         if (DC->isDependentContext()) {
6636           ContextRAII SavedContext(*this, DC);
6637           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6638             Invalid = true;
6639         }
6640 
6641 
6642         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6643                                                         NewFD->getLocation(),
6644                                                         Name, TemplateParams,
6645                                                         NewFD);
6646         FunctionTemplate->setLexicalDeclContext(CurContext);
6647         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6648 
6649         // For source fidelity, store the other template param lists.
6650         if (TemplateParamLists.size() > 1) {
6651           NewFD->setTemplateParameterListsInfo(Context,
6652                                                TemplateParamLists.size() - 1,
6653                                                TemplateParamLists.data());
6654         }
6655       } else {
6656         // This is a function template specialization.
6657         isFunctionTemplateSpecialization = true;
6658         // For source fidelity, store all the template param lists.
6659         NewFD->setTemplateParameterListsInfo(Context,
6660                                              TemplateParamLists.size(),
6661                                              TemplateParamLists.data());
6662 
6663         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6664         if (isFriend) {
6665           // We want to remove the "template<>", found here.
6666           SourceRange RemoveRange = TemplateParams->getSourceRange();
6667 
6668           // If we remove the template<> and the name is not a
6669           // template-id, we're actually silently creating a problem:
6670           // the friend declaration will refer to an untemplated decl,
6671           // and clearly the user wants a template specialization.  So
6672           // we need to insert '<>' after the name.
6673           SourceLocation InsertLoc;
6674           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6675             InsertLoc = D.getName().getSourceRange().getEnd();
6676             InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6677           }
6678 
6679           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6680             << Name << RemoveRange
6681             << FixItHint::CreateRemoval(RemoveRange)
6682             << FixItHint::CreateInsertion(InsertLoc, "<>");
6683         }
6684       }
6685     }
6686     else {
6687       // All template param lists were matched against the scope specifier:
6688       // this is NOT (an explicit specialization of) a template.
6689       if (TemplateParamLists.size() > 0)
6690         // For source fidelity, store all the template param lists.
6691         NewFD->setTemplateParameterListsInfo(Context,
6692                                              TemplateParamLists.size(),
6693                                              TemplateParamLists.data());
6694     }
6695 
6696     if (Invalid) {
6697       NewFD->setInvalidDecl();
6698       if (FunctionTemplate)
6699         FunctionTemplate->setInvalidDecl();
6700     }
6701 
6702     // C++ [dcl.fct.spec]p5:
6703     //   The virtual specifier shall only be used in declarations of
6704     //   nonstatic class member functions that appear within a
6705     //   member-specification of a class declaration; see 10.3.
6706     //
6707     if (isVirtual && !NewFD->isInvalidDecl()) {
6708       if (!isVirtualOkay) {
6709         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6710              diag::err_virtual_non_function);
6711       } else if (!CurContext->isRecord()) {
6712         // 'virtual' was specified outside of the class.
6713         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6714              diag::err_virtual_out_of_class)
6715           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6716       } else if (NewFD->getDescribedFunctionTemplate()) {
6717         // C++ [temp.mem]p3:
6718         //  A member function template shall not be virtual.
6719         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6720              diag::err_virtual_member_function_template)
6721           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6722       } else {
6723         // Okay: Add virtual to the method.
6724         NewFD->setVirtualAsWritten(true);
6725       }
6726 
6727       if (getLangOpts().CPlusPlus1y &&
6728           NewFD->getResultType()->isUndeducedType())
6729         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
6730     }
6731 
6732     if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() &&
6733         NewFD->getResultType()->isUndeducedType()) {
6734       // If the function template is referenced directly (for instance, as a
6735       // member of the current instantiation), pretend it has a dependent type.
6736       // This is not really justified by the standard, but is the only sane
6737       // thing to do.
6738       const FunctionProtoType *FPT =
6739           NewFD->getType()->castAs<FunctionProtoType>();
6740       QualType Result = SubstAutoType(FPT->getResultType(),
6741                                        Context.DependentTy);
6742       NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6743                                              FPT->getExtProtoInfo()));
6744     }
6745 
6746     // C++ [dcl.fct.spec]p3:
6747     //  The inline specifier shall not appear on a block scope function
6748     //  declaration.
6749     if (isInline && !NewFD->isInvalidDecl()) {
6750       if (CurContext->isFunctionOrMethod()) {
6751         // 'inline' is not allowed on block scope function declaration.
6752         Diag(D.getDeclSpec().getInlineSpecLoc(),
6753              diag::err_inline_declaration_block_scope) << Name
6754           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6755       }
6756     }
6757 
6758     // C++ [dcl.fct.spec]p6:
6759     //  The explicit specifier shall be used only in the declaration of a
6760     //  constructor or conversion function within its class definition;
6761     //  see 12.3.1 and 12.3.2.
6762     if (isExplicit && !NewFD->isInvalidDecl()) {
6763       if (!CurContext->isRecord()) {
6764         // 'explicit' was specified outside of the class.
6765         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6766              diag::err_explicit_out_of_class)
6767           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6768       } else if (!isa<CXXConstructorDecl>(NewFD) &&
6769                  !isa<CXXConversionDecl>(NewFD)) {
6770         // 'explicit' was specified on a function that wasn't a constructor
6771         // or conversion function.
6772         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6773              diag::err_explicit_non_ctor_or_conv_function)
6774           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6775       }
6776     }
6777 
6778     if (isConstexpr) {
6779       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6780       // are implicitly inline.
6781       NewFD->setImplicitlyInline();
6782 
6783       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6784       // be either constructors or to return a literal type. Therefore,
6785       // destructors cannot be declared constexpr.
6786       if (isa<CXXDestructorDecl>(NewFD))
6787         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6788     }
6789 
6790     // If __module_private__ was specified, mark the function accordingly.
6791     if (D.getDeclSpec().isModulePrivateSpecified()) {
6792       if (isFunctionTemplateSpecialization) {
6793         SourceLocation ModulePrivateLoc
6794           = D.getDeclSpec().getModulePrivateSpecLoc();
6795         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6796           << 0
6797           << FixItHint::CreateRemoval(ModulePrivateLoc);
6798       } else {
6799         NewFD->setModulePrivate();
6800         if (FunctionTemplate)
6801           FunctionTemplate->setModulePrivate();
6802       }
6803     }
6804 
6805     if (isFriend) {
6806       if (FunctionTemplate) {
6807         FunctionTemplate->setObjectOfFriendDecl();
6808         FunctionTemplate->setAccess(AS_public);
6809       }
6810       NewFD->setObjectOfFriendDecl();
6811       NewFD->setAccess(AS_public);
6812     }
6813 
6814     // If a function is defined as defaulted or deleted, mark it as such now.
6815     switch (D.getFunctionDefinitionKind()) {
6816       case FDK_Declaration:
6817       case FDK_Definition:
6818         break;
6819 
6820       case FDK_Defaulted:
6821         NewFD->setDefaulted();
6822         break;
6823 
6824       case FDK_Deleted:
6825         NewFD->setDeletedAsWritten();
6826         break;
6827     }
6828 
6829     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6830         D.isFunctionDefinition()) {
6831       // C++ [class.mfct]p2:
6832       //   A member function may be defined (8.4) in its class definition, in
6833       //   which case it is an inline member function (7.1.2)
6834       NewFD->setImplicitlyInline();
6835     }
6836 
6837     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6838         !CurContext->isRecord()) {
6839       // C++ [class.static]p1:
6840       //   A data or function member of a class may be declared static
6841       //   in a class definition, in which case it is a static member of
6842       //   the class.
6843 
6844       // Complain about the 'static' specifier if it's on an out-of-line
6845       // member function definition.
6846       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6847            diag::err_static_out_of_line)
6848         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6849     }
6850 
6851     // C++11 [except.spec]p15:
6852     //   A deallocation function with no exception-specification is treated
6853     //   as if it were specified with noexcept(true).
6854     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6855     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6856          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
6857         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
6858       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6859       EPI.ExceptionSpecType = EST_BasicNoexcept;
6860       NewFD->setType(Context.getFunctionType(FPT->getResultType(),
6861                                              FPT->getArgTypes(), EPI));
6862     }
6863 
6864     // C++11 [replacement.functions]p3:
6865     //  The program's definitions shall not be specified as inline.
6866     //
6867     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
6868     if (isInline && NewFD->isReplaceableGlobalAllocationFunction())
6869       Diag(D.getDeclSpec().getInlineSpecLoc(),
6870            diag::err_operator_new_delete_declared_inline)
6871         << NewFD->getDeclName();
6872   }
6873 
6874   // Filter out previous declarations that don't match the scope.
6875   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
6876                        isExplicitSpecialization ||
6877                        isFunctionTemplateSpecialization);
6878 
6879   // Handle GNU asm-label extension (encoded as an attribute).
6880   if (Expr *E = (Expr*) D.getAsmLabel()) {
6881     // The parser guarantees this is a string.
6882     StringLiteral *SE = cast<StringLiteral>(E);
6883     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6884                                                 SE->getString()));
6885   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6886     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6887       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6888     if (I != ExtnameUndeclaredIdentifiers.end()) {
6889       NewFD->addAttr(I->second);
6890       ExtnameUndeclaredIdentifiers.erase(I);
6891     }
6892   }
6893 
6894   // Copy the parameter declarations from the declarator D to the function
6895   // declaration NewFD, if they are available.  First scavenge them into Params.
6896   SmallVector<ParmVarDecl*, 16> Params;
6897   if (D.isFunctionDeclarator()) {
6898     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6899 
6900     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6901     // function that takes no arguments, not a function that takes a
6902     // single void argument.
6903     // We let through "const void" here because Sema::GetTypeForDeclarator
6904     // already checks for that case.
6905     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6906         FTI.ArgInfo[0].Param &&
6907         cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
6908       // Empty arg list, don't push any params.
6909       checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
6910     } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
6911       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6912         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
6913         assert(Param->getDeclContext() != NewFD && "Was set before ?");
6914         Param->setDeclContext(NewFD);
6915         Params.push_back(Param);
6916 
6917         if (Param->isInvalidDecl())
6918           NewFD->setInvalidDecl();
6919       }
6920     }
6921 
6922   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
6923     // When we're declaring a function with a typedef, typeof, etc as in the
6924     // following example, we'll need to synthesize (unnamed)
6925     // parameters for use in the declaration.
6926     //
6927     // @code
6928     // typedef void fn(int);
6929     // fn f;
6930     // @endcode
6931 
6932     // Synthesize a parameter for each argument type.
6933     for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6934          AE = FT->arg_type_end(); AI != AE; ++AI) {
6935       ParmVarDecl *Param =
6936         BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
6937       Param->setScopeInfo(0, Params.size());
6938       Params.push_back(Param);
6939     }
6940   } else {
6941     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6942            "Should not need args for typedef of non-prototype fn");
6943   }
6944 
6945   // Finally, we know we have the right number of parameters, install them.
6946   NewFD->setParams(Params);
6947 
6948   // Find all anonymous symbols defined during the declaration of this function
6949   // and add to NewFD. This lets us track decls such 'enum Y' in:
6950   //
6951   //   void f(enum Y {AA} x) {}
6952   //
6953   // which would otherwise incorrectly end up in the translation unit scope.
6954   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6955   DeclsInPrototypeScope.clear();
6956 
6957   if (D.getDeclSpec().isNoreturnSpecified())
6958     NewFD->addAttr(
6959         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6960                                        Context));
6961 
6962   // Functions returning a variably modified type violate C99 6.7.5.2p2
6963   // because all functions have linkage.
6964   if (!NewFD->isInvalidDecl() &&
6965       NewFD->getResultType()->isVariablyModifiedType()) {
6966     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6967     NewFD->setInvalidDecl();
6968   }
6969 
6970   // Handle attributes.
6971   ProcessDeclAttributes(S, NewFD, D);
6972 
6973   QualType RetType = NewFD->getResultType();
6974   const CXXRecordDecl *Ret = RetType->isRecordType() ?
6975       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6976   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6977       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
6978     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6979     // Attach the attribute to the new decl. Don't apply the attribute if it
6980     // returns an instance of the class (e.g. assignment operators).
6981     if (!MD || MD->getParent() != Ret) {
6982       NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6983                                                         Context));
6984     }
6985   }
6986 
6987   if (!getLangOpts().CPlusPlus) {
6988     // Perform semantic checking on the function declaration.
6989     bool isExplicitSpecialization=false;
6990     if (!NewFD->isInvalidDecl() && NewFD->isMain())
6991       CheckMain(NewFD, D.getDeclSpec());
6992 
6993     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6994       CheckMSVCRTEntryPoint(NewFD);
6995 
6996     if (!NewFD->isInvalidDecl())
6997       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6998                                                   isExplicitSpecialization));
6999     else if (!Previous.empty())
7000       // Make graceful recovery from an invalid redeclaration.
7001       D.setRedeclaration(true);
7002     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7003             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7004            "previous declaration set still overloaded");
7005   } else {
7006     // If the declarator is a template-id, translate the parser's template
7007     // argument list into our AST format.
7008     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7009       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7010       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7011       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7012       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7013                                          TemplateId->NumArgs);
7014       translateTemplateArguments(TemplateArgsPtr,
7015                                  TemplateArgs);
7016 
7017       HasExplicitTemplateArgs = true;
7018 
7019       if (NewFD->isInvalidDecl()) {
7020         HasExplicitTemplateArgs = false;
7021       } else if (FunctionTemplate) {
7022         // Function template with explicit template arguments.
7023         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7024           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7025 
7026         HasExplicitTemplateArgs = false;
7027       } else if (!isFunctionTemplateSpecialization &&
7028                  !D.getDeclSpec().isFriendSpecified()) {
7029         // We have encountered something that the user meant to be a
7030         // specialization (because it has explicitly-specified template
7031         // arguments) but that was not introduced with a "template<>" (or had
7032         // too few of them).
7033         // FIXME: Differentiate between attempts for explicit instantiations
7034         // (starting with "template") and the rest.
7035         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7036           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7037           << FixItHint::CreateInsertion(
7038                                     D.getDeclSpec().getLocStart(),
7039                                         "template<> ");
7040         isFunctionTemplateSpecialization = true;
7041       } else {
7042         // "friend void foo<>(int);" is an implicit specialization decl.
7043         isFunctionTemplateSpecialization = true;
7044       }
7045     } else if (isFriend && isFunctionTemplateSpecialization) {
7046       // This combination is only possible in a recovery case;  the user
7047       // wrote something like:
7048       //   template <> friend void foo(int);
7049       // which we're recovering from as if the user had written:
7050       //   friend void foo<>(int);
7051       // Go ahead and fake up a template id.
7052       HasExplicitTemplateArgs = true;
7053         TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7054       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7055     }
7056 
7057     // If it's a friend (and only if it's a friend), it's possible
7058     // that either the specialized function type or the specialized
7059     // template is dependent, and therefore matching will fail.  In
7060     // this case, don't check the specialization yet.
7061     bool InstantiationDependent = false;
7062     if (isFunctionTemplateSpecialization && isFriend &&
7063         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7064          TemplateSpecializationType::anyDependentTemplateArguments(
7065             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7066             InstantiationDependent))) {
7067       assert(HasExplicitTemplateArgs &&
7068              "friend function specialization without template args");
7069       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7070                                                        Previous))
7071         NewFD->setInvalidDecl();
7072     } else if (isFunctionTemplateSpecialization) {
7073       if (CurContext->isDependentContext() && CurContext->isRecord()
7074           && !isFriend) {
7075         isDependentClassScopeExplicitSpecialization = true;
7076         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7077           diag::ext_function_specialization_in_class :
7078           diag::err_function_specialization_in_class)
7079           << NewFD->getDeclName();
7080       } else if (CheckFunctionTemplateSpecialization(NewFD,
7081                                   (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7082                                                      Previous))
7083         NewFD->setInvalidDecl();
7084 
7085       // C++ [dcl.stc]p1:
7086       //   A storage-class-specifier shall not be specified in an explicit
7087       //   specialization (14.7.3)
7088       FunctionTemplateSpecializationInfo *Info =
7089           NewFD->getTemplateSpecializationInfo();
7090       if (Info && SC != SC_None) {
7091         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7092           Diag(NewFD->getLocation(),
7093                diag::err_explicit_specialization_inconsistent_storage_class)
7094             << SC
7095             << FixItHint::CreateRemoval(
7096                                       D.getDeclSpec().getStorageClassSpecLoc());
7097 
7098         else
7099           Diag(NewFD->getLocation(),
7100                diag::ext_explicit_specialization_storage_class)
7101             << FixItHint::CreateRemoval(
7102                                       D.getDeclSpec().getStorageClassSpecLoc());
7103       }
7104 
7105     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7106       if (CheckMemberSpecialization(NewFD, Previous))
7107           NewFD->setInvalidDecl();
7108     }
7109 
7110     // Perform semantic checking on the function declaration.
7111     if (!isDependentClassScopeExplicitSpecialization) {
7112       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7113         CheckMain(NewFD, D.getDeclSpec());
7114 
7115       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7116         CheckMSVCRTEntryPoint(NewFD);
7117 
7118       if (NewFD->isInvalidDecl()) {
7119         // If this is a class member, mark the class invalid immediately.
7120         // This avoids some consistency errors later.
7121         if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7122           methodDecl->getParent()->setInvalidDecl();
7123       } else
7124         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7125                                                     isExplicitSpecialization));
7126     }
7127 
7128     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7129             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7130            "previous declaration set still overloaded");
7131 
7132     NamedDecl *PrincipalDecl = (FunctionTemplate
7133                                 ? cast<NamedDecl>(FunctionTemplate)
7134                                 : NewFD);
7135 
7136     if (isFriend && D.isRedeclaration()) {
7137       AccessSpecifier Access = AS_public;
7138       if (!NewFD->isInvalidDecl())
7139         Access = NewFD->getPreviousDecl()->getAccess();
7140 
7141       NewFD->setAccess(Access);
7142       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7143     }
7144 
7145     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7146         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7147       PrincipalDecl->setNonMemberOperator();
7148 
7149     // If we have a function template, check the template parameter
7150     // list. This will check and merge default template arguments.
7151     if (FunctionTemplate) {
7152       FunctionTemplateDecl *PrevTemplate =
7153                                      FunctionTemplate->getPreviousDecl();
7154       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7155                        PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
7156                             D.getDeclSpec().isFriendSpecified()
7157                               ? (D.isFunctionDefinition()
7158                                    ? TPC_FriendFunctionTemplateDefinition
7159                                    : TPC_FriendFunctionTemplate)
7160                               : (D.getCXXScopeSpec().isSet() &&
7161                                  DC && DC->isRecord() &&
7162                                  DC->isDependentContext())
7163                                   ? TPC_ClassTemplateMember
7164                                   : TPC_FunctionTemplate);
7165     }
7166 
7167     if (NewFD->isInvalidDecl()) {
7168       // Ignore all the rest of this.
7169     } else if (!D.isRedeclaration()) {
7170       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7171                                        AddToScope };
7172       // Fake up an access specifier if it's supposed to be a class member.
7173       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7174         NewFD->setAccess(AS_public);
7175 
7176       // Qualified decls generally require a previous declaration.
7177       if (D.getCXXScopeSpec().isSet()) {
7178         // ...with the major exception of templated-scope or
7179         // dependent-scope friend declarations.
7180 
7181         // TODO: we currently also suppress this check in dependent
7182         // contexts because (1) the parameter depth will be off when
7183         // matching friend templates and (2) we might actually be
7184         // selecting a friend based on a dependent factor.  But there
7185         // are situations where these conditions don't apply and we
7186         // can actually do this check immediately.
7187         if (isFriend &&
7188             (TemplateParamLists.size() ||
7189              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7190              CurContext->isDependentContext())) {
7191           // ignore these
7192         } else {
7193           // The user tried to provide an out-of-line definition for a
7194           // function that is a member of a class or namespace, but there
7195           // was no such member function declared (C++ [class.mfct]p2,
7196           // C++ [namespace.memdef]p2). For example:
7197           //
7198           // class X {
7199           //   void f() const;
7200           // };
7201           //
7202           // void X::f() { } // ill-formed
7203           //
7204           // Complain about this problem, and attempt to suggest close
7205           // matches (e.g., those that differ only in cv-qualifiers and
7206           // whether the parameter types are references).
7207 
7208           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7209                   *this, Previous, NewFD, ExtraArgs, false, 0)) {
7210             AddToScope = ExtraArgs.AddToScope;
7211             return Result;
7212           }
7213         }
7214 
7215         // Unqualified local friend declarations are required to resolve
7216         // to something.
7217       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7218         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7219                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7220           AddToScope = ExtraArgs.AddToScope;
7221           return Result;
7222         }
7223       }
7224 
7225     } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
7226                !isFriend && !isFunctionTemplateSpecialization &&
7227                !isExplicitSpecialization) {
7228       // An out-of-line member function declaration must also be a
7229       // definition (C++ [dcl.meaning]p1).
7230       // Note that this is not the case for explicit specializations of
7231       // function templates or member functions of class templates, per
7232       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7233       // extension for compatibility with old SWIG code which likes to
7234       // generate them.
7235       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7236         << D.getCXXScopeSpec().getRange();
7237     }
7238   }
7239 
7240   ProcessPragmaWeak(S, NewFD);
7241   checkAttributesAfterMerging(*this, *NewFD);
7242 
7243   AddKnownFunctionAttributes(NewFD);
7244 
7245   if (NewFD->hasAttr<OverloadableAttr>() &&
7246       !NewFD->getType()->getAs<FunctionProtoType>()) {
7247     Diag(NewFD->getLocation(),
7248          diag::err_attribute_overloadable_no_prototype)
7249       << NewFD;
7250 
7251     // Turn this into a variadic function with no parameters.
7252     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7253     FunctionProtoType::ExtProtoInfo EPI(
7254         Context.getDefaultCallingConvention(true, false));
7255     EPI.Variadic = true;
7256     EPI.ExtInfo = FT->getExtInfo();
7257 
7258     QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
7259     NewFD->setType(R);
7260   }
7261 
7262   // If there's a #pragma GCC visibility in scope, and this isn't a class
7263   // member, set the visibility of this function.
7264   if (!DC->isRecord() && NewFD->isExternallyVisible())
7265     AddPushedVisibilityAttribute(NewFD);
7266 
7267   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7268   // marking the function.
7269   AddCFAuditedAttribute(NewFD);
7270 
7271   // If this is the first declaration of an extern C variable, update
7272   // the map of such variables.
7273   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7274       isIncompleteDeclExternC(*this, NewFD))
7275     RegisterLocallyScopedExternCDecl(NewFD, S);
7276 
7277   // Set this FunctionDecl's range up to the right paren.
7278   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7279 
7280   if (getLangOpts().CPlusPlus) {
7281     if (FunctionTemplate) {
7282       if (NewFD->isInvalidDecl())
7283         FunctionTemplate->setInvalidDecl();
7284       return FunctionTemplate;
7285     }
7286   }
7287 
7288   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7289     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7290     if ((getLangOpts().OpenCLVersion >= 120)
7291         && (SC == SC_Static)) {
7292       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7293       D.setInvalidType();
7294     }
7295 
7296     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7297     if (!NewFD->getResultType()->isVoidType()) {
7298       Diag(D.getIdentifierLoc(),
7299            diag::err_expected_kernel_void_return_type);
7300       D.setInvalidType();
7301     }
7302 
7303     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7304     for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7305          PE = NewFD->param_end(); PI != PE; ++PI) {
7306       ParmVarDecl *Param = *PI;
7307       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7308     }
7309   }
7310 
7311   MarkUnusedFileScopedDecl(NewFD);
7312 
7313   if (getLangOpts().CUDA)
7314     if (IdentifierInfo *II = NewFD->getIdentifier())
7315       if (!NewFD->isInvalidDecl() &&
7316           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7317         if (II->isStr("cudaConfigureCall")) {
7318           if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7319             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7320 
7321           Context.setcudaConfigureCallDecl(NewFD);
7322         }
7323       }
7324 
7325   // Here we have an function template explicit specialization at class scope.
7326   // The actually specialization will be postponed to template instatiation
7327   // time via the ClassScopeFunctionSpecializationDecl node.
7328   if (isDependentClassScopeExplicitSpecialization) {
7329     ClassScopeFunctionSpecializationDecl *NewSpec =
7330                          ClassScopeFunctionSpecializationDecl::Create(
7331                                 Context, CurContext, SourceLocation(),
7332                                 cast<CXXMethodDecl>(NewFD),
7333                                 HasExplicitTemplateArgs, TemplateArgs);
7334     CurContext->addDecl(NewSpec);
7335     AddToScope = false;
7336   }
7337 
7338   return NewFD;
7339 }
7340 
7341 /// \brief Perform semantic checking of a new function declaration.
7342 ///
7343 /// Performs semantic analysis of the new function declaration
7344 /// NewFD. This routine performs all semantic checking that does not
7345 /// require the actual declarator involved in the declaration, and is
7346 /// used both for the declaration of functions as they are parsed
7347 /// (called via ActOnDeclarator) and for the declaration of functions
7348 /// that have been instantiated via C++ template instantiation (called
7349 /// via InstantiateDecl).
7350 ///
7351 /// \param IsExplicitSpecialization whether this new function declaration is
7352 /// an explicit specialization of the previous declaration.
7353 ///
7354 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7355 ///
7356 /// \returns true if the function declaration is a redeclaration.
7357 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7358                                     LookupResult &Previous,
7359                                     bool IsExplicitSpecialization) {
7360   assert(!NewFD->getResultType()->isVariablyModifiedType()
7361          && "Variably modified return types are not handled here");
7362 
7363   // Determine whether the type of this function should be merged with
7364   // a previous visible declaration. This never happens for functions in C++,
7365   // and always happens in C if the previous declaration was visible.
7366   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7367                                !Previous.isShadowed();
7368 
7369   // Filter out any non-conflicting previous declarations.
7370   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7371 
7372   bool Redeclaration = false;
7373   NamedDecl *OldDecl = 0;
7374 
7375   // Merge or overload the declaration with an existing declaration of
7376   // the same name, if appropriate.
7377   if (!Previous.empty()) {
7378     // Determine whether NewFD is an overload of PrevDecl or
7379     // a declaration that requires merging. If it's an overload,
7380     // there's no more work to do here; we'll just add the new
7381     // function to the scope.
7382     if (!AllowOverloadingOfFunction(Previous, Context)) {
7383       NamedDecl *Candidate = Previous.getFoundDecl();
7384       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7385         Redeclaration = true;
7386         OldDecl = Candidate;
7387       }
7388     } else {
7389       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7390                             /*NewIsUsingDecl*/ false)) {
7391       case Ovl_Match:
7392         Redeclaration = true;
7393         break;
7394 
7395       case Ovl_NonFunction:
7396         Redeclaration = true;
7397         break;
7398 
7399       case Ovl_Overload:
7400         Redeclaration = false;
7401         break;
7402       }
7403 
7404       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7405         // If a function name is overloadable in C, then every function
7406         // with that name must be marked "overloadable".
7407         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7408           << Redeclaration << NewFD;
7409         NamedDecl *OverloadedDecl = 0;
7410         if (Redeclaration)
7411           OverloadedDecl = OldDecl;
7412         else if (!Previous.empty())
7413           OverloadedDecl = Previous.getRepresentativeDecl();
7414         if (OverloadedDecl)
7415           Diag(OverloadedDecl->getLocation(),
7416                diag::note_attribute_overloadable_prev_overload);
7417         NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7418                                                         Context));
7419       }
7420     }
7421   }
7422 
7423   // Check for a previous extern "C" declaration with this name.
7424   if (!Redeclaration &&
7425       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7426     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7427     if (!Previous.empty()) {
7428       // This is an extern "C" declaration with the same name as a previous
7429       // declaration, and thus redeclares that entity...
7430       Redeclaration = true;
7431       OldDecl = Previous.getFoundDecl();
7432       MergeTypeWithPrevious = false;
7433 
7434       // ... except in the presence of __attribute__((overloadable)).
7435       if (OldDecl->hasAttr<OverloadableAttr>()) {
7436         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7437           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7438             << Redeclaration << NewFD;
7439           Diag(Previous.getFoundDecl()->getLocation(),
7440                diag::note_attribute_overloadable_prev_overload);
7441           NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7442                                                           Context));
7443         }
7444         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7445           Redeclaration = false;
7446           OldDecl = 0;
7447         }
7448       }
7449     }
7450   }
7451 
7452   // C++11 [dcl.constexpr]p8:
7453   //   A constexpr specifier for a non-static member function that is not
7454   //   a constructor declares that member function to be const.
7455   //
7456   // This needs to be delayed until we know whether this is an out-of-line
7457   // definition of a static member function.
7458   //
7459   // This rule is not present in C++1y, so we produce a backwards
7460   // compatibility warning whenever it happens in C++11.
7461   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7462   if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7463       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7464       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7465     CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7466     if (FunctionTemplateDecl *OldTD =
7467           dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7468       OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7469     if (!OldMD || !OldMD->isStatic()) {
7470       const FunctionProtoType *FPT =
7471         MD->getType()->castAs<FunctionProtoType>();
7472       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7473       EPI.TypeQuals |= Qualifiers::Const;
7474       MD->setType(Context.getFunctionType(FPT->getResultType(),
7475                                           FPT->getArgTypes(), EPI));
7476 
7477       // Warn that we did this, if we're not performing template instantiation.
7478       // In that case, we'll have warned already when the template was defined.
7479       if (ActiveTemplateInstantiations.empty()) {
7480         SourceLocation AddConstLoc;
7481         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7482                 .IgnoreParens().getAs<FunctionTypeLoc>())
7483           AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7484 
7485         Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7486           << FixItHint::CreateInsertion(AddConstLoc, " const");
7487       }
7488     }
7489   }
7490 
7491   if (Redeclaration) {
7492     // NewFD and OldDecl represent declarations that need to be
7493     // merged.
7494     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7495       NewFD->setInvalidDecl();
7496       return Redeclaration;
7497     }
7498 
7499     Previous.clear();
7500     Previous.addDecl(OldDecl);
7501 
7502     if (FunctionTemplateDecl *OldTemplateDecl
7503                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7504       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7505       FunctionTemplateDecl *NewTemplateDecl
7506         = NewFD->getDescribedFunctionTemplate();
7507       assert(NewTemplateDecl && "Template/non-template mismatch");
7508       if (CXXMethodDecl *Method
7509             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7510         Method->setAccess(OldTemplateDecl->getAccess());
7511         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7512       }
7513 
7514       // If this is an explicit specialization of a member that is a function
7515       // template, mark it as a member specialization.
7516       if (IsExplicitSpecialization &&
7517           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7518         NewTemplateDecl->setMemberSpecialization();
7519         assert(OldTemplateDecl->isMemberSpecialization());
7520       }
7521 
7522     } else {
7523       // This needs to happen first so that 'inline' propagates.
7524       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7525 
7526       if (isa<CXXMethodDecl>(NewFD)) {
7527         // A valid redeclaration of a C++ method must be out-of-line,
7528         // but (unfortunately) it's not necessarily a definition
7529         // because of templates, which means that the previous
7530         // declaration is not necessarily from the class definition.
7531 
7532         // For just setting the access, that doesn't matter.
7533         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7534         NewFD->setAccess(oldMethod->getAccess());
7535 
7536         // Update the key-function state if necessary for this ABI.
7537         if (NewFD->isInlined() &&
7538             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7539           // setNonKeyFunction needs to work with the original
7540           // declaration from the class definition, and isVirtual() is
7541           // just faster in that case, so map back to that now.
7542           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7543           if (oldMethod->isVirtual()) {
7544             Context.setNonKeyFunction(oldMethod);
7545           }
7546         }
7547       }
7548     }
7549   }
7550 
7551   // Semantic checking for this function declaration (in isolation).
7552   if (getLangOpts().CPlusPlus) {
7553     // C++-specific checks.
7554     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7555       CheckConstructor(Constructor);
7556     } else if (CXXDestructorDecl *Destructor =
7557                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7558       CXXRecordDecl *Record = Destructor->getParent();
7559       QualType ClassType = Context.getTypeDeclType(Record);
7560 
7561       // FIXME: Shouldn't we be able to perform this check even when the class
7562       // type is dependent? Both gcc and edg can handle that.
7563       if (!ClassType->isDependentType()) {
7564         DeclarationName Name
7565           = Context.DeclarationNames.getCXXDestructorName(
7566                                         Context.getCanonicalType(ClassType));
7567         if (NewFD->getDeclName() != Name) {
7568           Diag(NewFD->getLocation(), diag::err_destructor_name);
7569           NewFD->setInvalidDecl();
7570           return Redeclaration;
7571         }
7572       }
7573     } else if (CXXConversionDecl *Conversion
7574                = dyn_cast<CXXConversionDecl>(NewFD)) {
7575       ActOnConversionDeclarator(Conversion);
7576     }
7577 
7578     // Find any virtual functions that this function overrides.
7579     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7580       if (!Method->isFunctionTemplateSpecialization() &&
7581           !Method->getDescribedFunctionTemplate() &&
7582           Method->isCanonicalDecl()) {
7583         if (AddOverriddenMethods(Method->getParent(), Method)) {
7584           // If the function was marked as "static", we have a problem.
7585           if (NewFD->getStorageClass() == SC_Static) {
7586             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7587           }
7588         }
7589       }
7590 
7591       if (Method->isStatic())
7592         checkThisInStaticMemberFunctionType(Method);
7593     }
7594 
7595     // Extra checking for C++ overloaded operators (C++ [over.oper]).
7596     if (NewFD->isOverloadedOperator() &&
7597         CheckOverloadedOperatorDeclaration(NewFD)) {
7598       NewFD->setInvalidDecl();
7599       return Redeclaration;
7600     }
7601 
7602     // Extra checking for C++0x literal operators (C++0x [over.literal]).
7603     if (NewFD->getLiteralIdentifier() &&
7604         CheckLiteralOperatorDeclaration(NewFD)) {
7605       NewFD->setInvalidDecl();
7606       return Redeclaration;
7607     }
7608 
7609     // In C++, check default arguments now that we have merged decls. Unless
7610     // the lexical context is the class, because in this case this is done
7611     // during delayed parsing anyway.
7612     if (!CurContext->isRecord())
7613       CheckCXXDefaultArguments(NewFD);
7614 
7615     // If this function declares a builtin function, check the type of this
7616     // declaration against the expected type for the builtin.
7617     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7618       ASTContext::GetBuiltinTypeError Error;
7619       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
7620       QualType T = Context.GetBuiltinType(BuiltinID, Error);
7621       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7622         // The type of this function differs from the type of the builtin,
7623         // so forget about the builtin entirely.
7624         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7625       }
7626     }
7627 
7628     // If this function is declared as being extern "C", then check to see if
7629     // the function returns a UDT (class, struct, or union type) that is not C
7630     // compatible, and if it does, warn the user.
7631     // But, issue any diagnostic on the first declaration only.
7632     if (NewFD->isExternC() && Previous.empty()) {
7633       QualType R = NewFD->getResultType();
7634       if (R->isIncompleteType() && !R->isVoidType())
7635         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7636             << NewFD << R;
7637       else if (!R.isPODType(Context) && !R->isVoidType() &&
7638                !R->isObjCObjectPointerType())
7639         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
7640     }
7641   }
7642   return Redeclaration;
7643 }
7644 
7645 static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7646   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7647   if (!TSI)
7648     return SourceRange();
7649 
7650   TypeLoc TL = TSI->getTypeLoc();
7651   FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
7652   if (!FunctionTL)
7653     return SourceRange();
7654 
7655   TypeLoc ResultTL = FunctionTL.getResultLoc();
7656   if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
7657     return ResultTL.getSourceRange();
7658 
7659   return SourceRange();
7660 }
7661 
7662 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
7663   // C++11 [basic.start.main]p3:  A program that declares main to be inline,
7664   //   static or constexpr is ill-formed.
7665   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
7666   //   appear in a declaration of main.
7667   // static main is not an error under C99, but we should warn about it.
7668   // We accept _Noreturn main as an extension.
7669   if (FD->getStorageClass() == SC_Static)
7670     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
7671          ? diag::err_static_main : diag::warn_static_main)
7672       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7673   if (FD->isInlineSpecified())
7674     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7675       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
7676   if (DS.isNoreturnSpecified()) {
7677     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7678     SourceRange NoreturnRange(NoreturnLoc,
7679                               PP.getLocForEndOfToken(NoreturnLoc));
7680     Diag(NoreturnLoc, diag::ext_noreturn_main);
7681     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7682       << FixItHint::CreateRemoval(NoreturnRange);
7683   }
7684   if (FD->isConstexpr()) {
7685     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7686       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7687     FD->setConstexpr(false);
7688   }
7689 
7690   QualType T = FD->getType();
7691   assert(T->isFunctionType() && "function decl is not of function type");
7692   const FunctionType* FT = T->castAs<FunctionType>();
7693 
7694   // All the standards say that main() should should return 'int'.
7695   if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7696     // In C and C++, main magically returns 0 if you fall off the end;
7697     // set the flag which tells us that.
7698     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7699     FD->setHasImplicitReturnZero(true);
7700 
7701   // In C with GNU extensions we allow main() to have non-integer return
7702   // type, but we should warn about the extension, and we disable the
7703   // implicit-return-zero rule.
7704   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
7705     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7706 
7707     SourceRange ResultRange = getResultSourceRange(FD);
7708     if (ResultRange.isValid())
7709       Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7710           << FixItHint::CreateReplacement(ResultRange, "int");
7711 
7712   // Otherwise, this is just a flat-out error.
7713   } else {
7714     SourceRange ResultRange = getResultSourceRange(FD);
7715     if (ResultRange.isValid())
7716       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7717           << FixItHint::CreateReplacement(ResultRange, "int");
7718     else
7719       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7720 
7721     FD->setInvalidDecl(true);
7722   }
7723 
7724   // Treat protoless main() as nullary.
7725   if (isa<FunctionNoProtoType>(FT)) return;
7726 
7727   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7728   unsigned nparams = FTP->getNumArgs();
7729   assert(FD->getNumParams() == nparams);
7730 
7731   bool HasExtraParameters = (nparams > 3);
7732 
7733   // Darwin passes an undocumented fourth argument of type char**.  If
7734   // other platforms start sprouting these, the logic below will start
7735   // getting shifty.
7736   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
7737     HasExtraParameters = false;
7738 
7739   if (HasExtraParameters) {
7740     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7741     FD->setInvalidDecl(true);
7742     nparams = 3;
7743   }
7744 
7745   // FIXME: a lot of the following diagnostics would be improved
7746   // if we had some location information about types.
7747 
7748   QualType CharPP =
7749     Context.getPointerType(Context.getPointerType(Context.CharTy));
7750   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
7751 
7752   for (unsigned i = 0; i < nparams; ++i) {
7753     QualType AT = FTP->getArgType(i);
7754 
7755     bool mismatch = true;
7756 
7757     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7758       mismatch = false;
7759     else if (Expected[i] == CharPP) {
7760       // As an extension, the following forms are okay:
7761       //   char const **
7762       //   char const * const *
7763       //   char * const *
7764 
7765       QualifierCollector qs;
7766       const PointerType* PT;
7767       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7768           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
7769           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7770                               Context.CharTy)) {
7771         qs.removeConst();
7772         mismatch = !qs.empty();
7773       }
7774     }
7775 
7776     if (mismatch) {
7777       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7778       // TODO: suggest replacing given type with expected type
7779       FD->setInvalidDecl(true);
7780     }
7781   }
7782 
7783   if (nparams == 1 && !FD->isInvalidDecl()) {
7784     Diag(FD->getLocation(), diag::warn_main_one_arg);
7785   }
7786 
7787   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7788     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7789     FD->setInvalidDecl();
7790   }
7791 }
7792 
7793 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7794   QualType T = FD->getType();
7795   assert(T->isFunctionType() && "function decl is not of function type");
7796   const FunctionType *FT = T->castAs<FunctionType>();
7797 
7798   // Set an implicit return of 'zero' if the function can return some integral,
7799   // enumeration, pointer or nullptr type.
7800   if (FT->getResultType()->isIntegralOrEnumerationType() ||
7801       FT->getResultType()->isAnyPointerType() ||
7802       FT->getResultType()->isNullPtrType())
7803     // DllMain is exempt because a return value of zero means it failed.
7804     if (FD->getName() != "DllMain")
7805       FD->setHasImplicitReturnZero(true);
7806 
7807   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7808     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7809     FD->setInvalidDecl();
7810   }
7811 }
7812 
7813 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
7814   // FIXME: Need strict checking.  In C89, we need to check for
7815   // any assignment, increment, decrement, function-calls, or
7816   // commas outside of a sizeof.  In C99, it's the same list,
7817   // except that the aforementioned are allowed in unevaluated
7818   // expressions.  Everything else falls under the
7819   // "may accept other forms of constant expressions" exception.
7820   // (We never end up here for C++, so the constant expression
7821   // rules there don't matter.)
7822   if (Init->isConstantInitializer(Context, false))
7823     return false;
7824   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7825     << Init->getSourceRange();
7826   return true;
7827 }
7828 
7829 namespace {
7830   // Visits an initialization expression to see if OrigDecl is evaluated in
7831   // its own initialization and throws a warning if it does.
7832   class SelfReferenceChecker
7833       : public EvaluatedExprVisitor<SelfReferenceChecker> {
7834     Sema &S;
7835     Decl *OrigDecl;
7836     bool isRecordType;
7837     bool isPODType;
7838     bool isReferenceType;
7839 
7840   public:
7841     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7842 
7843     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
7844                                                     S(S), OrigDecl(OrigDecl) {
7845       isPODType = false;
7846       isRecordType = false;
7847       isReferenceType = false;
7848       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7849         isPODType = VD->getType().isPODType(S.Context);
7850         isRecordType = VD->getType()->isRecordType();
7851         isReferenceType = VD->getType()->isReferenceType();
7852       }
7853     }
7854 
7855     // For most expressions, the cast is directly above the DeclRefExpr.
7856     // For conditional operators, the cast can be outside the conditional
7857     // operator if both expressions are DeclRefExpr's.
7858     void HandleValue(Expr *E) {
7859       if (isReferenceType)
7860         return;
7861       E = E->IgnoreParenImpCasts();
7862       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7863         HandleDeclRefExpr(DRE);
7864         return;
7865       }
7866 
7867       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7868         HandleValue(CO->getTrueExpr());
7869         HandleValue(CO->getFalseExpr());
7870         return;
7871       }
7872 
7873       if (isa<MemberExpr>(E)) {
7874         Expr *Base = E->IgnoreParenImpCasts();
7875         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7876           // Check for static member variables and don't warn on them.
7877           if (!isa<FieldDecl>(ME->getMemberDecl()))
7878             return;
7879           Base = ME->getBase()->IgnoreParenImpCasts();
7880         }
7881         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7882           HandleDeclRefExpr(DRE);
7883         return;
7884       }
7885     }
7886 
7887     // Reference types are handled here since all uses of references are
7888     // bad, not just r-value uses.
7889     void VisitDeclRefExpr(DeclRefExpr *E) {
7890       if (isReferenceType)
7891         HandleDeclRefExpr(E);
7892     }
7893 
7894     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
7895       if (E->getCastKind() == CK_LValueToRValue ||
7896           (isRecordType && E->getCastKind() == CK_NoOp))
7897         HandleValue(E->getSubExpr());
7898 
7899       Inherited::VisitImplicitCastExpr(E);
7900     }
7901 
7902     void VisitMemberExpr(MemberExpr *E) {
7903       // Don't warn on arrays since they can be treated as pointers.
7904       if (E->getType()->canDecayToPointerType()) return;
7905 
7906       // Warn when a non-static method call is followed by non-static member
7907       // field accesses, which is followed by a DeclRefExpr.
7908       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7909       bool Warn = (MD && !MD->isStatic());
7910       Expr *Base = E->getBase()->IgnoreParenImpCasts();
7911       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7912         if (!isa<FieldDecl>(ME->getMemberDecl()))
7913           Warn = false;
7914         Base = ME->getBase()->IgnoreParenImpCasts();
7915       }
7916 
7917       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7918         if (Warn)
7919           HandleDeclRefExpr(DRE);
7920         return;
7921       }
7922 
7923       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7924       // Visit that expression.
7925       Visit(Base);
7926     }
7927 
7928     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7929       if (E->getNumArgs() > 0)
7930         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7931           HandleDeclRefExpr(DRE);
7932 
7933       Inherited::VisitCXXOperatorCallExpr(E);
7934     }
7935 
7936     void VisitUnaryOperator(UnaryOperator *E) {
7937       // For POD record types, addresses of its own members are well-defined.
7938       if (E->getOpcode() == UO_AddrOf && isRecordType &&
7939           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7940         if (!isPODType)
7941           HandleValue(E->getSubExpr());
7942         return;
7943       }
7944       Inherited::VisitUnaryOperator(E);
7945     }
7946 
7947     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7948 
7949     void HandleDeclRefExpr(DeclRefExpr *DRE) {
7950       Decl* ReferenceDecl = DRE->getDecl();
7951       if (OrigDecl != ReferenceDecl) return;
7952       unsigned diag;
7953       if (isReferenceType) {
7954         diag = diag::warn_uninit_self_reference_in_reference_init;
7955       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7956         diag = diag::warn_static_self_reference_in_init;
7957       } else {
7958         diag = diag::warn_uninit_self_reference_in_init;
7959       }
7960 
7961       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
7962                             S.PDiag(diag)
7963                               << DRE->getNameInfo().getName()
7964                               << OrigDecl->getLocation()
7965                               << DRE->getSourceRange());
7966     }
7967   };
7968 
7969   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7970   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7971                                  bool DirectInit) {
7972     // Parameters arguments are occassionially constructed with itself,
7973     // for instance, in recursive functions.  Skip them.
7974     if (isa<ParmVarDecl>(OrigDecl))
7975       return;
7976 
7977     E = E->IgnoreParens();
7978 
7979     // Skip checking T a = a where T is not a record or reference type.
7980     // Doing so is a way to silence uninitialized warnings.
7981     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7982       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7983         if (ICE->getCastKind() == CK_LValueToRValue)
7984           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7985             if (DRE->getDecl() == OrigDecl)
7986               return;
7987 
7988     SelfReferenceChecker(S, OrigDecl).Visit(E);
7989   }
7990 }
7991 
7992 /// AddInitializerToDecl - Adds the initializer Init to the
7993 /// declaration dcl. If DirectInit is true, this is C++ direct
7994 /// initialization rather than copy initialization.
7995 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
7996                                 bool DirectInit, bool TypeMayContainAuto) {
7997   // If there is no declaration, there was an error parsing it.  Just ignore
7998   // the initializer.
7999   if (RealDecl == 0 || RealDecl->isInvalidDecl())
8000     return;
8001 
8002   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8003     // With declarators parsed the way they are, the parser cannot
8004     // distinguish between a normal initializer and a pure-specifier.
8005     // Thus this grotesque test.
8006     IntegerLiteral *IL;
8007     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8008         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8009       CheckPureMethod(Method, Init->getSourceRange());
8010     else {
8011       Diag(Method->getLocation(), diag::err_member_function_initialization)
8012         << Method->getDeclName() << Init->getSourceRange();
8013       Method->setInvalidDecl();
8014     }
8015     return;
8016   }
8017 
8018   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8019   if (!VDecl) {
8020     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8021     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8022     RealDecl->setInvalidDecl();
8023     return;
8024   }
8025   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8026 
8027   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8028   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8029     Expr *DeduceInit = Init;
8030     // Initializer could be a C++ direct-initializer. Deduction only works if it
8031     // contains exactly one expression.
8032     if (CXXDirectInit) {
8033       if (CXXDirectInit->getNumExprs() == 0) {
8034         // It isn't possible to write this directly, but it is possible to
8035         // end up in this situation with "auto x(some_pack...);"
8036         Diag(CXXDirectInit->getLocStart(),
8037              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8038                                     : diag::err_auto_var_init_no_expression)
8039           << VDecl->getDeclName() << VDecl->getType()
8040           << VDecl->getSourceRange();
8041         RealDecl->setInvalidDecl();
8042         return;
8043       } else if (CXXDirectInit->getNumExprs() > 1) {
8044         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8045              VDecl->isInitCapture()
8046                  ? diag::err_init_capture_multiple_expressions
8047                  : diag::err_auto_var_init_multiple_expressions)
8048           << VDecl->getDeclName() << VDecl->getType()
8049           << VDecl->getSourceRange();
8050         RealDecl->setInvalidDecl();
8051         return;
8052       } else {
8053         DeduceInit = CXXDirectInit->getExpr(0);
8054       }
8055     }
8056 
8057     // Expressions default to 'id' when we're in a debugger.
8058     bool DefaultedToAuto = false;
8059     if (getLangOpts().DebuggerCastResultToId &&
8060         Init->getType() == Context.UnknownAnyTy) {
8061       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8062       if (Result.isInvalid()) {
8063         VDecl->setInvalidDecl();
8064         return;
8065       }
8066       Init = Result.take();
8067       DefaultedToAuto = true;
8068     }
8069 
8070     QualType DeducedType;
8071     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8072             DAR_Failed)
8073       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8074     if (DeducedType.isNull()) {
8075       RealDecl->setInvalidDecl();
8076       return;
8077     }
8078     VDecl->setType(DeducedType);
8079     assert(VDecl->isLinkageValid());
8080 
8081     // In ARC, infer lifetime.
8082     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8083       VDecl->setInvalidDecl();
8084 
8085     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8086     // 'id' instead of a specific object type prevents most of our usual checks.
8087     // We only want to warn outside of template instantiations, though:
8088     // inside a template, the 'id' could have come from a parameter.
8089     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8090         DeducedType->isObjCIdType()) {
8091       SourceLocation Loc =
8092           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8093       Diag(Loc, diag::warn_auto_var_is_id)
8094         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8095     }
8096 
8097     // If this is a redeclaration, check that the type we just deduced matches
8098     // the previously declared type.
8099     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8100       // We never need to merge the type, because we cannot form an incomplete
8101       // array of auto, nor deduce such a type.
8102       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8103     }
8104 
8105     // Check the deduced type is valid for a variable declaration.
8106     CheckVariableDeclarationType(VDecl);
8107     if (VDecl->isInvalidDecl())
8108       return;
8109   }
8110 
8111   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8112     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8113     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8114     VDecl->setInvalidDecl();
8115     return;
8116   }
8117 
8118   if (!VDecl->getType()->isDependentType()) {
8119     // A definition must end up with a complete type, which means it must be
8120     // complete with the restriction that an array type might be completed by
8121     // the initializer; note that later code assumes this restriction.
8122     QualType BaseDeclType = VDecl->getType();
8123     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8124       BaseDeclType = Array->getElementType();
8125     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8126                             diag::err_typecheck_decl_incomplete_type)) {
8127       RealDecl->setInvalidDecl();
8128       return;
8129     }
8130 
8131     // The variable can not have an abstract class type.
8132     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8133                                diag::err_abstract_type_in_decl,
8134                                AbstractVariableType))
8135       VDecl->setInvalidDecl();
8136   }
8137 
8138   const VarDecl *Def;
8139   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8140     Diag(VDecl->getLocation(), diag::err_redefinition)
8141       << VDecl->getDeclName();
8142     Diag(Def->getLocation(), diag::note_previous_definition);
8143     VDecl->setInvalidDecl();
8144     return;
8145   }
8146 
8147   const VarDecl* PrevInit = 0;
8148   if (getLangOpts().CPlusPlus) {
8149     // C++ [class.static.data]p4
8150     //   If a static data member is of const integral or const
8151     //   enumeration type, its declaration in the class definition can
8152     //   specify a constant-initializer which shall be an integral
8153     //   constant expression (5.19). In that case, the member can appear
8154     //   in integral constant expressions. The member shall still be
8155     //   defined in a namespace scope if it is used in the program and the
8156     //   namespace scope definition shall not contain an initializer.
8157     //
8158     // We already performed a redefinition check above, but for static
8159     // data members we also need to check whether there was an in-class
8160     // declaration with an initializer.
8161     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8162       Diag(VDecl->getLocation(), diag::err_redefinition)
8163         << VDecl->getDeclName();
8164       Diag(PrevInit->getLocation(), diag::note_previous_definition);
8165       return;
8166     }
8167 
8168     if (VDecl->hasLocalStorage())
8169       getCurFunction()->setHasBranchProtectedScope();
8170 
8171     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8172       VDecl->setInvalidDecl();
8173       return;
8174     }
8175   }
8176 
8177   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8178   // a kernel function cannot be initialized."
8179   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8180     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8181     VDecl->setInvalidDecl();
8182     return;
8183   }
8184 
8185   // Get the decls type and save a reference for later, since
8186   // CheckInitializerTypes may change it.
8187   QualType DclT = VDecl->getType(), SavT = DclT;
8188 
8189   // Expressions default to 'id' when we're in a debugger
8190   // and we are assigning it to a variable of Objective-C pointer type.
8191   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8192       Init->getType() == Context.UnknownAnyTy) {
8193     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8194     if (Result.isInvalid()) {
8195       VDecl->setInvalidDecl();
8196       return;
8197     }
8198     Init = Result.take();
8199   }
8200 
8201   // Perform the initialization.
8202   if (!VDecl->isInvalidDecl()) {
8203     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8204     InitializationKind Kind
8205       = DirectInit ?
8206           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8207                                                            Init->getLocStart(),
8208                                                            Init->getLocEnd())
8209                         : InitializationKind::CreateDirectList(
8210                                                           VDecl->getLocation())
8211                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8212                                                     Init->getLocStart());
8213 
8214     MultiExprArg Args = Init;
8215     if (CXXDirectInit)
8216       Args = MultiExprArg(CXXDirectInit->getExprs(),
8217                           CXXDirectInit->getNumExprs());
8218 
8219     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8220     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8221     if (Result.isInvalid()) {
8222       VDecl->setInvalidDecl();
8223       return;
8224     }
8225 
8226     Init = Result.takeAs<Expr>();
8227   }
8228 
8229   // Check for self-references within variable initializers.
8230   // Variables declared within a function/method body (except for references)
8231   // are handled by a dataflow analysis.
8232   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8233       VDecl->getType()->isReferenceType()) {
8234     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8235   }
8236 
8237   // If the type changed, it means we had an incomplete type that was
8238   // completed by the initializer. For example:
8239   //   int ary[] = { 1, 3, 5 };
8240   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8241   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8242     VDecl->setType(DclT);
8243 
8244   if (!VDecl->isInvalidDecl()) {
8245     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8246 
8247     if (VDecl->hasAttr<BlocksAttr>())
8248       checkRetainCycles(VDecl, Init);
8249 
8250     // It is safe to assign a weak reference into a strong variable.
8251     // Although this code can still have problems:
8252     //   id x = self.weakProp;
8253     //   id y = self.weakProp;
8254     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8255     // paths through the function. This should be revisited if
8256     // -Wrepeated-use-of-weak is made flow-sensitive.
8257     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
8258       DiagnosticsEngine::Level Level =
8259         Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8260                                  Init->getLocStart());
8261       if (Level != DiagnosticsEngine::Ignored)
8262         getCurFunction()->markSafeWeakUse(Init);
8263     }
8264   }
8265 
8266   // The initialization is usually a full-expression.
8267   //
8268   // FIXME: If this is a braced initialization of an aggregate, it is not
8269   // an expression, and each individual field initializer is a separate
8270   // full-expression. For instance, in:
8271   //
8272   //   struct Temp { ~Temp(); };
8273   //   struct S { S(Temp); };
8274   //   struct T { S a, b; } t = { Temp(), Temp() }
8275   //
8276   // we should destroy the first Temp before constructing the second.
8277   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8278                                           false,
8279                                           VDecl->isConstexpr());
8280   if (Result.isInvalid()) {
8281     VDecl->setInvalidDecl();
8282     return;
8283   }
8284   Init = Result.take();
8285 
8286   // Attach the initializer to the decl.
8287   VDecl->setInit(Init);
8288 
8289   if (VDecl->isLocalVarDecl()) {
8290     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8291     // static storage duration shall be constant expressions or string literals.
8292     // C++ does not have this restriction.
8293     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8294       if (VDecl->getStorageClass() == SC_Static)
8295         CheckForConstantInitializer(Init, DclT);
8296       // C89 is stricter than C99 for non-static aggregate types.
8297       // C89 6.5.7p3: All the expressions [...] in an initializer list
8298       // for an object that has aggregate or union type shall be
8299       // constant expressions.
8300       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8301                isa<InitListExpr>(Init) &&
8302                !Init->isConstantInitializer(Context, false))
8303         Diag(Init->getExprLoc(),
8304              diag::ext_aggregate_init_not_constant)
8305           << Init->getSourceRange();
8306     }
8307   } else if (VDecl->isStaticDataMember() &&
8308              VDecl->getLexicalDeclContext()->isRecord()) {
8309     // This is an in-class initialization for a static data member, e.g.,
8310     //
8311     // struct S {
8312     //   static const int value = 17;
8313     // };
8314 
8315     // C++ [class.mem]p4:
8316     //   A member-declarator can contain a constant-initializer only
8317     //   if it declares a static member (9.4) of const integral or
8318     //   const enumeration type, see 9.4.2.
8319     //
8320     // C++11 [class.static.data]p3:
8321     //   If a non-volatile const static data member is of integral or
8322     //   enumeration type, its declaration in the class definition can
8323     //   specify a brace-or-equal-initializer in which every initalizer-clause
8324     //   that is an assignment-expression is a constant expression. A static
8325     //   data member of literal type can be declared in the class definition
8326     //   with the constexpr specifier; if so, its declaration shall specify a
8327     //   brace-or-equal-initializer in which every initializer-clause that is
8328     //   an assignment-expression is a constant expression.
8329 
8330     // Do nothing on dependent types.
8331     if (DclT->isDependentType()) {
8332 
8333     // Allow any 'static constexpr' members, whether or not they are of literal
8334     // type. We separately check that every constexpr variable is of literal
8335     // type.
8336     } else if (VDecl->isConstexpr()) {
8337 
8338     // Require constness.
8339     } else if (!DclT.isConstQualified()) {
8340       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8341         << Init->getSourceRange();
8342       VDecl->setInvalidDecl();
8343 
8344     // We allow integer constant expressions in all cases.
8345     } else if (DclT->isIntegralOrEnumerationType()) {
8346       // Check whether the expression is a constant expression.
8347       SourceLocation Loc;
8348       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8349         // In C++11, a non-constexpr const static data member with an
8350         // in-class initializer cannot be volatile.
8351         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8352       else if (Init->isValueDependent())
8353         ; // Nothing to check.
8354       else if (Init->isIntegerConstantExpr(Context, &Loc))
8355         ; // Ok, it's an ICE!
8356       else if (Init->isEvaluatable(Context)) {
8357         // If we can constant fold the initializer through heroics, accept it,
8358         // but report this as a use of an extension for -pedantic.
8359         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8360           << Init->getSourceRange();
8361       } else {
8362         // Otherwise, this is some crazy unknown case.  Report the issue at the
8363         // location provided by the isIntegerConstantExpr failed check.
8364         Diag(Loc, diag::err_in_class_initializer_non_constant)
8365           << Init->getSourceRange();
8366         VDecl->setInvalidDecl();
8367       }
8368 
8369     // We allow foldable floating-point constants as an extension.
8370     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8371       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8372       // it anyway and provide a fixit to add the 'constexpr'.
8373       if (getLangOpts().CPlusPlus11) {
8374         Diag(VDecl->getLocation(),
8375              diag::ext_in_class_initializer_float_type_cxx11)
8376             << DclT << Init->getSourceRange();
8377         Diag(VDecl->getLocStart(),
8378              diag::note_in_class_initializer_float_type_cxx11)
8379             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8380       } else {
8381         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8382           << DclT << Init->getSourceRange();
8383 
8384         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8385           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8386             << Init->getSourceRange();
8387           VDecl->setInvalidDecl();
8388         }
8389       }
8390 
8391     // Suggest adding 'constexpr' in C++11 for literal types.
8392     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8393       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8394         << DclT << Init->getSourceRange()
8395         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8396       VDecl->setConstexpr(true);
8397 
8398     } else {
8399       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8400         << DclT << Init->getSourceRange();
8401       VDecl->setInvalidDecl();
8402     }
8403   } else if (VDecl->isFileVarDecl()) {
8404     if (VDecl->getStorageClass() == SC_Extern &&
8405         (!getLangOpts().CPlusPlus ||
8406          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8407            VDecl->isExternC())) &&
8408         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
8409       Diag(VDecl->getLocation(), diag::warn_extern_init);
8410 
8411     // C99 6.7.8p4. All file scoped initializers need to be constant.
8412     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8413       CheckForConstantInitializer(Init, DclT);
8414     else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8415              !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8416              !Init->isValueDependent() && !VDecl->isConstexpr() &&
8417              !Init->isConstantInitializer(
8418                  Context, VDecl->getType()->isReferenceType())) {
8419       // GNU C++98 edits for __thread, [basic.start.init]p4:
8420       //   An object of thread storage duration shall not require dynamic
8421       //   initialization.
8422       // FIXME: Need strict checking here.
8423       Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8424       if (getLangOpts().CPlusPlus11)
8425         Diag(VDecl->getLocation(), diag::note_use_thread_local);
8426     }
8427   }
8428 
8429   // We will represent direct-initialization similarly to copy-initialization:
8430   //    int x(1);  -as-> int x = 1;
8431   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8432   //
8433   // Clients that want to distinguish between the two forms, can check for
8434   // direct initializer using VarDecl::getInitStyle().
8435   // A major benefit is that clients that don't particularly care about which
8436   // exactly form was it (like the CodeGen) can handle both cases without
8437   // special case code.
8438 
8439   // C++ 8.5p11:
8440   // The form of initialization (using parentheses or '=') is generally
8441   // insignificant, but does matter when the entity being initialized has a
8442   // class type.
8443   if (CXXDirectInit) {
8444     assert(DirectInit && "Call-style initializer must be direct init.");
8445     VDecl->setInitStyle(VarDecl::CallInit);
8446   } else if (DirectInit) {
8447     // This must be list-initialization. No other way is direct-initialization.
8448     VDecl->setInitStyle(VarDecl::ListInit);
8449   }
8450 
8451   CheckCompleteVariableDeclaration(VDecl);
8452 }
8453 
8454 /// ActOnInitializerError - Given that there was an error parsing an
8455 /// initializer for the given declaration, try to return to some form
8456 /// of sanity.
8457 void Sema::ActOnInitializerError(Decl *D) {
8458   // Our main concern here is re-establishing invariants like "a
8459   // variable's type is either dependent or complete".
8460   if (!D || D->isInvalidDecl()) return;
8461 
8462   VarDecl *VD = dyn_cast<VarDecl>(D);
8463   if (!VD) return;
8464 
8465   // Auto types are meaningless if we can't make sense of the initializer.
8466   if (ParsingInitForAutoVars.count(D)) {
8467     D->setInvalidDecl();
8468     return;
8469   }
8470 
8471   QualType Ty = VD->getType();
8472   if (Ty->isDependentType()) return;
8473 
8474   // Require a complete type.
8475   if (RequireCompleteType(VD->getLocation(),
8476                           Context.getBaseElementType(Ty),
8477                           diag::err_typecheck_decl_incomplete_type)) {
8478     VD->setInvalidDecl();
8479     return;
8480   }
8481 
8482   // Require an abstract type.
8483   if (RequireNonAbstractType(VD->getLocation(), Ty,
8484                              diag::err_abstract_type_in_decl,
8485                              AbstractVariableType)) {
8486     VD->setInvalidDecl();
8487     return;
8488   }
8489 
8490   // Don't bother complaining about constructors or destructors,
8491   // though.
8492 }
8493 
8494 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
8495                                   bool TypeMayContainAuto) {
8496   // If there is no declaration, there was an error parsing it. Just ignore it.
8497   if (RealDecl == 0)
8498     return;
8499 
8500   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8501     QualType Type = Var->getType();
8502 
8503     // C++11 [dcl.spec.auto]p3
8504     if (TypeMayContainAuto && Type->getContainedAutoType()) {
8505       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8506         << Var->getDeclName() << Type;
8507       Var->setInvalidDecl();
8508       return;
8509     }
8510 
8511     // C++11 [class.static.data]p3: A static data member can be declared with
8512     // the constexpr specifier; if so, its declaration shall specify
8513     // a brace-or-equal-initializer.
8514     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8515     // the definition of a variable [...] or the declaration of a static data
8516     // member.
8517     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8518       if (Var->isStaticDataMember())
8519         Diag(Var->getLocation(),
8520              diag::err_constexpr_static_mem_var_requires_init)
8521           << Var->getDeclName();
8522       else
8523         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8524       Var->setInvalidDecl();
8525       return;
8526     }
8527 
8528     switch (Var->isThisDeclarationADefinition()) {
8529     case VarDecl::Definition:
8530       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8531         break;
8532 
8533       // We have an out-of-line definition of a static data member
8534       // that has an in-class initializer, so we type-check this like
8535       // a declaration.
8536       //
8537       // Fall through
8538 
8539     case VarDecl::DeclarationOnly:
8540       // It's only a declaration.
8541 
8542       // Block scope. C99 6.7p7: If an identifier for an object is
8543       // declared with no linkage (C99 6.2.2p6), the type for the
8544       // object shall be complete.
8545       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
8546           !Var->hasLinkage() && !Var->isInvalidDecl() &&
8547           RequireCompleteType(Var->getLocation(), Type,
8548                               diag::err_typecheck_decl_incomplete_type))
8549         Var->setInvalidDecl();
8550 
8551       // Make sure that the type is not abstract.
8552       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8553           RequireNonAbstractType(Var->getLocation(), Type,
8554                                  diag::err_abstract_type_in_decl,
8555                                  AbstractVariableType))
8556         Var->setInvalidDecl();
8557       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8558           Var->getStorageClass() == SC_PrivateExtern) {
8559         Diag(Var->getLocation(), diag::warn_private_extern);
8560         Diag(Var->getLocation(), diag::note_private_extern);
8561       }
8562 
8563       return;
8564 
8565     case VarDecl::TentativeDefinition:
8566       // File scope. C99 6.9.2p2: A declaration of an identifier for an
8567       // object that has file scope without an initializer, and without a
8568       // storage-class specifier or with the storage-class specifier "static",
8569       // constitutes a tentative definition. Note: A tentative definition with
8570       // external linkage is valid (C99 6.2.2p5).
8571       if (!Var->isInvalidDecl()) {
8572         if (const IncompleteArrayType *ArrayT
8573                                     = Context.getAsIncompleteArrayType(Type)) {
8574           if (RequireCompleteType(Var->getLocation(),
8575                                   ArrayT->getElementType(),
8576                                   diag::err_illegal_decl_array_incomplete_type))
8577             Var->setInvalidDecl();
8578         } else if (Var->getStorageClass() == SC_Static) {
8579           // C99 6.9.2p3: If the declaration of an identifier for an object is
8580           // a tentative definition and has internal linkage (C99 6.2.2p3), the
8581           // declared type shall not be an incomplete type.
8582           // NOTE: code such as the following
8583           //     static struct s;
8584           //     struct s { int a; };
8585           // is accepted by gcc. Hence here we issue a warning instead of
8586           // an error and we do not invalidate the static declaration.
8587           // NOTE: to avoid multiple warnings, only check the first declaration.
8588           if (Var->isFirstDecl())
8589             RequireCompleteType(Var->getLocation(), Type,
8590                                 diag::ext_typecheck_decl_incomplete_type);
8591         }
8592       }
8593 
8594       // Record the tentative definition; we're done.
8595       if (!Var->isInvalidDecl())
8596         TentativeDefinitions.push_back(Var);
8597       return;
8598     }
8599 
8600     // Provide a specific diagnostic for uninitialized variable
8601     // definitions with incomplete array type.
8602     if (Type->isIncompleteArrayType()) {
8603       Diag(Var->getLocation(),
8604            diag::err_typecheck_incomplete_array_needs_initializer);
8605       Var->setInvalidDecl();
8606       return;
8607     }
8608 
8609     // Provide a specific diagnostic for uninitialized variable
8610     // definitions with reference type.
8611     if (Type->isReferenceType()) {
8612       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8613         << Var->getDeclName()
8614         << SourceRange(Var->getLocation(), Var->getLocation());
8615       Var->setInvalidDecl();
8616       return;
8617     }
8618 
8619     // Do not attempt to type-check the default initializer for a
8620     // variable with dependent type.
8621     if (Type->isDependentType())
8622       return;
8623 
8624     if (Var->isInvalidDecl())
8625       return;
8626 
8627     if (RequireCompleteType(Var->getLocation(),
8628                             Context.getBaseElementType(Type),
8629                             diag::err_typecheck_decl_incomplete_type)) {
8630       Var->setInvalidDecl();
8631       return;
8632     }
8633 
8634     // The variable can not have an abstract class type.
8635     if (RequireNonAbstractType(Var->getLocation(), Type,
8636                                diag::err_abstract_type_in_decl,
8637                                AbstractVariableType)) {
8638       Var->setInvalidDecl();
8639       return;
8640     }
8641 
8642     // Check for jumps past the implicit initializer.  C++0x
8643     // clarifies that this applies to a "variable with automatic
8644     // storage duration", not a "local variable".
8645     // C++11 [stmt.dcl]p3
8646     //   A program that jumps from a point where a variable with automatic
8647     //   storage duration is not in scope to a point where it is in scope is
8648     //   ill-formed unless the variable has scalar type, class type with a
8649     //   trivial default constructor and a trivial destructor, a cv-qualified
8650     //   version of one of these types, or an array of one of the preceding
8651     //   types and is declared without an initializer.
8652     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
8653       if (const RecordType *Record
8654             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
8655         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
8656         // Mark the function for further checking even if the looser rules of
8657         // C++11 do not require such checks, so that we can diagnose
8658         // incompatibilities with C++98.
8659         if (!CXXRecord->isPOD())
8660           getCurFunction()->setHasBranchProtectedScope();
8661       }
8662     }
8663 
8664     // C++03 [dcl.init]p9:
8665     //   If no initializer is specified for an object, and the
8666     //   object is of (possibly cv-qualified) non-POD class type (or
8667     //   array thereof), the object shall be default-initialized; if
8668     //   the object is of const-qualified type, the underlying class
8669     //   type shall have a user-declared default
8670     //   constructor. Otherwise, if no initializer is specified for
8671     //   a non- static object, the object and its subobjects, if
8672     //   any, have an indeterminate initial value); if the object
8673     //   or any of its subobjects are of const-qualified type, the
8674     //   program is ill-formed.
8675     // C++0x [dcl.init]p11:
8676     //   If no initializer is specified for an object, the object is
8677     //   default-initialized; [...].
8678     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8679     InitializationKind Kind
8680       = InitializationKind::CreateDefault(Var->getLocation());
8681 
8682     InitializationSequence InitSeq(*this, Entity, Kind, None);
8683     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
8684     if (Init.isInvalid())
8685       Var->setInvalidDecl();
8686     else if (Init.get()) {
8687       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
8688       // This is important for template substitution.
8689       Var->setInitStyle(VarDecl::CallInit);
8690     }
8691 
8692     CheckCompleteVariableDeclaration(Var);
8693   }
8694 }
8695 
8696 void Sema::ActOnCXXForRangeDecl(Decl *D) {
8697   VarDecl *VD = dyn_cast<VarDecl>(D);
8698   if (!VD) {
8699     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8700     D->setInvalidDecl();
8701     return;
8702   }
8703 
8704   VD->setCXXForRangeDecl(true);
8705 
8706   // for-range-declaration cannot be given a storage class specifier.
8707   int Error = -1;
8708   switch (VD->getStorageClass()) {
8709   case SC_None:
8710     break;
8711   case SC_Extern:
8712     Error = 0;
8713     break;
8714   case SC_Static:
8715     Error = 1;
8716     break;
8717   case SC_PrivateExtern:
8718     Error = 2;
8719     break;
8720   case SC_Auto:
8721     Error = 3;
8722     break;
8723   case SC_Register:
8724     Error = 4;
8725     break;
8726   case SC_OpenCLWorkGroupLocal:
8727     llvm_unreachable("Unexpected storage class");
8728   }
8729   if (VD->isConstexpr())
8730     Error = 5;
8731   if (Error != -1) {
8732     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8733       << VD->getDeclName() << Error;
8734     D->setInvalidDecl();
8735   }
8736 }
8737 
8738 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8739   if (var->isInvalidDecl()) return;
8740 
8741   // In ARC, don't allow jumps past the implicit initialization of a
8742   // local retaining variable.
8743   if (getLangOpts().ObjCAutoRefCount &&
8744       var->hasLocalStorage()) {
8745     switch (var->getType().getObjCLifetime()) {
8746     case Qualifiers::OCL_None:
8747     case Qualifiers::OCL_ExplicitNone:
8748     case Qualifiers::OCL_Autoreleasing:
8749       break;
8750 
8751     case Qualifiers::OCL_Weak:
8752     case Qualifiers::OCL_Strong:
8753       getCurFunction()->setHasBranchProtectedScope();
8754       break;
8755     }
8756   }
8757 
8758   if (var->isThisDeclarationADefinition() &&
8759       var->isExternallyVisible() && var->hasLinkage() &&
8760       getDiagnostics().getDiagnosticLevel(
8761                        diag::warn_missing_variable_declarations,
8762                        var->getLocation())) {
8763     // Find a previous declaration that's not a definition.
8764     VarDecl *prev = var->getPreviousDecl();
8765     while (prev && prev->isThisDeclarationADefinition())
8766       prev = prev->getPreviousDecl();
8767 
8768     if (!prev)
8769       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8770   }
8771 
8772   if (var->getTLSKind() == VarDecl::TLS_Static &&
8773       var->getType().isDestructedType()) {
8774     // GNU C++98 edits for __thread, [basic.start.term]p3:
8775     //   The type of an object with thread storage duration shall not
8776     //   have a non-trivial destructor.
8777     Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8778     if (getLangOpts().CPlusPlus11)
8779       Diag(var->getLocation(), diag::note_use_thread_local);
8780   }
8781 
8782   // All the following checks are C++ only.
8783   if (!getLangOpts().CPlusPlus) return;
8784 
8785   QualType type = var->getType();
8786   if (type->isDependentType()) return;
8787 
8788   // __block variables might require us to capture a copy-initializer.
8789   if (var->hasAttr<BlocksAttr>()) {
8790     // It's currently invalid to ever have a __block variable with an
8791     // array type; should we diagnose that here?
8792 
8793     // Regardless, we don't want to ignore array nesting when
8794     // constructing this copy.
8795     if (type->isStructureOrClassType()) {
8796       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
8797       SourceLocation poi = var->getLocation();
8798       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
8799       ExprResult result
8800         = PerformMoveOrCopyInitialization(
8801             InitializedEntity::InitializeBlock(poi, type, false),
8802             var, var->getType(), varRef, /*AllowNRVO=*/true);
8803       if (!result.isInvalid()) {
8804         result = MaybeCreateExprWithCleanups(result);
8805         Expr *init = result.takeAs<Expr>();
8806         Context.setBlockVarCopyInits(var, init);
8807       }
8808     }
8809   }
8810 
8811   Expr *Init = var->getInit();
8812   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
8813   QualType baseType = Context.getBaseElementType(type);
8814 
8815   if (!var->getDeclContext()->isDependentContext() &&
8816       Init && !Init->isValueDependent()) {
8817     if (IsGlobal && !var->isConstexpr() &&
8818         getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8819                                             var->getLocation())
8820           != DiagnosticsEngine::Ignored) {
8821       // Warn about globals which don't have a constant initializer.  Don't
8822       // warn about globals with a non-trivial destructor because we already
8823       // warned about them.
8824       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8825       if (!(RD && !RD->hasTrivialDestructor()) &&
8826           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8827         Diag(var->getLocation(), diag::warn_global_constructor)
8828           << Init->getSourceRange();
8829     }
8830 
8831     if (var->isConstexpr()) {
8832       SmallVector<PartialDiagnosticAt, 8> Notes;
8833       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8834         SourceLocation DiagLoc = var->getLocation();
8835         // If the note doesn't add any useful information other than a source
8836         // location, fold it into the primary diagnostic.
8837         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8838               diag::note_invalid_subexpr_in_const_expr) {
8839           DiagLoc = Notes[0].first;
8840           Notes.clear();
8841         }
8842         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8843           << var << Init->getSourceRange();
8844         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8845           Diag(Notes[I].first, Notes[I].second);
8846       }
8847     } else if (var->isUsableInConstantExpressions(Context)) {
8848       // Check whether the initializer of a const variable of integral or
8849       // enumeration type is an ICE now, since we can't tell whether it was
8850       // initialized by a constant expression if we check later.
8851       var->checkInitIsICE();
8852     }
8853   }
8854 
8855   // Require the destructor.
8856   if (const RecordType *recordType = baseType->getAs<RecordType>())
8857     FinalizeVarWithDestructor(var, recordType);
8858 }
8859 
8860 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8861 /// any semantic actions necessary after any initializer has been attached.
8862 void
8863 Sema::FinalizeDeclaration(Decl *ThisDecl) {
8864   // Note that we are no longer parsing the initializer for this declaration.
8865   ParsingInitForAutoVars.erase(ThisDecl);
8866 
8867   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
8868   if (!VD)
8869     return;
8870 
8871   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8872     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8873       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8874       VD->dropAttr<UsedAttr>();
8875     }
8876   }
8877 
8878   if (!VD->isInvalidDecl() &&
8879       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8880     if (const VarDecl *Def = VD->getDefinition()) {
8881       if (Def->hasAttr<AliasAttr>()) {
8882         Diag(VD->getLocation(), diag::err_tentative_after_alias)
8883             << VD->getDeclName();
8884         Diag(Def->getLocation(), diag::note_previous_definition);
8885         VD->setInvalidDecl();
8886       }
8887     }
8888   }
8889 
8890   const DeclContext *DC = VD->getDeclContext();
8891   // If there's a #pragma GCC visibility in scope, and this isn't a class
8892   // member, set the visibility of this variable.
8893   if (!DC->isRecord() && VD->isExternallyVisible())
8894     AddPushedVisibilityAttribute(VD);
8895 
8896   if (VD->isFileVarDecl())
8897     MarkUnusedFileScopedDecl(VD);
8898 
8899   // Now we have parsed the initializer and can update the table of magic
8900   // tag values.
8901   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8902       !VD->getType()->isIntegralOrEnumerationType())
8903     return;
8904 
8905   for (specific_attr_iterator<TypeTagForDatatypeAttr>
8906          I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8907          E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8908        I != E; ++I) {
8909     const Expr *MagicValueExpr = VD->getInit();
8910     if (!MagicValueExpr) {
8911       continue;
8912     }
8913     llvm::APSInt MagicValueInt;
8914     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8915       Diag(I->getRange().getBegin(),
8916            diag::err_type_tag_for_datatype_not_ice)
8917         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8918       continue;
8919     }
8920     if (MagicValueInt.getActiveBits() > 64) {
8921       Diag(I->getRange().getBegin(),
8922            diag::err_type_tag_for_datatype_too_large)
8923         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8924       continue;
8925     }
8926     uint64_t MagicValue = MagicValueInt.getZExtValue();
8927     RegisterTypeTagForDatatype(I->getArgumentKind(),
8928                                MagicValue,
8929                                I->getMatchingCType(),
8930                                I->getLayoutCompatible(),
8931                                I->getMustBeNull());
8932   }
8933 }
8934 
8935 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8936                                                    ArrayRef<Decl *> Group) {
8937   SmallVector<Decl*, 8> Decls;
8938 
8939   if (DS.isTypeSpecOwned())
8940     Decls.push_back(DS.getRepAsDecl());
8941 
8942   DeclaratorDecl *FirstDeclaratorInGroup = 0;
8943   for (unsigned i = 0, e = Group.size(); i != e; ++i)
8944     if (Decl *D = Group[i]) {
8945       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8946         if (!FirstDeclaratorInGroup)
8947           FirstDeclaratorInGroup = DD;
8948       Decls.push_back(D);
8949     }
8950 
8951   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
8952     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
8953       HandleTagNumbering(*this, Tag);
8954       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8955         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8956     }
8957   }
8958 
8959   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
8960 }
8961 
8962 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
8963 /// group, performing any necessary semantic checking.
8964 Sema::DeclGroupPtrTy
8965 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
8966                            bool TypeMayContainAuto) {
8967   // C++0x [dcl.spec.auto]p7:
8968   //   If the type deduced for the template parameter U is not the same in each
8969   //   deduction, the program is ill-formed.
8970   // FIXME: When initializer-list support is added, a distinction is needed
8971   // between the deduced type U and the deduced type which 'auto' stands for.
8972   //   auto a = 0, b = { 1, 2, 3 };
8973   // is legal because the deduced type U is 'int' in both cases.
8974   if (TypeMayContainAuto && Group.size() > 1) {
8975     QualType Deduced;
8976     CanQualType DeducedCanon;
8977     VarDecl *DeducedDecl = 0;
8978     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
8979       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8980         AutoType *AT = D->getType()->getContainedAutoType();
8981         // Don't reissue diagnostics when instantiating a template.
8982         if (AT && D->isInvalidDecl())
8983           break;
8984         QualType U = AT ? AT->getDeducedType() : QualType();
8985         if (!U.isNull()) {
8986           CanQualType UCanon = Context.getCanonicalType(U);
8987           if (Deduced.isNull()) {
8988             Deduced = U;
8989             DeducedCanon = UCanon;
8990             DeducedDecl = D;
8991           } else if (DeducedCanon != UCanon) {
8992             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
8993                  diag::err_auto_different_deductions)
8994               << (AT->isDecltypeAuto() ? 1 : 0)
8995               << Deduced << DeducedDecl->getDeclName()
8996               << U << D->getDeclName()
8997               << DeducedDecl->getInit()->getSourceRange()
8998               << D->getInit()->getSourceRange();
8999             D->setInvalidDecl();
9000             break;
9001           }
9002         }
9003       }
9004     }
9005   }
9006 
9007   ActOnDocumentableDecls(Group);
9008 
9009   return DeclGroupPtrTy::make(
9010       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9011 }
9012 
9013 void Sema::ActOnDocumentableDecl(Decl *D) {
9014   ActOnDocumentableDecls(D);
9015 }
9016 
9017 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9018   // Don't parse the comment if Doxygen diagnostics are ignored.
9019   if (Group.empty() || !Group[0])
9020    return;
9021 
9022   if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9023                                Group[0]->getLocation())
9024         == DiagnosticsEngine::Ignored)
9025     return;
9026 
9027   if (Group.size() >= 2) {
9028     // This is a decl group.  Normally it will contain only declarations
9029     // produced from declarator list.  But in case we have any definitions or
9030     // additional declaration references:
9031     //   'typedef struct S {} S;'
9032     //   'typedef struct S *S;'
9033     //   'struct S *pS;'
9034     // FinalizeDeclaratorGroup adds these as separate declarations.
9035     Decl *MaybeTagDecl = Group[0];
9036     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9037       Group = Group.slice(1);
9038     }
9039   }
9040 
9041   // See if there are any new comments that are not attached to a decl.
9042   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9043   if (!Comments.empty() &&
9044       !Comments.back()->isAttached()) {
9045     // There is at least one comment that not attached to a decl.
9046     // Maybe it should be attached to one of these decls?
9047     //
9048     // Note that this way we pick up not only comments that precede the
9049     // declaration, but also comments that *follow* the declaration -- thanks to
9050     // the lookahead in the lexer: we've consumed the semicolon and looked
9051     // ahead through comments.
9052     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9053       Context.getCommentForDecl(Group[i], &PP);
9054   }
9055 }
9056 
9057 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9058 /// to introduce parameters into function prototype scope.
9059 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9060   const DeclSpec &DS = D.getDeclSpec();
9061 
9062   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9063 
9064   // C++03 [dcl.stc]p2 also permits 'auto'.
9065   VarDecl::StorageClass StorageClass = SC_None;
9066   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9067     StorageClass = SC_Register;
9068   } else if (getLangOpts().CPlusPlus &&
9069              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9070     StorageClass = SC_Auto;
9071   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9072     Diag(DS.getStorageClassSpecLoc(),
9073          diag::err_invalid_storage_class_in_func_decl);
9074     D.getMutableDeclSpec().ClearStorageClassSpecs();
9075   }
9076 
9077   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9078     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9079       << DeclSpec::getSpecifierName(TSCS);
9080   if (DS.isConstexprSpecified())
9081     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9082       << 0;
9083 
9084   DiagnoseFunctionSpecifiers(DS);
9085 
9086   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9087   QualType parmDeclType = TInfo->getType();
9088 
9089   if (getLangOpts().CPlusPlus) {
9090     // Check that there are no default arguments inside the type of this
9091     // parameter.
9092     CheckExtraCXXDefaultArguments(D);
9093 
9094     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9095     if (D.getCXXScopeSpec().isSet()) {
9096       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9097         << D.getCXXScopeSpec().getRange();
9098       D.getCXXScopeSpec().clear();
9099     }
9100   }
9101 
9102   // Ensure we have a valid name
9103   IdentifierInfo *II = 0;
9104   if (D.hasName()) {
9105     II = D.getIdentifier();
9106     if (!II) {
9107       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9108         << GetNameForDeclarator(D).getName().getAsString();
9109       D.setInvalidType(true);
9110     }
9111   }
9112 
9113   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9114   if (II) {
9115     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9116                    ForRedeclaration);
9117     LookupName(R, S);
9118     if (R.isSingleResult()) {
9119       NamedDecl *PrevDecl = R.getFoundDecl();
9120       if (PrevDecl->isTemplateParameter()) {
9121         // Maybe we will complain about the shadowed template parameter.
9122         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9123         // Just pretend that we didn't see the previous declaration.
9124         PrevDecl = 0;
9125       } else if (S->isDeclScope(PrevDecl)) {
9126         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9127         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9128 
9129         // Recover by removing the name
9130         II = 0;
9131         D.SetIdentifier(0, D.getIdentifierLoc());
9132         D.setInvalidType(true);
9133       }
9134     }
9135   }
9136 
9137   // Temporarily put parameter variables in the translation unit, not
9138   // the enclosing context.  This prevents them from accidentally
9139   // looking like class members in C++.
9140   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9141                                     D.getLocStart(),
9142                                     D.getIdentifierLoc(), II,
9143                                     parmDeclType, TInfo,
9144                                     StorageClass);
9145 
9146   if (D.isInvalidType())
9147     New->setInvalidDecl();
9148 
9149   assert(S->isFunctionPrototypeScope());
9150   assert(S->getFunctionPrototypeDepth() >= 1);
9151   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9152                     S->getNextFunctionPrototypeIndex());
9153 
9154   // Add the parameter declaration into this scope.
9155   S->AddDecl(New);
9156   if (II)
9157     IdResolver.AddDecl(New);
9158 
9159   ProcessDeclAttributes(S, New, D);
9160 
9161   if (D.getDeclSpec().isModulePrivateSpecified())
9162     Diag(New->getLocation(), diag::err_module_private_local)
9163       << 1 << New->getDeclName()
9164       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9165       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9166 
9167   if (New->hasAttr<BlocksAttr>()) {
9168     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9169   }
9170   return New;
9171 }
9172 
9173 /// \brief Synthesizes a variable for a parameter arising from a
9174 /// typedef.
9175 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9176                                               SourceLocation Loc,
9177                                               QualType T) {
9178   /* FIXME: setting StartLoc == Loc.
9179      Would it be worth to modify callers so as to provide proper source
9180      location for the unnamed parameters, embedding the parameter's type? */
9181   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
9182                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9183                                            SC_None, 0);
9184   Param->setImplicit();
9185   return Param;
9186 }
9187 
9188 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9189                                     ParmVarDecl * const *ParamEnd) {
9190   // Don't diagnose unused-parameter errors in template instantiations; we
9191   // will already have done so in the template itself.
9192   if (!ActiveTemplateInstantiations.empty())
9193     return;
9194 
9195   for (; Param != ParamEnd; ++Param) {
9196     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9197         !(*Param)->hasAttr<UnusedAttr>()) {
9198       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9199         << (*Param)->getDeclName();
9200     }
9201   }
9202 }
9203 
9204 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9205                                                   ParmVarDecl * const *ParamEnd,
9206                                                   QualType ReturnTy,
9207                                                   NamedDecl *D) {
9208   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9209     return;
9210 
9211   // Warn if the return value is pass-by-value and larger than the specified
9212   // threshold.
9213   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9214     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9215     if (Size > LangOpts.NumLargeByValueCopy)
9216       Diag(D->getLocation(), diag::warn_return_value_size)
9217           << D->getDeclName() << Size;
9218   }
9219 
9220   // Warn if any parameter is pass-by-value and larger than the specified
9221   // threshold.
9222   for (; Param != ParamEnd; ++Param) {
9223     QualType T = (*Param)->getType();
9224     if (T->isDependentType() || !T.isPODType(Context))
9225       continue;
9226     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9227     if (Size > LangOpts.NumLargeByValueCopy)
9228       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9229           << (*Param)->getDeclName() << Size;
9230   }
9231 }
9232 
9233 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9234                                   SourceLocation NameLoc, IdentifierInfo *Name,
9235                                   QualType T, TypeSourceInfo *TSInfo,
9236                                   VarDecl::StorageClass StorageClass) {
9237   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9238   if (getLangOpts().ObjCAutoRefCount &&
9239       T.getObjCLifetime() == Qualifiers::OCL_None &&
9240       T->isObjCLifetimeType()) {
9241 
9242     Qualifiers::ObjCLifetime lifetime;
9243 
9244     // Special cases for arrays:
9245     //   - if it's const, use __unsafe_unretained
9246     //   - otherwise, it's an error
9247     if (T->isArrayType()) {
9248       if (!T.isConstQualified()) {
9249         DelayedDiagnostics.add(
9250             sema::DelayedDiagnostic::makeForbiddenType(
9251             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9252       }
9253       lifetime = Qualifiers::OCL_ExplicitNone;
9254     } else {
9255       lifetime = T->getObjCARCImplicitLifetime();
9256     }
9257     T = Context.getLifetimeQualifiedType(T, lifetime);
9258   }
9259 
9260   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9261                                          Context.getAdjustedParameterType(T),
9262                                          TSInfo,
9263                                          StorageClass, 0);
9264 
9265   // Parameters can not be abstract class types.
9266   // For record types, this is done by the AbstractClassUsageDiagnoser once
9267   // the class has been completely parsed.
9268   if (!CurContext->isRecord() &&
9269       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9270                              AbstractParamType))
9271     New->setInvalidDecl();
9272 
9273   // Parameter declarators cannot be interface types. All ObjC objects are
9274   // passed by reference.
9275   if (T->isObjCObjectType()) {
9276     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9277     Diag(NameLoc,
9278          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9279       << FixItHint::CreateInsertion(TypeEndLoc, "*");
9280     T = Context.getObjCObjectPointerType(T);
9281     New->setType(T);
9282   }
9283 
9284   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9285   // duration shall not be qualified by an address-space qualifier."
9286   // Since all parameters have automatic store duration, they can not have
9287   // an address space.
9288   if (T.getAddressSpace() != 0) {
9289     Diag(NameLoc, diag::err_arg_with_address_space);
9290     New->setInvalidDecl();
9291   }
9292 
9293   return New;
9294 }
9295 
9296 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9297                                            SourceLocation LocAfterDecls) {
9298   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9299 
9300   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9301   // for a K&R function.
9302   if (!FTI.hasPrototype) {
9303     for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9304       --i;
9305       if (FTI.ArgInfo[i].Param == 0) {
9306         SmallString<256> Code;
9307         llvm::raw_svector_ostream(Code) << "  int "
9308                                         << FTI.ArgInfo[i].Ident->getName()
9309                                         << ";\n";
9310         Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
9311           << FTI.ArgInfo[i].Ident
9312           << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9313 
9314         // Implicitly declare the argument as type 'int' for lack of a better
9315         // type.
9316         AttributeFactory attrs;
9317         DeclSpec DS(attrs);
9318         const char* PrevSpec; // unused
9319         unsigned DiagID; // unused
9320         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
9321                            PrevSpec, DiagID);
9322         // Use the identifier location for the type source range.
9323         DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9324         DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
9325         Declarator ParamD(DS, Declarator::KNRTypeListContext);
9326         ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
9327         FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
9328       }
9329     }
9330   }
9331 }
9332 
9333 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9334   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
9335   assert(D.isFunctionDeclarator() && "Not a function declarator!");
9336   Scope *ParentScope = FnBodyScope->getParent();
9337 
9338   D.setFunctionDefinitionKind(FDK_Definition);
9339   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9340   return ActOnStartOfFunctionDef(FnBodyScope, DP);
9341 }
9342 
9343 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9344                              const FunctionDecl*& PossibleZeroParamPrototype) {
9345   // Don't warn about invalid declarations.
9346   if (FD->isInvalidDecl())
9347     return false;
9348 
9349   // Or declarations that aren't global.
9350   if (!FD->isGlobal())
9351     return false;
9352 
9353   // Don't warn about C++ member functions.
9354   if (isa<CXXMethodDecl>(FD))
9355     return false;
9356 
9357   // Don't warn about 'main'.
9358   if (FD->isMain())
9359     return false;
9360 
9361   // Don't warn about inline functions.
9362   if (FD->isInlined())
9363     return false;
9364 
9365   // Don't warn about function templates.
9366   if (FD->getDescribedFunctionTemplate())
9367     return false;
9368 
9369   // Don't warn about function template specializations.
9370   if (FD->isFunctionTemplateSpecialization())
9371     return false;
9372 
9373   // Don't warn for OpenCL kernels.
9374   if (FD->hasAttr<OpenCLKernelAttr>())
9375     return false;
9376 
9377   bool MissingPrototype = true;
9378   for (const FunctionDecl *Prev = FD->getPreviousDecl();
9379        Prev; Prev = Prev->getPreviousDecl()) {
9380     // Ignore any declarations that occur in function or method
9381     // scope, because they aren't visible from the header.
9382     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9383       continue;
9384 
9385     MissingPrototype = !Prev->getType()->isFunctionProtoType();
9386     if (FD->getNumParams() == 0)
9387       PossibleZeroParamPrototype = Prev;
9388     break;
9389   }
9390 
9391   return MissingPrototype;
9392 }
9393 
9394 void
9395 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9396                                    const FunctionDecl *EffectiveDefinition) {
9397   // Don't complain if we're in GNU89 mode and the previous definition
9398   // was an extern inline function.
9399   const FunctionDecl *Definition = EffectiveDefinition;
9400   if (!Definition)
9401     if (!FD->isDefined(Definition))
9402       return;
9403 
9404   if (canRedefineFunction(Definition, getLangOpts()))
9405     return;
9406 
9407   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9408       Definition->getStorageClass() == SC_Extern)
9409     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9410         << FD->getDeclName() << getLangOpts().CPlusPlus;
9411   else
9412     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9413 
9414   Diag(Definition->getLocation(), diag::note_previous_definition);
9415   FD->setInvalidDecl();
9416 }
9417 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9418                                    Sema &S) {
9419   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9420   S.PushLambdaScope();
9421   LambdaScopeInfo *LSI = S.getCurLambda();
9422   LSI->CallOperator = CallOperator;
9423   LSI->Lambda = LambdaClass;
9424   LSI->ReturnType = CallOperator->getResultType();
9425   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9426 
9427   if (LCD == LCD_None)
9428     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9429   else if (LCD == LCD_ByCopy)
9430     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9431   else if (LCD == LCD_ByRef)
9432     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9433   DeclarationNameInfo DNI = CallOperator->getNameInfo();
9434 
9435   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9436   LSI->Mutable = !CallOperator->isConst();
9437 
9438   // FIXME: Add the captures to the LSI.
9439 }
9440 
9441 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
9442   // Clear the last template instantiation error context.
9443   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9444 
9445   if (!D)
9446     return D;
9447   FunctionDecl *FD = 0;
9448 
9449   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
9450     FD = FunTmpl->getTemplatedDecl();
9451   else
9452     FD = cast<FunctionDecl>(D);
9453   // If we are instantiating a generic lambda call operator, push
9454   // a LambdaScopeInfo onto the function stack.  But use the information
9455   // that's already been calculated (ActOnLambdaExpr) to prime the current
9456   // LambdaScopeInfo.
9457   // When the template operator is being specialized, the LambdaScopeInfo,
9458   // has to be properly restored so that tryCaptureVariable doesn't try
9459   // and capture any new variables. In addition when calculating potential
9460   // captures during transformation of nested lambdas, it is necessary to
9461   // have the LSI properly restored.
9462   if (isGenericLambdaCallOperatorSpecialization(FD)) {
9463     assert(ActiveTemplateInstantiations.size() &&
9464       "There should be an active template instantiation on the stack "
9465       "when instantiating a generic lambda!");
9466     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
9467   }
9468   else
9469     // Enter a new function scope
9470     PushFunctionScope();
9471 
9472   // See if this is a redefinition.
9473   if (!FD->isLateTemplateParsed())
9474     CheckForFunctionRedefinition(FD);
9475 
9476   // Builtin functions cannot be defined.
9477   if (unsigned BuiltinID = FD->getBuiltinID()) {
9478     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9479         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
9480       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
9481       FD->setInvalidDecl();
9482     }
9483   }
9484 
9485   // The return type of a function definition must be complete
9486   // (C99 6.9.1p3, C++ [dcl.fct]p6).
9487   QualType ResultType = FD->getResultType();
9488   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
9489       !FD->isInvalidDecl() &&
9490       RequireCompleteType(FD->getLocation(), ResultType,
9491                           diag::err_func_def_incomplete_result))
9492     FD->setInvalidDecl();
9493 
9494   // GNU warning -Wmissing-prototypes:
9495   //   Warn if a global function is defined without a previous
9496   //   prototype declaration. This warning is issued even if the
9497   //   definition itself provides a prototype. The aim is to detect
9498   //   global functions that fail to be declared in header files.
9499   const FunctionDecl *PossibleZeroParamPrototype = 0;
9500   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
9501     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
9502 
9503     if (PossibleZeroParamPrototype) {
9504       // We found a declaration that is not a prototype,
9505       // but that could be a zero-parameter prototype
9506       if (TypeSourceInfo *TI =
9507               PossibleZeroParamPrototype->getTypeSourceInfo()) {
9508         TypeLoc TL = TI->getTypeLoc();
9509         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9510           Diag(PossibleZeroParamPrototype->getLocation(),
9511                diag::note_declaration_not_a_prototype)
9512             << PossibleZeroParamPrototype
9513             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9514       }
9515     }
9516   }
9517 
9518   if (FnBodyScope)
9519     PushDeclContext(FnBodyScope, FD);
9520 
9521   // Check the validity of our function parameters
9522   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9523                            /*CheckParameterNames=*/true);
9524 
9525   // Introduce our parameters into the function scope
9526   for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9527     ParmVarDecl *Param = FD->getParamDecl(p);
9528     Param->setOwningFunction(FD);
9529 
9530     // If this has an identifier, add it to the scope stack.
9531     if (Param->getIdentifier() && FnBodyScope) {
9532       CheckShadow(FnBodyScope, Param);
9533 
9534       PushOnScopeChains(Param, FnBodyScope);
9535     }
9536   }
9537 
9538   // If we had any tags defined in the function prototype,
9539   // introduce them into the function scope.
9540   if (FnBodyScope) {
9541     for (ArrayRef<NamedDecl *>::iterator
9542              I = FD->getDeclsInPrototypeScope().begin(),
9543              E = FD->getDeclsInPrototypeScope().end();
9544          I != E; ++I) {
9545       NamedDecl *D = *I;
9546 
9547       // Some of these decls (like enums) may have been pinned to the translation unit
9548       // for lack of a real context earlier. If so, remove from the translation unit
9549       // and reattach to the current context.
9550       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9551         // Is the decl actually in the context?
9552         for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9553                DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9554           if (*DI == D) {
9555             Context.getTranslationUnitDecl()->removeDecl(D);
9556             break;
9557           }
9558         }
9559         // Either way, reassign the lexical decl context to our FunctionDecl.
9560         D->setLexicalDeclContext(CurContext);
9561       }
9562 
9563       // If the decl has a non-null name, make accessible in the current scope.
9564       if (!D->getName().empty())
9565         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9566 
9567       // Similarly, dive into enums and fish their constants out, making them
9568       // accessible in this scope.
9569       if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9570         for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9571                EE = ED->enumerator_end(); EI != EE; ++EI)
9572           PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
9573       }
9574     }
9575   }
9576 
9577   // Ensure that the function's exception specification is instantiated.
9578   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9579     ResolveExceptionSpec(D->getLocation(), FPT);
9580 
9581   // Checking attributes of current function definition
9582   // dllimport attribute.
9583   DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9584   if (DA && (!FD->getAttr<DLLExportAttr>())) {
9585     // dllimport attribute cannot be directly applied to definition.
9586     // Microsoft accepts dllimport for functions defined within class scope.
9587     if (!DA->isInherited() &&
9588         !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
9589       Diag(FD->getLocation(),
9590            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9591         << "dllimport";
9592       FD->setInvalidDecl();
9593       return D;
9594     }
9595 
9596     // Visual C++ appears to not think this is an issue, so only issue
9597     // a warning when Microsoft extensions are disabled.
9598     if (!LangOpts.MicrosoftExt) {
9599       // If a symbol previously declared dllimport is later defined, the
9600       // attribute is ignored in subsequent references, and a warning is
9601       // emitted.
9602       Diag(FD->getLocation(),
9603            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
9604         << FD->getName() << "dllimport";
9605     }
9606   }
9607   // We want to attach documentation to original Decl (which might be
9608   // a function template).
9609   ActOnDocumentableDecl(D);
9610   return D;
9611 }
9612 
9613 /// \brief Given the set of return statements within a function body,
9614 /// compute the variables that are subject to the named return value
9615 /// optimization.
9616 ///
9617 /// Each of the variables that is subject to the named return value
9618 /// optimization will be marked as NRVO variables in the AST, and any
9619 /// return statement that has a marked NRVO variable as its NRVO candidate can
9620 /// use the named return value optimization.
9621 ///
9622 /// This function applies a very simplistic algorithm for NRVO: if every return
9623 /// statement in the function has the same NRVO candidate, that candidate is
9624 /// the NRVO variable.
9625 ///
9626 /// FIXME: Employ a smarter algorithm that accounts for multiple return
9627 /// statements and the lifetimes of the NRVO candidates. We should be able to
9628 /// find a maximal set of NRVO variables.
9629 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
9630   ReturnStmt **Returns = Scope->Returns.data();
9631 
9632   const VarDecl *NRVOCandidate = 0;
9633   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
9634     if (!Returns[I]->getNRVOCandidate())
9635       return;
9636 
9637     if (!NRVOCandidate)
9638       NRVOCandidate = Returns[I]->getNRVOCandidate();
9639     else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9640       return;
9641   }
9642 
9643   if (NRVOCandidate)
9644     const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9645 }
9646 
9647 bool Sema::canSkipFunctionBody(Decl *D) {
9648   if (!Consumer.shouldSkipFunctionBody(D))
9649     return false;
9650 
9651   if (isa<ObjCMethodDecl>(D))
9652     return true;
9653 
9654   FunctionDecl *FD = 0;
9655   if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9656     FD = FTD->getTemplatedDecl();
9657   else
9658     FD = cast<FunctionDecl>(D);
9659 
9660   // We cannot skip the body of a function (or function template) which is
9661   // constexpr, since we may need to evaluate its body in order to parse the
9662   // rest of the file.
9663   // We cannot skip the body of a function with an undeduced return type,
9664   // because any callers of that function need to know the type.
9665   return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
9666 }
9667 
9668 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
9669   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
9670     FD->setHasSkippedBody();
9671   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
9672     MD->setHasSkippedBody();
9673   return ActOnFinishFunctionBody(Decl, 0);
9674 }
9675 
9676 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
9677   return ActOnFinishFunctionBody(D, BodyArg, false);
9678 }
9679 
9680 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9681                                     bool IsInstantiation) {
9682   FunctionDecl *FD = 0;
9683   FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9684   if (FunTmpl)
9685     FD = FunTmpl->getTemplatedDecl();
9686   else
9687     FD = dyn_cast_or_null<FunctionDecl>(dcl);
9688 
9689   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
9690   sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
9691 
9692   if (FD) {
9693     FD->setBody(Body);
9694 
9695     if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9696         !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9697       // If the function has a deduced result type but contains no 'return'
9698       // statements, the result type as written must be exactly 'auto', and
9699       // the deduced result type is 'void'.
9700       if (!FD->getResultType()->getAs<AutoType>()) {
9701         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9702           << FD->getResultType();
9703         FD->setInvalidDecl();
9704       } else {
9705         // Substitute 'void' for the 'auto' in the type.
9706         TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9707             IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9708         Context.adjustDeducedFunctionResultType(
9709             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
9710       }
9711     }
9712 
9713     // The only way to be included in UndefinedButUsed is if there is an
9714     // ODR use before the definition. Avoid the expensive map lookup if this
9715     // is the first declaration.
9716     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
9717       if (!FD->isExternallyVisible())
9718         UndefinedButUsed.erase(FD);
9719       else if (FD->isInlined() &&
9720                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9721                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9722         UndefinedButUsed.erase(FD);
9723     }
9724 
9725     // If the function implicitly returns zero (like 'main') or is naked,
9726     // don't complain about missing return statements.
9727     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
9728       WP.disableCheckFallThrough();
9729 
9730     // MSVC permits the use of pure specifier (=0) on function definition,
9731     // defined at class scope, warn about this non standard construct.
9732     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
9733       Diag(FD->getLocation(), diag::warn_pure_function_definition);
9734 
9735     if (!FD->isInvalidDecl()) {
9736       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
9737       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9738                                              FD->getResultType(), FD);
9739 
9740       // If this is a constructor, we need a vtable.
9741       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9742         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
9743 
9744       // Try to apply the named return value optimization. We have to check
9745       // if we can do this here because lambdas keep return statements around
9746       // to deduce an implicit return type.
9747       if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9748           !FD->isDependentContext())
9749         computeNRVO(Body, getCurFunction());
9750     }
9751 
9752     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9753            "Function parsing confused");
9754   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
9755     assert(MD == getCurMethodDecl() && "Method parsing confused");
9756     MD->setBody(Body);
9757     if (!MD->isInvalidDecl()) {
9758       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
9759       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9760                                              MD->getResultType(), MD);
9761 
9762       if (Body)
9763         computeNRVO(Body, getCurFunction());
9764     }
9765     if (getCurFunction()->ObjCShouldCallSuper) {
9766       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9767         << MD->getSelector().getAsString();
9768       getCurFunction()->ObjCShouldCallSuper = false;
9769     }
9770   } else {
9771     return 0;
9772   }
9773 
9774   assert(!getCurFunction()->ObjCShouldCallSuper &&
9775          "This should only be set for ObjC methods, which should have been "
9776          "handled in the block above.");
9777 
9778   // Verify and clean out per-function state.
9779   if (Body) {
9780     // C++ constructors that have function-try-blocks can't have return
9781     // statements in the handlers of that block. (C++ [except.handle]p14)
9782     // Verify this.
9783     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9784       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9785 
9786     // Verify that gotos and switch cases don't jump into scopes illegally.
9787     if (getCurFunction()->NeedsScopeChecking() &&
9788         !dcl->isInvalidDecl() &&
9789         !hasAnyUnrecoverableErrorsInThisFunction() &&
9790         !PP.isCodeCompletionEnabled())
9791       DiagnoseInvalidJumps(Body);
9792 
9793     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9794       if (!Destructor->getParent()->isDependentType())
9795         CheckDestructor(Destructor);
9796 
9797       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9798                                              Destructor->getParent());
9799     }
9800 
9801     // If any errors have occurred, clear out any temporaries that may have
9802     // been leftover. This ensures that these temporaries won't be picked up for
9803     // deletion in some later function.
9804     if (PP.getDiagnostics().hasErrorOccurred() ||
9805         PP.getDiagnostics().getSuppressAllDiagnostics()) {
9806       DiscardCleanupsInEvaluationContext();
9807     }
9808     if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9809         !isa<FunctionTemplateDecl>(dcl)) {
9810       // Since the body is valid, issue any analysis-based warnings that are
9811       // enabled.
9812       ActivePolicy = &WP;
9813     }
9814 
9815     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9816         (!CheckConstexprFunctionDecl(FD) ||
9817          !CheckConstexprFunctionBody(FD, Body)))
9818       FD->setInvalidDecl();
9819 
9820     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
9821     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
9822     assert(MaybeODRUseExprs.empty() &&
9823            "Leftover expressions for odr-use checking");
9824   }
9825 
9826   if (!IsInstantiation)
9827     PopDeclContext();
9828 
9829   PopFunctionScopeInfo(ActivePolicy, dcl);
9830   // If any errors have occurred, clear out any temporaries that may have
9831   // been leftover. This ensures that these temporaries won't be picked up for
9832   // deletion in some later function.
9833   if (getDiagnostics().hasErrorOccurred()) {
9834     DiscardCleanupsInEvaluationContext();
9835   }
9836 
9837   return dcl;
9838 }
9839 
9840 
9841 /// When we finish delayed parsing of an attribute, we must attach it to the
9842 /// relevant Decl.
9843 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9844                                        ParsedAttributes &Attrs) {
9845   // Always attach attributes to the underlying decl.
9846   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9847     D = TD->getTemplatedDecl();
9848   ProcessDeclAttributeList(S, D, Attrs.getList());
9849 
9850   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9851     if (Method->isStatic())
9852       checkThisInStaticMemberFunctionAttributes(Method);
9853 }
9854 
9855 
9856 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9857 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
9858 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
9859                                           IdentifierInfo &II, Scope *S) {
9860   // Before we produce a declaration for an implicitly defined
9861   // function, see whether there was a locally-scoped declaration of
9862   // this name as a function or variable. If so, use that
9863   // (non-visible) declaration, and complain about it.
9864   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9865     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9866     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9867     return ExternCPrev;
9868   }
9869 
9870   // Extension in C99.  Legal in C90, but warn about it.
9871   unsigned diag_id;
9872   if (II.getName().startswith("__builtin_"))
9873     diag_id = diag::warn_builtin_unknown;
9874   else if (getLangOpts().C99)
9875     diag_id = diag::ext_implicit_function_decl;
9876   else
9877     diag_id = diag::warn_implicit_function_decl;
9878   Diag(Loc, diag_id) << &II;
9879 
9880   // Because typo correction is expensive, only do it if the implicit
9881   // function declaration is going to be treated as an error.
9882   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9883     TypoCorrection Corrected;
9884     DeclFilterCCC<FunctionDecl> Validator;
9885     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
9886                                       LookupOrdinaryName, S, 0, Validator)))
9887       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9888                    /*ErrorRecovery*/false);
9889   }
9890 
9891   // Set a Declarator for the implicit definition: int foo();
9892   const char *Dummy;
9893   AttributeFactory attrFactory;
9894   DeclSpec DS(attrFactory);
9895   unsigned DiagID;
9896   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
9897   (void)Error; // Silence warning.
9898   assert(!Error && "Error setting up implicit decl!");
9899   SourceLocation NoLoc;
9900   Declarator D(DS, Declarator::BlockContext);
9901   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9902                                              /*IsAmbiguous=*/false,
9903                                              /*RParenLoc=*/NoLoc,
9904                                              /*ArgInfo=*/0,
9905                                              /*NumArgs=*/0,
9906                                              /*EllipsisLoc=*/NoLoc,
9907                                              /*RParenLoc=*/NoLoc,
9908                                              /*TypeQuals=*/0,
9909                                              /*RefQualifierIsLvalueRef=*/true,
9910                                              /*RefQualifierLoc=*/NoLoc,
9911                                              /*ConstQualifierLoc=*/NoLoc,
9912                                              /*VolatileQualifierLoc=*/NoLoc,
9913                                              /*MutableLoc=*/NoLoc,
9914                                              EST_None,
9915                                              /*ESpecLoc=*/NoLoc,
9916                                              /*Exceptions=*/0,
9917                                              /*ExceptionRanges=*/0,
9918                                              /*NumExceptions=*/0,
9919                                              /*NoexceptExpr=*/0,
9920                                              Loc, Loc, D),
9921                 DS.getAttributes(),
9922                 SourceLocation());
9923   D.SetIdentifier(&II, Loc);
9924 
9925   // Insert this function into translation-unit scope.
9926 
9927   DeclContext *PrevDC = CurContext;
9928   CurContext = Context.getTranslationUnitDecl();
9929 
9930   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
9931   FD->setImplicit();
9932 
9933   CurContext = PrevDC;
9934 
9935   AddKnownFunctionAttributes(FD);
9936 
9937   return FD;
9938 }
9939 
9940 /// \brief Adds any function attributes that we know a priori based on
9941 /// the declaration of this function.
9942 ///
9943 /// These attributes can apply both to implicitly-declared builtins
9944 /// (like __builtin___printf_chk) or to library-declared functions
9945 /// like NSLog or printf.
9946 ///
9947 /// We need to check for duplicate attributes both here and where user-written
9948 /// attributes are applied to declarations.
9949 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9950   if (FD->isInvalidDecl())
9951     return;
9952 
9953   // If this is a built-in function, map its builtin attributes to
9954   // actual attributes.
9955   if (unsigned BuiltinID = FD->getBuiltinID()) {
9956     // Handle printf-formatting attributes.
9957     unsigned FormatIdx;
9958     bool HasVAListArg;
9959     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
9960       if (!FD->getAttr<FormatAttr>()) {
9961         const char *fmt = "printf";
9962         unsigned int NumParams = FD->getNumParams();
9963         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
9964             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
9965           fmt = "NSString";
9966         FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9967                                                &Context.Idents.get(fmt),
9968                                                FormatIdx+1,
9969                                                HasVAListArg ? 0 : FormatIdx+2));
9970       }
9971     }
9972     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
9973                                              HasVAListArg)) {
9974      if (!FD->getAttr<FormatAttr>())
9975        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9976                                               &Context.Idents.get("scanf"),
9977                                               FormatIdx+1,
9978                                               HasVAListArg ? 0 : FormatIdx+2));
9979     }
9980 
9981     // Mark const if we don't care about errno and that is the only
9982     // thing preventing the function from being const. This allows
9983     // IRgen to use LLVM intrinsics for such functions.
9984     if (!getLangOpts().MathErrno &&
9985         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
9986       if (!FD->getAttr<ConstAttr>())
9987         FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
9988     }
9989 
9990     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
9991         !FD->getAttr<ReturnsTwiceAttr>())
9992       FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
9993     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
9994       FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
9995     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
9996       FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
9997   }
9998 
9999   IdentifierInfo *Name = FD->getIdentifier();
10000   if (!Name)
10001     return;
10002   if ((!getLangOpts().CPlusPlus &&
10003        FD->getDeclContext()->isTranslationUnit()) ||
10004       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10005        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10006        LinkageSpecDecl::lang_c)) {
10007     // Okay: this could be a libc/libm/Objective-C function we know
10008     // about.
10009   } else
10010     return;
10011 
10012   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10013     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10014     // target-specific builtins, perhaps?
10015     if (!FD->getAttr<FormatAttr>())
10016       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
10017                                              &Context.Idents.get("printf"), 2,
10018                                              Name->isStr("vasprintf") ? 0 : 3));
10019   }
10020 
10021   if (Name->isStr("__CFStringMakeConstantString")) {
10022     // We already have a __builtin___CFStringMakeConstantString,
10023     // but builds that use -fno-constant-cfstrings don't go through that.
10024     if (!FD->getAttr<FormatArgAttr>())
10025       FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10026   }
10027 }
10028 
10029 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10030                                     TypeSourceInfo *TInfo) {
10031   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10032   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10033 
10034   if (!TInfo) {
10035     assert(D.isInvalidType() && "no declarator info for valid type");
10036     TInfo = Context.getTrivialTypeSourceInfo(T);
10037   }
10038 
10039   // Scope manipulation handled by caller.
10040   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10041                                            D.getLocStart(),
10042                                            D.getIdentifierLoc(),
10043                                            D.getIdentifier(),
10044                                            TInfo);
10045 
10046   // Bail out immediately if we have an invalid declaration.
10047   if (D.isInvalidType()) {
10048     NewTD->setInvalidDecl();
10049     return NewTD;
10050   }
10051 
10052   if (D.getDeclSpec().isModulePrivateSpecified()) {
10053     if (CurContext->isFunctionOrMethod())
10054       Diag(NewTD->getLocation(), diag::err_module_private_local)
10055         << 2 << NewTD->getDeclName()
10056         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10057         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10058     else
10059       NewTD->setModulePrivate();
10060   }
10061 
10062   // C++ [dcl.typedef]p8:
10063   //   If the typedef declaration defines an unnamed class (or
10064   //   enum), the first typedef-name declared by the declaration
10065   //   to be that class type (or enum type) is used to denote the
10066   //   class type (or enum type) for linkage purposes only.
10067   // We need to check whether the type was declared in the declaration.
10068   switch (D.getDeclSpec().getTypeSpecType()) {
10069   case TST_enum:
10070   case TST_struct:
10071   case TST_interface:
10072   case TST_union:
10073   case TST_class: {
10074     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10075 
10076     // Do nothing if the tag is not anonymous or already has an
10077     // associated typedef (from an earlier typedef in this decl group).
10078     if (tagFromDeclSpec->getIdentifier()) break;
10079     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10080 
10081     // A well-formed anonymous tag must always be a TUK_Definition.
10082     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10083 
10084     // The type must match the tag exactly;  no qualifiers allowed.
10085     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10086       break;
10087 
10088     // Otherwise, set this is the anon-decl typedef for the tag.
10089     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10090     break;
10091   }
10092 
10093   default:
10094     break;
10095   }
10096 
10097   return NewTD;
10098 }
10099 
10100 
10101 /// \brief Check that this is a valid underlying type for an enum declaration.
10102 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10103   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10104   QualType T = TI->getType();
10105 
10106   if (T->isDependentType())
10107     return false;
10108 
10109   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10110     if (BT->isInteger())
10111       return false;
10112 
10113   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10114   return true;
10115 }
10116 
10117 /// Check whether this is a valid redeclaration of a previous enumeration.
10118 /// \return true if the redeclaration was invalid.
10119 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10120                                   QualType EnumUnderlyingTy,
10121                                   const EnumDecl *Prev) {
10122   bool IsFixed = !EnumUnderlyingTy.isNull();
10123 
10124   if (IsScoped != Prev->isScoped()) {
10125     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10126       << Prev->isScoped();
10127     Diag(Prev->getLocation(), diag::note_previous_use);
10128     return true;
10129   }
10130 
10131   if (IsFixed && Prev->isFixed()) {
10132     if (!EnumUnderlyingTy->isDependentType() &&
10133         !Prev->getIntegerType()->isDependentType() &&
10134         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10135                                         Prev->getIntegerType())) {
10136       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10137         << EnumUnderlyingTy << Prev->getIntegerType();
10138       Diag(Prev->getLocation(), diag::note_previous_use);
10139       return true;
10140     }
10141   } else if (IsFixed != Prev->isFixed()) {
10142     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10143       << Prev->isFixed();
10144     Diag(Prev->getLocation(), diag::note_previous_use);
10145     return true;
10146   }
10147 
10148   return false;
10149 }
10150 
10151 /// \brief Get diagnostic %select index for tag kind for
10152 /// redeclaration diagnostic message.
10153 /// WARNING: Indexes apply to particular diagnostics only!
10154 ///
10155 /// \returns diagnostic %select index.
10156 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10157   switch (Tag) {
10158   case TTK_Struct: return 0;
10159   case TTK_Interface: return 1;
10160   case TTK_Class:  return 2;
10161   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10162   }
10163 }
10164 
10165 /// \brief Determine if tag kind is a class-key compatible with
10166 /// class for redeclaration (class, struct, or __interface).
10167 ///
10168 /// \returns true iff the tag kind is compatible.
10169 static bool isClassCompatTagKind(TagTypeKind Tag)
10170 {
10171   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10172 }
10173 
10174 /// \brief Determine whether a tag with a given kind is acceptable
10175 /// as a redeclaration of the given tag declaration.
10176 ///
10177 /// \returns true if the new tag kind is acceptable, false otherwise.
10178 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10179                                         TagTypeKind NewTag, bool isDefinition,
10180                                         SourceLocation NewTagLoc,
10181                                         const IdentifierInfo &Name) {
10182   // C++ [dcl.type.elab]p3:
10183   //   The class-key or enum keyword present in the
10184   //   elaborated-type-specifier shall agree in kind with the
10185   //   declaration to which the name in the elaborated-type-specifier
10186   //   refers. This rule also applies to the form of
10187   //   elaborated-type-specifier that declares a class-name or
10188   //   friend class since it can be construed as referring to the
10189   //   definition of the class. Thus, in any
10190   //   elaborated-type-specifier, the enum keyword shall be used to
10191   //   refer to an enumeration (7.2), the union class-key shall be
10192   //   used to refer to a union (clause 9), and either the class or
10193   //   struct class-key shall be used to refer to a class (clause 9)
10194   //   declared using the class or struct class-key.
10195   TagTypeKind OldTag = Previous->getTagKind();
10196   if (!isDefinition || !isClassCompatTagKind(NewTag))
10197     if (OldTag == NewTag)
10198       return true;
10199 
10200   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10201     // Warn about the struct/class tag mismatch.
10202     bool isTemplate = false;
10203     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10204       isTemplate = Record->getDescribedClassTemplate();
10205 
10206     if (!ActiveTemplateInstantiations.empty()) {
10207       // In a template instantiation, do not offer fix-its for tag mismatches
10208       // since they usually mess up the template instead of fixing the problem.
10209       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10210         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10211         << getRedeclDiagFromTagKind(OldTag);
10212       return true;
10213     }
10214 
10215     if (isDefinition) {
10216       // On definitions, check previous tags and issue a fix-it for each
10217       // one that doesn't match the current tag.
10218       if (Previous->getDefinition()) {
10219         // Don't suggest fix-its for redefinitions.
10220         return true;
10221       }
10222 
10223       bool previousMismatch = false;
10224       for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10225            E(Previous->redecls_end()); I != E; ++I) {
10226         if (I->getTagKind() != NewTag) {
10227           if (!previousMismatch) {
10228             previousMismatch = true;
10229             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10230               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10231               << getRedeclDiagFromTagKind(I->getTagKind());
10232           }
10233           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10234             << getRedeclDiagFromTagKind(NewTag)
10235             << FixItHint::CreateReplacement(I->getInnerLocStart(),
10236                  TypeWithKeyword::getTagTypeKindName(NewTag));
10237         }
10238       }
10239       return true;
10240     }
10241 
10242     // Check for a previous definition.  If current tag and definition
10243     // are same type, do nothing.  If no definition, but disagree with
10244     // with previous tag type, give a warning, but no fix-it.
10245     const TagDecl *Redecl = Previous->getDefinition() ?
10246                             Previous->getDefinition() : Previous;
10247     if (Redecl->getTagKind() == NewTag) {
10248       return true;
10249     }
10250 
10251     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10252       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10253       << getRedeclDiagFromTagKind(OldTag);
10254     Diag(Redecl->getLocation(), diag::note_previous_use);
10255 
10256     // If there is a previous defintion, suggest a fix-it.
10257     if (Previous->getDefinition()) {
10258         Diag(NewTagLoc, diag::note_struct_class_suggestion)
10259           << getRedeclDiagFromTagKind(Redecl->getTagKind())
10260           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10261                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10262     }
10263 
10264     return true;
10265   }
10266   return false;
10267 }
10268 
10269 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10270 /// former case, Name will be non-null.  In the later case, Name will be null.
10271 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10272 /// reference/declaration/definition of a tag.
10273 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10274                      SourceLocation KWLoc, CXXScopeSpec &SS,
10275                      IdentifierInfo *Name, SourceLocation NameLoc,
10276                      AttributeList *Attr, AccessSpecifier AS,
10277                      SourceLocation ModulePrivateLoc,
10278                      MultiTemplateParamsArg TemplateParameterLists,
10279                      bool &OwnedDecl, bool &IsDependent,
10280                      SourceLocation ScopedEnumKWLoc,
10281                      bool ScopedEnumUsesClassTag,
10282                      TypeResult UnderlyingType) {
10283   // If this is not a definition, it must have a name.
10284   IdentifierInfo *OrigName = Name;
10285   assert((Name != 0 || TUK == TUK_Definition) &&
10286          "Nameless record must be a definition!");
10287   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10288 
10289   OwnedDecl = false;
10290   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10291   bool ScopedEnum = ScopedEnumKWLoc.isValid();
10292 
10293   // FIXME: Check explicit specializations more carefully.
10294   bool isExplicitSpecialization = false;
10295   bool Invalid = false;
10296 
10297   // We only need to do this matching if we have template parameters
10298   // or a scope specifier, which also conveniently avoids this work
10299   // for non-C++ cases.
10300   if (TemplateParameterLists.size() > 0 ||
10301       (SS.isNotEmpty() && TUK != TUK_Reference)) {
10302     if (TemplateParameterList *TemplateParams =
10303             MatchTemplateParametersToScopeSpecifier(
10304                 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10305                 isExplicitSpecialization, Invalid)) {
10306       if (Kind == TTK_Enum) {
10307         Diag(KWLoc, diag::err_enum_template);
10308         return 0;
10309       }
10310 
10311       if (TemplateParams->size() > 0) {
10312         // This is a declaration or definition of a class template (which may
10313         // be a member of another template).
10314 
10315         if (Invalid)
10316           return 0;
10317 
10318         OwnedDecl = false;
10319         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
10320                                                SS, Name, NameLoc, Attr,
10321                                                TemplateParams, AS,
10322                                                ModulePrivateLoc,
10323                                                TemplateParameterLists.size()-1,
10324                                                TemplateParameterLists.data());
10325         return Result.get();
10326       } else {
10327         // The "template<>" header is extraneous.
10328         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10329           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10330         isExplicitSpecialization = true;
10331       }
10332     }
10333   }
10334 
10335   // Figure out the underlying type if this a enum declaration. We need to do
10336   // this early, because it's needed to detect if this is an incompatible
10337   // redeclaration.
10338   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10339 
10340   if (Kind == TTK_Enum) {
10341     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10342       // No underlying type explicitly specified, or we failed to parse the
10343       // type, default to int.
10344       EnumUnderlying = Context.IntTy.getTypePtr();
10345     else if (UnderlyingType.get()) {
10346       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10347       // integral type; any cv-qualification is ignored.
10348       TypeSourceInfo *TI = 0;
10349       GetTypeFromParser(UnderlyingType.get(), &TI);
10350       EnumUnderlying = TI;
10351 
10352       if (CheckEnumUnderlyingType(TI))
10353         // Recover by falling back to int.
10354         EnumUnderlying = Context.IntTy.getTypePtr();
10355 
10356       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
10357                                           UPPC_FixedUnderlyingType))
10358         EnumUnderlying = Context.IntTy.getTypePtr();
10359 
10360     } else if (getLangOpts().MicrosoftMode)
10361       // Microsoft enums are always of int type.
10362       EnumUnderlying = Context.IntTy.getTypePtr();
10363   }
10364 
10365   DeclContext *SearchDC = CurContext;
10366   DeclContext *DC = CurContext;
10367   bool isStdBadAlloc = false;
10368 
10369   RedeclarationKind Redecl = ForRedeclaration;
10370   if (TUK == TUK_Friend || TUK == TUK_Reference)
10371     Redecl = NotForRedeclaration;
10372 
10373   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
10374   bool FriendSawTagOutsideEnclosingNamespace = false;
10375   if (Name && SS.isNotEmpty()) {
10376     // We have a nested-name tag ('struct foo::bar').
10377 
10378     // Check for invalid 'foo::'.
10379     if (SS.isInvalid()) {
10380       Name = 0;
10381       goto CreateNewDecl;
10382     }
10383 
10384     // If this is a friend or a reference to a class in a dependent
10385     // context, don't try to make a decl for it.
10386     if (TUK == TUK_Friend || TUK == TUK_Reference) {
10387       DC = computeDeclContext(SS, false);
10388       if (!DC) {
10389         IsDependent = true;
10390         return 0;
10391       }
10392     } else {
10393       DC = computeDeclContext(SS, true);
10394       if (!DC) {
10395         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10396           << SS.getRange();
10397         return 0;
10398       }
10399     }
10400 
10401     if (RequireCompleteDeclContext(SS, DC))
10402       return 0;
10403 
10404     SearchDC = DC;
10405     // Look-up name inside 'foo::'.
10406     LookupQualifiedName(Previous, DC);
10407 
10408     if (Previous.isAmbiguous())
10409       return 0;
10410 
10411     if (Previous.empty()) {
10412       // Name lookup did not find anything. However, if the
10413       // nested-name-specifier refers to the current instantiation,
10414       // and that current instantiation has any dependent base
10415       // classes, we might find something at instantiation time: treat
10416       // this as a dependent elaborated-type-specifier.
10417       // But this only makes any sense for reference-like lookups.
10418       if (Previous.wasNotFoundInCurrentInstantiation() &&
10419           (TUK == TUK_Reference || TUK == TUK_Friend)) {
10420         IsDependent = true;
10421         return 0;
10422       }
10423 
10424       // A tag 'foo::bar' must already exist.
10425       Diag(NameLoc, diag::err_not_tag_in_scope)
10426         << Kind << Name << DC << SS.getRange();
10427       Name = 0;
10428       Invalid = true;
10429       goto CreateNewDecl;
10430     }
10431   } else if (Name) {
10432     // If this is a named struct, check to see if there was a previous forward
10433     // declaration or definition.
10434     // FIXME: We're looking into outer scopes here, even when we
10435     // shouldn't be. Doing so can result in ambiguities that we
10436     // shouldn't be diagnosing.
10437     LookupName(Previous, S);
10438 
10439     // When declaring or defining a tag, ignore ambiguities introduced
10440     // by types using'ed into this scope.
10441     if (Previous.isAmbiguous() &&
10442         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
10443       LookupResult::Filter F = Previous.makeFilter();
10444       while (F.hasNext()) {
10445         NamedDecl *ND = F.next();
10446         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10447           F.erase();
10448       }
10449       F.done();
10450     }
10451 
10452     // C++11 [namespace.memdef]p3:
10453     //   If the name in a friend declaration is neither qualified nor
10454     //   a template-id and the declaration is a function or an
10455     //   elaborated-type-specifier, the lookup to determine whether
10456     //   the entity has been previously declared shall not consider
10457     //   any scopes outside the innermost enclosing namespace.
10458     //
10459     // Does it matter that this should be by scope instead of by
10460     // semantic context?
10461     if (!Previous.empty() && TUK == TUK_Friend) {
10462       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10463       LookupResult::Filter F = Previous.makeFilter();
10464       while (F.hasNext()) {
10465         NamedDecl *ND = F.next();
10466         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10467         if (DC->isFileContext() &&
10468             !EnclosingNS->Encloses(ND->getDeclContext())) {
10469           F.erase();
10470           FriendSawTagOutsideEnclosingNamespace = true;
10471         }
10472       }
10473       F.done();
10474     }
10475 
10476     // Note:  there used to be some attempt at recovery here.
10477     if (Previous.isAmbiguous())
10478       return 0;
10479 
10480     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
10481       // FIXME: This makes sure that we ignore the contexts associated
10482       // with C structs, unions, and enums when looking for a matching
10483       // tag declaration or definition. See the similar lookup tweak
10484       // in Sema::LookupName; is there a better way to deal with this?
10485       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10486         SearchDC = SearchDC->getParent();
10487     }
10488   } else if (S->isFunctionPrototypeScope()) {
10489     // If this is an enum declaration in function prototype scope, set its
10490     // initial context to the translation unit.
10491     // FIXME: [citation needed]
10492     SearchDC = Context.getTranslationUnitDecl();
10493   }
10494 
10495   if (Previous.isSingleResult() &&
10496       Previous.getFoundDecl()->isTemplateParameter()) {
10497     // Maybe we will complain about the shadowed template parameter.
10498     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
10499     // Just pretend that we didn't see the previous declaration.
10500     Previous.clear();
10501   }
10502 
10503   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
10504       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
10505     // This is a declaration of or a reference to "std::bad_alloc".
10506     isStdBadAlloc = true;
10507 
10508     if (Previous.empty() && StdBadAlloc) {
10509       // std::bad_alloc has been implicitly declared (but made invisible to
10510       // name lookup). Fill in this implicit declaration as the previous
10511       // declaration, so that the declarations get chained appropriately.
10512       Previous.addDecl(getStdBadAlloc());
10513     }
10514   }
10515 
10516   // If we didn't find a previous declaration, and this is a reference
10517   // (or friend reference), move to the correct scope.  In C++, we
10518   // also need to do a redeclaration lookup there, just in case
10519   // there's a shadow friend decl.
10520   if (Name && Previous.empty() &&
10521       (TUK == TUK_Reference || TUK == TUK_Friend)) {
10522     if (Invalid) goto CreateNewDecl;
10523     assert(SS.isEmpty());
10524 
10525     if (TUK == TUK_Reference) {
10526       // C++ [basic.scope.pdecl]p5:
10527       //   -- for an elaborated-type-specifier of the form
10528       //
10529       //          class-key identifier
10530       //
10531       //      if the elaborated-type-specifier is used in the
10532       //      decl-specifier-seq or parameter-declaration-clause of a
10533       //      function defined in namespace scope, the identifier is
10534       //      declared as a class-name in the namespace that contains
10535       //      the declaration; otherwise, except as a friend
10536       //      declaration, the identifier is declared in the smallest
10537       //      non-class, non-function-prototype scope that contains the
10538       //      declaration.
10539       //
10540       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10541       // C structs and unions.
10542       //
10543       // It is an error in C++ to declare (rather than define) an enum
10544       // type, including via an elaborated type specifier.  We'll
10545       // diagnose that later; for now, declare the enum in the same
10546       // scope as we would have picked for any other tag type.
10547       //
10548       // GNU C also supports this behavior as part of its incomplete
10549       // enum types extension, while GNU C++ does not.
10550       //
10551       // Find the context where we'll be declaring the tag.
10552       // FIXME: We would like to maintain the current DeclContext as the
10553       // lexical context,
10554       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
10555         SearchDC = SearchDC->getParent();
10556 
10557       // Find the scope where we'll be declaring the tag.
10558       while (S->isClassScope() ||
10559              (getLangOpts().CPlusPlus &&
10560               S->isFunctionPrototypeScope()) ||
10561              ((S->getFlags() & Scope::DeclScope) == 0) ||
10562              (S->getEntity() && S->getEntity()->isTransparentContext()))
10563         S = S->getParent();
10564     } else {
10565       assert(TUK == TUK_Friend);
10566       // C++ [namespace.memdef]p3:
10567       //   If a friend declaration in a non-local class first declares a
10568       //   class or function, the friend class or function is a member of
10569       //   the innermost enclosing namespace.
10570       SearchDC = SearchDC->getEnclosingNamespaceContext();
10571     }
10572 
10573     // In C++, we need to do a redeclaration lookup to properly
10574     // diagnose some problems.
10575     if (getLangOpts().CPlusPlus) {
10576       Previous.setRedeclarationKind(ForRedeclaration);
10577       LookupQualifiedName(Previous, SearchDC);
10578     }
10579   }
10580 
10581   if (!Previous.empty()) {
10582     NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
10583 
10584     // It's okay to have a tag decl in the same scope as a typedef
10585     // which hides a tag decl in the same scope.  Finding this
10586     // insanity with a redeclaration lookup can only actually happen
10587     // in C++.
10588     //
10589     // This is also okay for elaborated-type-specifiers, which is
10590     // technically forbidden by the current standard but which is
10591     // okay according to the likely resolution of an open issue;
10592     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
10593     if (getLangOpts().CPlusPlus) {
10594       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10595         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10596           TagDecl *Tag = TT->getDecl();
10597           if (Tag->getDeclName() == Name &&
10598               Tag->getDeclContext()->getRedeclContext()
10599                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
10600             PrevDecl = Tag;
10601             Previous.clear();
10602             Previous.addDecl(Tag);
10603             Previous.resolveKind();
10604           }
10605         }
10606       }
10607     }
10608 
10609     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
10610       // If this is a use of a previous tag, or if the tag is already declared
10611       // in the same scope (so that the definition/declaration completes or
10612       // rementions the tag), reuse the decl.
10613       if (TUK == TUK_Reference || TUK == TUK_Friend ||
10614           isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
10615         // Make sure that this wasn't declared as an enum and now used as a
10616         // struct or something similar.
10617         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10618                                           TUK == TUK_Definition, KWLoc,
10619                                           *Name)) {
10620           bool SafeToContinue
10621             = (PrevTagDecl->getTagKind() != TTK_Enum &&
10622                Kind != TTK_Enum);
10623           if (SafeToContinue)
10624             Diag(KWLoc, diag::err_use_with_wrong_tag)
10625               << Name
10626               << FixItHint::CreateReplacement(SourceRange(KWLoc),
10627                                               PrevTagDecl->getKindName());
10628           else
10629             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
10630           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
10631 
10632           if (SafeToContinue)
10633             Kind = PrevTagDecl->getTagKind();
10634           else {
10635             // Recover by making this an anonymous redefinition.
10636             Name = 0;
10637             Previous.clear();
10638             Invalid = true;
10639           }
10640         }
10641 
10642         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10643           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10644 
10645           // If this is an elaborated-type-specifier for a scoped enumeration,
10646           // the 'class' keyword is not necessary and not permitted.
10647           if (TUK == TUK_Reference || TUK == TUK_Friend) {
10648             if (ScopedEnum)
10649               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10650                 << PrevEnum->isScoped()
10651                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10652             return PrevTagDecl;
10653           }
10654 
10655           QualType EnumUnderlyingTy;
10656           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10657             EnumUnderlyingTy = TI->getType();
10658           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10659             EnumUnderlyingTy = QualType(T, 0);
10660 
10661           // All conflicts with previous declarations are recovered by
10662           // returning the previous declaration, unless this is a definition,
10663           // in which case we want the caller to bail out.
10664           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10665                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
10666             return TUK == TUK_Declaration ? PrevTagDecl : 0;
10667         }
10668 
10669         // C++11 [class.mem]p1:
10670         //   A member shall not be declared twice in the member-specification,
10671         //   except that a nested class or member class template can be declared
10672         //   and then later defined.
10673         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10674             S->isDeclScope(PrevDecl)) {
10675           Diag(NameLoc, diag::ext_member_redeclared);
10676           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10677         }
10678 
10679         if (!Invalid) {
10680           // If this is a use, just return the declaration we found.
10681 
10682           // FIXME: In the future, return a variant or some other clue
10683           // for the consumer of this Decl to know it doesn't own it.
10684           // For our current ASTs this shouldn't be a problem, but will
10685           // need to be changed with DeclGroups.
10686           if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
10687                getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
10688             return PrevTagDecl;
10689 
10690           // Diagnose attempts to redefine a tag.
10691           if (TUK == TUK_Definition) {
10692             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
10693               // If we're defining a specialization and the previous definition
10694               // is from an implicit instantiation, don't emit an error
10695               // here; we'll catch this in the general case below.
10696               bool IsExplicitSpecializationAfterInstantiation = false;
10697               if (isExplicitSpecialization) {
10698                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10699                   IsExplicitSpecializationAfterInstantiation =
10700                     RD->getTemplateSpecializationKind() !=
10701                     TSK_ExplicitSpecialization;
10702                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10703                   IsExplicitSpecializationAfterInstantiation =
10704                     ED->getTemplateSpecializationKind() !=
10705                     TSK_ExplicitSpecialization;
10706               }
10707 
10708               if (!IsExplicitSpecializationAfterInstantiation) {
10709                 // A redeclaration in function prototype scope in C isn't
10710                 // visible elsewhere, so merely issue a warning.
10711                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
10712                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10713                 else
10714                   Diag(NameLoc, diag::err_redefinition) << Name;
10715                 Diag(Def->getLocation(), diag::note_previous_definition);
10716                 // If this is a redefinition, recover by making this
10717                 // struct be anonymous, which will make any later
10718                 // references get the previous definition.
10719                 Name = 0;
10720                 Previous.clear();
10721                 Invalid = true;
10722               }
10723             } else {
10724               // If the type is currently being defined, complain
10725               // about a nested redefinition.
10726               const TagType *Tag
10727                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
10728               if (Tag->isBeingDefined()) {
10729                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
10730                 Diag(PrevTagDecl->getLocation(),
10731                      diag::note_previous_definition);
10732                 Name = 0;
10733                 Previous.clear();
10734                 Invalid = true;
10735               }
10736             }
10737 
10738             // Okay, this is definition of a previously declared or referenced
10739             // tag PrevDecl. We're going to create a new Decl for it.
10740           }
10741         }
10742         // If we get here we have (another) forward declaration or we
10743         // have a definition.  Just create a new decl.
10744 
10745       } else {
10746         // If we get here, this is a definition of a new tag type in a nested
10747         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
10748         // new decl/type.  We set PrevDecl to NULL so that the entities
10749         // have distinct types.
10750         Previous.clear();
10751       }
10752       // If we get here, we're going to create a new Decl. If PrevDecl
10753       // is non-NULL, it's a definition of the tag declared by
10754       // PrevDecl. If it's NULL, we have a new definition.
10755 
10756 
10757     // Otherwise, PrevDecl is not a tag, but was found with tag
10758     // lookup.  This is only actually possible in C++, where a few
10759     // things like templates still live in the tag namespace.
10760     } else {
10761       // Use a better diagnostic if an elaborated-type-specifier
10762       // found the wrong kind of type on the first
10763       // (non-redeclaration) lookup.
10764       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10765           !Previous.isForRedeclaration()) {
10766         unsigned Kind = 0;
10767         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10768         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10769         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10770         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10771         Diag(PrevDecl->getLocation(), diag::note_declared_at);
10772         Invalid = true;
10773 
10774       // Otherwise, only diagnose if the declaration is in scope.
10775       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10776                                 isExplicitSpecialization)) {
10777         // do nothing
10778 
10779       // Diagnose implicit declarations introduced by elaborated types.
10780       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10781         unsigned Kind = 0;
10782         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10783         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10784         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10785         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10786         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10787         Invalid = true;
10788 
10789       // Otherwise it's a declaration.  Call out a particularly common
10790       // case here.
10791       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10792         unsigned Kind = 0;
10793         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
10794         Diag(NameLoc, diag::err_tag_definition_of_typedef)
10795           << Name << Kind << TND->getUnderlyingType();
10796         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10797         Invalid = true;
10798 
10799       // Otherwise, diagnose.
10800       } else {
10801         // The tag name clashes with something else in the target scope,
10802         // issue an error and recover by making this tag be anonymous.
10803         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
10804         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10805         Name = 0;
10806         Invalid = true;
10807       }
10808 
10809       // The existing declaration isn't relevant to us; we're in a
10810       // new scope, so clear out the previous declaration.
10811       Previous.clear();
10812     }
10813   }
10814 
10815 CreateNewDecl:
10816 
10817   TagDecl *PrevDecl = 0;
10818   if (Previous.isSingleResult())
10819     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10820 
10821   // If there is an identifier, use the location of the identifier as the
10822   // location of the decl, otherwise use the location of the struct/union
10823   // keyword.
10824   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
10825 
10826   // Otherwise, create a new declaration. If there is a previous
10827   // declaration of the same entity, the two will be linked via
10828   // PrevDecl.
10829   TagDecl *New;
10830 
10831   bool IsForwardReference = false;
10832   if (Kind == TTK_Enum) {
10833     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10834     // enum X { A, B, C } D;    D should chain to X.
10835     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
10836                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
10837                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
10838     // If this is an undefined enum, warn.
10839     if (TUK != TUK_Definition && !Invalid) {
10840       TagDecl *Def;
10841       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10842           cast<EnumDecl>(New)->isFixed()) {
10843         // C++0x: 7.2p2: opaque-enum-declaration.
10844         // Conflicts are diagnosed above. Do nothing.
10845       }
10846       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
10847         Diag(Loc, diag::ext_forward_ref_enum_def)
10848           << New;
10849         Diag(Def->getLocation(), diag::note_previous_definition);
10850       } else {
10851         unsigned DiagID = diag::ext_forward_ref_enum;
10852         if (getLangOpts().MicrosoftMode)
10853           DiagID = diag::ext_ms_forward_ref_enum;
10854         else if (getLangOpts().CPlusPlus)
10855           DiagID = diag::err_forward_ref_enum;
10856         Diag(Loc, DiagID);
10857 
10858         // If this is a forward-declared reference to an enumeration, make a
10859         // note of it; we won't actually be introducing the declaration into
10860         // the declaration context.
10861         if (TUK == TUK_Reference)
10862           IsForwardReference = true;
10863       }
10864     }
10865 
10866     if (EnumUnderlying) {
10867       EnumDecl *ED = cast<EnumDecl>(New);
10868       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10869         ED->setIntegerTypeSourceInfo(TI);
10870       else
10871         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10872       ED->setPromotionType(ED->getIntegerType());
10873     }
10874 
10875   } else {
10876     // struct/union/class
10877 
10878     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10879     // struct X { int A; } D;    D should chain to X.
10880     if (getLangOpts().CPlusPlus) {
10881       // FIXME: Look for a way to use RecordDecl for simple structs.
10882       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10883                                   cast_or_null<CXXRecordDecl>(PrevDecl));
10884 
10885       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
10886         StdBadAlloc = cast<CXXRecordDecl>(New);
10887     } else
10888       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10889                                cast_or_null<RecordDecl>(PrevDecl));
10890   }
10891 
10892   // Maybe add qualifier info.
10893   if (SS.isNotEmpty()) {
10894     if (SS.isSet()) {
10895       // If this is either a declaration or a definition, check the
10896       // nested-name-specifier against the current context. We don't do this
10897       // for explicit specializations, because they have similar checking
10898       // (with more specific diagnostics) in the call to
10899       // CheckMemberSpecialization, below.
10900       if (!isExplicitSpecialization &&
10901           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10902           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10903         Invalid = true;
10904 
10905       New->setQualifierInfo(SS.getWithLocInContext(Context));
10906       if (TemplateParameterLists.size() > 0) {
10907         New->setTemplateParameterListsInfo(Context,
10908                                            TemplateParameterLists.size(),
10909                                            TemplateParameterLists.data());
10910       }
10911     }
10912     else
10913       Invalid = true;
10914   }
10915 
10916   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10917     // Add alignment attributes if necessary; these attributes are checked when
10918     // the ASTContext lays out the structure.
10919     //
10920     // It is important for implementing the correct semantics that this
10921     // happen here (in act on tag decl). The #pragma pack stack is
10922     // maintained as a result of parser callbacks which can occur at
10923     // many points during the parsing of a struct declaration (because
10924     // the #pragma tokens are effectively skipped over during the
10925     // parsing of the struct).
10926     if (TUK == TUK_Definition) {
10927       AddAlignmentAttributesForRecord(RD);
10928       AddMsStructLayoutForRecord(RD);
10929     }
10930   }
10931 
10932   if (ModulePrivateLoc.isValid()) {
10933     if (isExplicitSpecialization)
10934       Diag(New->getLocation(), diag::err_module_private_specialization)
10935         << 2
10936         << FixItHint::CreateRemoval(ModulePrivateLoc);
10937     // __module_private__ does not apply to local classes. However, we only
10938     // diagnose this as an error when the declaration specifiers are
10939     // freestanding. Here, we just ignore the __module_private__.
10940     else if (!SearchDC->isFunctionOrMethod())
10941       New->setModulePrivate();
10942   }
10943 
10944   // If this is a specialization of a member class (of a class template),
10945   // check the specialization.
10946   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
10947     Invalid = true;
10948 
10949   if (Invalid)
10950     New->setInvalidDecl();
10951 
10952   if (Attr)
10953     ProcessDeclAttributeList(S, New, Attr);
10954 
10955   // If we're declaring or defining a tag in function prototype scope
10956   // in C, note that this type can only be used within the function.
10957   if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
10958     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
10959 
10960   // Set the lexical context. If the tag has a C++ scope specifier, the
10961   // lexical context will be different from the semantic context.
10962   New->setLexicalDeclContext(CurContext);
10963 
10964   // Mark this as a friend decl if applicable.
10965   // In Microsoft mode, a friend declaration also acts as a forward
10966   // declaration so we always pass true to setObjectOfFriendDecl to make
10967   // the tag name visible.
10968   if (TUK == TUK_Friend)
10969     New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
10970                                getLangOpts().MicrosoftExt);
10971 
10972   // Set the access specifier.
10973   if (!Invalid && SearchDC->isRecord())
10974     SetMemberAccessSpecifier(New, PrevDecl, AS);
10975 
10976   if (TUK == TUK_Definition)
10977     New->startDefinition();
10978 
10979   // If this has an identifier, add it to the scope stack.
10980   if (TUK == TUK_Friend) {
10981     // We might be replacing an existing declaration in the lookup tables;
10982     // if so, borrow its access specifier.
10983     if (PrevDecl)
10984       New->setAccess(PrevDecl->getAccess());
10985 
10986     DeclContext *DC = New->getDeclContext()->getRedeclContext();
10987     DC->makeDeclVisibleInContext(New);
10988     if (Name) // can be null along some error paths
10989       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10990         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
10991   } else if (Name) {
10992     S = getNonFieldDeclScope(S);
10993     PushOnScopeChains(New, S, !IsForwardReference);
10994     if (IsForwardReference)
10995       SearchDC->makeDeclVisibleInContext(New);
10996 
10997   } else {
10998     CurContext->addDecl(New);
10999   }
11000 
11001   // If this is the C FILE type, notify the AST context.
11002   if (IdentifierInfo *II = New->getIdentifier())
11003     if (!New->isInvalidDecl() &&
11004         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11005         II->isStr("FILE"))
11006       Context.setFILEDecl(New);
11007 
11008   // If we were in function prototype scope (and not in C++ mode), add this
11009   // tag to the list of decls to inject into the function definition scope.
11010   if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
11011       InFunctionDeclarator && Name)
11012     DeclsInPrototypeScope.push_back(New);
11013 
11014   if (PrevDecl)
11015     mergeDeclAttributes(New, PrevDecl);
11016 
11017   // If there's a #pragma GCC visibility in scope, set the visibility of this
11018   // record.
11019   AddPushedVisibilityAttribute(New);
11020 
11021   OwnedDecl = true;
11022   // In C++, don't return an invalid declaration. We can't recover well from
11023   // the cases where we make the type anonymous.
11024   return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
11025 }
11026 
11027 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11028   AdjustDeclIfTemplate(TagD);
11029   TagDecl *Tag = cast<TagDecl>(TagD);
11030 
11031   // Enter the tag context.
11032   PushDeclContext(S, Tag);
11033 
11034   ActOnDocumentableDecl(TagD);
11035 
11036   // If there's a #pragma GCC visibility in scope, set the visibility of this
11037   // record.
11038   AddPushedVisibilityAttribute(Tag);
11039 }
11040 
11041 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11042   assert(isa<ObjCContainerDecl>(IDecl) &&
11043          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11044   DeclContext *OCD = cast<DeclContext>(IDecl);
11045   assert(getContainingDC(OCD) == CurContext &&
11046       "The next DeclContext should be lexically contained in the current one.");
11047   CurContext = OCD;
11048   return IDecl;
11049 }
11050 
11051 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11052                                            SourceLocation FinalLoc,
11053                                            bool IsFinalSpelledSealed,
11054                                            SourceLocation LBraceLoc) {
11055   AdjustDeclIfTemplate(TagD);
11056   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11057 
11058   FieldCollector->StartClass();
11059 
11060   if (!Record->getIdentifier())
11061     return;
11062 
11063   if (FinalLoc.isValid())
11064     Record->addAttr(new (Context)
11065                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11066 
11067   // C++ [class]p2:
11068   //   [...] The class-name is also inserted into the scope of the
11069   //   class itself; this is known as the injected-class-name. For
11070   //   purposes of access checking, the injected-class-name is treated
11071   //   as if it were a public member name.
11072   CXXRecordDecl *InjectedClassName
11073     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11074                             Record->getLocStart(), Record->getLocation(),
11075                             Record->getIdentifier(),
11076                             /*PrevDecl=*/0,
11077                             /*DelayTypeCreation=*/true);
11078   Context.getTypeDeclType(InjectedClassName, Record);
11079   InjectedClassName->setImplicit();
11080   InjectedClassName->setAccess(AS_public);
11081   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11082       InjectedClassName->setDescribedClassTemplate(Template);
11083   PushOnScopeChains(InjectedClassName, S);
11084   assert(InjectedClassName->isInjectedClassName() &&
11085          "Broken injected-class-name");
11086 }
11087 
11088 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11089                                     SourceLocation RBraceLoc) {
11090   AdjustDeclIfTemplate(TagD);
11091   TagDecl *Tag = cast<TagDecl>(TagD);
11092   Tag->setRBraceLoc(RBraceLoc);
11093 
11094   // Make sure we "complete" the definition even it is invalid.
11095   if (Tag->isBeingDefined()) {
11096     assert(Tag->isInvalidDecl() && "We should already have completed it");
11097     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11098       RD->completeDefinition();
11099   }
11100 
11101   if (isa<CXXRecordDecl>(Tag))
11102     FieldCollector->FinishClass();
11103 
11104   // Exit this scope of this tag's definition.
11105   PopDeclContext();
11106 
11107   if (getCurLexicalContext()->isObjCContainer() &&
11108       Tag->getDeclContext()->isFileContext())
11109     Tag->setTopLevelDeclInObjCContainer();
11110 
11111   // Notify the consumer that we've defined a tag.
11112   if (!Tag->isInvalidDecl())
11113     Consumer.HandleTagDeclDefinition(Tag);
11114 }
11115 
11116 void Sema::ActOnObjCContainerFinishDefinition() {
11117   // Exit this scope of this interface definition.
11118   PopDeclContext();
11119 }
11120 
11121 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
11122   assert(DC == CurContext && "Mismatch of container contexts");
11123   OriginalLexicalContext = DC;
11124   ActOnObjCContainerFinishDefinition();
11125 }
11126 
11127 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11128   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
11129   OriginalLexicalContext = 0;
11130 }
11131 
11132 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11133   AdjustDeclIfTemplate(TagD);
11134   TagDecl *Tag = cast<TagDecl>(TagD);
11135   Tag->setInvalidDecl();
11136 
11137   // Make sure we "complete" the definition even it is invalid.
11138   if (Tag->isBeingDefined()) {
11139     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11140       RD->completeDefinition();
11141   }
11142 
11143   // We're undoing ActOnTagStartDefinition here, not
11144   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11145   // the FieldCollector.
11146 
11147   PopDeclContext();
11148 }
11149 
11150 // Note that FieldName may be null for anonymous bitfields.
11151 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11152                                 IdentifierInfo *FieldName,
11153                                 QualType FieldTy, bool IsMsStruct,
11154                                 Expr *BitWidth, bool *ZeroWidth) {
11155   // Default to true; that shouldn't confuse checks for emptiness
11156   if (ZeroWidth)
11157     *ZeroWidth = true;
11158 
11159   // C99 6.7.2.1p4 - verify the field type.
11160   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11161   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11162     // Handle incomplete types with specific error.
11163     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11164       return ExprError();
11165     if (FieldName)
11166       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11167         << FieldName << FieldTy << BitWidth->getSourceRange();
11168     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11169       << FieldTy << BitWidth->getSourceRange();
11170   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11171                                              UPPC_BitFieldWidth))
11172     return ExprError();
11173 
11174   // If the bit-width is type- or value-dependent, don't try to check
11175   // it now.
11176   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11177     return Owned(BitWidth);
11178 
11179   llvm::APSInt Value;
11180   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11181   if (ICE.isInvalid())
11182     return ICE;
11183   BitWidth = ICE.take();
11184 
11185   if (Value != 0 && ZeroWidth)
11186     *ZeroWidth = false;
11187 
11188   // Zero-width bitfield is ok for anonymous field.
11189   if (Value == 0 && FieldName)
11190     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11191 
11192   if (Value.isSigned() && Value.isNegative()) {
11193     if (FieldName)
11194       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11195                << FieldName << Value.toString(10);
11196     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11197       << Value.toString(10);
11198   }
11199 
11200   if (!FieldTy->isDependentType()) {
11201     uint64_t TypeSize = Context.getTypeSize(FieldTy);
11202     if (Value.getZExtValue() > TypeSize) {
11203       if (!getLangOpts().CPlusPlus || IsMsStruct) {
11204         if (FieldName)
11205           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11206             << FieldName << (unsigned)Value.getZExtValue()
11207             << (unsigned)TypeSize;
11208 
11209         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11210           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11211       }
11212 
11213       if (FieldName)
11214         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11215           << FieldName << (unsigned)Value.getZExtValue()
11216           << (unsigned)TypeSize;
11217       else
11218         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11219           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11220     }
11221   }
11222 
11223   return Owned(BitWidth);
11224 }
11225 
11226 /// ActOnField - Each field of a C struct/union is passed into this in order
11227 /// to create a FieldDecl object for it.
11228 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11229                        Declarator &D, Expr *BitfieldWidth) {
11230   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11231                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11232                                /*InitStyle=*/ICIS_NoInit, AS_public);
11233   return Res;
11234 }
11235 
11236 /// HandleField - Analyze a field of a C struct or a C++ data member.
11237 ///
11238 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11239                              SourceLocation DeclStart,
11240                              Declarator &D, Expr *BitWidth,
11241                              InClassInitStyle InitStyle,
11242                              AccessSpecifier AS) {
11243   IdentifierInfo *II = D.getIdentifier();
11244   SourceLocation Loc = DeclStart;
11245   if (II) Loc = D.getIdentifierLoc();
11246 
11247   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11248   QualType T = TInfo->getType();
11249   if (getLangOpts().CPlusPlus) {
11250     CheckExtraCXXDefaultArguments(D);
11251 
11252     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11253                                         UPPC_DataMemberType)) {
11254       D.setInvalidType();
11255       T = Context.IntTy;
11256       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11257     }
11258   }
11259 
11260   // TR 18037 does not allow fields to be declared with address spaces.
11261   if (T.getQualifiers().hasAddressSpace()) {
11262     Diag(Loc, diag::err_field_with_address_space);
11263     D.setInvalidType();
11264   }
11265 
11266   // OpenCL 1.2 spec, s6.9 r:
11267   // The event type cannot be used to declare a structure or union field.
11268   if (LangOpts.OpenCL && T->isEventT()) {
11269     Diag(Loc, diag::err_event_t_struct_field);
11270     D.setInvalidType();
11271   }
11272 
11273   DiagnoseFunctionSpecifiers(D.getDeclSpec());
11274 
11275   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11276     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11277          diag::err_invalid_thread)
11278       << DeclSpec::getSpecifierName(TSCS);
11279 
11280   // Check to see if this name was declared as a member previously
11281   NamedDecl *PrevDecl = 0;
11282   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11283   LookupName(Previous, S);
11284   switch (Previous.getResultKind()) {
11285     case LookupResult::Found:
11286     case LookupResult::FoundUnresolvedValue:
11287       PrevDecl = Previous.getAsSingle<NamedDecl>();
11288       break;
11289 
11290     case LookupResult::FoundOverloaded:
11291       PrevDecl = Previous.getRepresentativeDecl();
11292       break;
11293 
11294     case LookupResult::NotFound:
11295     case LookupResult::NotFoundInCurrentInstantiation:
11296     case LookupResult::Ambiguous:
11297       break;
11298   }
11299   Previous.suppressDiagnostics();
11300 
11301   if (PrevDecl && PrevDecl->isTemplateParameter()) {
11302     // Maybe we will complain about the shadowed template parameter.
11303     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11304     // Just pretend that we didn't see the previous declaration.
11305     PrevDecl = 0;
11306   }
11307 
11308   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11309     PrevDecl = 0;
11310 
11311   bool Mutable
11312     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
11313   SourceLocation TSSL = D.getLocStart();
11314   FieldDecl *NewFD
11315     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
11316                      TSSL, AS, PrevDecl, &D);
11317 
11318   if (NewFD->isInvalidDecl())
11319     Record->setInvalidDecl();
11320 
11321   if (D.getDeclSpec().isModulePrivateSpecified())
11322     NewFD->setModulePrivate();
11323 
11324   if (NewFD->isInvalidDecl() && PrevDecl) {
11325     // Don't introduce NewFD into scope; there's already something
11326     // with the same name in the same scope.
11327   } else if (II) {
11328     PushOnScopeChains(NewFD, S);
11329   } else
11330     Record->addDecl(NewFD);
11331 
11332   return NewFD;
11333 }
11334 
11335 /// \brief Build a new FieldDecl and check its well-formedness.
11336 ///
11337 /// This routine builds a new FieldDecl given the fields name, type,
11338 /// record, etc. \p PrevDecl should refer to any previous declaration
11339 /// with the same name and in the same scope as the field to be
11340 /// created.
11341 ///
11342 /// \returns a new FieldDecl.
11343 ///
11344 /// \todo The Declarator argument is a hack. It will be removed once
11345 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
11346                                 TypeSourceInfo *TInfo,
11347                                 RecordDecl *Record, SourceLocation Loc,
11348                                 bool Mutable, Expr *BitWidth,
11349                                 InClassInitStyle InitStyle,
11350                                 SourceLocation TSSL,
11351                                 AccessSpecifier AS, NamedDecl *PrevDecl,
11352                                 Declarator *D) {
11353   IdentifierInfo *II = Name.getAsIdentifierInfo();
11354   bool InvalidDecl = false;
11355   if (D) InvalidDecl = D->isInvalidType();
11356 
11357   // If we receive a broken type, recover by assuming 'int' and
11358   // marking this declaration as invalid.
11359   if (T.isNull()) {
11360     InvalidDecl = true;
11361     T = Context.IntTy;
11362   }
11363 
11364   QualType EltTy = Context.getBaseElementType(T);
11365   if (!EltTy->isDependentType()) {
11366     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11367       // Fields of incomplete type force their record to be invalid.
11368       Record->setInvalidDecl();
11369       InvalidDecl = true;
11370     } else {
11371       NamedDecl *Def;
11372       EltTy->isIncompleteType(&Def);
11373       if (Def && Def->isInvalidDecl()) {
11374         Record->setInvalidDecl();
11375         InvalidDecl = true;
11376       }
11377     }
11378   }
11379 
11380   // OpenCL v1.2 s6.9.c: bitfields are not supported.
11381   if (BitWidth && getLangOpts().OpenCL) {
11382     Diag(Loc, diag::err_opencl_bitfields);
11383     InvalidDecl = true;
11384   }
11385 
11386   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11387   // than a variably modified type.
11388   if (!InvalidDecl && T->isVariablyModifiedType()) {
11389     bool SizeIsNegative;
11390     llvm::APSInt Oversized;
11391 
11392     TypeSourceInfo *FixedTInfo =
11393       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11394                                                     SizeIsNegative,
11395                                                     Oversized);
11396     if (FixedTInfo) {
11397       Diag(Loc, diag::warn_illegal_constant_array_size);
11398       TInfo = FixedTInfo;
11399       T = FixedTInfo->getType();
11400     } else {
11401       if (SizeIsNegative)
11402         Diag(Loc, diag::err_typecheck_negative_array_size);
11403       else if (Oversized.getBoolValue())
11404         Diag(Loc, diag::err_array_too_large)
11405           << Oversized.toString(10);
11406       else
11407         Diag(Loc, diag::err_typecheck_field_variable_size);
11408       InvalidDecl = true;
11409     }
11410   }
11411 
11412   // Fields can not have abstract class types
11413   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11414                                              diag::err_abstract_type_in_decl,
11415                                              AbstractFieldType))
11416     InvalidDecl = true;
11417 
11418   bool ZeroWidth = false;
11419   // If this is declared as a bit-field, check the bit-field.
11420   if (!InvalidDecl && BitWidth) {
11421     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11422                               &ZeroWidth).take();
11423     if (!BitWidth) {
11424       InvalidDecl = true;
11425       BitWidth = 0;
11426       ZeroWidth = false;
11427     }
11428   }
11429 
11430   // Check that 'mutable' is consistent with the type of the declaration.
11431   if (!InvalidDecl && Mutable) {
11432     unsigned DiagID = 0;
11433     if (T->isReferenceType())
11434       DiagID = diag::err_mutable_reference;
11435     else if (T.isConstQualified())
11436       DiagID = diag::err_mutable_const;
11437 
11438     if (DiagID) {
11439       SourceLocation ErrLoc = Loc;
11440       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11441         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11442       Diag(ErrLoc, DiagID);
11443       Mutable = false;
11444       InvalidDecl = true;
11445     }
11446   }
11447 
11448   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
11449                                        BitWidth, Mutable, InitStyle);
11450   if (InvalidDecl)
11451     NewFD->setInvalidDecl();
11452 
11453   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11454     Diag(Loc, diag::err_duplicate_member) << II;
11455     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11456     NewFD->setInvalidDecl();
11457   }
11458 
11459   if (!InvalidDecl && getLangOpts().CPlusPlus) {
11460     if (Record->isUnion()) {
11461       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11462         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11463         if (RDecl->getDefinition()) {
11464           // C++ [class.union]p1: An object of a class with a non-trivial
11465           // constructor, a non-trivial copy constructor, a non-trivial
11466           // destructor, or a non-trivial copy assignment operator
11467           // cannot be a member of a union, nor can an array of such
11468           // objects.
11469           if (CheckNontrivialField(NewFD))
11470             NewFD->setInvalidDecl();
11471         }
11472       }
11473 
11474       // C++ [class.union]p1: If a union contains a member of reference type,
11475       // the program is ill-formed, except when compiling with MSVC extensions
11476       // enabled.
11477       if (EltTy->isReferenceType()) {
11478         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11479                                     diag::ext_union_member_of_reference_type :
11480                                     diag::err_union_member_of_reference_type)
11481           << NewFD->getDeclName() << EltTy;
11482         if (!getLangOpts().MicrosoftExt)
11483           NewFD->setInvalidDecl();
11484       }
11485     }
11486   }
11487 
11488   // FIXME: We need to pass in the attributes given an AST
11489   // representation, not a parser representation.
11490   if (D) {
11491     // FIXME: The current scope is almost... but not entirely... correct here.
11492     ProcessDeclAttributes(getCurScope(), NewFD, *D);
11493 
11494     if (NewFD->hasAttrs())
11495       CheckAlignasUnderalignment(NewFD);
11496   }
11497 
11498   // In auto-retain/release, infer strong retension for fields of
11499   // retainable type.
11500   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
11501     NewFD->setInvalidDecl();
11502 
11503   if (T.isObjCGCWeak())
11504     Diag(Loc, diag::warn_attribute_weak_on_field);
11505 
11506   NewFD->setAccess(AS);
11507   return NewFD;
11508 }
11509 
11510 bool Sema::CheckNontrivialField(FieldDecl *FD) {
11511   assert(FD);
11512   assert(getLangOpts().CPlusPlus && "valid check only for C++");
11513 
11514   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11515     return false;
11516 
11517   QualType EltTy = Context.getBaseElementType(FD->getType());
11518   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11519     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
11520     if (RDecl->getDefinition()) {
11521       // We check for copy constructors before constructors
11522       // because otherwise we'll never get complaints about
11523       // copy constructors.
11524 
11525       CXXSpecialMember member = CXXInvalid;
11526       // We're required to check for any non-trivial constructors. Since the
11527       // implicit default constructor is suppressed if there are any
11528       // user-declared constructors, we just need to check that there is a
11529       // trivial default constructor and a trivial copy constructor. (We don't
11530       // worry about move constructors here, since this is a C++98 check.)
11531       if (RDecl->hasNonTrivialCopyConstructor())
11532         member = CXXCopyConstructor;
11533       else if (!RDecl->hasTrivialDefaultConstructor())
11534         member = CXXDefaultConstructor;
11535       else if (RDecl->hasNonTrivialCopyAssignment())
11536         member = CXXCopyAssignment;
11537       else if (RDecl->hasNonTrivialDestructor())
11538         member = CXXDestructor;
11539 
11540       if (member != CXXInvalid) {
11541         if (!getLangOpts().CPlusPlus11 &&
11542             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
11543           // Objective-C++ ARC: it is an error to have a non-trivial field of
11544           // a union. However, system headers in Objective-C programs
11545           // occasionally have Objective-C lifetime objects within unions,
11546           // and rather than cause the program to fail, we make those
11547           // members unavailable.
11548           SourceLocation Loc = FD->getLocation();
11549           if (getSourceManager().isInSystemHeader(Loc)) {
11550             if (!FD->hasAttr<UnavailableAttr>())
11551               FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
11552                                   "this system field has retaining ownership"));
11553             return false;
11554           }
11555         }
11556 
11557         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
11558                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11559                diag::err_illegal_union_or_anon_struct_member)
11560           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
11561         DiagnoseNontrivial(RDecl, member);
11562         return !getLangOpts().CPlusPlus11;
11563       }
11564     }
11565   }
11566 
11567   return false;
11568 }
11569 
11570 /// TranslateIvarVisibility - Translate visibility from a token ID to an
11571 ///  AST enum value.
11572 static ObjCIvarDecl::AccessControl
11573 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
11574   switch (ivarVisibility) {
11575   default: llvm_unreachable("Unknown visitibility kind");
11576   case tok::objc_private: return ObjCIvarDecl::Private;
11577   case tok::objc_public: return ObjCIvarDecl::Public;
11578   case tok::objc_protected: return ObjCIvarDecl::Protected;
11579   case tok::objc_package: return ObjCIvarDecl::Package;
11580   }
11581 }
11582 
11583 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
11584 /// in order to create an IvarDecl object for it.
11585 Decl *Sema::ActOnIvar(Scope *S,
11586                                 SourceLocation DeclStart,
11587                                 Declarator &D, Expr *BitfieldWidth,
11588                                 tok::ObjCKeywordKind Visibility) {
11589 
11590   IdentifierInfo *II = D.getIdentifier();
11591   Expr *BitWidth = (Expr*)BitfieldWidth;
11592   SourceLocation Loc = DeclStart;
11593   if (II) Loc = D.getIdentifierLoc();
11594 
11595   // FIXME: Unnamed fields can be handled in various different ways, for
11596   // example, unnamed unions inject all members into the struct namespace!
11597 
11598   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11599   QualType T = TInfo->getType();
11600 
11601   if (BitWidth) {
11602     // 6.7.2.1p3, 6.7.2.1p4
11603     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
11604     if (!BitWidth)
11605       D.setInvalidType();
11606   } else {
11607     // Not a bitfield.
11608 
11609     // validate II.
11610 
11611   }
11612   if (T->isReferenceType()) {
11613     Diag(Loc, diag::err_ivar_reference_type);
11614     D.setInvalidType();
11615   }
11616   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11617   // than a variably modified type.
11618   else if (T->isVariablyModifiedType()) {
11619     Diag(Loc, diag::err_typecheck_ivar_variable_size);
11620     D.setInvalidType();
11621   }
11622 
11623   // Get the visibility (access control) for this ivar.
11624   ObjCIvarDecl::AccessControl ac =
11625     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11626                                         : ObjCIvarDecl::None;
11627   // Must set ivar's DeclContext to its enclosing interface.
11628   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
11629   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11630     return 0;
11631   ObjCContainerDecl *EnclosingContext;
11632   if (ObjCImplementationDecl *IMPDecl =
11633       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11634     if (LangOpts.ObjCRuntime.isFragile()) {
11635     // Case of ivar declared in an implementation. Context is that of its class.
11636       EnclosingContext = IMPDecl->getClassInterface();
11637       assert(EnclosingContext && "Implementation has no class interface!");
11638     }
11639     else
11640       EnclosingContext = EnclosingDecl;
11641   } else {
11642     if (ObjCCategoryDecl *CDecl =
11643         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11644       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
11645         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
11646         return 0;
11647       }
11648     }
11649     EnclosingContext = EnclosingDecl;
11650   }
11651 
11652   // Construct the decl.
11653   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11654                                              DeclStart, Loc, II, T,
11655                                              TInfo, ac, (Expr *)BitfieldWidth);
11656 
11657   if (II) {
11658     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
11659                                            ForRedeclaration);
11660     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
11661         && !isa<TagDecl>(PrevDecl)) {
11662       Diag(Loc, diag::err_duplicate_member) << II;
11663       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11664       NewID->setInvalidDecl();
11665     }
11666   }
11667 
11668   // Process attributes attached to the ivar.
11669   ProcessDeclAttributes(S, NewID, D);
11670 
11671   if (D.isInvalidType())
11672     NewID->setInvalidDecl();
11673 
11674   // In ARC, infer 'retaining' for ivars of retainable type.
11675   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
11676     NewID->setInvalidDecl();
11677 
11678   if (D.getDeclSpec().isModulePrivateSpecified())
11679     NewID->setModulePrivate();
11680 
11681   if (II) {
11682     // FIXME: When interfaces are DeclContexts, we'll need to add
11683     // these to the interface.
11684     S->AddDecl(NewID);
11685     IdResolver.AddDecl(NewID);
11686   }
11687 
11688   if (LangOpts.ObjCRuntime.isNonFragile() &&
11689       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
11690     Diag(Loc, diag::warn_ivars_in_interface);
11691 
11692   return NewID;
11693 }
11694 
11695 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
11696 /// class and class extensions. For every class \@interface and class
11697 /// extension \@interface, if the last ivar is a bitfield of any type,
11698 /// then add an implicit `char :0` ivar to the end of that interface.
11699 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
11700                              SmallVectorImpl<Decl *> &AllIvarDecls) {
11701   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
11702     return;
11703 
11704   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11705   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11706 
11707   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
11708     return;
11709   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
11710   if (!ID) {
11711     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
11712       if (!CD->IsClassExtension())
11713         return;
11714     }
11715     // No need to add this to end of @implementation.
11716     else
11717       return;
11718   }
11719   // All conditions are met. Add a new bitfield to the tail end of ivars.
11720   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11721   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
11722 
11723   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
11724                               DeclLoc, DeclLoc, 0,
11725                               Context.CharTy,
11726                               Context.getTrivialTypeSourceInfo(Context.CharTy,
11727                                                                DeclLoc),
11728                               ObjCIvarDecl::Private, BW,
11729                               true);
11730   AllIvarDecls.push_back(Ivar);
11731 }
11732 
11733 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11734                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
11735                        SourceLocation RBrac, AttributeList *Attr) {
11736   assert(EnclosingDecl && "missing record or interface decl");
11737 
11738   // If this is an Objective-C @implementation or category and we have
11739   // new fields here we should reset the layout of the interface since
11740   // it will now change.
11741   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11742     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11743     switch (DC->getKind()) {
11744     default: break;
11745     case Decl::ObjCCategory:
11746       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11747       break;
11748     case Decl::ObjCImplementation:
11749       Context.
11750         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11751       break;
11752     }
11753   }
11754 
11755   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11756 
11757   // Start counting up the number of named members; make sure to include
11758   // members of anonymous structs and unions in the total.
11759   unsigned NumNamedMembers = 0;
11760   if (Record) {
11761     for (RecordDecl::decl_iterator i = Record->decls_begin(),
11762                                    e = Record->decls_end(); i != e; i++) {
11763       if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11764         if (IFD->getDeclName())
11765           ++NumNamedMembers;
11766     }
11767   }
11768 
11769   // Verify that all the fields are okay.
11770   SmallVector<FieldDecl*, 32> RecFields;
11771 
11772   bool ARCErrReported = false;
11773   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
11774        i != end; ++i) {
11775     FieldDecl *FD = cast<FieldDecl>(*i);
11776 
11777     // Get the type for the field.
11778     const Type *FDTy = FD->getType().getTypePtr();
11779 
11780     if (!FD->isAnonymousStructOrUnion()) {
11781       // Remember all fields written by the user.
11782       RecFields.push_back(FD);
11783     }
11784 
11785     // If the field is already invalid for some reason, don't emit more
11786     // diagnostics about it.
11787     if (FD->isInvalidDecl()) {
11788       EnclosingDecl->setInvalidDecl();
11789       continue;
11790     }
11791 
11792     // C99 6.7.2.1p2:
11793     //   A structure or union shall not contain a member with
11794     //   incomplete or function type (hence, a structure shall not
11795     //   contain an instance of itself, but may contain a pointer to
11796     //   an instance of itself), except that the last member of a
11797     //   structure with more than one named member may have incomplete
11798     //   array type; such a structure (and any union containing,
11799     //   possibly recursively, a member that is such a structure)
11800     //   shall not be a member of a structure or an element of an
11801     //   array.
11802     if (FDTy->isFunctionType()) {
11803       // Field declared as a function.
11804       Diag(FD->getLocation(), diag::err_field_declared_as_function)
11805         << FD->getDeclName();
11806       FD->setInvalidDecl();
11807       EnclosingDecl->setInvalidDecl();
11808       continue;
11809     } else if (FDTy->isIncompleteArrayType() && Record &&
11810                ((i + 1 == Fields.end() && !Record->isUnion()) ||
11811                 ((getLangOpts().MicrosoftExt ||
11812                   getLangOpts().CPlusPlus) &&
11813                  (i + 1 == Fields.end() || Record->isUnion())))) {
11814       // Flexible array member.
11815       // Microsoft and g++ is more permissive regarding flexible array.
11816       // It will accept flexible array in union and also
11817       // as the sole element of a struct/class.
11818       if (getLangOpts().MicrosoftExt) {
11819         if (Record->isUnion())
11820           Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
11821             << FD->getDeclName();
11822         else if (Fields.size() == 1)
11823           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
11824             << FD->getDeclName() << Record->getTagKind();
11825       } else if (getLangOpts().CPlusPlus) {
11826         if (Record->isUnion())
11827           Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11828             << FD->getDeclName();
11829         else if (Fields.size() == 1)
11830           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
11831             << FD->getDeclName() << Record->getTagKind();
11832       } else if (!getLangOpts().C99) {
11833       if (Record->isUnion())
11834         Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
11835           << FD->getDeclName();
11836       else
11837         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11838           << FD->getDeclName() << Record->getTagKind();
11839       } else if (NumNamedMembers < 1) {
11840         Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
11841           << FD->getDeclName();
11842         FD->setInvalidDecl();
11843         EnclosingDecl->setInvalidDecl();
11844         continue;
11845       }
11846       if (!FD->getType()->isDependentType() &&
11847           !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
11848         Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
11849           << FD->getDeclName() << FD->getType();
11850         FD->setInvalidDecl();
11851         EnclosingDecl->setInvalidDecl();
11852         continue;
11853       }
11854       // Okay, we have a legal flexible array member at the end of the struct.
11855       if (Record)
11856         Record->setHasFlexibleArrayMember(true);
11857     } else if (!FDTy->isDependentType() &&
11858                RequireCompleteType(FD->getLocation(), FD->getType(),
11859                                    diag::err_field_incomplete)) {
11860       // Incomplete type
11861       FD->setInvalidDecl();
11862       EnclosingDecl->setInvalidDecl();
11863       continue;
11864     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
11865       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11866         // If this is a member of a union, then entire union becomes "flexible".
11867         if (Record && Record->isUnion()) {
11868           Record->setHasFlexibleArrayMember(true);
11869         } else {
11870           // If this is a struct/class and this is not the last element, reject
11871           // it.  Note that GCC supports variable sized arrays in the middle of
11872           // structures.
11873           if (i + 1 != Fields.end())
11874             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
11875               << FD->getDeclName() << FD->getType();
11876           else {
11877             // We support flexible arrays at the end of structs in
11878             // other structs as an extension.
11879             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11880               << FD->getDeclName();
11881             if (Record)
11882               Record->setHasFlexibleArrayMember(true);
11883           }
11884         }
11885       }
11886       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11887           RequireNonAbstractType(FD->getLocation(), FD->getType(),
11888                                  diag::err_abstract_type_in_decl,
11889                                  AbstractIvarType)) {
11890         // Ivars can not have abstract class types
11891         FD->setInvalidDecl();
11892       }
11893       if (Record && FDTTy->getDecl()->hasObjectMember())
11894         Record->setHasObjectMember(true);
11895       if (Record && FDTTy->getDecl()->hasVolatileMember())
11896         Record->setHasVolatileMember(true);
11897     } else if (FDTy->isObjCObjectType()) {
11898       /// A field cannot be an Objective-c object
11899       Diag(FD->getLocation(), diag::err_statically_allocated_object)
11900         << FixItHint::CreateInsertion(FD->getLocation(), "*");
11901       QualType T = Context.getObjCObjectPointerType(FD->getType());
11902       FD->setType(T);
11903     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11904                (!getLangOpts().CPlusPlus || Record->isUnion())) {
11905       // It's an error in ARC if a field has lifetime.
11906       // We don't want to report this in a system header, though,
11907       // so we just make the field unavailable.
11908       // FIXME: that's really not sufficient; we need to make the type
11909       // itself invalid to, say, initialize or copy.
11910       QualType T = FD->getType();
11911       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11912       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11913         SourceLocation loc = FD->getLocation();
11914         if (getSourceManager().isInSystemHeader(loc)) {
11915           if (!FD->hasAttr<UnavailableAttr>()) {
11916             FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11917                               "this system field has retaining ownership"));
11918           }
11919         } else {
11920           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
11921             << T->isBlockPointerType() << Record->getTagKind();
11922         }
11923         ARCErrReported = true;
11924       }
11925     } else if (getLangOpts().ObjC1 &&
11926                getLangOpts().getGC() != LangOptions::NonGC &&
11927                Record && !Record->hasObjectMember()) {
11928       if (FD->getType()->isObjCObjectPointerType() ||
11929           FD->getType().isObjCGCStrong())
11930         Record->setHasObjectMember(true);
11931       else if (Context.getAsArrayType(FD->getType())) {
11932         QualType BaseType = Context.getBaseElementType(FD->getType());
11933         if (BaseType->isRecordType() &&
11934             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
11935           Record->setHasObjectMember(true);
11936         else if (BaseType->isObjCObjectPointerType() ||
11937                  BaseType.isObjCGCStrong())
11938                Record->setHasObjectMember(true);
11939       }
11940     }
11941     if (Record && FD->getType().isVolatileQualified())
11942       Record->setHasVolatileMember(true);
11943     // Keep track of the number of named members.
11944     if (FD->getIdentifier())
11945       ++NumNamedMembers;
11946   }
11947 
11948   // Okay, we successfully defined 'Record'.
11949   if (Record) {
11950     bool Completed = false;
11951     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
11952       if (!CXXRecord->isInvalidDecl()) {
11953         // Set access bits correctly on the directly-declared conversions.
11954         for (CXXRecordDecl::conversion_iterator
11955                I = CXXRecord->conversion_begin(),
11956                E = CXXRecord->conversion_end(); I != E; ++I)
11957           I.setAccess((*I)->getAccess());
11958 
11959         if (!CXXRecord->isDependentType()) {
11960           if (CXXRecord->hasUserDeclaredDestructor()) {
11961             // Adjust user-defined destructor exception spec.
11962             if (getLangOpts().CPlusPlus11)
11963               AdjustDestructorExceptionSpec(CXXRecord,
11964                                             CXXRecord->getDestructor());
11965 
11966             // The Microsoft ABI requires that we perform the destructor body
11967             // checks (i.e. operator delete() lookup) at every declaration, as
11968             // any translation unit may need to emit a deleting destructor.
11969             if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11970               CheckDestructor(CXXRecord->getDestructor());
11971           }
11972 
11973           // Add any implicitly-declared members to this class.
11974           AddImplicitlyDeclaredMembersToClass(CXXRecord);
11975 
11976           // If we have virtual base classes, we may end up finding multiple
11977           // final overriders for a given virtual function. Check for this
11978           // problem now.
11979           if (CXXRecord->getNumVBases()) {
11980             CXXFinalOverriderMap FinalOverriders;
11981             CXXRecord->getFinalOverriders(FinalOverriders);
11982 
11983             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
11984                                              MEnd = FinalOverriders.end();
11985                  M != MEnd; ++M) {
11986               for (OverridingMethods::iterator SO = M->second.begin(),
11987                                             SOEnd = M->second.end();
11988                    SO != SOEnd; ++SO) {
11989                 assert(SO->second.size() > 0 &&
11990                        "Virtual function without overridding functions?");
11991                 if (SO->second.size() == 1)
11992                   continue;
11993 
11994                 // C++ [class.virtual]p2:
11995                 //   In a derived class, if a virtual member function of a base
11996                 //   class subobject has more than one final overrider the
11997                 //   program is ill-formed.
11998                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
11999                   << (const NamedDecl *)M->first << Record;
12000                 Diag(M->first->getLocation(),
12001                      diag::note_overridden_virtual_function);
12002                 for (OverridingMethods::overriding_iterator
12003                           OM = SO->second.begin(),
12004                        OMEnd = SO->second.end();
12005                      OM != OMEnd; ++OM)
12006                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12007                     << (const NamedDecl *)M->first << OM->Method->getParent();
12008 
12009                 Record->setInvalidDecl();
12010               }
12011             }
12012             CXXRecord->completeDefinition(&FinalOverriders);
12013             Completed = true;
12014           }
12015         }
12016       }
12017     }
12018 
12019     if (!Completed)
12020       Record->completeDefinition();
12021 
12022     if (Record->hasAttrs())
12023       CheckAlignasUnderalignment(Record);
12024 
12025     // Check if the structure/union declaration is a language extension.
12026     if (!getLangOpts().CPlusPlus) {
12027       bool ZeroSize = true;
12028       bool IsEmpty = true;
12029       unsigned NonBitFields = 0;
12030       for (RecordDecl::field_iterator I = Record->field_begin(),
12031                                       E = Record->field_end();
12032            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12033         IsEmpty = false;
12034         if (I->isUnnamedBitfield()) {
12035           if (I->getBitWidthValue(Context) > 0)
12036             ZeroSize = false;
12037         } else {
12038           ++NonBitFields;
12039           QualType FieldType = I->getType();
12040           if (FieldType->isIncompleteType() ||
12041               !Context.getTypeSizeInChars(FieldType).isZero())
12042             ZeroSize = false;
12043         }
12044       }
12045 
12046       // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
12047       // C++.
12048       if (ZeroSize)
12049         Diag(RecLoc, diag::warn_zero_size_struct_union_compat) << IsEmpty
12050             << Record->isUnion() << (NonBitFields > 1);
12051 
12052       // Structs without named members are extension in C (C99 6.7.2.1p7), but
12053       // are accepted by GCC.
12054       if (NonBitFields == 0) {
12055         if (IsEmpty)
12056           Diag(RecLoc, diag::ext_empty_struct_union) << Record->isUnion();
12057         else
12058           Diag(RecLoc, diag::ext_no_named_members_in_struct_union) << Record->isUnion();
12059       }
12060     }
12061   } else {
12062     ObjCIvarDecl **ClsFields =
12063       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12064     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12065       ID->setEndOfDefinitionLoc(RBrac);
12066       // Add ivar's to class's DeclContext.
12067       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12068         ClsFields[i]->setLexicalDeclContext(ID);
12069         ID->addDecl(ClsFields[i]);
12070       }
12071       // Must enforce the rule that ivars in the base classes may not be
12072       // duplicates.
12073       if (ID->getSuperClass())
12074         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12075     } else if (ObjCImplementationDecl *IMPDecl =
12076                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12077       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12078       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12079         // Ivar declared in @implementation never belongs to the implementation.
12080         // Only it is in implementation's lexical context.
12081         ClsFields[I]->setLexicalDeclContext(IMPDecl);
12082       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12083       IMPDecl->setIvarLBraceLoc(LBrac);
12084       IMPDecl->setIvarRBraceLoc(RBrac);
12085     } else if (ObjCCategoryDecl *CDecl =
12086                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12087       // case of ivars in class extension; all other cases have been
12088       // reported as errors elsewhere.
12089       // FIXME. Class extension does not have a LocEnd field.
12090       // CDecl->setLocEnd(RBrac);
12091       // Add ivar's to class extension's DeclContext.
12092       // Diagnose redeclaration of private ivars.
12093       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
12094       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12095         if (IDecl) {
12096           if (const ObjCIvarDecl *ClsIvar =
12097               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12098             Diag(ClsFields[i]->getLocation(),
12099                  diag::err_duplicate_ivar_declaration);
12100             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12101             continue;
12102           }
12103           for (ObjCInterfaceDecl::known_extensions_iterator
12104                  Ext = IDecl->known_extensions_begin(),
12105                  ExtEnd = IDecl->known_extensions_end();
12106                Ext != ExtEnd; ++Ext) {
12107             if (const ObjCIvarDecl *ClsExtIvar
12108                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
12109               Diag(ClsFields[i]->getLocation(),
12110                    diag::err_duplicate_ivar_declaration);
12111               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12112               continue;
12113             }
12114           }
12115         }
12116         ClsFields[i]->setLexicalDeclContext(CDecl);
12117         CDecl->addDecl(ClsFields[i]);
12118       }
12119       CDecl->setIvarLBraceLoc(LBrac);
12120       CDecl->setIvarRBraceLoc(RBrac);
12121     }
12122   }
12123 
12124   if (Attr)
12125     ProcessDeclAttributeList(S, Record, Attr);
12126 }
12127 
12128 /// \brief Determine whether the given integral value is representable within
12129 /// the given type T.
12130 static bool isRepresentableIntegerValue(ASTContext &Context,
12131                                         llvm::APSInt &Value,
12132                                         QualType T) {
12133   assert(T->isIntegralType(Context) && "Integral type required!");
12134   unsigned BitWidth = Context.getIntWidth(T);
12135 
12136   if (Value.isUnsigned() || Value.isNonNegative()) {
12137     if (T->isSignedIntegerOrEnumerationType())
12138       --BitWidth;
12139     return Value.getActiveBits() <= BitWidth;
12140   }
12141   return Value.getMinSignedBits() <= BitWidth;
12142 }
12143 
12144 // \brief Given an integral type, return the next larger integral type
12145 // (or a NULL type of no such type exists).
12146 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12147   // FIXME: Int128/UInt128 support, which also needs to be introduced into
12148   // enum checking below.
12149   assert(T->isIntegralType(Context) && "Integral type required!");
12150   const unsigned NumTypes = 4;
12151   QualType SignedIntegralTypes[NumTypes] = {
12152     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12153   };
12154   QualType UnsignedIntegralTypes[NumTypes] = {
12155     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12156     Context.UnsignedLongLongTy
12157   };
12158 
12159   unsigned BitWidth = Context.getTypeSize(T);
12160   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12161                                                         : UnsignedIntegralTypes;
12162   for (unsigned I = 0; I != NumTypes; ++I)
12163     if (Context.getTypeSize(Types[I]) > BitWidth)
12164       return Types[I];
12165 
12166   return QualType();
12167 }
12168 
12169 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12170                                           EnumConstantDecl *LastEnumConst,
12171                                           SourceLocation IdLoc,
12172                                           IdentifierInfo *Id,
12173                                           Expr *Val) {
12174   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12175   llvm::APSInt EnumVal(IntWidth);
12176   QualType EltTy;
12177 
12178   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12179     Val = 0;
12180 
12181   if (Val)
12182     Val = DefaultLvalueConversion(Val).take();
12183 
12184   if (Val) {
12185     if (Enum->isDependentType() || Val->isTypeDependent())
12186       EltTy = Context.DependentTy;
12187     else {
12188       SourceLocation ExpLoc;
12189       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12190           !getLangOpts().MicrosoftMode) {
12191         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12192         // constant-expression in the enumerator-definition shall be a converted
12193         // constant expression of the underlying type.
12194         EltTy = Enum->getIntegerType();
12195         ExprResult Converted =
12196           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12197                                            CCEK_Enumerator);
12198         if (Converted.isInvalid())
12199           Val = 0;
12200         else
12201           Val = Converted.take();
12202       } else if (!Val->isValueDependent() &&
12203                  !(Val = VerifyIntegerConstantExpression(Val,
12204                                                          &EnumVal).take())) {
12205         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12206       } else {
12207         if (Enum->isFixed()) {
12208           EltTy = Enum->getIntegerType();
12209 
12210           // In Obj-C and Microsoft mode, require the enumeration value to be
12211           // representable in the underlying type of the enumeration. In C++11,
12212           // we perform a non-narrowing conversion as part of converted constant
12213           // expression checking.
12214           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12215             if (getLangOpts().MicrosoftMode) {
12216               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12217               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12218             } else
12219               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12220           } else
12221             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12222         } else if (getLangOpts().CPlusPlus) {
12223           // C++11 [dcl.enum]p5:
12224           //   If the underlying type is not fixed, the type of each enumerator
12225           //   is the type of its initializing value:
12226           //     - If an initializer is specified for an enumerator, the
12227           //       initializing value has the same type as the expression.
12228           EltTy = Val->getType();
12229         } else {
12230           // C99 6.7.2.2p2:
12231           //   The expression that defines the value of an enumeration constant
12232           //   shall be an integer constant expression that has a value
12233           //   representable as an int.
12234 
12235           // Complain if the value is not representable in an int.
12236           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12237             Diag(IdLoc, diag::ext_enum_value_not_int)
12238               << EnumVal.toString(10) << Val->getSourceRange()
12239               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12240           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12241             // Force the type of the expression to 'int'.
12242             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12243           }
12244           EltTy = Val->getType();
12245         }
12246       }
12247     }
12248   }
12249 
12250   if (!Val) {
12251     if (Enum->isDependentType())
12252       EltTy = Context.DependentTy;
12253     else if (!LastEnumConst) {
12254       // C++0x [dcl.enum]p5:
12255       //   If the underlying type is not fixed, the type of each enumerator
12256       //   is the type of its initializing value:
12257       //     - If no initializer is specified for the first enumerator, the
12258       //       initializing value has an unspecified integral type.
12259       //
12260       // GCC uses 'int' for its unspecified integral type, as does
12261       // C99 6.7.2.2p3.
12262       if (Enum->isFixed()) {
12263         EltTy = Enum->getIntegerType();
12264       }
12265       else {
12266         EltTy = Context.IntTy;
12267       }
12268     } else {
12269       // Assign the last value + 1.
12270       EnumVal = LastEnumConst->getInitVal();
12271       ++EnumVal;
12272       EltTy = LastEnumConst->getType();
12273 
12274       // Check for overflow on increment.
12275       if (EnumVal < LastEnumConst->getInitVal()) {
12276         // C++0x [dcl.enum]p5:
12277         //   If the underlying type is not fixed, the type of each enumerator
12278         //   is the type of its initializing value:
12279         //
12280         //     - Otherwise the type of the initializing value is the same as
12281         //       the type of the initializing value of the preceding enumerator
12282         //       unless the incremented value is not representable in that type,
12283         //       in which case the type is an unspecified integral type
12284         //       sufficient to contain the incremented value. If no such type
12285         //       exists, the program is ill-formed.
12286         QualType T = getNextLargerIntegralType(Context, EltTy);
12287         if (T.isNull() || Enum->isFixed()) {
12288           // There is no integral type larger enough to represent this
12289           // value. Complain, then allow the value to wrap around.
12290           EnumVal = LastEnumConst->getInitVal();
12291           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
12292           ++EnumVal;
12293           if (Enum->isFixed())
12294             // When the underlying type is fixed, this is ill-formed.
12295             Diag(IdLoc, diag::err_enumerator_wrapped)
12296               << EnumVal.toString(10)
12297               << EltTy;
12298           else
12299             Diag(IdLoc, diag::warn_enumerator_too_large)
12300               << EnumVal.toString(10);
12301         } else {
12302           EltTy = T;
12303         }
12304 
12305         // Retrieve the last enumerator's value, extent that type to the
12306         // type that is supposed to be large enough to represent the incremented
12307         // value, then increment.
12308         EnumVal = LastEnumConst->getInitVal();
12309         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12310         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
12311         ++EnumVal;
12312 
12313         // If we're not in C++, diagnose the overflow of enumerator values,
12314         // which in C99 means that the enumerator value is not representable in
12315         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12316         // permits enumerator values that are representable in some larger
12317         // integral type.
12318         if (!getLangOpts().CPlusPlus && !T.isNull())
12319           Diag(IdLoc, diag::warn_enum_value_overflow);
12320       } else if (!getLangOpts().CPlusPlus &&
12321                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12322         // Enforce C99 6.7.2.2p2 even when we compute the next value.
12323         Diag(IdLoc, diag::ext_enum_value_not_int)
12324           << EnumVal.toString(10) << 1;
12325       }
12326     }
12327   }
12328 
12329   if (!EltTy->isDependentType()) {
12330     // Make the enumerator value match the signedness and size of the
12331     // enumerator's type.
12332     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
12333     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12334   }
12335 
12336   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
12337                                   Val, EnumVal);
12338 }
12339 
12340 
12341 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12342                               SourceLocation IdLoc, IdentifierInfo *Id,
12343                               AttributeList *Attr,
12344                               SourceLocation EqualLoc, Expr *Val) {
12345   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
12346   EnumConstantDecl *LastEnumConst =
12347     cast_or_null<EnumConstantDecl>(lastEnumConst);
12348 
12349   // The scope passed in may not be a decl scope.  Zip up the scope tree until
12350   // we find one that is.
12351   S = getNonFieldDeclScope(S);
12352 
12353   // Verify that there isn't already something declared with this name in this
12354   // scope.
12355   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
12356                                          ForRedeclaration);
12357   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12358     // Maybe we will complain about the shadowed template parameter.
12359     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12360     // Just pretend that we didn't see the previous declaration.
12361     PrevDecl = 0;
12362   }
12363 
12364   if (PrevDecl) {
12365     // When in C++, we may get a TagDecl with the same name; in this case the
12366     // enum constant will 'hide' the tag.
12367     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
12368            "Received TagDecl when not in C++!");
12369     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
12370       if (isa<EnumConstantDecl>(PrevDecl))
12371         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
12372       else
12373         Diag(IdLoc, diag::err_redefinition) << Id;
12374       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12375       return 0;
12376     }
12377   }
12378 
12379   // C++ [class.mem]p15:
12380   // If T is the name of a class, then each of the following shall have a name
12381   // different from T:
12382   // - every enumerator of every member of class T that is an unscoped
12383   // enumerated type
12384   if (CXXRecordDecl *Record
12385                       = dyn_cast<CXXRecordDecl>(
12386                              TheEnumDecl->getDeclContext()->getRedeclContext()))
12387     if (!TheEnumDecl->isScoped() &&
12388         Record->getIdentifier() && Record->getIdentifier() == Id)
12389       Diag(IdLoc, diag::err_member_name_of_class) << Id;
12390 
12391   EnumConstantDecl *New =
12392     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
12393 
12394   if (New) {
12395     // Process attributes.
12396     if (Attr) ProcessDeclAttributeList(S, New, Attr);
12397 
12398     // Register this decl in the current scope stack.
12399     New->setAccess(TheEnumDecl->getAccess());
12400     PushOnScopeChains(New, S);
12401   }
12402 
12403   ActOnDocumentableDecl(New);
12404 
12405   return New;
12406 }
12407 
12408 // Returns true when the enum initial expression does not trigger the
12409 // duplicate enum warning.  A few common cases are exempted as follows:
12410 // Element2 = Element1
12411 // Element2 = Element1 + 1
12412 // Element2 = Element1 - 1
12413 // Where Element2 and Element1 are from the same enum.
12414 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12415   Expr *InitExpr = ECD->getInitExpr();
12416   if (!InitExpr)
12417     return true;
12418   InitExpr = InitExpr->IgnoreImpCasts();
12419 
12420   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12421     if (!BO->isAdditiveOp())
12422       return true;
12423     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12424     if (!IL)
12425       return true;
12426     if (IL->getValue() != 1)
12427       return true;
12428 
12429     InitExpr = BO->getLHS();
12430   }
12431 
12432   // This checks if the elements are from the same enum.
12433   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12434   if (!DRE)
12435     return true;
12436 
12437   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12438   if (!EnumConstant)
12439     return true;
12440 
12441   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12442       Enum)
12443     return true;
12444 
12445   return false;
12446 }
12447 
12448 struct DupKey {
12449   int64_t val;
12450   bool isTombstoneOrEmptyKey;
12451   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12452     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12453 };
12454 
12455 static DupKey GetDupKey(const llvm::APSInt& Val) {
12456   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12457                 false);
12458 }
12459 
12460 struct DenseMapInfoDupKey {
12461   static DupKey getEmptyKey() { return DupKey(0, true); }
12462   static DupKey getTombstoneKey() { return DupKey(1, true); }
12463   static unsigned getHashValue(const DupKey Key) {
12464     return (unsigned)(Key.val * 37);
12465   }
12466   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12467     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12468            LHS.val == RHS.val;
12469   }
12470 };
12471 
12472 // Emits a warning when an element is implicitly set a value that
12473 // a previous element has already been set to.
12474 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12475                                         EnumDecl *Enum,
12476                                         QualType EnumType) {
12477   if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12478                                  Enum->getLocation()) ==
12479       DiagnosticsEngine::Ignored)
12480     return;
12481   // Avoid anonymous enums
12482   if (!Enum->getIdentifier())
12483     return;
12484 
12485   // Only check for small enums.
12486   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12487     return;
12488 
12489   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12490   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
12491 
12492   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12493   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12494           ValueToVectorMap;
12495 
12496   DuplicatesVector DupVector;
12497   ValueToVectorMap EnumMap;
12498 
12499   // Populate the EnumMap with all values represented by enum constants without
12500   // an initialier.
12501   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12502     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12503 
12504     // Null EnumConstantDecl means a previous diagnostic has been emitted for
12505     // this constant.  Skip this enum since it may be ill-formed.
12506     if (!ECD) {
12507       return;
12508     }
12509 
12510     if (ECD->getInitExpr())
12511       continue;
12512 
12513     DupKey Key = GetDupKey(ECD->getInitVal());
12514     DeclOrVector &Entry = EnumMap[Key];
12515 
12516     // First time encountering this value.
12517     if (Entry.isNull())
12518       Entry = ECD;
12519   }
12520 
12521   // Create vectors for any values that has duplicates.
12522   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12523     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12524     if (!ValidDuplicateEnum(ECD, Enum))
12525       continue;
12526 
12527     DupKey Key = GetDupKey(ECD->getInitVal());
12528 
12529     DeclOrVector& Entry = EnumMap[Key];
12530     if (Entry.isNull())
12531       continue;
12532 
12533     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12534       // Ensure constants are different.
12535       if (D == ECD)
12536         continue;
12537 
12538       // Create new vector and push values onto it.
12539       ECDVector *Vec = new ECDVector();
12540       Vec->push_back(D);
12541       Vec->push_back(ECD);
12542 
12543       // Update entry to point to the duplicates vector.
12544       Entry = Vec;
12545 
12546       // Store the vector somewhere we can consult later for quick emission of
12547       // diagnostics.
12548       DupVector.push_back(Vec);
12549       continue;
12550     }
12551 
12552     ECDVector *Vec = Entry.get<ECDVector*>();
12553     // Make sure constants are not added more than once.
12554     if (*Vec->begin() == ECD)
12555       continue;
12556 
12557     Vec->push_back(ECD);
12558   }
12559 
12560   // Emit diagnostics.
12561   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12562                                   DupVectorEnd = DupVector.end();
12563        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12564     ECDVector *Vec = *DupVectorIter;
12565     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12566 
12567     // Emit warning for one enum constant.
12568     ECDVector::iterator I = Vec->begin();
12569     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12570       << (*I)->getName() << (*I)->getInitVal().toString(10)
12571       << (*I)->getSourceRange();
12572     ++I;
12573 
12574     // Emit one note for each of the remaining enum constants with
12575     // the same value.
12576     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12577       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12578         << (*I)->getName() << (*I)->getInitVal().toString(10)
12579         << (*I)->getSourceRange();
12580     delete Vec;
12581   }
12582 }
12583 
12584 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
12585                          SourceLocation RBraceLoc, Decl *EnumDeclX,
12586                          ArrayRef<Decl *> Elements,
12587                          Scope *S, AttributeList *Attr) {
12588   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
12589   QualType EnumType = Context.getTypeDeclType(Enum);
12590 
12591   if (Attr)
12592     ProcessDeclAttributeList(S, Enum, Attr);
12593 
12594   if (Enum->isDependentType()) {
12595     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12596       EnumConstantDecl *ECD =
12597         cast_or_null<EnumConstantDecl>(Elements[i]);
12598       if (!ECD) continue;
12599 
12600       ECD->setType(EnumType);
12601     }
12602 
12603     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
12604     return;
12605   }
12606 
12607   // TODO: If the result value doesn't fit in an int, it must be a long or long
12608   // long value.  ISO C does not support this, but GCC does as an extension,
12609   // emit a warning.
12610   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12611   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12612   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
12613 
12614   // Verify that all the values are okay, compute the size of the values, and
12615   // reverse the list.
12616   unsigned NumNegativeBits = 0;
12617   unsigned NumPositiveBits = 0;
12618 
12619   // Keep track of whether all elements have type int.
12620   bool AllElementsInt = true;
12621 
12622   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12623     EnumConstantDecl *ECD =
12624       cast_or_null<EnumConstantDecl>(Elements[i]);
12625     if (!ECD) continue;  // Already issued a diagnostic.
12626 
12627     const llvm::APSInt &InitVal = ECD->getInitVal();
12628 
12629     // Keep track of the size of positive and negative values.
12630     if (InitVal.isUnsigned() || InitVal.isNonNegative())
12631       NumPositiveBits = std::max(NumPositiveBits,
12632                                  (unsigned)InitVal.getActiveBits());
12633     else
12634       NumNegativeBits = std::max(NumNegativeBits,
12635                                  (unsigned)InitVal.getMinSignedBits());
12636 
12637     // Keep track of whether every enum element has type int (very commmon).
12638     if (AllElementsInt)
12639       AllElementsInt = ECD->getType() == Context.IntTy;
12640   }
12641 
12642   // Figure out the type that should be used for this enum.
12643   QualType BestType;
12644   unsigned BestWidth;
12645 
12646   // C++0x N3000 [conv.prom]p3:
12647   //   An rvalue of an unscoped enumeration type whose underlying
12648   //   type is not fixed can be converted to an rvalue of the first
12649   //   of the following types that can represent all the values of
12650   //   the enumeration: int, unsigned int, long int, unsigned long
12651   //   int, long long int, or unsigned long long int.
12652   // C99 6.4.4.3p2:
12653   //   An identifier declared as an enumeration constant has type int.
12654   // The C99 rule is modified by a gcc extension
12655   QualType BestPromotionType;
12656 
12657   bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
12658   // -fshort-enums is the equivalent to specifying the packed attribute on all
12659   // enum definitions.
12660   if (LangOpts.ShortEnums)
12661     Packed = true;
12662 
12663   if (Enum->isFixed()) {
12664     BestType = Enum->getIntegerType();
12665     if (BestType->isPromotableIntegerType())
12666       BestPromotionType = Context.getPromotedIntegerType(BestType);
12667     else
12668       BestPromotionType = BestType;
12669     // We don't need to set BestWidth, because BestType is going to be the type
12670     // of the enumerators, but we do anyway because otherwise some compilers
12671     // warn that it might be used uninitialized.
12672     BestWidth = CharWidth;
12673   }
12674   else if (NumNegativeBits) {
12675     // If there is a negative value, figure out the smallest integer type (of
12676     // int/long/longlong) that fits.
12677     // If it's packed, check also if it fits a char or a short.
12678     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
12679       BestType = Context.SignedCharTy;
12680       BestWidth = CharWidth;
12681     } else if (Packed && NumNegativeBits <= ShortWidth &&
12682                NumPositiveBits < ShortWidth) {
12683       BestType = Context.ShortTy;
12684       BestWidth = ShortWidth;
12685     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
12686       BestType = Context.IntTy;
12687       BestWidth = IntWidth;
12688     } else {
12689       BestWidth = Context.getTargetInfo().getLongWidth();
12690 
12691       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
12692         BestType = Context.LongTy;
12693       } else {
12694         BestWidth = Context.getTargetInfo().getLongLongWidth();
12695 
12696         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
12697           Diag(Enum->getLocation(), diag::warn_enum_too_large);
12698         BestType = Context.LongLongTy;
12699       }
12700     }
12701     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
12702   } else {
12703     // If there is no negative value, figure out the smallest type that fits
12704     // all of the enumerator values.
12705     // If it's packed, check also if it fits a char or a short.
12706     if (Packed && NumPositiveBits <= CharWidth) {
12707       BestType = Context.UnsignedCharTy;
12708       BestPromotionType = Context.IntTy;
12709       BestWidth = CharWidth;
12710     } else if (Packed && NumPositiveBits <= ShortWidth) {
12711       BestType = Context.UnsignedShortTy;
12712       BestPromotionType = Context.IntTy;
12713       BestWidth = ShortWidth;
12714     } else if (NumPositiveBits <= IntWidth) {
12715       BestType = Context.UnsignedIntTy;
12716       BestWidth = IntWidth;
12717       BestPromotionType
12718         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12719                            ? Context.UnsignedIntTy : Context.IntTy;
12720     } else if (NumPositiveBits <=
12721                (BestWidth = Context.getTargetInfo().getLongWidth())) {
12722       BestType = Context.UnsignedLongTy;
12723       BestPromotionType
12724         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12725                            ? Context.UnsignedLongTy : Context.LongTy;
12726     } else {
12727       BestWidth = Context.getTargetInfo().getLongLongWidth();
12728       assert(NumPositiveBits <= BestWidth &&
12729              "How could an initializer get larger than ULL?");
12730       BestType = Context.UnsignedLongLongTy;
12731       BestPromotionType
12732         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12733                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
12734     }
12735   }
12736 
12737   // Loop over all of the enumerator constants, changing their types to match
12738   // the type of the enum if needed.
12739   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12740     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12741     if (!ECD) continue;  // Already issued a diagnostic.
12742 
12743     // Standard C says the enumerators have int type, but we allow, as an
12744     // extension, the enumerators to be larger than int size.  If each
12745     // enumerator value fits in an int, type it as an int, otherwise type it the
12746     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
12747     // that X has type 'int', not 'unsigned'.
12748 
12749     // Determine whether the value fits into an int.
12750     llvm::APSInt InitVal = ECD->getInitVal();
12751 
12752     // If it fits into an integer type, force it.  Otherwise force it to match
12753     // the enum decl type.
12754     QualType NewTy;
12755     unsigned NewWidth;
12756     bool NewSign;
12757     if (!getLangOpts().CPlusPlus &&
12758         !Enum->isFixed() &&
12759         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
12760       NewTy = Context.IntTy;
12761       NewWidth = IntWidth;
12762       NewSign = true;
12763     } else if (ECD->getType() == BestType) {
12764       // Already the right type!
12765       if (getLangOpts().CPlusPlus)
12766         // C++ [dcl.enum]p4: Following the closing brace of an
12767         // enum-specifier, each enumerator has the type of its
12768         // enumeration.
12769         ECD->setType(EnumType);
12770       continue;
12771     } else {
12772       NewTy = BestType;
12773       NewWidth = BestWidth;
12774       NewSign = BestType->isSignedIntegerOrEnumerationType();
12775     }
12776 
12777     // Adjust the APSInt value.
12778     InitVal = InitVal.extOrTrunc(NewWidth);
12779     InitVal.setIsSigned(NewSign);
12780     ECD->setInitVal(InitVal);
12781 
12782     // Adjust the Expr initializer and type.
12783     if (ECD->getInitExpr() &&
12784         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
12785       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
12786                                                 CK_IntegralCast,
12787                                                 ECD->getInitExpr(),
12788                                                 /*base paths*/ 0,
12789                                                 VK_RValue));
12790     if (getLangOpts().CPlusPlus)
12791       // C++ [dcl.enum]p4: Following the closing brace of an
12792       // enum-specifier, each enumerator has the type of its
12793       // enumeration.
12794       ECD->setType(EnumType);
12795     else
12796       ECD->setType(NewTy);
12797   }
12798 
12799   Enum->completeDefinition(BestType, BestPromotionType,
12800                            NumPositiveBits, NumNegativeBits);
12801 
12802   // If we're declaring a function, ensure this decl isn't forgotten about -
12803   // it needs to go into the function scope.
12804   if (InFunctionDeclarator)
12805     DeclsInPrototypeScope.push_back(Enum);
12806 
12807   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
12808 
12809   // Now that the enum type is defined, ensure it's not been underaligned.
12810   if (Enum->hasAttrs())
12811     CheckAlignasUnderalignment(Enum);
12812 }
12813 
12814 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12815                                   SourceLocation StartLoc,
12816                                   SourceLocation EndLoc) {
12817   StringLiteral *AsmString = cast<StringLiteral>(expr);
12818 
12819   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
12820                                                    AsmString, StartLoc,
12821                                                    EndLoc);
12822   CurContext->addDecl(New);
12823   return New;
12824 }
12825 
12826 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12827                                    SourceLocation ImportLoc,
12828                                    ModuleIdPath Path) {
12829   Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
12830                                                 Module::AllVisible,
12831                                                 /*IsIncludeDirective=*/false);
12832   if (!Mod)
12833     return true;
12834 
12835   SmallVector<SourceLocation, 2> IdentifierLocs;
12836   Module *ModCheck = Mod;
12837   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12838     // If we've run out of module parents, just drop the remaining identifiers.
12839     // We need the length to be consistent.
12840     if (!ModCheck)
12841       break;
12842     ModCheck = ModCheck->Parent;
12843 
12844     IdentifierLocs.push_back(Path[I].second);
12845   }
12846 
12847   ImportDecl *Import = ImportDecl::Create(Context,
12848                                           Context.getTranslationUnitDecl(),
12849                                           AtLoc.isValid()? AtLoc : ImportLoc,
12850                                           Mod, IdentifierLocs);
12851   Context.getTranslationUnitDecl()->addDecl(Import);
12852   return Import;
12853 }
12854 
12855 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12856   // Create the implicit import declaration.
12857   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12858   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12859                                                    Loc, Mod, Loc);
12860   TU->addDecl(ImportD);
12861   Consumer.HandleImplicitImportDecl(ImportD);
12862 
12863   // Make the module visible.
12864   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12865                                          /*Complain=*/false);
12866 }
12867 
12868 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12869                                       IdentifierInfo* AliasName,
12870                                       SourceLocation PragmaLoc,
12871                                       SourceLocation NameLoc,
12872                                       SourceLocation AliasNameLoc) {
12873   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12874                                     LookupOrdinaryName);
12875   AsmLabelAttr *Attr =
12876      ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
12877 
12878   if (PrevDecl)
12879     PrevDecl->addAttr(Attr);
12880   else
12881     (void)ExtnameUndeclaredIdentifiers.insert(
12882       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12883 }
12884 
12885 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12886                              SourceLocation PragmaLoc,
12887                              SourceLocation NameLoc) {
12888   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
12889 
12890   if (PrevDecl) {
12891     PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
12892   } else {
12893     (void)WeakUndeclaredIdentifiers.insert(
12894       std::pair<IdentifierInfo*,WeakInfo>
12895         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
12896   }
12897 }
12898 
12899 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12900                                 IdentifierInfo* AliasName,
12901                                 SourceLocation PragmaLoc,
12902                                 SourceLocation NameLoc,
12903                                 SourceLocation AliasNameLoc) {
12904   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12905                                     LookupOrdinaryName);
12906   WeakInfo W = WeakInfo(Name, NameLoc);
12907 
12908   if (PrevDecl) {
12909     if (!PrevDecl->hasAttr<AliasAttr>())
12910       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
12911         DeclApplyPragmaWeak(TUScope, ND, W);
12912   } else {
12913     (void)WeakUndeclaredIdentifiers.insert(
12914       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
12915   }
12916 }
12917 
12918 Decl *Sema::getObjCDeclContext() const {
12919   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12920 }
12921 
12922 AvailabilityResult Sema::getCurContextAvailability() const {
12923   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
12924   return D->getAvailability();
12925 }
12926