]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaDecl.cpp
Vendor import of clang trunk r154661:
[FreeBSD/FreeBSD.git] / lib / Sema / SemaDecl.cpp
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/CXXFieldCollector.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "TypeLocBuilder.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/EvaluatedExprVisitor.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/CharUnits.h"
31 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/ParsedTemplate.h"
33 #include "clang/Parse/ParseDiagnostic.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Sema/DelayedDiagnostic.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Lex/HeaderSearch.h"
41 #include "clang/Lex/ModuleLoader.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/Triple.h"
44 #include <algorithm>
45 #include <cstring>
46 #include <functional>
47 using namespace clang;
48 using namespace sema;
49
50 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
51   if (OwnedType) {
52     Decl *Group[2] = { OwnedType, Ptr };
53     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
54   }
55
56   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
57 }
58
59 namespace {
60
61 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
62  public:
63   TypeNameValidatorCCC(bool AllowInvalid) : AllowInvalidDecl(AllowInvalid) {
64     WantExpressionKeywords = false;
65     WantCXXNamedCasts = false;
66     WantRemainingKeywords = false;
67   }
68
69   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
70     if (NamedDecl *ND = candidate.getCorrectionDecl())
71       return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
72           (AllowInvalidDecl || !ND->isInvalidDecl());
73     else
74       return candidate.isKeyword();
75   }
76
77  private:
78   bool AllowInvalidDecl;
79 };
80
81 }
82
83 /// \brief If the identifier refers to a type name within this scope,
84 /// return the declaration of that type.
85 ///
86 /// This routine performs ordinary name lookup of the identifier II
87 /// within the given scope, with optional C++ scope specifier SS, to
88 /// determine whether the name refers to a type. If so, returns an
89 /// opaque pointer (actually a QualType) corresponding to that
90 /// type. Otherwise, returns NULL.
91 ///
92 /// If name lookup results in an ambiguity, this routine will complain
93 /// and then return NULL.
94 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
95                              Scope *S, CXXScopeSpec *SS,
96                              bool isClassName, bool HasTrailingDot,
97                              ParsedType ObjectTypePtr,
98                              bool IsCtorOrDtorName,
99                              bool WantNontrivialTypeSourceInfo,
100                              IdentifierInfo **CorrectedII) {
101   // Determine where we will perform name lookup.
102   DeclContext *LookupCtx = 0;
103   if (ObjectTypePtr) {
104     QualType ObjectType = ObjectTypePtr.get();
105     if (ObjectType->isRecordType())
106       LookupCtx = computeDeclContext(ObjectType);
107   } else if (SS && SS->isNotEmpty()) {
108     LookupCtx = computeDeclContext(*SS, false);
109
110     if (!LookupCtx) {
111       if (isDependentScopeSpecifier(*SS)) {
112         // C++ [temp.res]p3:
113         //   A qualified-id that refers to a type and in which the
114         //   nested-name-specifier depends on a template-parameter (14.6.2)
115         //   shall be prefixed by the keyword typename to indicate that the
116         //   qualified-id denotes a type, forming an
117         //   elaborated-type-specifier (7.1.5.3).
118         //
119         // We therefore do not perform any name lookup if the result would
120         // refer to a member of an unknown specialization.
121         if (!isClassName && !IsCtorOrDtorName)
122           return ParsedType();
123         
124         // We know from the grammar that this name refers to a type,
125         // so build a dependent node to describe the type.
126         if (WantNontrivialTypeSourceInfo)
127           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
128         
129         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
130         QualType T =
131           CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
132                             II, NameLoc);
133         
134           return ParsedType::make(T);
135       }
136       
137       return ParsedType();
138     }
139     
140     if (!LookupCtx->isDependentContext() &&
141         RequireCompleteDeclContext(*SS, LookupCtx))
142       return ParsedType();
143   }
144
145   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
146   // lookup for class-names.
147   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
148                                       LookupOrdinaryName;
149   LookupResult Result(*this, &II, NameLoc, Kind);
150   if (LookupCtx) {
151     // Perform "qualified" name lookup into the declaration context we
152     // computed, which is either the type of the base of a member access
153     // expression or the declaration context associated with a prior
154     // nested-name-specifier.
155     LookupQualifiedName(Result, LookupCtx);
156
157     if (ObjectTypePtr && Result.empty()) {
158       // C++ [basic.lookup.classref]p3:
159       //   If the unqualified-id is ~type-name, the type-name is looked up
160       //   in the context of the entire postfix-expression. If the type T of 
161       //   the object expression is of a class type C, the type-name is also
162       //   looked up in the scope of class C. At least one of the lookups shall
163       //   find a name that refers to (possibly cv-qualified) T.
164       LookupName(Result, S);
165     }
166   } else {
167     // Perform unqualified name lookup.
168     LookupName(Result, S);
169   }
170   
171   NamedDecl *IIDecl = 0;
172   switch (Result.getResultKind()) {
173   case LookupResult::NotFound:
174   case LookupResult::NotFoundInCurrentInstantiation:
175     if (CorrectedII) {
176       TypeNameValidatorCCC Validator(true);
177       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
178                                               Kind, S, SS, Validator);
179       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
180       TemplateTy Template;
181       bool MemberOfUnknownSpecialization;
182       UnqualifiedId TemplateName;
183       TemplateName.setIdentifier(NewII, NameLoc);
184       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
185       CXXScopeSpec NewSS, *NewSSPtr = SS;
186       if (SS && NNS) {
187         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
188         NewSSPtr = &NewSS;
189       }
190       if (Correction && (NNS || NewII != &II) &&
191           // Ignore a correction to a template type as the to-be-corrected
192           // identifier is not a template (typo correction for template names
193           // is handled elsewhere).
194           !(getLangOpts().CPlusPlus && NewSSPtr &&
195             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
196                            false, Template, MemberOfUnknownSpecialization))) {
197         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
198                                     isClassName, HasTrailingDot, ObjectTypePtr,
199                                     IsCtorOrDtorName,
200                                     WantNontrivialTypeSourceInfo);
201         if (Ty) {
202           std::string CorrectedStr(Correction.getAsString(getLangOpts()));
203           std::string CorrectedQuotedStr(
204               Correction.getQuoted(getLangOpts()));
205           Diag(NameLoc, diag::err_unknown_typename_suggest)
206               << Result.getLookupName() << CorrectedQuotedStr
207               << FixItHint::CreateReplacement(SourceRange(NameLoc),
208                                               CorrectedStr);
209           if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
210             Diag(FirstDecl->getLocation(), diag::note_previous_decl)
211               << CorrectedQuotedStr;
212
213           if (SS && NNS)
214             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
215           *CorrectedII = NewII;
216           return Ty;
217         }
218       }
219     }
220     // If typo correction failed or was not performed, fall through
221   case LookupResult::FoundOverloaded:
222   case LookupResult::FoundUnresolvedValue:
223     Result.suppressDiagnostics();
224     return ParsedType();
225
226   case LookupResult::Ambiguous:
227     // Recover from type-hiding ambiguities by hiding the type.  We'll
228     // do the lookup again when looking for an object, and we can
229     // diagnose the error then.  If we don't do this, then the error
230     // about hiding the type will be immediately followed by an error
231     // that only makes sense if the identifier was treated like a type.
232     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
233       Result.suppressDiagnostics();
234       return ParsedType();
235     }
236
237     // Look to see if we have a type anywhere in the list of results.
238     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
239          Res != ResEnd; ++Res) {
240       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
241         if (!IIDecl ||
242             (*Res)->getLocation().getRawEncoding() <
243               IIDecl->getLocation().getRawEncoding())
244           IIDecl = *Res;
245       }
246     }
247
248     if (!IIDecl) {
249       // None of the entities we found is a type, so there is no way
250       // to even assume that the result is a type. In this case, don't
251       // complain about the ambiguity. The parser will either try to
252       // perform this lookup again (e.g., as an object name), which
253       // will produce the ambiguity, or will complain that it expected
254       // a type name.
255       Result.suppressDiagnostics();
256       return ParsedType();
257     }
258
259     // We found a type within the ambiguous lookup; diagnose the
260     // ambiguity and then return that type. This might be the right
261     // answer, or it might not be, but it suppresses any attempt to
262     // perform the name lookup again.
263     break;
264
265   case LookupResult::Found:
266     IIDecl = Result.getFoundDecl();
267     break;
268   }
269
270   assert(IIDecl && "Didn't find decl");
271
272   QualType T;
273   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
274     DiagnoseUseOfDecl(IIDecl, NameLoc);
275
276     if (T.isNull())
277       T = Context.getTypeDeclType(TD);
278
279     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
280     // constructor or destructor name (in such a case, the scope specifier
281     // will be attached to the enclosing Expr or Decl node).
282     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
283       if (WantNontrivialTypeSourceInfo) {
284         // Construct a type with type-source information.
285         TypeLocBuilder Builder;
286         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
287         
288         T = getElaboratedType(ETK_None, *SS, T);
289         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
290         ElabTL.setElaboratedKeywordLoc(SourceLocation());
291         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
292         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
293       } else {
294         T = getElaboratedType(ETK_None, *SS, T);
295       }
296     }
297   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
298     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
299     if (!HasTrailingDot)
300       T = Context.getObjCInterfaceType(IDecl);
301   }
302
303   if (T.isNull()) {
304     // If it's not plausibly a type, suppress diagnostics.
305     Result.suppressDiagnostics();
306     return ParsedType();
307   }
308   return ParsedType::make(T);
309 }
310
311 /// isTagName() - This method is called *for error recovery purposes only*
312 /// to determine if the specified name is a valid tag name ("struct foo").  If
313 /// so, this returns the TST for the tag corresponding to it (TST_enum,
314 /// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
315 /// where the user forgot to specify the tag.
316 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
317   // Do a tag name lookup in this scope.
318   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
319   LookupName(R, S, false);
320   R.suppressDiagnostics();
321   if (R.getResultKind() == LookupResult::Found)
322     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
323       switch (TD->getTagKind()) {
324       case TTK_Struct: return DeclSpec::TST_struct;
325       case TTK_Union:  return DeclSpec::TST_union;
326       case TTK_Class:  return DeclSpec::TST_class;
327       case TTK_Enum:   return DeclSpec::TST_enum;
328       }
329     }
330
331   return DeclSpec::TST_unspecified;
332 }
333
334 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
335 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
336 /// then downgrade the missing typename error to a warning.
337 /// This is needed for MSVC compatibility; Example:
338 /// @code
339 /// template<class T> class A {
340 /// public:
341 ///   typedef int TYPE;
342 /// };
343 /// template<class T> class B : public A<T> {
344 /// public:
345 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
346 /// };
347 /// @endcode
348 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
349   if (CurContext->isRecord()) {
350     const Type *Ty = SS->getScopeRep()->getAsType();
351
352     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
353     for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
354           BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
355       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
356         return true;
357     return S->isFunctionPrototypeScope();
358   } 
359   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
360 }
361
362 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 
363                                    SourceLocation IILoc,
364                                    Scope *S,
365                                    CXXScopeSpec *SS,
366                                    ParsedType &SuggestedType) {
367   // We don't have anything to suggest (yet).
368   SuggestedType = ParsedType();
369   
370   // There may have been a typo in the name of the type. Look up typo
371   // results, in case we have something that we can suggest.
372   TypeNameValidatorCCC Validator(false);
373   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
374                                              LookupOrdinaryName, S, SS,
375                                              Validator)) {
376     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
377     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
378
379     if (Corrected.isKeyword()) {
380       // We corrected to a keyword.
381       // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
382       Diag(IILoc, diag::err_unknown_typename_suggest)
383         << &II << CorrectedQuotedStr;
384     } else {
385       NamedDecl *Result = Corrected.getCorrectionDecl();
386       // We found a similarly-named type or interface; suggest that.
387       if (!SS || !SS->isSet())
388         Diag(IILoc, diag::err_unknown_typename_suggest)
389           << &II << CorrectedQuotedStr
390           << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
391       else if (DeclContext *DC = computeDeclContext(*SS, false))
392         Diag(IILoc, diag::err_unknown_nested_typename_suggest)
393           << &II << DC << CorrectedQuotedStr << SS->getRange()
394           << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
395       else
396         llvm_unreachable("could not have corrected a typo here");
397
398       Diag(Result->getLocation(), diag::note_previous_decl)
399         << CorrectedQuotedStr;
400
401       SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
402                                   false, false, ParsedType(),
403                                   /*IsCtorOrDtorName=*/false,
404                                   /*NonTrivialTypeSourceInfo=*/true);
405     }
406     return true;
407   }
408
409   if (getLangOpts().CPlusPlus) {
410     // See if II is a class template that the user forgot to pass arguments to.
411     UnqualifiedId Name;
412     Name.setIdentifier(&II, IILoc);
413     CXXScopeSpec EmptySS;
414     TemplateTy TemplateResult;
415     bool MemberOfUnknownSpecialization;
416     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
417                        Name, ParsedType(), true, TemplateResult,
418                        MemberOfUnknownSpecialization) == TNK_Type_template) {
419       TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
420       Diag(IILoc, diag::err_template_missing_args) << TplName;
421       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
422         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
423           << TplDecl->getTemplateParameters()->getSourceRange();
424       }
425       return true;
426     }
427   }
428
429   // FIXME: Should we move the logic that tries to recover from a missing tag
430   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
431   
432   if (!SS || (!SS->isSet() && !SS->isInvalid()))
433     Diag(IILoc, diag::err_unknown_typename) << &II;
434   else if (DeclContext *DC = computeDeclContext(*SS, false))
435     Diag(IILoc, diag::err_typename_nested_not_found) 
436       << &II << DC << SS->getRange();
437   else if (isDependentScopeSpecifier(*SS)) {
438     unsigned DiagID = diag::err_typename_missing;
439     if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
440       DiagID = diag::warn_typename_missing;
441
442     Diag(SS->getRange().getBegin(), DiagID)
443       << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
444       << SourceRange(SS->getRange().getBegin(), IILoc)
445       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
446     SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc)
447                                                                          .get();
448   } else {
449     assert(SS && SS->isInvalid() && 
450            "Invalid scope specifier has already been diagnosed");
451   }
452   
453   return true;
454 }
455
456 /// \brief Determine whether the given result set contains either a type name
457 /// or 
458 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
459   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
460                        NextToken.is(tok::less);
461   
462   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
463     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
464       return true;
465     
466     if (CheckTemplate && isa<TemplateDecl>(*I))
467       return true;
468   }
469   
470   return false;
471 }
472
473 Sema::NameClassification Sema::ClassifyName(Scope *S,
474                                             CXXScopeSpec &SS,
475                                             IdentifierInfo *&Name,
476                                             SourceLocation NameLoc,
477                                             const Token &NextToken) {
478   DeclarationNameInfo NameInfo(Name, NameLoc);
479   ObjCMethodDecl *CurMethod = getCurMethodDecl();
480   
481   if (NextToken.is(tok::coloncolon)) {
482     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
483                                 QualType(), false, SS, 0, false);
484     
485   }
486       
487   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
488   LookupParsedName(Result, S, &SS, !CurMethod);
489   
490   // Perform lookup for Objective-C instance variables (including automatically 
491   // synthesized instance variables), if we're in an Objective-C method.
492   // FIXME: This lookup really, really needs to be folded in to the normal
493   // unqualified lookup mechanism.
494   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
495     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
496     if (E.get() || E.isInvalid())
497       return E;
498   }
499   
500   bool SecondTry = false;
501   bool IsFilteredTemplateName = false;
502   
503 Corrected:
504   switch (Result.getResultKind()) {
505   case LookupResult::NotFound:
506     // If an unqualified-id is followed by a '(', then we have a function
507     // call.
508     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
509       // In C++, this is an ADL-only call.
510       // FIXME: Reference?
511       if (getLangOpts().CPlusPlus)
512         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
513       
514       // C90 6.3.2.2:
515       //   If the expression that precedes the parenthesized argument list in a 
516       //   function call consists solely of an identifier, and if no 
517       //   declaration is visible for this identifier, the identifier is 
518       //   implicitly declared exactly as if, in the innermost block containing
519       //   the function call, the declaration
520       //
521       //     extern int identifier (); 
522       //
523       //   appeared. 
524       // 
525       // We also allow this in C99 as an extension.
526       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
527         Result.addDecl(D);
528         Result.resolveKind();
529         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
530       }
531     }
532     
533     // In C, we first see whether there is a tag type by the same name, in 
534     // which case it's likely that the user just forget to write "enum", 
535     // "struct", or "union".
536     if (!getLangOpts().CPlusPlus && !SecondTry) {
537       Result.clear(LookupTagName);
538       LookupParsedName(Result, S, &SS);
539       if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
540         const char *TagName = 0;
541         const char *FixItTagName = 0;
542         switch (Tag->getTagKind()) {
543           case TTK_Class:
544             TagName = "class";
545             FixItTagName = "class ";
546             break;
547
548           case TTK_Enum:
549             TagName = "enum";
550             FixItTagName = "enum ";
551             break;
552             
553           case TTK_Struct:
554             TagName = "struct";
555             FixItTagName = "struct ";
556             break;
557             
558           case TTK_Union:
559             TagName = "union";
560             FixItTagName = "union ";
561             break;
562         }
563
564         Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
565           << Name << TagName << getLangOpts().CPlusPlus
566           << FixItHint::CreateInsertion(NameLoc, FixItTagName);
567         break;
568       }
569       
570       Result.clear(LookupOrdinaryName);
571     }
572
573     // Perform typo correction to determine if there is another name that is
574     // close to this name.
575     if (!SecondTry) {
576       SecondTry = true;
577       CorrectionCandidateCallback DefaultValidator;
578       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
579                                                  Result.getLookupKind(), S, 
580                                                  &SS, DefaultValidator)) {
581         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
582         unsigned QualifiedDiag = diag::err_no_member_suggest;
583         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
584         std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
585         
586         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
587         NamedDecl *UnderlyingFirstDecl
588           = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
589         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
590             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
591           UnqualifiedDiag = diag::err_no_template_suggest;
592           QualifiedDiag = diag::err_no_member_template_suggest;
593         } else if (UnderlyingFirstDecl && 
594                    (isa<TypeDecl>(UnderlyingFirstDecl) || 
595                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
596                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
597            UnqualifiedDiag = diag::err_unknown_typename_suggest;
598            QualifiedDiag = diag::err_unknown_nested_typename_suggest;
599          }
600
601         if (SS.isEmpty())
602           Diag(NameLoc, UnqualifiedDiag)
603             << Name << CorrectedQuotedStr
604             << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
605         else
606           Diag(NameLoc, QualifiedDiag)
607             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
608             << SS.getRange()
609             << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
610
611         // Update the name, so that the caller has the new name.
612         Name = Corrected.getCorrectionAsIdentifierInfo();
613         
614         // Typo correction corrected to a keyword.
615         if (Corrected.isKeyword())
616           return Corrected.getCorrectionAsIdentifierInfo();
617
618         // Also update the LookupResult...
619         // FIXME: This should probably go away at some point
620         Result.clear();
621         Result.setLookupName(Corrected.getCorrection());
622         if (FirstDecl) {
623           Result.addDecl(FirstDecl);
624           Diag(FirstDecl->getLocation(), diag::note_previous_decl)
625             << CorrectedQuotedStr;
626         }
627
628         // If we found an Objective-C instance variable, let
629         // LookupInObjCMethod build the appropriate expression to
630         // reference the ivar.
631         // FIXME: This is a gross hack.
632         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
633           Result.clear();
634           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
635           return move(E);
636         }
637         
638         goto Corrected;
639       }
640     }
641       
642     // We failed to correct; just fall through and let the parser deal with it.
643     Result.suppressDiagnostics();
644     return NameClassification::Unknown();
645       
646   case LookupResult::NotFoundInCurrentInstantiation: {
647     // We performed name lookup into the current instantiation, and there were 
648     // dependent bases, so we treat this result the same way as any other
649     // dependent nested-name-specifier.
650       
651     // C++ [temp.res]p2:
652     //   A name used in a template declaration or definition and that is 
653     //   dependent on a template-parameter is assumed not to name a type 
654     //   unless the applicable name lookup finds a type name or the name is 
655     //   qualified by the keyword typename.
656     //
657     // FIXME: If the next token is '<', we might want to ask the parser to
658     // perform some heroics to see if we actually have a 
659     // template-argument-list, which would indicate a missing 'template'
660     // keyword here.
661     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
662                                      NameInfo, /*TemplateArgs=*/0);
663   }
664
665   case LookupResult::Found:
666   case LookupResult::FoundOverloaded:
667   case LookupResult::FoundUnresolvedValue:
668     break;
669       
670   case LookupResult::Ambiguous:
671     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
672         hasAnyAcceptableTemplateNames(Result)) {
673       // C++ [temp.local]p3:
674       //   A lookup that finds an injected-class-name (10.2) can result in an
675       //   ambiguity in certain cases (for example, if it is found in more than
676       //   one base class). If all of the injected-class-names that are found
677       //   refer to specializations of the same class template, and if the name
678       //   is followed by a template-argument-list, the reference refers to the
679       //   class template itself and not a specialization thereof, and is not
680       //   ambiguous.
681       //
682       // This filtering can make an ambiguous result into an unambiguous one,
683       // so try again after filtering out template names.
684       FilterAcceptableTemplateNames(Result);
685       if (!Result.isAmbiguous()) {
686         IsFilteredTemplateName = true;
687         break;
688       }
689     }
690       
691     // Diagnose the ambiguity and return an error.
692     return NameClassification::Error();
693   }
694   
695   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
696       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
697     // C++ [temp.names]p3:
698     //   After name lookup (3.4) finds that a name is a template-name or that
699     //   an operator-function-id or a literal- operator-id refers to a set of
700     //   overloaded functions any member of which is a function template if 
701     //   this is followed by a <, the < is always taken as the delimiter of a
702     //   template-argument-list and never as the less-than operator.
703     if (!IsFilteredTemplateName)
704       FilterAcceptableTemplateNames(Result);
705     
706     if (!Result.empty()) {
707       bool IsFunctionTemplate;
708       TemplateName Template;
709       if (Result.end() - Result.begin() > 1) {
710         IsFunctionTemplate = true;
711         Template = Context.getOverloadedTemplateName(Result.begin(), 
712                                                      Result.end());
713       } else {
714         TemplateDecl *TD
715           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
716         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
717         
718         if (SS.isSet() && !SS.isInvalid())
719           Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 
720                                                     /*TemplateKeyword=*/false,
721                                                       TD);
722         else
723           Template = TemplateName(TD);
724       }
725       
726       if (IsFunctionTemplate) {
727         // Function templates always go through overload resolution, at which
728         // point we'll perform the various checks (e.g., accessibility) we need
729         // to based on which function we selected.
730         Result.suppressDiagnostics();
731         
732         return NameClassification::FunctionTemplate(Template);
733       }
734       
735       return NameClassification::TypeTemplate(Template);
736     }
737   }
738   
739   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
740   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
741     DiagnoseUseOfDecl(Type, NameLoc);
742     QualType T = Context.getTypeDeclType(Type);
743     return ParsedType::make(T);    
744   }
745   
746   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
747   if (!Class) {
748     // FIXME: It's unfortunate that we don't have a Type node for handling this.
749     if (ObjCCompatibleAliasDecl *Alias 
750                                 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
751       Class = Alias->getClassInterface();
752   }
753   
754   if (Class) {
755     DiagnoseUseOfDecl(Class, NameLoc);
756     
757     if (NextToken.is(tok::period)) {
758       // Interface. <something> is parsed as a property reference expression.
759       // Just return "unknown" as a fall-through for now.
760       Result.suppressDiagnostics();
761       return NameClassification::Unknown();
762     }
763     
764     QualType T = Context.getObjCInterfaceType(Class);
765     return ParsedType::make(T);
766   }
767   
768   if (!Result.empty() && (*Result.begin())->isCXXClassMember())
769     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
770
771   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
772   return BuildDeclarationNameExpr(SS, Result, ADL);
773 }
774
775 // Determines the context to return to after temporarily entering a
776 // context.  This depends in an unnecessarily complicated way on the
777 // exact ordering of callbacks from the parser.
778 DeclContext *Sema::getContainingDC(DeclContext *DC) {
779
780   // Functions defined inline within classes aren't parsed until we've
781   // finished parsing the top-level class, so the top-level class is
782   // the context we'll need to return to.
783   if (isa<FunctionDecl>(DC)) {
784     DC = DC->getLexicalParent();
785
786     // A function not defined within a class will always return to its
787     // lexical context.
788     if (!isa<CXXRecordDecl>(DC))
789       return DC;
790
791     // A C++ inline method/friend is parsed *after* the topmost class
792     // it was declared in is fully parsed ("complete");  the topmost
793     // class is the context we need to return to.
794     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
795       DC = RD;
796
797     // Return the declaration context of the topmost class the inline method is
798     // declared in.
799     return DC;
800   }
801
802   return DC->getLexicalParent();
803 }
804
805 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
806   assert(getContainingDC(DC) == CurContext &&
807       "The next DeclContext should be lexically contained in the current one.");
808   CurContext = DC;
809   S->setEntity(DC);
810 }
811
812 void Sema::PopDeclContext() {
813   assert(CurContext && "DeclContext imbalance!");
814
815   CurContext = getContainingDC(CurContext);
816   assert(CurContext && "Popped translation unit!");
817 }
818
819 /// EnterDeclaratorContext - Used when we must lookup names in the context
820 /// of a declarator's nested name specifier.
821 ///
822 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
823   // C++0x [basic.lookup.unqual]p13:
824   //   A name used in the definition of a static data member of class
825   //   X (after the qualified-id of the static member) is looked up as
826   //   if the name was used in a member function of X.
827   // C++0x [basic.lookup.unqual]p14:
828   //   If a variable member of a namespace is defined outside of the
829   //   scope of its namespace then any name used in the definition of
830   //   the variable member (after the declarator-id) is looked up as
831   //   if the definition of the variable member occurred in its
832   //   namespace.
833   // Both of these imply that we should push a scope whose context
834   // is the semantic context of the declaration.  We can't use
835   // PushDeclContext here because that context is not necessarily
836   // lexically contained in the current context.  Fortunately,
837   // the containing scope should have the appropriate information.
838
839   assert(!S->getEntity() && "scope already has entity");
840
841 #ifndef NDEBUG
842   Scope *Ancestor = S->getParent();
843   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
844   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
845 #endif
846
847   CurContext = DC;
848   S->setEntity(DC);
849 }
850
851 void Sema::ExitDeclaratorContext(Scope *S) {
852   assert(S->getEntity() == CurContext && "Context imbalance!");
853
854   // Switch back to the lexical context.  The safety of this is
855   // enforced by an assert in EnterDeclaratorContext.
856   Scope *Ancestor = S->getParent();
857   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
858   CurContext = (DeclContext*) Ancestor->getEntity();
859
860   // We don't need to do anything with the scope, which is going to
861   // disappear.
862 }
863
864
865 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
866   FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
867   if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
868     // We assume that the caller has already called
869     // ActOnReenterTemplateScope
870     FD = TFD->getTemplatedDecl();
871   }
872   if (!FD)
873     return;
874
875   // Same implementation as PushDeclContext, but enters the context
876   // from the lexical parent, rather than the top-level class.
877   assert(CurContext == FD->getLexicalParent() &&
878     "The next DeclContext should be lexically contained in the current one.");
879   CurContext = FD;
880   S->setEntity(CurContext);
881
882   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
883     ParmVarDecl *Param = FD->getParamDecl(P);
884     // If the parameter has an identifier, then add it to the scope
885     if (Param->getIdentifier()) {
886       S->AddDecl(Param);
887       IdResolver.AddDecl(Param);
888     }
889   }
890 }
891
892
893 void Sema::ActOnExitFunctionContext() {
894   // Same implementation as PopDeclContext, but returns to the lexical parent,
895   // rather than the top-level class.
896   assert(CurContext && "DeclContext imbalance!");
897   CurContext = CurContext->getLexicalParent();
898   assert(CurContext && "Popped translation unit!");
899 }
900
901
902 /// \brief Determine whether we allow overloading of the function
903 /// PrevDecl with another declaration.
904 ///
905 /// This routine determines whether overloading is possible, not
906 /// whether some new function is actually an overload. It will return
907 /// true in C++ (where we can always provide overloads) or, as an
908 /// extension, in C when the previous function is already an
909 /// overloaded function declaration or has the "overloadable"
910 /// attribute.
911 static bool AllowOverloadingOfFunction(LookupResult &Previous,
912                                        ASTContext &Context) {
913   if (Context.getLangOpts().CPlusPlus)
914     return true;
915
916   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
917     return true;
918
919   return (Previous.getResultKind() == LookupResult::Found
920           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
921 }
922
923 /// Add this decl to the scope shadowed decl chains.
924 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
925   // Move up the scope chain until we find the nearest enclosing
926   // non-transparent context. The declaration will be introduced into this
927   // scope.
928   while (S->getEntity() &&
929          ((DeclContext *)S->getEntity())->isTransparentContext())
930     S = S->getParent();
931
932   // Add scoped declarations into their context, so that they can be
933   // found later. Declarations without a context won't be inserted
934   // into any context.
935   if (AddToContext)
936     CurContext->addDecl(D);
937
938   // Out-of-line definitions shouldn't be pushed into scope in C++.
939   // Out-of-line variable and function definitions shouldn't even in C.
940   if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
941       D->isOutOfLine() &&
942       !D->getDeclContext()->getRedeclContext()->Equals(
943         D->getLexicalDeclContext()->getRedeclContext()))
944     return;
945
946   // Template instantiations should also not be pushed into scope.
947   if (isa<FunctionDecl>(D) &&
948       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
949     return;
950
951   // If this replaces anything in the current scope, 
952   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
953                                IEnd = IdResolver.end();
954   for (; I != IEnd; ++I) {
955     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
956       S->RemoveDecl(*I);
957       IdResolver.RemoveDecl(*I);
958
959       // Should only need to replace one decl.
960       break;
961     }
962   }
963
964   S->AddDecl(D);
965   
966   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
967     // Implicitly-generated labels may end up getting generated in an order that
968     // isn't strictly lexical, which breaks name lookup. Be careful to insert
969     // the label at the appropriate place in the identifier chain.
970     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
971       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
972       if (IDC == CurContext) {
973         if (!S->isDeclScope(*I))
974           continue;
975       } else if (IDC->Encloses(CurContext))
976         break;
977     }
978     
979     IdResolver.InsertDeclAfter(I, D);
980   } else {
981     IdResolver.AddDecl(D);
982   }
983 }
984
985 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
986   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
987     TUScope->AddDecl(D);
988 }
989
990 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
991                          bool ExplicitInstantiationOrSpecialization) {
992   return IdResolver.isDeclInScope(D, Ctx, Context, S,
993                                   ExplicitInstantiationOrSpecialization);
994 }
995
996 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
997   DeclContext *TargetDC = DC->getPrimaryContext();
998   do {
999     if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1000       if (ScopeDC->getPrimaryContext() == TargetDC)
1001         return S;
1002   } while ((S = S->getParent()));
1003
1004   return 0;
1005 }
1006
1007 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1008                                             DeclContext*,
1009                                             ASTContext&);
1010
1011 /// Filters out lookup results that don't fall within the given scope
1012 /// as determined by isDeclInScope.
1013 void Sema::FilterLookupForScope(LookupResult &R,
1014                                 DeclContext *Ctx, Scope *S,
1015                                 bool ConsiderLinkage,
1016                                 bool ExplicitInstantiationOrSpecialization) {
1017   LookupResult::Filter F = R.makeFilter();
1018   while (F.hasNext()) {
1019     NamedDecl *D = F.next();
1020
1021     if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1022       continue;
1023
1024     if (ConsiderLinkage &&
1025         isOutOfScopePreviousDeclaration(D, Ctx, Context))
1026       continue;
1027     
1028     F.erase();
1029   }
1030
1031   F.done();
1032 }
1033
1034 static bool isUsingDecl(NamedDecl *D) {
1035   return isa<UsingShadowDecl>(D) ||
1036          isa<UnresolvedUsingTypenameDecl>(D) ||
1037          isa<UnresolvedUsingValueDecl>(D);
1038 }
1039
1040 /// Removes using shadow declarations from the lookup results.
1041 static void RemoveUsingDecls(LookupResult &R) {
1042   LookupResult::Filter F = R.makeFilter();
1043   while (F.hasNext())
1044     if (isUsingDecl(F.next()))
1045       F.erase();
1046
1047   F.done();
1048 }
1049
1050 /// \brief Check for this common pattern:
1051 /// @code
1052 /// class S {
1053 ///   S(const S&); // DO NOT IMPLEMENT
1054 ///   void operator=(const S&); // DO NOT IMPLEMENT
1055 /// };
1056 /// @endcode
1057 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1058   // FIXME: Should check for private access too but access is set after we get
1059   // the decl here.
1060   if (D->doesThisDeclarationHaveABody())
1061     return false;
1062
1063   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1064     return CD->isCopyConstructor();
1065   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1066     return Method->isCopyAssignmentOperator();
1067   return false;
1068 }
1069
1070 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1071   assert(D);
1072
1073   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1074     return false;
1075
1076   // Ignore class templates.
1077   if (D->getDeclContext()->isDependentContext() ||
1078       D->getLexicalDeclContext()->isDependentContext())
1079     return false;
1080
1081   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1082     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1083       return false;
1084
1085     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1086       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1087         return false;
1088     } else {
1089       // 'static inline' functions are used in headers; don't warn.
1090       if (FD->getStorageClass() == SC_Static &&
1091           FD->isInlineSpecified())
1092         return false;
1093     }
1094
1095     if (FD->doesThisDeclarationHaveABody() &&
1096         Context.DeclMustBeEmitted(FD))
1097       return false;
1098   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1099     if (!VD->isFileVarDecl() ||
1100         VD->getType().isConstant(Context) ||
1101         Context.DeclMustBeEmitted(VD))
1102       return false;
1103
1104     if (VD->isStaticDataMember() &&
1105         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1106       return false;
1107
1108   } else {
1109     return false;
1110   }
1111
1112   // Only warn for unused decls internal to the translation unit.
1113   if (D->getLinkage() == ExternalLinkage)
1114     return false;
1115
1116   return true;
1117 }
1118
1119 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1120   if (!D)
1121     return;
1122
1123   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1124     const FunctionDecl *First = FD->getFirstDeclaration();
1125     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1126       return; // First should already be in the vector.
1127   }
1128
1129   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1130     const VarDecl *First = VD->getFirstDeclaration();
1131     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1132       return; // First should already be in the vector.
1133   }
1134
1135    if (ShouldWarnIfUnusedFileScopedDecl(D))
1136      UnusedFileScopedDecls.push_back(D);
1137  }
1138
1139 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1140   if (D->isInvalidDecl())
1141     return false;
1142
1143   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1144     return false;
1145
1146   if (isa<LabelDecl>(D))
1147     return true;
1148   
1149   // White-list anything that isn't a local variable.
1150   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1151       !D->getDeclContext()->isFunctionOrMethod())
1152     return false;
1153
1154   // Types of valid local variables should be complete, so this should succeed.
1155   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1156
1157     // White-list anything with an __attribute__((unused)) type.
1158     QualType Ty = VD->getType();
1159
1160     // Only look at the outermost level of typedef.
1161     if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1162       if (TT->getDecl()->hasAttr<UnusedAttr>())
1163         return false;
1164     }
1165
1166     // If we failed to complete the type for some reason, or if the type is
1167     // dependent, don't diagnose the variable. 
1168     if (Ty->isIncompleteType() || Ty->isDependentType())
1169       return false;
1170
1171     if (const TagType *TT = Ty->getAs<TagType>()) {
1172       const TagDecl *Tag = TT->getDecl();
1173       if (Tag->hasAttr<UnusedAttr>())
1174         return false;
1175
1176       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1177         if (!RD->hasTrivialDestructor())
1178           return false;
1179
1180         if (const Expr *Init = VD->getInit()) {
1181           const CXXConstructExpr *Construct =
1182             dyn_cast<CXXConstructExpr>(Init);
1183           if (Construct && !Construct->isElidable()) {
1184             CXXConstructorDecl *CD = Construct->getConstructor();
1185             if (!CD->isTrivial())
1186               return false;
1187           }
1188         }
1189       }
1190     }
1191
1192     // TODO: __attribute__((unused)) templates?
1193   }
1194   
1195   return true;
1196 }
1197
1198 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1199                                      FixItHint &Hint) {
1200   if (isa<LabelDecl>(D)) {
1201     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1202                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1203     if (AfterColon.isInvalid())
1204       return;
1205     Hint = FixItHint::CreateRemoval(CharSourceRange::
1206                                     getCharRange(D->getLocStart(), AfterColon));
1207   }
1208   return;
1209 }
1210
1211 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1212 /// unless they are marked attr(unused).
1213 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1214   FixItHint Hint;
1215   if (!ShouldDiagnoseUnusedDecl(D))
1216     return;
1217   
1218   GenerateFixForUnusedDecl(D, Context, Hint);
1219
1220   unsigned DiagID;
1221   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1222     DiagID = diag::warn_unused_exception_param;
1223   else if (isa<LabelDecl>(D))
1224     DiagID = diag::warn_unused_label;
1225   else
1226     DiagID = diag::warn_unused_variable;
1227
1228   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1229 }
1230
1231 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1232   // Verify that we have no forward references left.  If so, there was a goto
1233   // or address of a label taken, but no definition of it.  Label fwd
1234   // definitions are indicated with a null substmt.
1235   if (L->getStmt() == 0)
1236     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1237 }
1238
1239 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1240   if (S->decl_empty()) return;
1241   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1242          "Scope shouldn't contain decls!");
1243
1244   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1245        I != E; ++I) {
1246     Decl *TmpD = (*I);
1247     assert(TmpD && "This decl didn't get pushed??");
1248
1249     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1250     NamedDecl *D = cast<NamedDecl>(TmpD);
1251
1252     if (!D->getDeclName()) continue;
1253
1254     // Diagnose unused variables in this scope.
1255     if (!S->hasErrorOccurred())
1256       DiagnoseUnusedDecl(D);
1257     
1258     // If this was a forward reference to a label, verify it was defined.
1259     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1260       CheckPoppedLabel(LD, *this);
1261     
1262     // Remove this name from our lexical scope.
1263     IdResolver.RemoveDecl(D);
1264   }
1265 }
1266
1267 void Sema::ActOnStartFunctionDeclarator() {
1268   ++InFunctionDeclarator;
1269 }
1270
1271 void Sema::ActOnEndFunctionDeclarator() {
1272   assert(InFunctionDeclarator);
1273   --InFunctionDeclarator;
1274 }
1275
1276 /// \brief Look for an Objective-C class in the translation unit.
1277 ///
1278 /// \param Id The name of the Objective-C class we're looking for. If
1279 /// typo-correction fixes this name, the Id will be updated
1280 /// to the fixed name.
1281 ///
1282 /// \param IdLoc The location of the name in the translation unit.
1283 ///
1284 /// \param TypoCorrection If true, this routine will attempt typo correction
1285 /// if there is no class with the given name.
1286 ///
1287 /// \returns The declaration of the named Objective-C class, or NULL if the
1288 /// class could not be found.
1289 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1290                                               SourceLocation IdLoc,
1291                                               bool DoTypoCorrection) {
1292   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1293   // creation from this context.
1294   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1295
1296   if (!IDecl && DoTypoCorrection) {
1297     // Perform typo correction at the given location, but only if we
1298     // find an Objective-C class name.
1299     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1300     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1301                                        LookupOrdinaryName, TUScope, NULL,
1302                                        Validator)) {
1303       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1304       Diag(IdLoc, diag::err_undef_interface_suggest)
1305         << Id << IDecl->getDeclName() 
1306         << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1307       Diag(IDecl->getLocation(), diag::note_previous_decl)
1308         << IDecl->getDeclName();
1309       
1310       Id = IDecl->getIdentifier();
1311     }
1312   }
1313   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1314   // This routine must always return a class definition, if any.
1315   if (Def && Def->getDefinition())
1316       Def = Def->getDefinition();
1317   return Def;
1318 }
1319
1320 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1321 /// from S, where a non-field would be declared. This routine copes
1322 /// with the difference between C and C++ scoping rules in structs and
1323 /// unions. For example, the following code is well-formed in C but
1324 /// ill-formed in C++:
1325 /// @code
1326 /// struct S6 {
1327 ///   enum { BAR } e;
1328 /// };
1329 ///
1330 /// void test_S6() {
1331 ///   struct S6 a;
1332 ///   a.e = BAR;
1333 /// }
1334 /// @endcode
1335 /// For the declaration of BAR, this routine will return a different
1336 /// scope. The scope S will be the scope of the unnamed enumeration
1337 /// within S6. In C++, this routine will return the scope associated
1338 /// with S6, because the enumeration's scope is a transparent
1339 /// context but structures can contain non-field names. In C, this
1340 /// routine will return the translation unit scope, since the
1341 /// enumeration's scope is a transparent context and structures cannot
1342 /// contain non-field names.
1343 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1344   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1345          (S->getEntity() &&
1346           ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1347          (S->isClassScope() && !getLangOpts().CPlusPlus))
1348     S = S->getParent();
1349   return S;
1350 }
1351
1352 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1353 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1354 /// if we're creating this built-in in anticipation of redeclaring the
1355 /// built-in.
1356 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1357                                      Scope *S, bool ForRedeclaration,
1358                                      SourceLocation Loc) {
1359   Builtin::ID BID = (Builtin::ID)bid;
1360
1361   ASTContext::GetBuiltinTypeError Error;
1362   QualType R = Context.GetBuiltinType(BID, Error);
1363   switch (Error) {
1364   case ASTContext::GE_None:
1365     // Okay
1366     break;
1367
1368   case ASTContext::GE_Missing_stdio:
1369     if (ForRedeclaration)
1370       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1371         << Context.BuiltinInfo.GetName(BID);
1372     return 0;
1373
1374   case ASTContext::GE_Missing_setjmp:
1375     if (ForRedeclaration)
1376       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1377         << Context.BuiltinInfo.GetName(BID);
1378     return 0;
1379
1380   case ASTContext::GE_Missing_ucontext:
1381     if (ForRedeclaration)
1382       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1383         << Context.BuiltinInfo.GetName(BID);
1384     return 0;
1385   }
1386
1387   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1388     Diag(Loc, diag::ext_implicit_lib_function_decl)
1389       << Context.BuiltinInfo.GetName(BID)
1390       << R;
1391     if (Context.BuiltinInfo.getHeaderName(BID) &&
1392         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1393           != DiagnosticsEngine::Ignored)
1394       Diag(Loc, diag::note_please_include_header)
1395         << Context.BuiltinInfo.getHeaderName(BID)
1396         << Context.BuiltinInfo.GetName(BID);
1397   }
1398
1399   FunctionDecl *New = FunctionDecl::Create(Context,
1400                                            Context.getTranslationUnitDecl(),
1401                                            Loc, Loc, II, R, /*TInfo=*/0,
1402                                            SC_Extern,
1403                                            SC_None, false,
1404                                            /*hasPrototype=*/true);
1405   New->setImplicit();
1406
1407   // Create Decl objects for each parameter, adding them to the
1408   // FunctionDecl.
1409   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1410     SmallVector<ParmVarDecl*, 16> Params;
1411     for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1412       ParmVarDecl *parm =
1413         ParmVarDecl::Create(Context, New, SourceLocation(),
1414                             SourceLocation(), 0,
1415                             FT->getArgType(i), /*TInfo=*/0,
1416                             SC_None, SC_None, 0);
1417       parm->setScopeInfo(0, i);
1418       Params.push_back(parm);
1419     }
1420     New->setParams(Params);
1421   }
1422
1423   AddKnownFunctionAttributes(New);
1424
1425   // TUScope is the translation-unit scope to insert this function into.
1426   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1427   // relate Scopes to DeclContexts, and probably eliminate CurContext
1428   // entirely, but we're not there yet.
1429   DeclContext *SavedContext = CurContext;
1430   CurContext = Context.getTranslationUnitDecl();
1431   PushOnScopeChains(New, TUScope);
1432   CurContext = SavedContext;
1433   return New;
1434 }
1435
1436 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1437   QualType OldType;
1438   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1439     OldType = OldTypedef->getUnderlyingType();
1440   else
1441     OldType = Context.getTypeDeclType(Old);
1442   QualType NewType = New->getUnderlyingType();
1443
1444   if (NewType->isVariablyModifiedType()) {
1445     // Must not redefine a typedef with a variably-modified type.
1446     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1447     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1448       << Kind << NewType;
1449     if (Old->getLocation().isValid())
1450       Diag(Old->getLocation(), diag::note_previous_definition);
1451     New->setInvalidDecl();
1452     return true;    
1453   }
1454   
1455   if (OldType != NewType &&
1456       !OldType->isDependentType() &&
1457       !NewType->isDependentType() &&
1458       !Context.hasSameType(OldType, NewType)) { 
1459     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1460     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1461       << Kind << NewType << OldType;
1462     if (Old->getLocation().isValid())
1463       Diag(Old->getLocation(), diag::note_previous_definition);
1464     New->setInvalidDecl();
1465     return true;
1466   }
1467   return false;
1468 }
1469
1470 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1471 /// same name and scope as a previous declaration 'Old'.  Figure out
1472 /// how to resolve this situation, merging decls or emitting
1473 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1474 ///
1475 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1476   // If the new decl is known invalid already, don't bother doing any
1477   // merging checks.
1478   if (New->isInvalidDecl()) return;
1479
1480   // Allow multiple definitions for ObjC built-in typedefs.
1481   // FIXME: Verify the underlying types are equivalent!
1482   if (getLangOpts().ObjC1) {
1483     const IdentifierInfo *TypeID = New->getIdentifier();
1484     switch (TypeID->getLength()) {
1485     default: break;
1486     case 2:
1487       if (!TypeID->isStr("id"))
1488         break;
1489       Context.setObjCIdRedefinitionType(New->getUnderlyingType());
1490       // Install the built-in type for 'id', ignoring the current definition.
1491       New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1492       return;
1493     case 5:
1494       if (!TypeID->isStr("Class"))
1495         break;
1496       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1497       // Install the built-in type for 'Class', ignoring the current definition.
1498       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1499       return;
1500     case 3:
1501       if (!TypeID->isStr("SEL"))
1502         break;
1503       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1504       // Install the built-in type for 'SEL', ignoring the current definition.
1505       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1506       return;
1507     }
1508     // Fall through - the typedef name was not a builtin type.
1509   }
1510
1511   // Verify the old decl was also a type.
1512   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1513   if (!Old) {
1514     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1515       << New->getDeclName();
1516
1517     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1518     if (OldD->getLocation().isValid())
1519       Diag(OldD->getLocation(), diag::note_previous_definition);
1520
1521     return New->setInvalidDecl();
1522   }
1523
1524   // If the old declaration is invalid, just give up here.
1525   if (Old->isInvalidDecl())
1526     return New->setInvalidDecl();
1527
1528   // If the typedef types are not identical, reject them in all languages and
1529   // with any extensions enabled.
1530   if (isIncompatibleTypedef(Old, New))
1531     return;
1532
1533   // The types match.  Link up the redeclaration chain if the old
1534   // declaration was a typedef.
1535   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1536     New->setPreviousDeclaration(Typedef);
1537
1538   if (getLangOpts().MicrosoftExt)
1539     return;
1540
1541   if (getLangOpts().CPlusPlus) {
1542     // C++ [dcl.typedef]p2:
1543     //   In a given non-class scope, a typedef specifier can be used to
1544     //   redefine the name of any type declared in that scope to refer
1545     //   to the type to which it already refers.
1546     if (!isa<CXXRecordDecl>(CurContext))
1547       return;
1548
1549     // C++0x [dcl.typedef]p4:
1550     //   In a given class scope, a typedef specifier can be used to redefine 
1551     //   any class-name declared in that scope that is not also a typedef-name
1552     //   to refer to the type to which it already refers.
1553     //
1554     // This wording came in via DR424, which was a correction to the
1555     // wording in DR56, which accidentally banned code like:
1556     //
1557     //   struct S {
1558     //     typedef struct A { } A;
1559     //   };
1560     //
1561     // in the C++03 standard. We implement the C++0x semantics, which
1562     // allow the above but disallow
1563     //
1564     //   struct S {
1565     //     typedef int I;
1566     //     typedef int I;
1567     //   };
1568     //
1569     // since that was the intent of DR56.
1570     if (!isa<TypedefNameDecl>(Old))
1571       return;
1572
1573     Diag(New->getLocation(), diag::err_redefinition)
1574       << New->getDeclName();
1575     Diag(Old->getLocation(), diag::note_previous_definition);
1576     return New->setInvalidDecl();
1577   }
1578
1579   // Modules always permit redefinition of typedefs, as does C11.
1580   if (getLangOpts().Modules || getLangOpts().C11)
1581     return;
1582   
1583   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1584   // is normally mapped to an error, but can be controlled with
1585   // -Wtypedef-redefinition.  If either the original or the redefinition is
1586   // in a system header, don't emit this for compatibility with GCC.
1587   if (getDiagnostics().getSuppressSystemWarnings() &&
1588       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1589        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1590     return;
1591
1592   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1593     << New->getDeclName();
1594   Diag(Old->getLocation(), diag::note_previous_definition);
1595   return;
1596 }
1597
1598 /// DeclhasAttr - returns true if decl Declaration already has the target
1599 /// attribute.
1600 static bool
1601 DeclHasAttr(const Decl *D, const Attr *A) {
1602   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1603   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1604   for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1605     if ((*i)->getKind() == A->getKind()) {
1606       if (Ann) {
1607         if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1608           return true;
1609         continue;
1610       }
1611       // FIXME: Don't hardcode this check
1612       if (OA && isa<OwnershipAttr>(*i))
1613         return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1614       return true;
1615     }
1616
1617   return false;
1618 }
1619
1620 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1621 void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1622                                bool MergeDeprecation) {
1623   if (!Old->hasAttrs())
1624     return;
1625
1626   bool foundAny = New->hasAttrs();
1627
1628   // Ensure that any moving of objects within the allocated map is done before
1629   // we process them.
1630   if (!foundAny) New->setAttrs(AttrVec());
1631
1632   for (specific_attr_iterator<InheritableAttr>
1633          i = Old->specific_attr_begin<InheritableAttr>(),
1634          e = Old->specific_attr_end<InheritableAttr>(); 
1635        i != e; ++i) {
1636     // Ignore deprecated/unavailable/availability attributes if requested.
1637     if (!MergeDeprecation &&
1638         (isa<DeprecatedAttr>(*i) || 
1639          isa<UnavailableAttr>(*i) ||
1640          isa<AvailabilityAttr>(*i)))
1641       continue;
1642
1643     if (!DeclHasAttr(New, *i)) {
1644       InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(Context));
1645       newAttr->setInherited(true);
1646       New->addAttr(newAttr);
1647       foundAny = true;
1648     }
1649   }
1650
1651   if (!foundAny) New->dropAttrs();
1652 }
1653
1654 /// mergeParamDeclAttributes - Copy attributes from the old parameter
1655 /// to the new one.
1656 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1657                                      const ParmVarDecl *oldDecl,
1658                                      ASTContext &C) {
1659   if (!oldDecl->hasAttrs())
1660     return;
1661
1662   bool foundAny = newDecl->hasAttrs();
1663
1664   // Ensure that any moving of objects within the allocated map is
1665   // done before we process them.
1666   if (!foundAny) newDecl->setAttrs(AttrVec());
1667
1668   for (specific_attr_iterator<InheritableParamAttr>
1669        i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1670        e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1671     if (!DeclHasAttr(newDecl, *i)) {
1672       InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1673       newAttr->setInherited(true);
1674       newDecl->addAttr(newAttr);
1675       foundAny = true;
1676     }
1677   }
1678
1679   if (!foundAny) newDecl->dropAttrs();
1680 }
1681
1682 namespace {
1683
1684 /// Used in MergeFunctionDecl to keep track of function parameters in
1685 /// C.
1686 struct GNUCompatibleParamWarning {
1687   ParmVarDecl *OldParm;
1688   ParmVarDecl *NewParm;
1689   QualType PromotedType;
1690 };
1691
1692 }
1693
1694 /// getSpecialMember - get the special member enum for a method.
1695 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1696   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1697     if (Ctor->isDefaultConstructor())
1698       return Sema::CXXDefaultConstructor;
1699
1700     if (Ctor->isCopyConstructor())
1701       return Sema::CXXCopyConstructor;
1702
1703     if (Ctor->isMoveConstructor())
1704       return Sema::CXXMoveConstructor;
1705   } else if (isa<CXXDestructorDecl>(MD)) {
1706     return Sema::CXXDestructor;
1707   } else if (MD->isCopyAssignmentOperator()) {
1708     return Sema::CXXCopyAssignment;
1709   } else if (MD->isMoveAssignmentOperator()) {
1710     return Sema::CXXMoveAssignment;
1711   }
1712
1713   return Sema::CXXInvalid;
1714 }
1715
1716 /// canRedefineFunction - checks if a function can be redefined. Currently,
1717 /// only extern inline functions can be redefined, and even then only in
1718 /// GNU89 mode.
1719 static bool canRedefineFunction(const FunctionDecl *FD,
1720                                 const LangOptions& LangOpts) {
1721   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1722           !LangOpts.CPlusPlus &&
1723           FD->isInlineSpecified() &&
1724           FD->getStorageClass() == SC_Extern);
1725 }
1726
1727 /// MergeFunctionDecl - We just parsed a function 'New' from
1728 /// declarator D which has the same name and scope as a previous
1729 /// declaration 'Old'.  Figure out how to resolve this situation,
1730 /// merging decls or emitting diagnostics as appropriate.
1731 ///
1732 /// In C++, New and Old must be declarations that are not
1733 /// overloaded. Use IsOverload to determine whether New and Old are
1734 /// overloaded, and to select the Old declaration that New should be
1735 /// merged with.
1736 ///
1737 /// Returns true if there was an error, false otherwise.
1738 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
1739   // Verify the old decl was also a function.
1740   FunctionDecl *Old = 0;
1741   if (FunctionTemplateDecl *OldFunctionTemplate
1742         = dyn_cast<FunctionTemplateDecl>(OldD))
1743     Old = OldFunctionTemplate->getTemplatedDecl();
1744   else
1745     Old = dyn_cast<FunctionDecl>(OldD);
1746   if (!Old) {
1747     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1748       Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1749       Diag(Shadow->getTargetDecl()->getLocation(),
1750            diag::note_using_decl_target);
1751       Diag(Shadow->getUsingDecl()->getLocation(),
1752            diag::note_using_decl) << 0;
1753       return true;
1754     }
1755
1756     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1757       << New->getDeclName();
1758     Diag(OldD->getLocation(), diag::note_previous_definition);
1759     return true;
1760   }
1761
1762   // Determine whether the previous declaration was a definition,
1763   // implicit declaration, or a declaration.
1764   diag::kind PrevDiag;
1765   if (Old->isThisDeclarationADefinition())
1766     PrevDiag = diag::note_previous_definition;
1767   else if (Old->isImplicit())
1768     PrevDiag = diag::note_previous_implicit_declaration;
1769   else
1770     PrevDiag = diag::note_previous_declaration;
1771
1772   QualType OldQType = Context.getCanonicalType(Old->getType());
1773   QualType NewQType = Context.getCanonicalType(New->getType());
1774
1775   // Don't complain about this if we're in GNU89 mode and the old function
1776   // is an extern inline function.
1777   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1778       New->getStorageClass() == SC_Static &&
1779       Old->getStorageClass() != SC_Static &&
1780       !canRedefineFunction(Old, getLangOpts())) {
1781     if (getLangOpts().MicrosoftExt) {
1782       Diag(New->getLocation(), diag::warn_static_non_static) << New;
1783       Diag(Old->getLocation(), PrevDiag);
1784     } else {
1785       Diag(New->getLocation(), diag::err_static_non_static) << New;
1786       Diag(Old->getLocation(), PrevDiag);
1787       return true;
1788     }
1789   }
1790
1791   // If a function is first declared with a calling convention, but is
1792   // later declared or defined without one, the second decl assumes the
1793   // calling convention of the first.
1794   //
1795   // For the new decl, we have to look at the NON-canonical type to tell the
1796   // difference between a function that really doesn't have a calling
1797   // convention and one that is declared cdecl. That's because in
1798   // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1799   // because it is the default calling convention.
1800   //
1801   // Note also that we DO NOT return at this point, because we still have
1802   // other tests to run.
1803   const FunctionType *OldType = cast<FunctionType>(OldQType);
1804   const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1805   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1806   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1807   bool RequiresAdjustment = false;
1808   if (OldTypeInfo.getCC() != CC_Default &&
1809       NewTypeInfo.getCC() == CC_Default) {
1810     NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1811     RequiresAdjustment = true;
1812   } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1813                                      NewTypeInfo.getCC())) {
1814     // Calling conventions really aren't compatible, so complain.
1815     Diag(New->getLocation(), diag::err_cconv_change)
1816       << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1817       << (OldTypeInfo.getCC() == CC_Default)
1818       << (OldTypeInfo.getCC() == CC_Default ? "" :
1819           FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1820     Diag(Old->getLocation(), diag::note_previous_declaration);
1821     return true;
1822   }
1823
1824   // FIXME: diagnose the other way around?
1825   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1826     NewTypeInfo = NewTypeInfo.withNoReturn(true);
1827     RequiresAdjustment = true;
1828   }
1829
1830   // Merge regparm attribute.
1831   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1832       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1833     if (NewTypeInfo.getHasRegParm()) {
1834       Diag(New->getLocation(), diag::err_regparm_mismatch)
1835         << NewType->getRegParmType()
1836         << OldType->getRegParmType();
1837       Diag(Old->getLocation(), diag::note_previous_declaration);      
1838       return true;
1839     }
1840
1841     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1842     RequiresAdjustment = true;
1843   }
1844
1845   // Merge ns_returns_retained attribute.
1846   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
1847     if (NewTypeInfo.getProducesResult()) {
1848       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
1849       Diag(Old->getLocation(), diag::note_previous_declaration);      
1850       return true;
1851     }
1852     
1853     NewTypeInfo = NewTypeInfo.withProducesResult(true);
1854     RequiresAdjustment = true;
1855   }
1856   
1857   if (RequiresAdjustment) {
1858     NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1859     New->setType(QualType(NewType, 0));
1860     NewQType = Context.getCanonicalType(New->getType());
1861   }
1862   
1863   if (getLangOpts().CPlusPlus) {
1864     // (C++98 13.1p2):
1865     //   Certain function declarations cannot be overloaded:
1866     //     -- Function declarations that differ only in the return type
1867     //        cannot be overloaded.
1868     QualType OldReturnType = OldType->getResultType();
1869     QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
1870     QualType ResQT;
1871     if (OldReturnType != NewReturnType) {
1872       if (NewReturnType->isObjCObjectPointerType()
1873           && OldReturnType->isObjCObjectPointerType())
1874         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1875       if (ResQT.isNull()) {
1876         if (New->isCXXClassMember() && New->isOutOfLine())
1877           Diag(New->getLocation(),
1878                diag::err_member_def_does_not_match_ret_type) << New;
1879         else
1880           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1881         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1882         return true;
1883       }
1884       else
1885         NewQType = ResQT;
1886     }
1887
1888     const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1889     CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1890     if (OldMethod && NewMethod) {
1891       // Preserve triviality.
1892       NewMethod->setTrivial(OldMethod->isTrivial());
1893
1894       // MSVC allows explicit template specialization at class scope:
1895       // 2 CXMethodDecls referring to the same function will be injected.
1896       // We don't want a redeclartion error.
1897       bool IsClassScopeExplicitSpecialization =
1898                               OldMethod->isFunctionTemplateSpecialization() &&
1899                               NewMethod->isFunctionTemplateSpecialization();
1900       bool isFriend = NewMethod->getFriendObjectKind();
1901
1902       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
1903           !IsClassScopeExplicitSpecialization) {
1904         //    -- Member function declarations with the same name and the
1905         //       same parameter types cannot be overloaded if any of them
1906         //       is a static member function declaration.
1907         if (OldMethod->isStatic() || NewMethod->isStatic()) {
1908           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1909           Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1910           return true;
1911         }
1912       
1913         // C++ [class.mem]p1:
1914         //   [...] A member shall not be declared twice in the
1915         //   member-specification, except that a nested class or member
1916         //   class template can be declared and then later defined.
1917         unsigned NewDiag;
1918         if (isa<CXXConstructorDecl>(OldMethod))
1919           NewDiag = diag::err_constructor_redeclared;
1920         else if (isa<CXXDestructorDecl>(NewMethod))
1921           NewDiag = diag::err_destructor_redeclared;
1922         else if (isa<CXXConversionDecl>(NewMethod))
1923           NewDiag = diag::err_conv_function_redeclared;
1924         else
1925           NewDiag = diag::err_member_redeclared;
1926
1927         Diag(New->getLocation(), NewDiag);
1928         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1929
1930       // Complain if this is an explicit declaration of a special
1931       // member that was initially declared implicitly.
1932       //
1933       // As an exception, it's okay to befriend such methods in order
1934       // to permit the implicit constructor/destructor/operator calls.
1935       } else if (OldMethod->isImplicit()) {
1936         if (isFriend) {
1937           NewMethod->setImplicit();
1938         } else {
1939           Diag(NewMethod->getLocation(),
1940                diag::err_definition_of_implicitly_declared_member) 
1941             << New << getSpecialMember(OldMethod);
1942           return true;
1943         }
1944       } else if (OldMethod->isExplicitlyDefaulted()) {
1945         Diag(NewMethod->getLocation(),
1946              diag::err_definition_of_explicitly_defaulted_member)
1947           << getSpecialMember(OldMethod);
1948         return true;
1949       }
1950     }
1951
1952     // (C++98 8.3.5p3):
1953     //   All declarations for a function shall agree exactly in both the
1954     //   return type and the parameter-type-list.
1955     // We also want to respect all the extended bits except noreturn.
1956
1957     // noreturn should now match unless the old type info didn't have it.
1958     QualType OldQTypeForComparison = OldQType;
1959     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1960       assert(OldQType == QualType(OldType, 0));
1961       const FunctionType *OldTypeForComparison
1962         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1963       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1964       assert(OldQTypeForComparison.isCanonical());
1965     }
1966
1967     if (OldQTypeForComparison == NewQType)
1968       return MergeCompatibleFunctionDecls(New, Old, S);
1969
1970     // Fall through for conflicting redeclarations and redefinitions.
1971   }
1972
1973   // C: Function types need to be compatible, not identical. This handles
1974   // duplicate function decls like "void f(int); void f(enum X);" properly.
1975   if (!getLangOpts().CPlusPlus &&
1976       Context.typesAreCompatible(OldQType, NewQType)) {
1977     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1978     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1979     const FunctionProtoType *OldProto = 0;
1980     if (isa<FunctionNoProtoType>(NewFuncType) &&
1981         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1982       // The old declaration provided a function prototype, but the
1983       // new declaration does not. Merge in the prototype.
1984       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1985       SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1986                                                  OldProto->arg_type_end());
1987       NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1988                                          ParamTypes.data(), ParamTypes.size(),
1989                                          OldProto->getExtProtoInfo());
1990       New->setType(NewQType);
1991       New->setHasInheritedPrototype();
1992
1993       // Synthesize a parameter for each argument type.
1994       SmallVector<ParmVarDecl*, 16> Params;
1995       for (FunctionProtoType::arg_type_iterator
1996              ParamType = OldProto->arg_type_begin(),
1997              ParamEnd = OldProto->arg_type_end();
1998            ParamType != ParamEnd; ++ParamType) {
1999         ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2000                                                  SourceLocation(),
2001                                                  SourceLocation(), 0,
2002                                                  *ParamType, /*TInfo=*/0,
2003                                                  SC_None, SC_None,
2004                                                  0);
2005         Param->setScopeInfo(0, Params.size());
2006         Param->setImplicit();
2007         Params.push_back(Param);
2008       }
2009
2010       New->setParams(Params);
2011     }
2012
2013     return MergeCompatibleFunctionDecls(New, Old, S);
2014   }
2015
2016   // GNU C permits a K&R definition to follow a prototype declaration
2017   // if the declared types of the parameters in the K&R definition
2018   // match the types in the prototype declaration, even when the
2019   // promoted types of the parameters from the K&R definition differ
2020   // from the types in the prototype. GCC then keeps the types from
2021   // the prototype.
2022   //
2023   // If a variadic prototype is followed by a non-variadic K&R definition,
2024   // the K&R definition becomes variadic.  This is sort of an edge case, but
2025   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2026   // C99 6.9.1p8.
2027   if (!getLangOpts().CPlusPlus &&
2028       Old->hasPrototype() && !New->hasPrototype() &&
2029       New->getType()->getAs<FunctionProtoType>() &&
2030       Old->getNumParams() == New->getNumParams()) {
2031     SmallVector<QualType, 16> ArgTypes;
2032     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2033     const FunctionProtoType *OldProto
2034       = Old->getType()->getAs<FunctionProtoType>();
2035     const FunctionProtoType *NewProto
2036       = New->getType()->getAs<FunctionProtoType>();
2037
2038     // Determine whether this is the GNU C extension.
2039     QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2040                                                NewProto->getResultType());
2041     bool LooseCompatible = !MergedReturn.isNull();
2042     for (unsigned Idx = 0, End = Old->getNumParams();
2043          LooseCompatible && Idx != End; ++Idx) {
2044       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2045       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2046       if (Context.typesAreCompatible(OldParm->getType(),
2047                                      NewProto->getArgType(Idx))) {
2048         ArgTypes.push_back(NewParm->getType());
2049       } else if (Context.typesAreCompatible(OldParm->getType(),
2050                                             NewParm->getType(),
2051                                             /*CompareUnqualified=*/true)) {
2052         GNUCompatibleParamWarning Warn
2053           = { OldParm, NewParm, NewProto->getArgType(Idx) };
2054         Warnings.push_back(Warn);
2055         ArgTypes.push_back(NewParm->getType());
2056       } else
2057         LooseCompatible = false;
2058     }
2059
2060     if (LooseCompatible) {
2061       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2062         Diag(Warnings[Warn].NewParm->getLocation(),
2063              diag::ext_param_promoted_not_compatible_with_prototype)
2064           << Warnings[Warn].PromotedType
2065           << Warnings[Warn].OldParm->getType();
2066         if (Warnings[Warn].OldParm->getLocation().isValid())
2067           Diag(Warnings[Warn].OldParm->getLocation(),
2068                diag::note_previous_declaration);
2069       }
2070
2071       New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2072                                            ArgTypes.size(),
2073                                            OldProto->getExtProtoInfo()));
2074       return MergeCompatibleFunctionDecls(New, Old, S);
2075     }
2076
2077     // Fall through to diagnose conflicting types.
2078   }
2079
2080   // A function that has already been declared has been redeclared or defined
2081   // with a different type- show appropriate diagnostic
2082   if (unsigned BuiltinID = Old->getBuiltinID()) {
2083     // The user has declared a builtin function with an incompatible
2084     // signature.
2085     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2086       // The function the user is redeclaring is a library-defined
2087       // function like 'malloc' or 'printf'. Warn about the
2088       // redeclaration, then pretend that we don't know about this
2089       // library built-in.
2090       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2091       Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2092         << Old << Old->getType();
2093       New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2094       Old->setInvalidDecl();
2095       return false;
2096     }
2097
2098     PrevDiag = diag::note_previous_builtin_declaration;
2099   }
2100
2101   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2102   Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2103   return true;
2104 }
2105
2106 /// \brief Completes the merge of two function declarations that are
2107 /// known to be compatible.
2108 ///
2109 /// This routine handles the merging of attributes and other
2110 /// properties of function declarations form the old declaration to
2111 /// the new declaration, once we know that New is in fact a
2112 /// redeclaration of Old.
2113 ///
2114 /// \returns false
2115 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2116                                         Scope *S) {
2117   // Merge the attributes
2118   mergeDeclAttributes(New, Old);
2119
2120   // Merge the storage class.
2121   if (Old->getStorageClass() != SC_Extern &&
2122       Old->getStorageClass() != SC_None)
2123     New->setStorageClass(Old->getStorageClass());
2124
2125   // Merge "pure" flag.
2126   if (Old->isPure())
2127     New->setPure();
2128
2129   // Merge attributes from the parameters.  These can mismatch with K&R
2130   // declarations.
2131   if (New->getNumParams() == Old->getNumParams())
2132     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2133       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2134                                Context);
2135
2136   if (getLangOpts().CPlusPlus)
2137     return MergeCXXFunctionDecl(New, Old, S);
2138
2139   return false;
2140 }
2141
2142
2143 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2144                                 ObjCMethodDecl *oldMethod) {
2145   // We don't want to merge unavailable and deprecated attributes
2146   // except from interface to implementation.
2147   bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
2148
2149   // Merge the attributes.
2150   mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation);
2151
2152   // Merge attributes from the parameters.
2153   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin();
2154   for (ObjCMethodDecl::param_iterator
2155          ni = newMethod->param_begin(), ne = newMethod->param_end();
2156        ni != ne; ++ni, ++oi)
2157     mergeParamDeclAttributes(*ni, *oi, Context);
2158
2159   CheckObjCMethodOverride(newMethod, oldMethod, true);
2160 }
2161
2162 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2163 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2164 /// emitting diagnostics as appropriate.
2165 ///
2166 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2167 /// to here in AddInitializerToDecl. We can't check them before the initializer
2168 /// is attached.
2169 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2170   if (New->isInvalidDecl() || Old->isInvalidDecl())
2171     return;
2172
2173   QualType MergedT;
2174   if (getLangOpts().CPlusPlus) {
2175     AutoType *AT = New->getType()->getContainedAutoType();
2176     if (AT && !AT->isDeduced()) {
2177       // We don't know what the new type is until the initializer is attached.
2178       return;
2179     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2180       // These could still be something that needs exception specs checked.
2181       return MergeVarDeclExceptionSpecs(New, Old);
2182     }
2183     // C++ [basic.link]p10:
2184     //   [...] the types specified by all declarations referring to a given
2185     //   object or function shall be identical, except that declarations for an
2186     //   array object can specify array types that differ by the presence or
2187     //   absence of a major array bound (8.3.4).
2188     else if (Old->getType()->isIncompleteArrayType() &&
2189              New->getType()->isArrayType()) {
2190       CanQual<ArrayType> OldArray
2191         = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2192       CanQual<ArrayType> NewArray
2193         = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2194       if (OldArray->getElementType() == NewArray->getElementType())
2195         MergedT = New->getType();
2196     } else if (Old->getType()->isArrayType() &&
2197              New->getType()->isIncompleteArrayType()) {
2198       CanQual<ArrayType> OldArray
2199         = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2200       CanQual<ArrayType> NewArray
2201         = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2202       if (OldArray->getElementType() == NewArray->getElementType())
2203         MergedT = Old->getType();
2204     } else if (New->getType()->isObjCObjectPointerType()
2205                && Old->getType()->isObjCObjectPointerType()) {
2206         MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2207                                                         Old->getType());
2208     }
2209   } else {
2210     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2211   }
2212   if (MergedT.isNull()) {
2213     Diag(New->getLocation(), diag::err_redefinition_different_type)
2214       << New->getDeclName();
2215     Diag(Old->getLocation(), diag::note_previous_definition);
2216     return New->setInvalidDecl();
2217   }
2218   New->setType(MergedT);
2219 }
2220
2221 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2222 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2223 /// situation, merging decls or emitting diagnostics as appropriate.
2224 ///
2225 /// Tentative definition rules (C99 6.9.2p2) are checked by
2226 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2227 /// definitions here, since the initializer hasn't been attached.
2228 ///
2229 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2230   // If the new decl is already invalid, don't do any other checking.
2231   if (New->isInvalidDecl())
2232     return;
2233
2234   // Verify the old decl was also a variable.
2235   VarDecl *Old = 0;
2236   if (!Previous.isSingleResult() ||
2237       !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2238     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2239       << New->getDeclName();
2240     Diag(Previous.getRepresentativeDecl()->getLocation(),
2241          diag::note_previous_definition);
2242     return New->setInvalidDecl();
2243   }
2244
2245   // C++ [class.mem]p1:
2246   //   A member shall not be declared twice in the member-specification [...]
2247   // 
2248   // Here, we need only consider static data members.
2249   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2250     Diag(New->getLocation(), diag::err_duplicate_member) 
2251       << New->getIdentifier();
2252     Diag(Old->getLocation(), diag::note_previous_declaration);
2253     New->setInvalidDecl();
2254   }
2255   
2256   mergeDeclAttributes(New, Old);
2257   // Warn if an already-declared variable is made a weak_import in a subsequent 
2258   // declaration
2259   if (New->getAttr<WeakImportAttr>() &&
2260       Old->getStorageClass() == SC_None &&
2261       !Old->getAttr<WeakImportAttr>()) {
2262     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2263     Diag(Old->getLocation(), diag::note_previous_definition);
2264     // Remove weak_import attribute on new declaration.
2265     New->dropAttr<WeakImportAttr>();
2266   }
2267
2268   // Merge the types.
2269   MergeVarDeclTypes(New, Old);
2270   if (New->isInvalidDecl())
2271     return;
2272
2273   // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2274   if (New->getStorageClass() == SC_Static &&
2275       (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2276     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2277     Diag(Old->getLocation(), diag::note_previous_definition);
2278     return New->setInvalidDecl();
2279   }
2280   // C99 6.2.2p4:
2281   //   For an identifier declared with the storage-class specifier
2282   //   extern in a scope in which a prior declaration of that
2283   //   identifier is visible,23) if the prior declaration specifies
2284   //   internal or external linkage, the linkage of the identifier at
2285   //   the later declaration is the same as the linkage specified at
2286   //   the prior declaration. If no prior declaration is visible, or
2287   //   if the prior declaration specifies no linkage, then the
2288   //   identifier has external linkage.
2289   if (New->hasExternalStorage() && Old->hasLinkage())
2290     /* Okay */;
2291   else if (New->getStorageClass() != SC_Static &&
2292            Old->getStorageClass() == SC_Static) {
2293     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2294     Diag(Old->getLocation(), diag::note_previous_definition);
2295     return New->setInvalidDecl();
2296   }
2297
2298   // Check if extern is followed by non-extern and vice-versa.
2299   if (New->hasExternalStorage() &&
2300       !Old->hasLinkage() && Old->isLocalVarDecl()) {
2301     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2302     Diag(Old->getLocation(), diag::note_previous_definition);
2303     return New->setInvalidDecl();
2304   }
2305   if (Old->hasExternalStorage() &&
2306       !New->hasLinkage() && New->isLocalVarDecl()) {
2307     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2308     Diag(Old->getLocation(), diag::note_previous_definition);
2309     return New->setInvalidDecl();
2310   }
2311
2312   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2313
2314   // FIXME: The test for external storage here seems wrong? We still
2315   // need to check for mismatches.
2316   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2317       // Don't complain about out-of-line definitions of static members.
2318       !(Old->getLexicalDeclContext()->isRecord() &&
2319         !New->getLexicalDeclContext()->isRecord())) {
2320     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2321     Diag(Old->getLocation(), diag::note_previous_definition);
2322     return New->setInvalidDecl();
2323   }
2324
2325   if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2326     Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2327     Diag(Old->getLocation(), diag::note_previous_definition);
2328   } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2329     Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2330     Diag(Old->getLocation(), diag::note_previous_definition);
2331   }
2332
2333   // C++ doesn't have tentative definitions, so go right ahead and check here.
2334   const VarDecl *Def;
2335   if (getLangOpts().CPlusPlus &&
2336       New->isThisDeclarationADefinition() == VarDecl::Definition &&
2337       (Def = Old->getDefinition())) {
2338     Diag(New->getLocation(), diag::err_redefinition)
2339       << New->getDeclName();
2340     Diag(Def->getLocation(), diag::note_previous_definition);
2341     New->setInvalidDecl();
2342     return;
2343   }
2344   // c99 6.2.2 P4.
2345   // For an identifier declared with the storage-class specifier extern in a
2346   // scope in which a prior declaration of that identifier is visible, if 
2347   // the prior declaration specifies internal or external linkage, the linkage 
2348   // of the identifier at the later declaration is the same as the linkage 
2349   // specified at the prior declaration.
2350   // FIXME. revisit this code.
2351   if (New->hasExternalStorage() &&
2352       Old->getLinkage() == InternalLinkage &&
2353       New->getDeclContext() == Old->getDeclContext())
2354     New->setStorageClass(Old->getStorageClass());
2355
2356   // Keep a chain of previous declarations.
2357   New->setPreviousDeclaration(Old);
2358
2359   // Inherit access appropriately.
2360   New->setAccess(Old->getAccess());
2361 }
2362
2363 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2364 /// no declarator (e.g. "struct foo;") is parsed.
2365 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2366                                        DeclSpec &DS) {
2367   return ParsedFreeStandingDeclSpec(S, AS, DS,
2368                                     MultiTemplateParamsArg(*this, 0, 0));
2369 }
2370
2371 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2372 /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2373 /// parameters to cope with template friend declarations.
2374 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2375                                        DeclSpec &DS,
2376                                        MultiTemplateParamsArg TemplateParams) {
2377   Decl *TagD = 0;
2378   TagDecl *Tag = 0;
2379   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2380       DS.getTypeSpecType() == DeclSpec::TST_struct ||
2381       DS.getTypeSpecType() == DeclSpec::TST_union ||
2382       DS.getTypeSpecType() == DeclSpec::TST_enum) {
2383     TagD = DS.getRepAsDecl();
2384
2385     if (!TagD) // We probably had an error
2386       return 0;
2387
2388     // Note that the above type specs guarantee that the
2389     // type rep is a Decl, whereas in many of the others
2390     // it's a Type.
2391     if (isa<TagDecl>(TagD))
2392       Tag = cast<TagDecl>(TagD);
2393     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2394       Tag = CTD->getTemplatedDecl();
2395   }
2396
2397   if (Tag) {
2398     Tag->setFreeStanding();
2399     if (Tag->isInvalidDecl())
2400       return Tag;
2401   }
2402
2403   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2404     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2405     // or incomplete types shall not be restrict-qualified."
2406     if (TypeQuals & DeclSpec::TQ_restrict)
2407       Diag(DS.getRestrictSpecLoc(),
2408            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2409            << DS.getSourceRange();
2410   }
2411
2412   if (DS.isConstexprSpecified()) {
2413     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2414     // and definitions of functions and variables.
2415     if (Tag)
2416       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2417         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2418             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2419             DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
2420     else
2421       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2422     // Don't emit warnings after this error.
2423     return TagD;
2424   }
2425
2426   if (DS.isFriendSpecified()) {
2427     // If we're dealing with a decl but not a TagDecl, assume that
2428     // whatever routines created it handled the friendship aspect.
2429     if (TagD && !Tag)
2430       return 0;
2431     return ActOnFriendTypeDecl(S, DS, TemplateParams);
2432   }
2433
2434   // Track whether we warned about the fact that there aren't any
2435   // declarators.
2436   bool emittedWarning = false;
2437          
2438   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
2439     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
2440         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2441       if (getLangOpts().CPlusPlus ||
2442           Record->getDeclContext()->isRecord())
2443         return BuildAnonymousStructOrUnion(S, DS, AS, Record);
2444
2445       Diag(DS.getLocStart(), diag::ext_no_declarators)
2446         << DS.getSourceRange();
2447       emittedWarning = true;
2448     }
2449   }
2450
2451   // Check for Microsoft C extension: anonymous struct.
2452   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
2453       CurContext->isRecord() &&
2454       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2455     // Handle 2 kinds of anonymous struct:
2456     //   struct STRUCT;
2457     // and
2458     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
2459     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2460     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
2461         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2462          DS.getRepAsType().get()->isStructureType())) {
2463       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
2464         << DS.getSourceRange();
2465       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2466     }
2467   }
2468   
2469   if (getLangOpts().CPlusPlus && 
2470       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2471     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2472       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
2473           !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
2474         Diag(Enum->getLocation(), diag::ext_no_declarators)
2475           << DS.getSourceRange();
2476         emittedWarning = true;
2477       }
2478
2479   // Skip all the checks below if we have a type error.
2480   if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
2481       
2482   if (!DS.isMissingDeclaratorOk()) {
2483     // Warn about typedefs of enums without names, since this is an
2484     // extension in both Microsoft and GNU.
2485     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2486         Tag && isa<EnumDecl>(Tag)) {
2487       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
2488         << DS.getSourceRange();
2489       return Tag;
2490     }
2491
2492     Diag(DS.getLocStart(), diag::ext_no_declarators)
2493       << DS.getSourceRange();
2494     emittedWarning = true;
2495   }
2496
2497   // We're going to complain about a bunch of spurious specifiers;
2498   // only do this if we're declaring a tag, because otherwise we
2499   // should be getting diag::ext_no_declarators.
2500   if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2501     return TagD;
2502
2503   // Note that a linkage-specification sets a storage class, but
2504   // 'extern "C" struct foo;' is actually valid and not theoretically
2505   // useless.
2506   if (DeclSpec::SCS scs = DS.getStorageClassSpec())
2507     if (!DS.isExternInLinkageSpec())
2508       Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2509         << DeclSpec::getSpecifierName(scs);
2510
2511   if (DS.isThreadSpecified())
2512     Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2513   if (DS.getTypeQualifiers()) {
2514     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2515       Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2516     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2517       Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2518     // Restrict is covered above.
2519   }
2520   if (DS.isInlineSpecified())
2521     Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2522   if (DS.isVirtualSpecified())
2523     Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2524   if (DS.isExplicitSpecified())
2525     Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2526
2527   if (DS.isModulePrivateSpecified() && 
2528       Tag && Tag->getDeclContext()->isFunctionOrMethod())
2529     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2530       << Tag->getTagKind()
2531       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2532
2533   // Warn about ignored type attributes, for example:
2534   // __attribute__((aligned)) struct A;
2535   // Attributes should be placed after tag to apply to type declaration.
2536   if (!DS.getAttributes().empty()) {
2537     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2538     if (TypeSpecType == DeclSpec::TST_class ||
2539         TypeSpecType == DeclSpec::TST_struct ||
2540         TypeSpecType == DeclSpec::TST_union ||
2541         TypeSpecType == DeclSpec::TST_enum) {
2542       AttributeList* attrs = DS.getAttributes().getList();
2543       while (attrs) {
2544         Diag(attrs->getScopeLoc(),
2545              diag::warn_declspec_attribute_ignored)
2546         << attrs->getName()
2547         << (TypeSpecType == DeclSpec::TST_class ? 0 :
2548             TypeSpecType == DeclSpec::TST_struct ? 1 :
2549             TypeSpecType == DeclSpec::TST_union ? 2 : 3);
2550         attrs = attrs->getNext();
2551       }
2552     }
2553   }
2554
2555   return TagD;
2556 }
2557
2558 /// We are trying to inject an anonymous member into the given scope;
2559 /// check if there's an existing declaration that can't be overloaded.
2560 ///
2561 /// \return true if this is a forbidden redeclaration
2562 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2563                                          Scope *S,
2564                                          DeclContext *Owner,
2565                                          DeclarationName Name,
2566                                          SourceLocation NameLoc,
2567                                          unsigned diagnostic) {
2568   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2569                  Sema::ForRedeclaration);
2570   if (!SemaRef.LookupName(R, S)) return false;
2571
2572   if (R.getAsSingle<TagDecl>())
2573     return false;
2574
2575   // Pick a representative declaration.
2576   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
2577   assert(PrevDecl && "Expected a non-null Decl");
2578
2579   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2580     return false;
2581
2582   SemaRef.Diag(NameLoc, diagnostic) << Name;
2583   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
2584
2585   return true;
2586 }
2587
2588 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
2589 /// anonymous struct or union AnonRecord into the owning context Owner
2590 /// and scope S. This routine will be invoked just after we realize
2591 /// that an unnamed union or struct is actually an anonymous union or
2592 /// struct, e.g.,
2593 ///
2594 /// @code
2595 /// union {
2596 ///   int i;
2597 ///   float f;
2598 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2599 ///    // f into the surrounding scope.x
2600 /// @endcode
2601 ///
2602 /// This routine is recursive, injecting the names of nested anonymous
2603 /// structs/unions into the owning context and scope as well.
2604 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2605                                                 DeclContext *Owner,
2606                                                 RecordDecl *AnonRecord,
2607                                                 AccessSpecifier AS,
2608                               SmallVector<NamedDecl*, 2> &Chaining,
2609                                                       bool MSAnonStruct) {
2610   unsigned diagKind
2611     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2612                             : diag::err_anonymous_struct_member_redecl;
2613
2614   bool Invalid = false;
2615
2616   // Look every FieldDecl and IndirectFieldDecl with a name.
2617   for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2618                                DEnd = AnonRecord->decls_end();
2619        D != DEnd; ++D) {
2620     if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2621         cast<NamedDecl>(*D)->getDeclName()) {
2622       ValueDecl *VD = cast<ValueDecl>(*D);
2623       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2624                                        VD->getLocation(), diagKind)) {
2625         // C++ [class.union]p2:
2626         //   The names of the members of an anonymous union shall be
2627         //   distinct from the names of any other entity in the
2628         //   scope in which the anonymous union is declared.
2629         Invalid = true;
2630       } else {
2631         // C++ [class.union]p2:
2632         //   For the purpose of name lookup, after the anonymous union
2633         //   definition, the members of the anonymous union are
2634         //   considered to have been defined in the scope in which the
2635         //   anonymous union is declared.
2636         unsigned OldChainingSize = Chaining.size();
2637         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2638           for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2639                PE = IF->chain_end(); PI != PE; ++PI)
2640             Chaining.push_back(*PI);
2641         else
2642           Chaining.push_back(VD);
2643
2644         assert(Chaining.size() >= 2);
2645         NamedDecl **NamedChain =
2646           new (SemaRef.Context)NamedDecl*[Chaining.size()];
2647         for (unsigned i = 0; i < Chaining.size(); i++)
2648           NamedChain[i] = Chaining[i];
2649
2650         IndirectFieldDecl* IndirectField =
2651           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2652                                     VD->getIdentifier(), VD->getType(),
2653                                     NamedChain, Chaining.size());
2654
2655         IndirectField->setAccess(AS);
2656         IndirectField->setImplicit();
2657         SemaRef.PushOnScopeChains(IndirectField, S);
2658
2659         // That includes picking up the appropriate access specifier.
2660         if (AS != AS_none) IndirectField->setAccess(AS);
2661
2662         Chaining.resize(OldChainingSize);
2663       }
2664     }
2665   }
2666
2667   return Invalid;
2668 }
2669
2670 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2671 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
2672 /// illegal input values are mapped to SC_None.
2673 static StorageClass
2674 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2675   switch (StorageClassSpec) {
2676   case DeclSpec::SCS_unspecified:    return SC_None;
2677   case DeclSpec::SCS_extern:         return SC_Extern;
2678   case DeclSpec::SCS_static:         return SC_Static;
2679   case DeclSpec::SCS_auto:           return SC_Auto;
2680   case DeclSpec::SCS_register:       return SC_Register;
2681   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2682     // Illegal SCSs map to None: error reporting is up to the caller.
2683   case DeclSpec::SCS_mutable:        // Fall through.
2684   case DeclSpec::SCS_typedef:        return SC_None;
2685   }
2686   llvm_unreachable("unknown storage class specifier");
2687 }
2688
2689 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
2690 /// a StorageClass. Any error reporting is up to the caller:
2691 /// illegal input values are mapped to SC_None.
2692 static StorageClass
2693 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2694   switch (StorageClassSpec) {
2695   case DeclSpec::SCS_unspecified:    return SC_None;
2696   case DeclSpec::SCS_extern:         return SC_Extern;
2697   case DeclSpec::SCS_static:         return SC_Static;
2698   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2699     // Illegal SCSs map to None: error reporting is up to the caller.
2700   case DeclSpec::SCS_auto:           // Fall through.
2701   case DeclSpec::SCS_mutable:        // Fall through.
2702   case DeclSpec::SCS_register:       // Fall through.
2703   case DeclSpec::SCS_typedef:        return SC_None;
2704   }
2705   llvm_unreachable("unknown storage class specifier");
2706 }
2707
2708 /// BuildAnonymousStructOrUnion - Handle the declaration of an
2709 /// anonymous structure or union. Anonymous unions are a C++ feature
2710 /// (C++ [class.union]) and a C11 feature; anonymous structures
2711 /// are a C11 feature and GNU C++ extension.
2712 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2713                                              AccessSpecifier AS,
2714                                              RecordDecl *Record) {
2715   DeclContext *Owner = Record->getDeclContext();
2716
2717   // Diagnose whether this anonymous struct/union is an extension.
2718   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
2719     Diag(Record->getLocation(), diag::ext_anonymous_union);
2720   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
2721     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
2722   else if (!Record->isUnion() && !getLangOpts().C11)
2723     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
2724
2725   // C and C++ require different kinds of checks for anonymous
2726   // structs/unions.
2727   bool Invalid = false;
2728   if (getLangOpts().CPlusPlus) {
2729     const char* PrevSpec = 0;
2730     unsigned DiagID;
2731     if (Record->isUnion()) {
2732       // C++ [class.union]p6:
2733       //   Anonymous unions declared in a named namespace or in the
2734       //   global namespace shall be declared static.
2735       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2736           (isa<TranslationUnitDecl>(Owner) ||
2737            (isa<NamespaceDecl>(Owner) &&
2738             cast<NamespaceDecl>(Owner)->getDeclName()))) {
2739         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
2740           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
2741   
2742         // Recover by adding 'static'.
2743         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
2744                                PrevSpec, DiagID);
2745       }
2746       // C++ [class.union]p6:
2747       //   A storage class is not allowed in a declaration of an
2748       //   anonymous union in a class scope.
2749       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2750                isa<RecordDecl>(Owner)) {
2751         Diag(DS.getStorageClassSpecLoc(),
2752              diag::err_anonymous_union_with_storage_spec)
2753           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2754   
2755         // Recover by removing the storage specifier.
2756         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 
2757                                SourceLocation(),
2758                                PrevSpec, DiagID);
2759       }
2760     }
2761
2762     // Ignore const/volatile/restrict qualifiers.
2763     if (DS.getTypeQualifiers()) {
2764       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2765         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2766           << Record->isUnion() << 0 
2767           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2768       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2769         Diag(DS.getVolatileSpecLoc(), 
2770              diag::ext_anonymous_struct_union_qualified)
2771           << Record->isUnion() << 1
2772           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2773       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2774         Diag(DS.getRestrictSpecLoc(), 
2775              diag::ext_anonymous_struct_union_qualified)
2776           << Record->isUnion() << 2 
2777           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2778
2779       DS.ClearTypeQualifiers();
2780     }
2781
2782     // C++ [class.union]p2:
2783     //   The member-specification of an anonymous union shall only
2784     //   define non-static data members. [Note: nested types and
2785     //   functions cannot be declared within an anonymous union. ]
2786     for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2787                                  MemEnd = Record->decls_end();
2788          Mem != MemEnd; ++Mem) {
2789       if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2790         // C++ [class.union]p3:
2791         //   An anonymous union shall not have private or protected
2792         //   members (clause 11).
2793         assert(FD->getAccess() != AS_none);
2794         if (FD->getAccess() != AS_public) {
2795           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2796             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2797           Invalid = true;
2798         }
2799
2800         // C++ [class.union]p1
2801         //   An object of a class with a non-trivial constructor, a non-trivial
2802         //   copy constructor, a non-trivial destructor, or a non-trivial copy
2803         //   assignment operator cannot be a member of a union, nor can an
2804         //   array of such objects.
2805         if (CheckNontrivialField(FD))
2806           Invalid = true;
2807       } else if ((*Mem)->isImplicit()) {
2808         // Any implicit members are fine.
2809       } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2810         // This is a type that showed up in an
2811         // elaborated-type-specifier inside the anonymous struct or
2812         // union, but which actually declares a type outside of the
2813         // anonymous struct or union. It's okay.
2814       } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2815         if (!MemRecord->isAnonymousStructOrUnion() &&
2816             MemRecord->getDeclName()) {
2817           // Visual C++ allows type definition in anonymous struct or union.
2818           if (getLangOpts().MicrosoftExt)
2819             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2820               << (int)Record->isUnion();
2821           else {
2822             // This is a nested type declaration.
2823             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2824               << (int)Record->isUnion();
2825             Invalid = true;
2826           }
2827         }
2828       } else if (isa<AccessSpecDecl>(*Mem)) {
2829         // Any access specifier is fine.
2830       } else {
2831         // We have something that isn't a non-static data
2832         // member. Complain about it.
2833         unsigned DK = diag::err_anonymous_record_bad_member;
2834         if (isa<TypeDecl>(*Mem))
2835           DK = diag::err_anonymous_record_with_type;
2836         else if (isa<FunctionDecl>(*Mem))
2837           DK = diag::err_anonymous_record_with_function;
2838         else if (isa<VarDecl>(*Mem))
2839           DK = diag::err_anonymous_record_with_static;
2840         
2841         // Visual C++ allows type definition in anonymous struct or union.
2842         if (getLangOpts().MicrosoftExt &&
2843             DK == diag::err_anonymous_record_with_type)
2844           Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
2845             << (int)Record->isUnion();
2846         else {
2847           Diag((*Mem)->getLocation(), DK)
2848               << (int)Record->isUnion();
2849           Invalid = true;
2850         }
2851       }
2852     }
2853   }
2854
2855   if (!Record->isUnion() && !Owner->isRecord()) {
2856     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2857       << (int)getLangOpts().CPlusPlus;
2858     Invalid = true;
2859   }
2860
2861   // Mock up a declarator.
2862   Declarator Dc(DS, Declarator::MemberContext);
2863   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2864   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
2865
2866   // Create a declaration for this anonymous struct/union.
2867   NamedDecl *Anon = 0;
2868   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
2869     Anon = FieldDecl::Create(Context, OwningClass,
2870                              DS.getLocStart(),
2871                              Record->getLocation(),
2872                              /*IdentifierInfo=*/0,
2873                              Context.getTypeDeclType(Record),
2874                              TInfo,
2875                              /*BitWidth=*/0, /*Mutable=*/false,
2876                              /*HasInit=*/false);
2877     Anon->setAccess(AS);
2878     if (getLangOpts().CPlusPlus)
2879       FieldCollector->Add(cast<FieldDecl>(Anon));
2880   } else {
2881     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2882     assert(SCSpec != DeclSpec::SCS_typedef &&
2883            "Parser allowed 'typedef' as storage class VarDecl.");
2884     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2885     if (SCSpec == DeclSpec::SCS_mutable) {
2886       // mutable can only appear on non-static class members, so it's always
2887       // an error here
2888       Diag(Record->getLocation(), diag::err_mutable_nonmember);
2889       Invalid = true;
2890       SC = SC_None;
2891     }
2892     SCSpec = DS.getStorageClassSpecAsWritten();
2893     VarDecl::StorageClass SCAsWritten
2894       = StorageClassSpecToVarDeclStorageClass(SCSpec);
2895
2896     Anon = VarDecl::Create(Context, Owner,
2897                            DS.getLocStart(),
2898                            Record->getLocation(), /*IdentifierInfo=*/0,
2899                            Context.getTypeDeclType(Record),
2900                            TInfo, SC, SCAsWritten);
2901
2902     // Default-initialize the implicit variable. This initialization will be
2903     // trivial in almost all cases, except if a union member has an in-class
2904     // initializer:
2905     //   union { int n = 0; };
2906     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
2907   }
2908   Anon->setImplicit();
2909
2910   // Add the anonymous struct/union object to the current
2911   // context. We'll be referencing this object when we refer to one of
2912   // its members.
2913   Owner->addDecl(Anon);
2914   
2915   // Inject the members of the anonymous struct/union into the owning
2916   // context and into the identifier resolver chain for name lookup
2917   // purposes.
2918   SmallVector<NamedDecl*, 2> Chain;
2919   Chain.push_back(Anon);
2920
2921   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2922                                           Chain, false))
2923     Invalid = true;
2924
2925   // Mark this as an anonymous struct/union type. Note that we do not
2926   // do this until after we have already checked and injected the
2927   // members of this anonymous struct/union type, because otherwise
2928   // the members could be injected twice: once by DeclContext when it
2929   // builds its lookup table, and once by
2930   // InjectAnonymousStructOrUnionMembers.
2931   Record->setAnonymousStructOrUnion(true);
2932
2933   if (Invalid)
2934     Anon->setInvalidDecl();
2935
2936   return Anon;
2937 }
2938
2939 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2940 /// Microsoft C anonymous structure.
2941 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2942 /// Example:
2943 ///
2944 /// struct A { int a; };
2945 /// struct B { struct A; int b; };
2946 ///
2947 /// void foo() {
2948 ///   B var;
2949 ///   var.a = 3; 
2950 /// }
2951 ///
2952 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2953                                            RecordDecl *Record) {
2954   
2955   // If there is no Record, get the record via the typedef.
2956   if (!Record)
2957     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2958
2959   // Mock up a declarator.
2960   Declarator Dc(DS, Declarator::TypeNameContext);
2961   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2962   assert(TInfo && "couldn't build declarator info for anonymous struct");
2963
2964   // Create a declaration for this anonymous struct.
2965   NamedDecl* Anon = FieldDecl::Create(Context,
2966                              cast<RecordDecl>(CurContext),
2967                              DS.getLocStart(),
2968                              DS.getLocStart(),
2969                              /*IdentifierInfo=*/0,
2970                              Context.getTypeDeclType(Record),
2971                              TInfo,
2972                              /*BitWidth=*/0, /*Mutable=*/false,
2973                              /*HasInit=*/false);
2974   Anon->setImplicit();
2975
2976   // Add the anonymous struct object to the current context.
2977   CurContext->addDecl(Anon);
2978
2979   // Inject the members of the anonymous struct into the current
2980   // context and into the identifier resolver chain for name lookup
2981   // purposes.
2982   SmallVector<NamedDecl*, 2> Chain;
2983   Chain.push_back(Anon);
2984
2985   RecordDecl *RecordDef = Record->getDefinition();
2986   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2987                                                         RecordDef, AS_none,
2988                                                         Chain, true))
2989     Anon->setInvalidDecl();
2990
2991   return Anon;
2992 }
2993
2994 /// GetNameForDeclarator - Determine the full declaration name for the
2995 /// given Declarator.
2996 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
2997   return GetNameFromUnqualifiedId(D.getName());
2998 }
2999
3000 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3001 DeclarationNameInfo
3002 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3003   DeclarationNameInfo NameInfo;
3004   NameInfo.setLoc(Name.StartLocation);
3005
3006   switch (Name.getKind()) {
3007
3008   case UnqualifiedId::IK_ImplicitSelfParam:
3009   case UnqualifiedId::IK_Identifier:
3010     NameInfo.setName(Name.Identifier);
3011     NameInfo.setLoc(Name.StartLocation);
3012     return NameInfo;
3013
3014   case UnqualifiedId::IK_OperatorFunctionId:
3015     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3016                                            Name.OperatorFunctionId.Operator));
3017     NameInfo.setLoc(Name.StartLocation);
3018     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3019       = Name.OperatorFunctionId.SymbolLocations[0];
3020     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3021       = Name.EndLocation.getRawEncoding();
3022     return NameInfo;
3023
3024   case UnqualifiedId::IK_LiteralOperatorId:
3025     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3026                                                            Name.Identifier));
3027     NameInfo.setLoc(Name.StartLocation);
3028     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3029     return NameInfo;
3030
3031   case UnqualifiedId::IK_ConversionFunctionId: {
3032     TypeSourceInfo *TInfo;
3033     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3034     if (Ty.isNull())
3035       return DeclarationNameInfo();
3036     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3037                                                Context.getCanonicalType(Ty)));
3038     NameInfo.setLoc(Name.StartLocation);
3039     NameInfo.setNamedTypeInfo(TInfo);
3040     return NameInfo;
3041   }
3042
3043   case UnqualifiedId::IK_ConstructorName: {
3044     TypeSourceInfo *TInfo;
3045     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3046     if (Ty.isNull())
3047       return DeclarationNameInfo();
3048     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3049                                               Context.getCanonicalType(Ty)));
3050     NameInfo.setLoc(Name.StartLocation);
3051     NameInfo.setNamedTypeInfo(TInfo);
3052     return NameInfo;
3053   }
3054
3055   case UnqualifiedId::IK_ConstructorTemplateId: {
3056     // In well-formed code, we can only have a constructor
3057     // template-id that refers to the current context, so go there
3058     // to find the actual type being constructed.
3059     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3060     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3061       return DeclarationNameInfo();
3062
3063     // Determine the type of the class being constructed.
3064     QualType CurClassType = Context.getTypeDeclType(CurClass);
3065
3066     // FIXME: Check two things: that the template-id names the same type as
3067     // CurClassType, and that the template-id does not occur when the name
3068     // was qualified.
3069
3070     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3071                                     Context.getCanonicalType(CurClassType)));
3072     NameInfo.setLoc(Name.StartLocation);
3073     // FIXME: should we retrieve TypeSourceInfo?
3074     NameInfo.setNamedTypeInfo(0);
3075     return NameInfo;
3076   }
3077
3078   case UnqualifiedId::IK_DestructorName: {
3079     TypeSourceInfo *TInfo;
3080     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3081     if (Ty.isNull())
3082       return DeclarationNameInfo();
3083     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3084                                               Context.getCanonicalType(Ty)));
3085     NameInfo.setLoc(Name.StartLocation);
3086     NameInfo.setNamedTypeInfo(TInfo);
3087     return NameInfo;
3088   }
3089
3090   case UnqualifiedId::IK_TemplateId: {
3091     TemplateName TName = Name.TemplateId->Template.get();
3092     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3093     return Context.getNameForTemplate(TName, TNameLoc);
3094   }
3095
3096   } // switch (Name.getKind())
3097
3098   llvm_unreachable("Unknown name kind");
3099 }
3100
3101 static QualType getCoreType(QualType Ty) {
3102   do {
3103     if (Ty->isPointerType() || Ty->isReferenceType())
3104       Ty = Ty->getPointeeType();
3105     else if (Ty->isArrayType())
3106       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3107     else
3108       return Ty.withoutLocalFastQualifiers();
3109   } while (true);
3110 }
3111
3112 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3113 /// and Definition have "nearly" matching parameters. This heuristic is
3114 /// used to improve diagnostics in the case where an out-of-line function
3115 /// definition doesn't match any declaration within the class or namespace.
3116 /// Also sets Params to the list of indices to the parameters that differ
3117 /// between the declaration and the definition. If hasSimilarParameters
3118 /// returns true and Params is empty, then all of the parameters match.
3119 static bool hasSimilarParameters(ASTContext &Context,
3120                                      FunctionDecl *Declaration,
3121                                      FunctionDecl *Definition,
3122                                      llvm::SmallVectorImpl<unsigned> &Params) {
3123   Params.clear();
3124   if (Declaration->param_size() != Definition->param_size())
3125     return false;
3126   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3127     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3128     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3129
3130     // The parameter types are identical
3131     if (Context.hasSameType(DefParamTy, DeclParamTy))
3132       continue;
3133
3134     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3135     QualType DefParamBaseTy = getCoreType(DefParamTy);
3136     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3137     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3138
3139     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3140         (DeclTyName && DeclTyName == DefTyName))
3141       Params.push_back(Idx);
3142     else  // The two parameters aren't even close
3143       return false;
3144   }
3145
3146   return true;
3147 }
3148
3149 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3150 /// declarator needs to be rebuilt in the current instantiation.
3151 /// Any bits of declarator which appear before the name are valid for
3152 /// consideration here.  That's specifically the type in the decl spec
3153 /// and the base type in any member-pointer chunks.
3154 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3155                                                     DeclarationName Name) {
3156   // The types we specifically need to rebuild are:
3157   //   - typenames, typeofs, and decltypes
3158   //   - types which will become injected class names
3159   // Of course, we also need to rebuild any type referencing such a
3160   // type.  It's safest to just say "dependent", but we call out a
3161   // few cases here.
3162
3163   DeclSpec &DS = D.getMutableDeclSpec();
3164   switch (DS.getTypeSpecType()) {
3165   case DeclSpec::TST_typename:
3166   case DeclSpec::TST_typeofType:
3167   case DeclSpec::TST_decltype:
3168   case DeclSpec::TST_underlyingType:
3169   case DeclSpec::TST_atomic: {
3170     // Grab the type from the parser.
3171     TypeSourceInfo *TSI = 0;
3172     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3173     if (T.isNull() || !T->isDependentType()) break;
3174
3175     // Make sure there's a type source info.  This isn't really much
3176     // of a waste; most dependent types should have type source info
3177     // attached already.
3178     if (!TSI)
3179       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3180
3181     // Rebuild the type in the current instantiation.
3182     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3183     if (!TSI) return true;
3184
3185     // Store the new type back in the decl spec.
3186     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3187     DS.UpdateTypeRep(LocType);
3188     break;
3189   }
3190
3191   case DeclSpec::TST_typeofExpr: {
3192     Expr *E = DS.getRepAsExpr();
3193     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3194     if (Result.isInvalid()) return true;
3195     DS.UpdateExprRep(Result.get());
3196     break;
3197   }
3198
3199   default:
3200     // Nothing to do for these decl specs.
3201     break;
3202   }
3203
3204   // It doesn't matter what order we do this in.
3205   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3206     DeclaratorChunk &Chunk = D.getTypeObject(I);
3207
3208     // The only type information in the declarator which can come
3209     // before the declaration name is the base type of a member
3210     // pointer.
3211     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3212       continue;
3213
3214     // Rebuild the scope specifier in-place.
3215     CXXScopeSpec &SS = Chunk.Mem.Scope();
3216     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3217       return true;
3218   }
3219
3220   return false;
3221 }
3222
3223 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3224   D.setFunctionDefinitionKind(FDK_Declaration);
3225   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
3226
3227   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3228       Dcl->getDeclContext()->isFileContext())
3229     Dcl->setTopLevelDeclInObjCContainer();
3230
3231   return Dcl;
3232 }
3233
3234 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3235 ///   If T is the name of a class, then each of the following shall have a 
3236 ///   name different from T:
3237 ///     - every static data member of class T;
3238 ///     - every member function of class T
3239 ///     - every member of class T that is itself a type;
3240 /// \returns true if the declaration name violates these rules.
3241 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3242                                    DeclarationNameInfo NameInfo) {
3243   DeclarationName Name = NameInfo.getName();
3244
3245   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 
3246     if (Record->getIdentifier() && Record->getDeclName() == Name) {
3247       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3248       return true;
3249     }
3250
3251   return false;
3252 }
3253
3254 /// \brief Diagnose a declaration whose declarator-id has the given 
3255 /// nested-name-specifier.
3256 ///
3257 /// \param SS The nested-name-specifier of the declarator-id.
3258 ///
3259 /// \param DC The declaration context to which the nested-name-specifier 
3260 /// resolves.
3261 ///
3262 /// \param Name The name of the entity being declared.
3263 ///
3264 /// \param Loc The location of the name of the entity being declared.
3265 ///
3266 /// \returns true if we cannot safely recover from this error, false otherwise.
3267 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3268                                         DeclarationName Name,
3269                                       SourceLocation Loc) {
3270   DeclContext *Cur = CurContext;
3271   while (isa<LinkageSpecDecl>(Cur))
3272     Cur = Cur->getParent();
3273   
3274   // C++ [dcl.meaning]p1:
3275   //   A declarator-id shall not be qualified except for the definition
3276   //   of a member function (9.3) or static data member (9.4) outside of
3277   //   its class, the definition or explicit instantiation of a function 
3278   //   or variable member of a namespace outside of its namespace, or the
3279   //   definition of an explicit specialization outside of its namespace,
3280   //   or the declaration of a friend function that is a member of 
3281   //   another class or namespace (11.3). [...]
3282     
3283   // The user provided a superfluous scope specifier that refers back to the
3284   // class or namespaces in which the entity is already declared.
3285   //
3286   // class X {
3287   //   void X::f();
3288   // };
3289   if (Cur->Equals(DC)) {
3290     Diag(Loc, diag::warn_member_extra_qualification)
3291       << Name << FixItHint::CreateRemoval(SS.getRange());
3292     SS.clear();
3293     return false;
3294   } 
3295
3296   // Check whether the qualifying scope encloses the scope of the original
3297   // declaration.
3298   if (!Cur->Encloses(DC)) {
3299     if (Cur->isRecord())
3300       Diag(Loc, diag::err_member_qualification)
3301         << Name << SS.getRange();
3302     else if (isa<TranslationUnitDecl>(DC))
3303       Diag(Loc, diag::err_invalid_declarator_global_scope)
3304         << Name << SS.getRange();
3305     else if (isa<FunctionDecl>(Cur))
3306       Diag(Loc, diag::err_invalid_declarator_in_function) 
3307         << Name << SS.getRange();
3308     else
3309       Diag(Loc, diag::err_invalid_declarator_scope)
3310       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
3311     
3312     return true;
3313   }
3314
3315   if (Cur->isRecord()) {
3316     // Cannot qualify members within a class.
3317     Diag(Loc, diag::err_member_qualification)
3318       << Name << SS.getRange();
3319     SS.clear();
3320     
3321     // C++ constructors and destructors with incorrect scopes can break
3322     // our AST invariants by having the wrong underlying types. If
3323     // that's the case, then drop this declaration entirely.
3324     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3325          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3326         !Context.hasSameType(Name.getCXXNameType(),
3327                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3328       return true;
3329     
3330     return false;
3331   }
3332   
3333   // C++11 [dcl.meaning]p1:
3334   //   [...] "The nested-name-specifier of the qualified declarator-id shall
3335   //   not begin with a decltype-specifer"
3336   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3337   while (SpecLoc.getPrefix())
3338     SpecLoc = SpecLoc.getPrefix();
3339   if (dyn_cast_or_null<DecltypeType>(
3340         SpecLoc.getNestedNameSpecifier()->getAsType()))
3341     Diag(Loc, diag::err_decltype_in_declarator)
3342       << SpecLoc.getTypeLoc().getSourceRange();
3343
3344   return false;
3345 }
3346
3347 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3348                              MultiTemplateParamsArg TemplateParamLists) {
3349   // TODO: consider using NameInfo for diagnostic.
3350   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3351   DeclarationName Name = NameInfo.getName();
3352
3353   // All of these full declarators require an identifier.  If it doesn't have
3354   // one, the ParsedFreeStandingDeclSpec action should be used.
3355   if (!Name) {
3356     if (!D.isInvalidType())  // Reject this if we think it is valid.
3357       Diag(D.getDeclSpec().getLocStart(),
3358            diag::err_declarator_need_ident)
3359         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
3360     return 0;
3361   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3362     return 0;
3363
3364   // The scope passed in may not be a decl scope.  Zip up the scope tree until
3365   // we find one that is.
3366   while ((S->getFlags() & Scope::DeclScope) == 0 ||
3367          (S->getFlags() & Scope::TemplateParamScope) != 0)
3368     S = S->getParent();
3369
3370   DeclContext *DC = CurContext;
3371   if (D.getCXXScopeSpec().isInvalid())
3372     D.setInvalidType();
3373   else if (D.getCXXScopeSpec().isSet()) {
3374     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 
3375                                         UPPC_DeclarationQualifier))
3376       return 0;
3377
3378     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3379     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3380     if (!DC) {
3381       // If we could not compute the declaration context, it's because the
3382       // declaration context is dependent but does not refer to a class,
3383       // class template, or class template partial specialization. Complain
3384       // and return early, to avoid the coming semantic disaster.
3385       Diag(D.getIdentifierLoc(),
3386            diag::err_template_qualified_declarator_no_match)
3387         << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3388         << D.getCXXScopeSpec().getRange();
3389       return 0;
3390     }
3391     bool IsDependentContext = DC->isDependentContext();
3392
3393     if (!IsDependentContext && 
3394         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
3395       return 0;
3396
3397     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3398       Diag(D.getIdentifierLoc(),
3399            diag::err_member_def_undefined_record)
3400         << Name << DC << D.getCXXScopeSpec().getRange();
3401       D.setInvalidType();
3402     } else if (!D.getDeclSpec().isFriendSpecified()) {
3403       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3404                                       Name, D.getIdentifierLoc())) {
3405         if (DC->isRecord())
3406           return 0;
3407         
3408         D.setInvalidType();
3409       }
3410     }
3411
3412     // Check whether we need to rebuild the type of the given
3413     // declaration in the current instantiation.
3414     if (EnteringContext && IsDependentContext &&
3415         TemplateParamLists.size() != 0) {
3416       ContextRAII SavedContext(*this, DC);
3417       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3418         D.setInvalidType();
3419     }
3420   }
3421
3422   if (DiagnoseClassNameShadow(DC, NameInfo))
3423     // If this is a typedef, we'll end up spewing multiple diagnostics.
3424     // Just return early; it's safer.
3425     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3426       return 0;
3427   
3428   NamedDecl *New;
3429
3430   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3431   QualType R = TInfo->getType();
3432
3433   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3434                                       UPPC_DeclarationType))
3435     D.setInvalidType();
3436
3437   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
3438                         ForRedeclaration);
3439
3440   // See if this is a redefinition of a variable in the same scope.
3441   if (!D.getCXXScopeSpec().isSet()) {
3442     bool IsLinkageLookup = false;
3443
3444     // If the declaration we're planning to build will be a function
3445     // or object with linkage, then look for another declaration with
3446     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3447     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3448       /* Do nothing*/;
3449     else if (R->isFunctionType()) {
3450       if (CurContext->isFunctionOrMethod() ||
3451           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3452         IsLinkageLookup = true;
3453     } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
3454       IsLinkageLookup = true;
3455     else if (CurContext->getRedeclContext()->isTranslationUnit() &&
3456              D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3457       IsLinkageLookup = true;
3458
3459     if (IsLinkageLookup)
3460       Previous.clear(LookupRedeclarationWithLinkage);
3461
3462     LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
3463   } else { // Something like "int foo::x;"
3464     LookupQualifiedName(Previous, DC);
3465
3466     // C++ [dcl.meaning]p1:
3467     //   When the declarator-id is qualified, the declaration shall refer to a 
3468     //  previously declared member of the class or namespace to which the 
3469     //  qualifier refers (or, in the case of a namespace, of an element of the
3470     //  inline namespace set of that namespace (7.3.1)) or to a specialization
3471     //  thereof; [...] 
3472     //
3473     // Note that we already checked the context above, and that we do not have
3474     // enough information to make sure that Previous contains the declaration
3475     // we want to match. For example, given:
3476     //
3477     //   class X {
3478     //     void f();
3479     //     void f(float);
3480     //   };
3481     //
3482     //   void X::f(int) { } // ill-formed
3483     //
3484     // In this case, Previous will point to the overload set
3485     // containing the two f's declared in X, but neither of them
3486     // matches.
3487     
3488     // C++ [dcl.meaning]p1:
3489     //   [...] the member shall not merely have been introduced by a 
3490     //   using-declaration in the scope of the class or namespace nominated by 
3491     //   the nested-name-specifier of the declarator-id.
3492     RemoveUsingDecls(Previous);
3493   }
3494
3495   if (Previous.isSingleResult() &&
3496       Previous.getFoundDecl()->isTemplateParameter()) {
3497     // Maybe we will complain about the shadowed template parameter.
3498     if (!D.isInvalidType())
3499       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3500                                       Previous.getFoundDecl());
3501
3502     // Just pretend that we didn't see the previous declaration.
3503     Previous.clear();
3504   }
3505
3506   // In C++, the previous declaration we find might be a tag type
3507   // (class or enum). In this case, the new declaration will hide the
3508   // tag type. Note that this does does not apply if we're declaring a
3509   // typedef (C++ [dcl.typedef]p4).
3510   if (Previous.isSingleTagDecl() &&
3511       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
3512     Previous.clear();
3513
3514   bool AddToScope = true;
3515   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3516     if (TemplateParamLists.size()) {
3517       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
3518       return 0;
3519     }
3520
3521     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
3522   } else if (R->isFunctionType()) {
3523     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
3524                                   move(TemplateParamLists),
3525                                   AddToScope);
3526   } else {
3527     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3528                                   move(TemplateParamLists));
3529   }
3530
3531   if (New == 0)
3532     return 0;
3533
3534   // If this has an identifier and is not an invalid redeclaration or 
3535   // function template specialization, add it to the scope stack.
3536   if (New->getDeclName() && AddToScope &&
3537        !(D.isRedeclaration() && New->isInvalidDecl()))
3538     PushOnScopeChains(New, S);
3539
3540   return New;
3541 }
3542
3543 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3544 /// types into constant array types in certain situations which would otherwise
3545 /// be errors (for GCC compatibility).
3546 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3547                                                     ASTContext &Context,
3548                                                     bool &SizeIsNegative,
3549                                                     llvm::APSInt &Oversized) {
3550   // This method tries to turn a variable array into a constant
3551   // array even when the size isn't an ICE.  This is necessary
3552   // for compatibility with code that depends on gcc's buggy
3553   // constant expression folding, like struct {char x[(int)(char*)2];}
3554   SizeIsNegative = false;
3555   Oversized = 0;
3556   
3557   if (T->isDependentType())
3558     return QualType();
3559   
3560   QualifierCollector Qs;
3561   const Type *Ty = Qs.strip(T);
3562
3563   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
3564     QualType Pointee = PTy->getPointeeType();
3565     QualType FixedType =
3566         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3567                                             Oversized);
3568     if (FixedType.isNull()) return FixedType;
3569     FixedType = Context.getPointerType(FixedType);
3570     return Qs.apply(Context, FixedType);
3571   }
3572   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3573     QualType Inner = PTy->getInnerType();
3574     QualType FixedType =
3575         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3576                                             Oversized);
3577     if (FixedType.isNull()) return FixedType;
3578     FixedType = Context.getParenType(FixedType);
3579     return Qs.apply(Context, FixedType);
3580   }
3581
3582   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3583   if (!VLATy)
3584     return QualType();
3585   // FIXME: We should probably handle this case
3586   if (VLATy->getElementType()->isVariablyModifiedType())
3587     return QualType();
3588
3589   llvm::APSInt Res;
3590   if (!VLATy->getSizeExpr() ||
3591       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
3592     return QualType();
3593
3594   // Check whether the array size is negative.
3595   if (Res.isSigned() && Res.isNegative()) {
3596     SizeIsNegative = true;
3597     return QualType();
3598   }
3599
3600   // Check whether the array is too large to be addressed.
3601   unsigned ActiveSizeBits
3602     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3603                                               Res);
3604   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3605     Oversized = Res;
3606     return QualType();
3607   }
3608   
3609   return Context.getConstantArrayType(VLATy->getElementType(),
3610                                       Res, ArrayType::Normal, 0);
3611 }
3612
3613 /// \brief Register the given locally-scoped external C declaration so
3614 /// that it can be found later for redeclarations
3615 void
3616 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3617                                        const LookupResult &Previous,
3618                                        Scope *S) {
3619   assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3620          "Decl is not a locally-scoped decl!");
3621   // Note that we have a locally-scoped external with this name.
3622   LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3623
3624   if (!Previous.isSingleResult())
3625     return;
3626
3627   NamedDecl *PrevDecl = Previous.getFoundDecl();
3628
3629   // If there was a previous declaration of this variable, it may be
3630   // in our identifier chain. Update the identifier chain with the new
3631   // declaration.
3632   if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
3633     // The previous declaration was found on the identifer resolver
3634     // chain, so remove it from its scope.
3635
3636     if (S->isDeclScope(PrevDecl)) {
3637       // Special case for redeclarations in the SAME scope.
3638       // Because this declaration is going to be added to the identifier chain
3639       // later, we should temporarily take it OFF the chain.
3640       IdResolver.RemoveDecl(ND);
3641
3642     } else {
3643       // Find the scope for the original declaration.
3644       while (S && !S->isDeclScope(PrevDecl))
3645         S = S->getParent();
3646     }
3647
3648     if (S)
3649       S->RemoveDecl(PrevDecl);
3650   }
3651 }
3652
3653 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3654 Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3655   if (ExternalSource) {
3656     // Load locally-scoped external decls from the external source.
3657     SmallVector<NamedDecl *, 4> Decls;
3658     ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3659     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3660       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3661         = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3662       if (Pos == LocallyScopedExternalDecls.end())
3663         LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3664     }
3665   }
3666   
3667   return LocallyScopedExternalDecls.find(Name);
3668 }
3669
3670 /// \brief Diagnose function specifiers on a declaration of an identifier that
3671 /// does not identify a function.
3672 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3673   // FIXME: We should probably indicate the identifier in question to avoid
3674   // confusion for constructs like "inline int a(), b;"
3675   if (D.getDeclSpec().isInlineSpecified())
3676     Diag(D.getDeclSpec().getInlineSpecLoc(),
3677          diag::err_inline_non_function);
3678
3679   if (D.getDeclSpec().isVirtualSpecified())
3680     Diag(D.getDeclSpec().getVirtualSpecLoc(),
3681          diag::err_virtual_non_function);
3682
3683   if (D.getDeclSpec().isExplicitSpecified())
3684     Diag(D.getDeclSpec().getExplicitSpecLoc(),
3685          diag::err_explicit_non_function);
3686 }
3687
3688 NamedDecl*
3689 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
3690                              TypeSourceInfo *TInfo, LookupResult &Previous) {
3691   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3692   if (D.getCXXScopeSpec().isSet()) {
3693     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3694       << D.getCXXScopeSpec().getRange();
3695     D.setInvalidType();
3696     // Pretend we didn't see the scope specifier.
3697     DC = CurContext;
3698     Previous.clear();
3699   }
3700
3701   if (getLangOpts().CPlusPlus) {
3702     // Check that there are no default arguments (C++ only).
3703     CheckExtraCXXDefaultArguments(D);
3704   }
3705
3706   DiagnoseFunctionSpecifiers(D);
3707
3708   if (D.getDeclSpec().isThreadSpecified())
3709     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3710   if (D.getDeclSpec().isConstexprSpecified())
3711     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
3712       << 1;
3713
3714   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3715     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3716       << D.getName().getSourceRange();
3717     return 0;
3718   }
3719
3720   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
3721   if (!NewTD) return 0;
3722
3723   // Handle attributes prior to checking for duplicates in MergeVarDecl
3724   ProcessDeclAttributes(S, NewTD, D);
3725
3726   CheckTypedefForVariablyModifiedType(S, NewTD);
3727
3728   bool Redeclaration = D.isRedeclaration();
3729   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3730   D.setRedeclaration(Redeclaration);
3731   return ND;
3732 }
3733
3734 void
3735 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
3736   // C99 6.7.7p2: If a typedef name specifies a variably modified type
3737   // then it shall have block scope.
3738   // Note that variably modified types must be fixed before merging the decl so
3739   // that redeclarations will match.
3740   QualType T = NewTD->getUnderlyingType();
3741   if (T->isVariablyModifiedType()) {
3742     getCurFunction()->setHasBranchProtectedScope();
3743
3744     if (S->getFnParent() == 0) {
3745       bool SizeIsNegative;
3746       llvm::APSInt Oversized;
3747       QualType FixedTy =
3748           TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3749                                               Oversized);
3750       if (!FixedTy.isNull()) {
3751         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
3752         NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
3753       } else {
3754         if (SizeIsNegative)
3755           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
3756         else if (T->isVariableArrayType())
3757           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
3758         else if (Oversized.getBoolValue())
3759           Diag(NewTD->getLocation(), diag::err_array_too_large) 
3760             << Oversized.toString(10);
3761         else
3762           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
3763         NewTD->setInvalidDecl();
3764       }
3765     }
3766   }
3767 }
3768
3769
3770 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3771 /// declares a typedef-name, either using the 'typedef' type specifier or via
3772 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3773 NamedDecl*
3774 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3775                            LookupResult &Previous, bool &Redeclaration) {
3776   // Merge the decl with the existing one if appropriate. If the decl is
3777   // in an outer scope, it isn't the same thing.
3778   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
3779                        /*ExplicitInstantiationOrSpecialization=*/false);
3780   if (!Previous.empty()) {
3781     Redeclaration = true;
3782     MergeTypedefNameDecl(NewTD, Previous);
3783   }
3784
3785   // If this is the C FILE type, notify the AST context.
3786   if (IdentifierInfo *II = NewTD->getIdentifier())
3787     if (!NewTD->isInvalidDecl() &&
3788         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
3789       if (II->isStr("FILE"))
3790         Context.setFILEDecl(NewTD);
3791       else if (II->isStr("jmp_buf"))
3792         Context.setjmp_bufDecl(NewTD);
3793       else if (II->isStr("sigjmp_buf"))
3794         Context.setsigjmp_bufDecl(NewTD);
3795       else if (II->isStr("ucontext_t"))
3796         Context.setucontext_tDecl(NewTD);
3797       else if (II->isStr("__builtin_va_list"))
3798         Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
3799     }
3800
3801   return NewTD;
3802 }
3803
3804 /// \brief Determines whether the given declaration is an out-of-scope
3805 /// previous declaration.
3806 ///
3807 /// This routine should be invoked when name lookup has found a
3808 /// previous declaration (PrevDecl) that is not in the scope where a
3809 /// new declaration by the same name is being introduced. If the new
3810 /// declaration occurs in a local scope, previous declarations with
3811 /// linkage may still be considered previous declarations (C99
3812 /// 6.2.2p4-5, C++ [basic.link]p6).
3813 ///
3814 /// \param PrevDecl the previous declaration found by name
3815 /// lookup
3816 ///
3817 /// \param DC the context in which the new declaration is being
3818 /// declared.
3819 ///
3820 /// \returns true if PrevDecl is an out-of-scope previous declaration
3821 /// for a new delcaration with the same name.
3822 static bool
3823 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3824                                 ASTContext &Context) {
3825   if (!PrevDecl)
3826     return false;
3827
3828   if (!PrevDecl->hasLinkage())
3829     return false;
3830
3831   if (Context.getLangOpts().CPlusPlus) {
3832     // C++ [basic.link]p6:
3833     //   If there is a visible declaration of an entity with linkage
3834     //   having the same name and type, ignoring entities declared
3835     //   outside the innermost enclosing namespace scope, the block
3836     //   scope declaration declares that same entity and receives the
3837     //   linkage of the previous declaration.
3838     DeclContext *OuterContext = DC->getRedeclContext();
3839     if (!OuterContext->isFunctionOrMethod())
3840       // This rule only applies to block-scope declarations.
3841       return false;
3842     
3843     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3844     if (PrevOuterContext->isRecord())
3845       // We found a member function: ignore it.
3846       return false;
3847     
3848     // Find the innermost enclosing namespace for the new and
3849     // previous declarations.
3850     OuterContext = OuterContext->getEnclosingNamespaceContext();
3851     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
3852
3853     // The previous declaration is in a different namespace, so it
3854     // isn't the same function.
3855     if (!OuterContext->Equals(PrevOuterContext))
3856       return false;
3857   }
3858
3859   return true;
3860 }
3861
3862 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3863   CXXScopeSpec &SS = D.getCXXScopeSpec();
3864   if (!SS.isSet()) return;
3865   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
3866 }
3867
3868 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3869   QualType type = decl->getType();
3870   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3871   if (lifetime == Qualifiers::OCL_Autoreleasing) {
3872     // Various kinds of declaration aren't allowed to be __autoreleasing.
3873     unsigned kind = -1U;
3874     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3875       if (var->hasAttr<BlocksAttr>())
3876         kind = 0; // __block
3877       else if (!var->hasLocalStorage())
3878         kind = 1; // global
3879     } else if (isa<ObjCIvarDecl>(decl)) {
3880       kind = 3; // ivar
3881     } else if (isa<FieldDecl>(decl)) {
3882       kind = 2; // field
3883     }
3884
3885     if (kind != -1U) {
3886       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3887         << kind;
3888     }
3889   } else if (lifetime == Qualifiers::OCL_None) {
3890     // Try to infer lifetime.
3891     if (!type->isObjCLifetimeType())
3892       return false;
3893
3894     lifetime = type->getObjCARCImplicitLifetime();
3895     type = Context.getLifetimeQualifiedType(type, lifetime);
3896     decl->setType(type);
3897   }
3898   
3899   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3900     // Thread-local variables cannot have lifetime.
3901     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3902         var->isThreadSpecified()) {
3903       Diag(var->getLocation(), diag::err_arc_thread_ownership)
3904         << var->getType();
3905       return true;
3906     }
3907   }
3908   
3909   return false;
3910 }
3911
3912 NamedDecl*
3913 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3914                               TypeSourceInfo *TInfo, LookupResult &Previous,
3915                               MultiTemplateParamsArg TemplateParamLists) {
3916   QualType R = TInfo->getType();
3917   DeclarationName Name = GetNameForDeclarator(D).getName();
3918
3919   // Check that there are no default arguments (C++ only).
3920   if (getLangOpts().CPlusPlus)
3921     CheckExtraCXXDefaultArguments(D);
3922
3923   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3924   assert(SCSpec != DeclSpec::SCS_typedef &&
3925          "Parser allowed 'typedef' as storage class VarDecl.");
3926   VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3927   if (SCSpec == DeclSpec::SCS_mutable) {
3928     // mutable can only appear on non-static class members, so it's always
3929     // an error here
3930     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
3931     D.setInvalidType();
3932     SC = SC_None;
3933   }
3934   SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3935   VarDecl::StorageClass SCAsWritten
3936     = StorageClassSpecToVarDeclStorageClass(SCSpec);
3937
3938   IdentifierInfo *II = Name.getAsIdentifierInfo();
3939   if (!II) {
3940     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3941       << Name;
3942     return 0;
3943   }
3944
3945   DiagnoseFunctionSpecifiers(D);
3946
3947   if (!DC->isRecord() && S->getFnParent() == 0) {
3948     // C99 6.9p2: The storage-class specifiers auto and register shall not
3949     // appear in the declaration specifiers in an external declaration.
3950     if (SC == SC_Auto || SC == SC_Register) {
3951
3952       // If this is a register variable with an asm label specified, then this
3953       // is a GNU extension.
3954       if (SC == SC_Register && D.getAsmLabel())
3955         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3956       else
3957         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
3958       D.setInvalidType();
3959     }
3960   }
3961   
3962   if (getLangOpts().OpenCL) {
3963     // Set up the special work-group-local storage class for variables in the
3964     // OpenCL __local address space.
3965     if (R.getAddressSpace() == LangAS::opencl_local)
3966       SC = SC_OpenCLWorkGroupLocal;
3967   }
3968
3969   bool isExplicitSpecialization = false;
3970   VarDecl *NewVD;
3971   if (!getLangOpts().CPlusPlus) {
3972     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
3973                             D.getIdentifierLoc(), II,
3974                             R, TInfo, SC, SCAsWritten);
3975   
3976     if (D.isInvalidType())
3977       NewVD->setInvalidDecl();
3978   } else {
3979     if (DC->isRecord() && !CurContext->isRecord()) {
3980       // This is an out-of-line definition of a static data member.
3981       if (SC == SC_Static) {
3982         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3983              diag::err_static_out_of_line)
3984           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3985       } else if (SC == SC_None)
3986         SC = SC_Static;
3987     }
3988     if (SC == SC_Static && CurContext->isRecord()) {
3989       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3990         if (RD->isLocalClass())
3991           Diag(D.getIdentifierLoc(),
3992                diag::err_static_data_member_not_allowed_in_local_class)
3993             << Name << RD->getDeclName();
3994
3995         // C++98 [class.union]p1: If a union contains a static data member,
3996         // the program is ill-formed. C++11 drops this restriction.
3997         if (RD->isUnion())
3998           Diag(D.getIdentifierLoc(),
3999                getLangOpts().CPlusPlus0x
4000                  ? diag::warn_cxx98_compat_static_data_member_in_union
4001                  : diag::ext_static_data_member_in_union) << Name;
4002         // We conservatively disallow static data members in anonymous structs.
4003         else if (!RD->getDeclName())
4004           Diag(D.getIdentifierLoc(),
4005                diag::err_static_data_member_not_allowed_in_anon_struct)
4006             << Name << RD->isUnion();
4007       }
4008     }
4009
4010     // Match up the template parameter lists with the scope specifier, then
4011     // determine whether we have a template or a template specialization.
4012     isExplicitSpecialization = false;
4013     bool Invalid = false;
4014     if (TemplateParameterList *TemplateParams
4015         = MatchTemplateParametersToScopeSpecifier(
4016                                   D.getDeclSpec().getLocStart(),
4017                                                   D.getIdentifierLoc(),
4018                                                   D.getCXXScopeSpec(),
4019                                                   TemplateParamLists.get(),
4020                                                   TemplateParamLists.size(),
4021                                                   /*never a friend*/ false,
4022                                                   isExplicitSpecialization,
4023                                                   Invalid)) {
4024       if (TemplateParams->size() > 0) {
4025         // There is no such thing as a variable template.
4026         Diag(D.getIdentifierLoc(), diag::err_template_variable)
4027           << II
4028           << SourceRange(TemplateParams->getTemplateLoc(),
4029                          TemplateParams->getRAngleLoc());
4030         return 0;
4031       } else {
4032         // There is an extraneous 'template<>' for this variable. Complain
4033         // about it, but allow the declaration of the variable.
4034         Diag(TemplateParams->getTemplateLoc(),
4035              diag::err_template_variable_noparams)
4036           << II
4037           << SourceRange(TemplateParams->getTemplateLoc(),
4038                          TemplateParams->getRAngleLoc());
4039       }
4040     }
4041
4042     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4043                             D.getIdentifierLoc(), II,
4044                             R, TInfo, SC, SCAsWritten);
4045
4046     // If this decl has an auto type in need of deduction, make a note of the
4047     // Decl so we can diagnose uses of it in its own initializer.
4048     if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4049         R->getContainedAutoType())
4050       ParsingInitForAutoVars.insert(NewVD);
4051
4052     if (D.isInvalidType() || Invalid)
4053       NewVD->setInvalidDecl();
4054
4055     SetNestedNameSpecifier(NewVD, D);
4056
4057     if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
4058       NewVD->setTemplateParameterListsInfo(Context,
4059                                            TemplateParamLists.size(),
4060                                            TemplateParamLists.release());
4061     }
4062
4063     if (D.getDeclSpec().isConstexprSpecified())
4064       NewVD->setConstexpr(true);
4065   }
4066
4067   // Set the lexical context. If the declarator has a C++ scope specifier, the
4068   // lexical context will be different from the semantic context.
4069   NewVD->setLexicalDeclContext(CurContext);
4070
4071   if (D.getDeclSpec().isThreadSpecified()) {
4072     if (NewVD->hasLocalStorage())
4073       Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
4074     else if (!Context.getTargetInfo().isTLSSupported())
4075       Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
4076     else
4077       NewVD->setThreadSpecified(true);
4078   }
4079
4080   if (D.getDeclSpec().isModulePrivateSpecified()) {
4081     if (isExplicitSpecialization)
4082       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4083         << 2
4084         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4085     else if (NewVD->hasLocalStorage())
4086       Diag(NewVD->getLocation(), diag::err_module_private_local)
4087         << 0 << NewVD->getDeclName()
4088         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4089         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4090     else
4091       NewVD->setModulePrivate();
4092   }
4093
4094   // Handle attributes prior to checking for duplicates in MergeVarDecl
4095   ProcessDeclAttributes(S, NewVD, D);
4096
4097   // In auto-retain/release, infer strong retension for variables of
4098   // retainable type.
4099   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4100     NewVD->setInvalidDecl();
4101
4102   // Handle GNU asm-label extension (encoded as an attribute).
4103   if (Expr *E = (Expr*)D.getAsmLabel()) {
4104     // The parser guarantees this is a string.
4105     StringLiteral *SE = cast<StringLiteral>(E);
4106     StringRef Label = SE->getString();
4107     if (S->getFnParent() != 0) {
4108       switch (SC) {
4109       case SC_None:
4110       case SC_Auto:
4111         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4112         break;
4113       case SC_Register:
4114         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4115           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4116         break;
4117       case SC_Static:
4118       case SC_Extern:
4119       case SC_PrivateExtern:
4120       case SC_OpenCLWorkGroupLocal:
4121         break;
4122       }
4123     }
4124
4125     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4126                                                 Context, Label));
4127   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4128     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4129       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4130     if (I != ExtnameUndeclaredIdentifiers.end()) {
4131       NewVD->addAttr(I->second);
4132       ExtnameUndeclaredIdentifiers.erase(I);
4133     }
4134   }
4135
4136   // Diagnose shadowed variables before filtering for scope.
4137   if (!D.getCXXScopeSpec().isSet())
4138     CheckShadow(S, NewVD, Previous);
4139
4140   // Don't consider existing declarations that are in a different
4141   // scope and are out-of-semantic-context declarations (if the new
4142   // declaration has linkage).
4143   FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
4144                        isExplicitSpecialization);
4145   
4146   if (!getLangOpts().CPlusPlus) {
4147     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4148   } else {
4149     // Merge the decl with the existing one if appropriate.
4150     if (!Previous.empty()) {
4151       if (Previous.isSingleResult() &&
4152           isa<FieldDecl>(Previous.getFoundDecl()) &&
4153           D.getCXXScopeSpec().isSet()) {
4154         // The user tried to define a non-static data member
4155         // out-of-line (C++ [dcl.meaning]p1).
4156         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4157           << D.getCXXScopeSpec().getRange();
4158         Previous.clear();
4159         NewVD->setInvalidDecl();
4160       }
4161     } else if (D.getCXXScopeSpec().isSet()) {
4162       // No previous declaration in the qualifying scope.
4163       Diag(D.getIdentifierLoc(), diag::err_no_member)
4164         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4165         << D.getCXXScopeSpec().getRange();
4166       NewVD->setInvalidDecl();
4167     }
4168
4169     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4170
4171     // This is an explicit specialization of a static data member. Check it.
4172     if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4173         CheckMemberSpecialization(NewVD, Previous))
4174       NewVD->setInvalidDecl();
4175   }
4176   
4177   // attributes declared post-definition are currently ignored
4178   // FIXME: This should be handled in attribute merging, not
4179   // here.
4180   if (Previous.isSingleResult()) {
4181     VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
4182     if (Def && (Def = Def->getDefinition()) &&
4183         Def != NewVD && D.hasAttributes()) {
4184       Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
4185       Diag(Def->getLocation(), diag::note_previous_definition);
4186     }
4187   }
4188
4189   // If this is a locally-scoped extern C variable, update the map of
4190   // such variables.
4191   if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4192       !NewVD->isInvalidDecl())
4193     RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4194
4195   // If there's a #pragma GCC visibility in scope, and this isn't a class
4196   // member, set the visibility of this variable.
4197   if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4198     AddPushedVisibilityAttribute(NewVD);
4199   
4200   MarkUnusedFileScopedDecl(NewVD);
4201
4202   return NewVD;
4203 }
4204
4205 /// \brief Diagnose variable or built-in function shadowing.  Implements
4206 /// -Wshadow.
4207 ///
4208 /// This method is called whenever a VarDecl is added to a "useful"
4209 /// scope.
4210 ///
4211 /// \param S the scope in which the shadowing name is being declared
4212 /// \param R the lookup of the name
4213 ///
4214 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4215   // Return if warning is ignored.
4216   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4217         DiagnosticsEngine::Ignored)
4218     return;
4219
4220   // Don't diagnose declarations at file scope.
4221   if (D->hasGlobalStorage())
4222     return;
4223
4224   DeclContext *NewDC = D->getDeclContext();
4225
4226   // Only diagnose if we're shadowing an unambiguous field or variable.
4227   if (R.getResultKind() != LookupResult::Found)
4228     return;
4229
4230   NamedDecl* ShadowedDecl = R.getFoundDecl();
4231   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4232     return;
4233
4234   // Fields are not shadowed by variables in C++ static methods.
4235   if (isa<FieldDecl>(ShadowedDecl))
4236     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4237       if (MD->isStatic())
4238         return;
4239
4240   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4241     if (shadowedVar->isExternC()) {
4242       // For shadowing external vars, make sure that we point to the global
4243       // declaration, not a locally scoped extern declaration.
4244       for (VarDecl::redecl_iterator
4245              I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4246            I != E; ++I)
4247         if (I->isFileVarDecl()) {
4248           ShadowedDecl = *I;
4249           break;
4250         }
4251     }
4252
4253   DeclContext *OldDC = ShadowedDecl->getDeclContext();
4254
4255   // Only warn about certain kinds of shadowing for class members.
4256   if (NewDC && NewDC->isRecord()) {
4257     // In particular, don't warn about shadowing non-class members.
4258     if (!OldDC->isRecord())
4259       return;
4260
4261     // TODO: should we warn about static data members shadowing
4262     // static data members from base classes?
4263     
4264     // TODO: don't diagnose for inaccessible shadowed members.
4265     // This is hard to do perfectly because we might friend the
4266     // shadowing context, but that's just a false negative.
4267   }
4268
4269   // Determine what kind of declaration we're shadowing.
4270   unsigned Kind;
4271   if (isa<RecordDecl>(OldDC)) {
4272     if (isa<FieldDecl>(ShadowedDecl))
4273       Kind = 3; // field
4274     else
4275       Kind = 2; // static data member
4276   } else if (OldDC->isFileContext())
4277     Kind = 1; // global
4278   else
4279     Kind = 0; // local
4280
4281   DeclarationName Name = R.getLookupName();
4282
4283   // Emit warning and note.
4284   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
4285   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4286 }
4287
4288 /// \brief Check -Wshadow without the advantage of a previous lookup.
4289 void Sema::CheckShadow(Scope *S, VarDecl *D) {
4290   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4291         DiagnosticsEngine::Ignored)
4292     return;
4293
4294   LookupResult R(*this, D->getDeclName(), D->getLocation(),
4295                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4296   LookupName(R, S);
4297   CheckShadow(S, D, R);
4298 }
4299
4300 /// \brief Perform semantic checking on a newly-created variable
4301 /// declaration.
4302 ///
4303 /// This routine performs all of the type-checking required for a
4304 /// variable declaration once it has been built. It is used both to
4305 /// check variables after they have been parsed and their declarators
4306 /// have been translated into a declaration, and to check variables
4307 /// that have been instantiated from a template.
4308 ///
4309 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4310 ///
4311 /// Returns true if the variable declaration is a redeclaration.
4312 bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4313                                     LookupResult &Previous) {
4314   // If the decl is already known invalid, don't check it.
4315   if (NewVD->isInvalidDecl())
4316     return false;
4317
4318   QualType T = NewVD->getType();
4319
4320   if (T->isObjCObjectType()) {
4321     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4322       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
4323     T = Context.getObjCObjectPointerType(T);
4324     NewVD->setType(T);
4325   }
4326
4327   // Emit an error if an address space was applied to decl with local storage.
4328   // This includes arrays of objects with address space qualifiers, but not
4329   // automatic variables that point to other address spaces.
4330   // ISO/IEC TR 18037 S5.1.2
4331   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
4332     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
4333     NewVD->setInvalidDecl();
4334     return false;
4335   }
4336
4337   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
4338       && !NewVD->hasAttr<BlocksAttr>()) {
4339     if (getLangOpts().getGC() != LangOptions::NonGC)
4340       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4341     else
4342       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4343   }
4344   
4345   bool isVM = T->isVariablyModifiedType();
4346   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
4347       NewVD->hasAttr<BlocksAttr>())
4348     getCurFunction()->setHasBranchProtectedScope();
4349
4350   if ((isVM && NewVD->hasLinkage()) ||
4351       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
4352     bool SizeIsNegative;
4353     llvm::APSInt Oversized;
4354     QualType FixedTy =
4355         TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
4356                                             Oversized);
4357
4358     if (FixedTy.isNull() && T->isVariableArrayType()) {
4359       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
4360       // FIXME: This won't give the correct result for
4361       // int a[10][n];
4362       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
4363
4364       if (NewVD->isFileVarDecl())
4365         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
4366         << SizeRange;
4367       else if (NewVD->getStorageClass() == SC_Static)
4368         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
4369         << SizeRange;
4370       else
4371         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
4372         << SizeRange;
4373       NewVD->setInvalidDecl();
4374       return false;
4375     }
4376
4377     if (FixedTy.isNull()) {
4378       if (NewVD->isFileVarDecl())
4379         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4380       else
4381         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
4382       NewVD->setInvalidDecl();
4383       return false;
4384     }
4385
4386     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4387     NewVD->setType(FixedTy);
4388   }
4389
4390   if (Previous.empty() && NewVD->isExternC()) {
4391     // Since we did not find anything by this name and we're declaring
4392     // an extern "C" variable, look for a non-visible extern "C"
4393     // declaration with the same name.
4394     llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4395       = findLocallyScopedExternalDecl(NewVD->getDeclName());
4396     if (Pos != LocallyScopedExternalDecls.end())
4397       Previous.addDecl(Pos->second);
4398   }
4399
4400   if (T->isVoidType() && !NewVD->hasExternalStorage()) {
4401     Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4402       << T;
4403     NewVD->setInvalidDecl();
4404     return false;
4405   }
4406
4407   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
4408     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4409     NewVD->setInvalidDecl();
4410     return false;
4411   }
4412
4413   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
4414     Diag(NewVD->getLocation(), diag::err_block_on_vm);
4415     NewVD->setInvalidDecl();
4416     return false;
4417   }
4418
4419   if (NewVD->isConstexpr() && !T->isDependentType() &&
4420       RequireLiteralType(NewVD->getLocation(), T,
4421                          PDiag(diag::err_constexpr_var_non_literal))) {
4422     NewVD->setInvalidDecl();
4423     return false;
4424   }
4425
4426   if (!Previous.empty()) {
4427     MergeVarDecl(NewVD, Previous);
4428     return true;
4429   }
4430   return false;
4431 }
4432
4433 /// \brief Data used with FindOverriddenMethod
4434 struct FindOverriddenMethodData {
4435   Sema *S;
4436   CXXMethodDecl *Method;
4437 };
4438
4439 /// \brief Member lookup function that determines whether a given C++
4440 /// method overrides a method in a base class, to be used with
4441 /// CXXRecordDecl::lookupInBases().
4442 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
4443                                  CXXBasePath &Path,
4444                                  void *UserData) {
4445   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4446
4447   FindOverriddenMethodData *Data 
4448     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
4449   
4450   DeclarationName Name = Data->Method->getDeclName();
4451   
4452   // FIXME: Do we care about other names here too?
4453   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4454     // We really want to find the base class destructor here.
4455     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4456     CanQualType CT = Data->S->Context.getCanonicalType(T);
4457     
4458     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
4459   }    
4460   
4461   for (Path.Decls = BaseRecord->lookup(Name);
4462        Path.Decls.first != Path.Decls.second;
4463        ++Path.Decls.first) {
4464     NamedDecl *D = *Path.Decls.first;
4465     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4466       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
4467         return true;
4468     }
4469   }
4470   
4471   return false;
4472 }
4473
4474 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4475 /// and if so, check that it's a valid override and remember it.
4476 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4477   // Look for virtual methods in base classes that this method might override.
4478   CXXBasePaths Paths;
4479   FindOverriddenMethodData Data;
4480   Data.Method = MD;
4481   Data.S = this;
4482   bool AddedAny = false;
4483   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4484     for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4485          E = Paths.found_decls_end(); I != E; ++I) {
4486       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4487         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
4488         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
4489             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
4490             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
4491           AddedAny = true;
4492         }
4493       }
4494     }
4495   }
4496   
4497   return AddedAny;
4498 }
4499
4500 namespace {
4501   // Struct for holding all of the extra arguments needed by
4502   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4503   struct ActOnFDArgs {
4504     Scope *S;
4505     Declarator &D;
4506     MultiTemplateParamsArg TemplateParamLists;
4507     bool AddToScope;
4508   };
4509 }
4510
4511 namespace {
4512
4513 // Callback to only accept typo corrections that have a non-zero edit distance.
4514 // Also only accept corrections that have the same parent decl.
4515 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4516  public:
4517   DifferentNameValidatorCCC(CXXRecordDecl *Parent)
4518       : ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
4519
4520   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
4521     if (candidate.getEditDistance() == 0)
4522       return false;
4523
4524     if (CXXMethodDecl *MD = candidate.getCorrectionDeclAs<CXXMethodDecl>()) {
4525       CXXRecordDecl *Parent = MD->getParent();
4526       return Parent && Parent->getCanonicalDecl() == ExpectedParent;
4527     }
4528
4529     return !ExpectedParent;
4530   }
4531
4532  private:
4533   CXXRecordDecl *ExpectedParent;
4534 };
4535
4536 }
4537
4538 /// \brief Generate diagnostics for an invalid function redeclaration.
4539 ///
4540 /// This routine handles generating the diagnostic messages for an invalid
4541 /// function redeclaration, including finding possible similar declarations
4542 /// or performing typo correction if there are no previous declarations with
4543 /// the same name.
4544 ///
4545 /// Returns a NamedDecl iff typo correction was performed and substituting in
4546 /// the new declaration name does not cause new errors.
4547 static NamedDecl* DiagnoseInvalidRedeclaration(
4548     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
4549     ActOnFDArgs &ExtraArgs) {
4550   NamedDecl *Result = NULL;
4551   DeclarationName Name = NewFD->getDeclName();
4552   DeclContext *NewDC = NewFD->getDeclContext();
4553   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
4554                     Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4555   llvm::SmallVector<unsigned, 1> MismatchedParams;
4556   llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4557   TypoCorrection Correction;
4558   bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
4559                        ExtraArgs.D.getDeclSpec().isFriendSpecified());
4560   unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4561                                   : diag::err_member_def_does_not_match;
4562
4563   NewFD->setInvalidDecl();
4564   SemaRef.LookupQualifiedName(Prev, NewDC);
4565   assert(!Prev.isAmbiguous() &&
4566          "Cannot have an ambiguity in previous-declaration lookup");
4567   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
4568   DifferentNameValidatorCCC Validator(MD ? MD->getParent() : 0);
4569   if (!Prev.empty()) {
4570     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4571          Func != FuncEnd; ++Func) {
4572       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
4573       if (FD &&
4574           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4575         // Add 1 to the index so that 0 can mean the mismatch didn't
4576         // involve a parameter
4577         unsigned ParamNum =
4578             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4579         NearMatches.push_back(std::make_pair(FD, ParamNum));
4580       }
4581     }
4582   // If the qualified name lookup yielded nothing, try typo correction
4583   } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
4584                                          Prev.getLookupKind(), 0, 0,
4585                                          Validator, NewDC))) {
4586     // Trap errors.
4587     Sema::SFINAETrap Trap(SemaRef);
4588
4589     // Set up everything for the call to ActOnFunctionDeclarator
4590     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4591                               ExtraArgs.D.getIdentifierLoc());
4592     Previous.clear();
4593     Previous.setLookupName(Correction.getCorrection());
4594     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4595                                     CDeclEnd = Correction.end();
4596          CDecl != CDeclEnd; ++CDecl) {
4597       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4598       if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD,
4599                                      MismatchedParams)) {
4600         Previous.addDecl(FD);
4601       }
4602     }
4603     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
4604     // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4605     // pieces need to verify the typo-corrected C++ declaraction and hopefully
4606     // eliminate the need for the parameter pack ExtraArgs.
4607     Result = SemaRef.ActOnFunctionDeclarator(
4608         ExtraArgs.S, ExtraArgs.D,
4609         Correction.getCorrectionDecl()->getDeclContext(),
4610         NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4611         ExtraArgs.AddToScope);
4612     if (Trap.hasErrorOccurred()) {
4613       // Pretend the typo correction never occurred
4614       ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
4615                                 ExtraArgs.D.getIdentifierLoc());
4616       ExtraArgs.D.setRedeclaration(wasRedeclaration);
4617       Previous.clear();
4618       Previous.setLookupName(Name);
4619       Result = NULL;
4620     } else {
4621       for (LookupResult::iterator Func = Previous.begin(),
4622                                FuncEnd = Previous.end();
4623            Func != FuncEnd; ++Func) {
4624         if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
4625           NearMatches.push_back(std::make_pair(FD, 0));
4626       }
4627     }
4628     if (NearMatches.empty()) {
4629       // Ignore the correction if it didn't yield any close FunctionDecl matches
4630       Correction = TypoCorrection();
4631     } else {
4632       DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
4633                              : diag::err_member_def_does_not_match_suggest;
4634     }
4635   }
4636
4637   if (Correction)
4638     SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4639         << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
4640         << FixItHint::CreateReplacement(
4641             NewFD->getLocation(),
4642             Correction.getAsString(SemaRef.getLangOpts()));
4643   else
4644     SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4645         << Name << NewDC << NewFD->getLocation();
4646
4647   bool NewFDisConst = false;
4648   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
4649     NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
4650
4651   for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
4652        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
4653        NearMatch != NearMatchEnd; ++NearMatch) {
4654     FunctionDecl *FD = NearMatch->first;
4655     bool FDisConst = false;
4656     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
4657       FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
4658
4659     if (unsigned Idx = NearMatch->second) {
4660       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
4661       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
4662       if (Loc.isInvalid()) Loc = FD->getLocation();
4663       SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
4664           << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
4665     } else if (Correction) {
4666       SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
4667           << Correction.getQuoted(SemaRef.getLangOpts());
4668     } else if (FDisConst != NewFDisConst) {
4669       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
4670           << NewFDisConst << FD->getSourceRange().getEnd();
4671     } else
4672       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
4673   }
4674   return Result;
4675 }
4676
4677 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 
4678                                                           Declarator &D) {
4679   switch (D.getDeclSpec().getStorageClassSpec()) {
4680   default: llvm_unreachable("Unknown storage class!");
4681   case DeclSpec::SCS_auto:
4682   case DeclSpec::SCS_register:
4683   case DeclSpec::SCS_mutable:
4684     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4685                  diag::err_typecheck_sclass_func);
4686     D.setInvalidType();
4687     break;
4688   case DeclSpec::SCS_unspecified: break;
4689   case DeclSpec::SCS_extern: return SC_Extern;
4690   case DeclSpec::SCS_static: {
4691     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4692       // C99 6.7.1p5:
4693       //   The declaration of an identifier for a function that has
4694       //   block scope shall have no explicit storage-class specifier
4695       //   other than extern
4696       // See also (C++ [dcl.stc]p4).
4697       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4698                    diag::err_static_block_func);
4699       break;
4700     } else
4701       return SC_Static;
4702   }
4703   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4704   }
4705
4706   // No explicit storage class has already been returned
4707   return SC_None;
4708 }
4709
4710 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
4711                                            DeclContext *DC, QualType &R,
4712                                            TypeSourceInfo *TInfo,
4713                                            FunctionDecl::StorageClass SC,
4714                                            bool &IsVirtualOkay) {
4715   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
4716   DeclarationName Name = NameInfo.getName();
4717
4718   FunctionDecl *NewFD = 0;
4719   bool isInline = D.getDeclSpec().isInlineSpecified();
4720   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4721   FunctionDecl::StorageClass SCAsWritten
4722     = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
4723
4724   if (!SemaRef.getLangOpts().CPlusPlus) {
4725     // Determine whether the function was written with a
4726     // prototype. This true when:
4727     //   - there is a prototype in the declarator, or
4728     //   - the type R of the function is some kind of typedef or other reference
4729     //     to a type name (which eventually refers to a function type).
4730     bool HasPrototype =
4731       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
4732       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4733
4734     NewFD = FunctionDecl::Create(SemaRef.Context, DC, 
4735                                  D.getLocStart(), NameInfo, R, 
4736                                  TInfo, SC, SCAsWritten, isInline, 
4737                                  HasPrototype);
4738     if (D.isInvalidType())
4739       NewFD->setInvalidDecl();
4740
4741     // Set the lexical context.
4742     NewFD->setLexicalDeclContext(SemaRef.CurContext);
4743
4744     return NewFD;
4745   }
4746
4747   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4748   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4749
4750   // Check that the return type is not an abstract class type.
4751   // For record types, this is done by the AbstractClassUsageDiagnoser once
4752   // the class has been completely parsed.
4753   if (!DC->isRecord() &&
4754       SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
4755                                      R->getAs<FunctionType>()->getResultType(),
4756                                      diag::err_abstract_type_in_decl,
4757                                      SemaRef.AbstractReturnType))
4758     D.setInvalidType();
4759
4760   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4761     // This is a C++ constructor declaration.
4762     assert(DC->isRecord() &&
4763            "Constructors can only be declared in a member context");
4764
4765     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
4766     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4767                                       D.getLocStart(), NameInfo,
4768                                       R, TInfo, isExplicit, isInline,
4769                                       /*isImplicitlyDeclared=*/false,
4770                                       isConstexpr);
4771
4772   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4773     // This is a C++ destructor declaration.
4774     if (DC->isRecord()) {
4775       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
4776       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
4777       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
4778                                         SemaRef.Context, Record,
4779                                         D.getLocStart(),
4780                                         NameInfo, R, TInfo, isInline,
4781                                         /*isImplicitlyDeclared=*/false);
4782
4783       // If the class is complete, then we now create the implicit exception
4784       // specification. If the class is incomplete or dependent, we can't do
4785       // it yet.
4786       if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
4787           Record->getDefinition() && !Record->isBeingDefined() &&
4788           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4789         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
4790       }
4791
4792       IsVirtualOkay = true;
4793       return NewDD;
4794
4795     } else {
4796       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4797       D.setInvalidType();
4798
4799       // Create a FunctionDecl to satisfy the function definition parsing
4800       // code path.
4801       return FunctionDecl::Create(SemaRef.Context, DC,
4802                                   D.getLocStart(),
4803                                   D.getIdentifierLoc(), Name, R, TInfo,
4804                                   SC, SCAsWritten, isInline,
4805                                   /*hasPrototype=*/true, isConstexpr);
4806     }
4807
4808   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4809     if (!DC->isRecord()) {
4810       SemaRef.Diag(D.getIdentifierLoc(),
4811            diag::err_conv_function_not_member);
4812       return 0;
4813     }
4814
4815     SemaRef.CheckConversionDeclarator(D, R, SC);
4816     IsVirtualOkay = true;
4817     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4818                                      D.getLocStart(), NameInfo,
4819                                      R, TInfo, isInline, isExplicit,
4820                                      isConstexpr, SourceLocation());
4821
4822   } else if (DC->isRecord()) {
4823     // If the name of the function is the same as the name of the record,
4824     // then this must be an invalid constructor that has a return type.
4825     // (The parser checks for a return type and makes the declarator a
4826     // constructor if it has no return type).
4827     if (Name.getAsIdentifierInfo() &&
4828         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4829       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4830         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4831         << SourceRange(D.getIdentifierLoc());
4832       return 0;
4833     }
4834
4835     bool isStatic = SC == SC_Static;
4836
4837     // [class.free]p1:
4838     // Any allocation function for a class T is a static member
4839     // (even if not explicitly declared static).
4840     if (Name.getCXXOverloadedOperator() == OO_New ||
4841         Name.getCXXOverloadedOperator() == OO_Array_New)
4842       isStatic = true;
4843
4844     // [class.free]p6 Any deallocation function for a class X is a static member
4845     // (even if not explicitly declared static).
4846     if (Name.getCXXOverloadedOperator() == OO_Delete ||
4847         Name.getCXXOverloadedOperator() == OO_Array_Delete)
4848       isStatic = true;
4849
4850     IsVirtualOkay = !isStatic;
4851
4852     // This is a C++ method declaration.
4853     return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4854                                  D.getLocStart(), NameInfo, R,
4855                                  TInfo, isStatic, SCAsWritten, isInline,
4856                                  isConstexpr, SourceLocation());
4857
4858   } else {
4859     // Determine whether the function was written with a
4860     // prototype. This true when:
4861     //   - we're in C++ (where every function has a prototype),
4862     return FunctionDecl::Create(SemaRef.Context, DC,
4863                                 D.getLocStart(),
4864                                 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4865                                 true/*HasPrototype*/, isConstexpr);
4866   }
4867 }
4868
4869 NamedDecl*
4870 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4871                               TypeSourceInfo *TInfo, LookupResult &Previous,
4872                               MultiTemplateParamsArg TemplateParamLists,
4873                               bool &AddToScope) {
4874   QualType R = TInfo->getType();
4875
4876   assert(R.getTypePtr()->isFunctionType());
4877
4878   // TODO: consider using NameInfo for diagnostic.
4879   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4880   DeclarationName Name = NameInfo.getName();
4881   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
4882
4883   if (D.getDeclSpec().isThreadSpecified())
4884     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4885
4886   // Do not allow returning a objc interface by-value.
4887   if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
4888     Diag(D.getIdentifierLoc(),
4889          diag::err_object_cannot_be_passed_returned_by_value) << 0
4890     << R->getAs<FunctionType>()->getResultType()
4891     << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
4892
4893     QualType T = R->getAs<FunctionType>()->getResultType();
4894     T = Context.getObjCObjectPointerType(T);
4895     if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
4896       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4897       R = Context.getFunctionType(T, FPT->arg_type_begin(),
4898                                   FPT->getNumArgs(), EPI);
4899     }
4900     else if (isa<FunctionNoProtoType>(R))
4901       R = Context.getFunctionNoProtoType(T);
4902   }
4903
4904   bool isFriend = false;
4905   FunctionTemplateDecl *FunctionTemplate = 0;
4906   bool isExplicitSpecialization = false;
4907   bool isFunctionTemplateSpecialization = false;
4908   bool isDependentClassScopeExplicitSpecialization = false;
4909   bool isVirtualOkay = false;
4910
4911   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
4912                                               isVirtualOkay);
4913   if (!NewFD) return 0;
4914
4915   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
4916     NewFD->setTopLevelDeclInObjCContainer();
4917
4918   if (getLangOpts().CPlusPlus) {
4919     bool isInline = D.getDeclSpec().isInlineSpecified();
4920     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4921     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4922     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4923     isFriend = D.getDeclSpec().isFriendSpecified();
4924     if (isFriend && !isInline && D.isFunctionDefinition()) {
4925       // C++ [class.friend]p5
4926       //   A function can be defined in a friend declaration of a
4927       //   class . . . . Such a function is implicitly inline.
4928       NewFD->setImplicitlyInline();
4929     }
4930
4931     SetNestedNameSpecifier(NewFD, D);
4932     isExplicitSpecialization = false;
4933     isFunctionTemplateSpecialization = false;
4934     if (D.isInvalidType())
4935       NewFD->setInvalidDecl();
4936     
4937     // Set the lexical context. If the declarator has a C++
4938     // scope specifier, or is the object of a friend declaration, the
4939     // lexical context will be different from the semantic context.
4940     NewFD->setLexicalDeclContext(CurContext);
4941         
4942     // Match up the template parameter lists with the scope specifier, then
4943     // determine whether we have a template or a template specialization.
4944     bool Invalid = false;
4945     if (TemplateParameterList *TemplateParams
4946           = MatchTemplateParametersToScopeSpecifier(
4947                                   D.getDeclSpec().getLocStart(),
4948                                   D.getIdentifierLoc(),
4949                                   D.getCXXScopeSpec(),
4950                                   TemplateParamLists.get(),
4951                                   TemplateParamLists.size(),
4952                                   isFriend,
4953                                   isExplicitSpecialization,
4954                                   Invalid)) {
4955       if (TemplateParams->size() > 0) {
4956         // This is a function template
4957
4958         // Check that we can declare a template here.
4959         if (CheckTemplateDeclScope(S, TemplateParams))
4960           return 0;
4961
4962         // A destructor cannot be a template.
4963         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4964           Diag(NewFD->getLocation(), diag::err_destructor_template);
4965           return 0;
4966         }
4967         
4968         // If we're adding a template to a dependent context, we may need to 
4969         // rebuilding some of the types used within the template parameter list,
4970         // now that we know what the current instantiation is.
4971         if (DC->isDependentContext()) {
4972           ContextRAII SavedContext(*this, DC);
4973           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
4974             Invalid = true;
4975         }
4976         
4977
4978         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4979                                                         NewFD->getLocation(),
4980                                                         Name, TemplateParams,
4981                                                         NewFD);
4982         FunctionTemplate->setLexicalDeclContext(CurContext);
4983         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4984
4985         // For source fidelity, store the other template param lists.
4986         if (TemplateParamLists.size() > 1) {
4987           NewFD->setTemplateParameterListsInfo(Context,
4988                                                TemplateParamLists.size() - 1,
4989                                                TemplateParamLists.release());
4990         }
4991       } else {
4992         // This is a function template specialization.
4993         isFunctionTemplateSpecialization = true;
4994         // For source fidelity, store all the template param lists.
4995         NewFD->setTemplateParameterListsInfo(Context,
4996                                              TemplateParamLists.size(),
4997                                              TemplateParamLists.release());
4998
4999         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5000         if (isFriend) {
5001           // We want to remove the "template<>", found here.
5002           SourceRange RemoveRange = TemplateParams->getSourceRange();
5003
5004           // If we remove the template<> and the name is not a
5005           // template-id, we're actually silently creating a problem:
5006           // the friend declaration will refer to an untemplated decl,
5007           // and clearly the user wants a template specialization.  So
5008           // we need to insert '<>' after the name.
5009           SourceLocation InsertLoc;
5010           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5011             InsertLoc = D.getName().getSourceRange().getEnd();
5012             InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5013           }
5014
5015           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5016             << Name << RemoveRange
5017             << FixItHint::CreateRemoval(RemoveRange)
5018             << FixItHint::CreateInsertion(InsertLoc, "<>");
5019         }
5020       }
5021     }
5022     else {
5023       // All template param lists were matched against the scope specifier:
5024       // this is NOT (an explicit specialization of) a template.
5025       if (TemplateParamLists.size() > 0)
5026         // For source fidelity, store all the template param lists.
5027         NewFD->setTemplateParameterListsInfo(Context,
5028                                              TemplateParamLists.size(),
5029                                              TemplateParamLists.release());
5030     }
5031
5032     if (Invalid) {
5033       NewFD->setInvalidDecl();
5034       if (FunctionTemplate)
5035         FunctionTemplate->setInvalidDecl();
5036     }
5037
5038     // If we see "T var();" at block scope, where T is a class type, it is
5039     // probably an attempt to initialize a variable, not a function declaration.
5040     // We don't catch this case earlier, since there is no ambiguity here.
5041     if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration &&
5042         CurContext->isFunctionOrMethod() &&
5043         D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() &&
5044         D.getDeclSpec().getStorageClassSpecAsWritten()
5045           == DeclSpec::SCS_unspecified) {
5046       QualType T = R->getAs<FunctionType>()->getResultType();
5047       DeclaratorChunk &C = D.getTypeObject(0);
5048       if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic &&
5049           !C.Fun.TrailingReturnType &&
5050           C.Fun.getExceptionSpecType() == EST_None) {
5051         SourceRange ParenRange(C.Loc, C.EndLoc);
5052         Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange;
5053
5054         // If the declaration looks like:
5055         //   T var1,
5056         //   f();
5057         // and name lookup finds a function named 'f', then the ',' was
5058         // probably intended to be a ';'.
5059         if (!D.isFirstDeclarator() && D.getIdentifier()) {
5060           FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
5061           FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
5062           if (Comma.getFileID() != Name.getFileID() ||
5063               Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
5064             LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
5065                                 LookupOrdinaryName);
5066             if (LookupName(Result, S))
5067               Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
5068                 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD;
5069           }
5070         }
5071         const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5072         // Empty parens mean value-initialization, and no parens mean default
5073         // initialization. These are equivalent if the default constructor is
5074         // user-provided, or if zero-initialization is a no-op.
5075         if (RD && RD->hasDefinition() &&
5076             (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
5077           Diag(C.Loc, diag::note_empty_parens_default_ctor)
5078             << FixItHint::CreateRemoval(ParenRange);
5079         else if (const char *Init = getFixItZeroInitializerForType(T))
5080           Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5081             << FixItHint::CreateReplacement(ParenRange, Init);
5082         else if (LangOpts.CPlusPlus0x)
5083           Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5084             << FixItHint::CreateReplacement(ParenRange, "{}");
5085       }
5086     }
5087
5088     // C++ [dcl.fct.spec]p5:
5089     //   The virtual specifier shall only be used in declarations of
5090     //   nonstatic class member functions that appear within a
5091     //   member-specification of a class declaration; see 10.3.
5092     //
5093     if (isVirtual && !NewFD->isInvalidDecl()) {
5094       if (!isVirtualOkay) {
5095         Diag(D.getDeclSpec().getVirtualSpecLoc(),
5096              diag::err_virtual_non_function);
5097       } else if (!CurContext->isRecord()) {
5098         // 'virtual' was specified outside of the class.
5099         Diag(D.getDeclSpec().getVirtualSpecLoc(), 
5100              diag::err_virtual_out_of_class)
5101           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5102       } else if (NewFD->getDescribedFunctionTemplate()) {
5103         // C++ [temp.mem]p3:
5104         //  A member function template shall not be virtual.
5105         Diag(D.getDeclSpec().getVirtualSpecLoc(),
5106              diag::err_virtual_member_function_template)
5107           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5108       } else {
5109         // Okay: Add virtual to the method.
5110         NewFD->setVirtualAsWritten(true);
5111       }
5112     }
5113
5114     // C++ [dcl.fct.spec]p3:
5115     //  The inline specifier shall not appear on a block scope function 
5116     //  declaration.
5117     if (isInline && !NewFD->isInvalidDecl()) {
5118       if (CurContext->isFunctionOrMethod()) {
5119         // 'inline' is not allowed on block scope function declaration.
5120         Diag(D.getDeclSpec().getInlineSpecLoc(), 
5121              diag::err_inline_declaration_block_scope) << Name
5122           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5123       }
5124     }
5125
5126     // C++ [dcl.fct.spec]p6:
5127     //  The explicit specifier shall be used only in the declaration of a
5128     //  constructor or conversion function within its class definition; 
5129     //  see 12.3.1 and 12.3.2.
5130     if (isExplicit && !NewFD->isInvalidDecl()) {
5131       if (!CurContext->isRecord()) {
5132         // 'explicit' was specified outside of the class.
5133         Diag(D.getDeclSpec().getExplicitSpecLoc(), 
5134              diag::err_explicit_out_of_class)
5135           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5136       } else if (!isa<CXXConstructorDecl>(NewFD) && 
5137                  !isa<CXXConversionDecl>(NewFD)) {
5138         // 'explicit' was specified on a function that wasn't a constructor
5139         // or conversion function.
5140         Diag(D.getDeclSpec().getExplicitSpecLoc(),
5141              diag::err_explicit_non_ctor_or_conv_function)
5142           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5143       }      
5144     }
5145
5146     if (isConstexpr) {
5147       // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5148       // are implicitly inline.
5149       NewFD->setImplicitlyInline();
5150
5151       // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5152       // be either constructors or to return a literal type. Therefore,
5153       // destructors cannot be declared constexpr.
5154       if (isa<CXXDestructorDecl>(NewFD))
5155         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
5156     }
5157
5158     // If __module_private__ was specified, mark the function accordingly.
5159     if (D.getDeclSpec().isModulePrivateSpecified()) {
5160       if (isFunctionTemplateSpecialization) {
5161         SourceLocation ModulePrivateLoc
5162           = D.getDeclSpec().getModulePrivateSpecLoc();
5163         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5164           << 0
5165           << FixItHint::CreateRemoval(ModulePrivateLoc);
5166       } else {
5167         NewFD->setModulePrivate();
5168         if (FunctionTemplate)
5169           FunctionTemplate->setModulePrivate();
5170       }
5171     }
5172
5173     if (isFriend) {
5174       // For now, claim that the objects have no previous declaration.
5175       if (FunctionTemplate) {
5176         FunctionTemplate->setObjectOfFriendDecl(false);
5177         FunctionTemplate->setAccess(AS_public);
5178       }
5179       NewFD->setObjectOfFriendDecl(false);
5180       NewFD->setAccess(AS_public);
5181     }
5182
5183     // If a function is defined as defaulted or deleted, mark it as such now.
5184     switch (D.getFunctionDefinitionKind()) {
5185       case FDK_Declaration:
5186       case FDK_Definition:
5187         break;
5188         
5189       case FDK_Defaulted:
5190         NewFD->setDefaulted();
5191         break;
5192         
5193       case FDK_Deleted:
5194         NewFD->setDeletedAsWritten();
5195         break;
5196     }
5197
5198     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5199         D.isFunctionDefinition()) {
5200       // C++ [class.mfct]p2:
5201       //   A member function may be defined (8.4) in its class definition, in 
5202       //   which case it is an inline member function (7.1.2)
5203       NewFD->setImplicitlyInline();
5204     }
5205
5206     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5207         !CurContext->isRecord()) {
5208       // C++ [class.static]p1:
5209       //   A data or function member of a class may be declared static
5210       //   in a class definition, in which case it is a static member of
5211       //   the class.
5212
5213       // Complain about the 'static' specifier if it's on an out-of-line
5214       // member function definition.
5215       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5216            diag::err_static_out_of_line)
5217         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5218     }
5219   }
5220
5221   // Filter out previous declarations that don't match the scope.
5222   FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5223                        isExplicitSpecialization ||
5224                        isFunctionTemplateSpecialization);
5225   
5226   // Handle GNU asm-label extension (encoded as an attribute).
5227   if (Expr *E = (Expr*) D.getAsmLabel()) {
5228     // The parser guarantees this is a string.
5229     StringLiteral *SE = cast<StringLiteral>(E);
5230     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5231                                                 SE->getString()));
5232   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5233     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5234       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5235     if (I != ExtnameUndeclaredIdentifiers.end()) {
5236       NewFD->addAttr(I->second);
5237       ExtnameUndeclaredIdentifiers.erase(I);
5238     }
5239   }
5240
5241   // Copy the parameter declarations from the declarator D to the function
5242   // declaration NewFD, if they are available.  First scavenge them into Params.
5243   SmallVector<ParmVarDecl*, 16> Params;
5244   if (D.isFunctionDeclarator()) {
5245     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5246
5247     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5248     // function that takes no arguments, not a function that takes a
5249     // single void argument.
5250     // We let through "const void" here because Sema::GetTypeForDeclarator
5251     // already checks for that case.
5252     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5253         FTI.ArgInfo[0].Param &&
5254         cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5255       // Empty arg list, don't push any params.
5256       ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
5257
5258       // In C++, the empty parameter-type-list must be spelled "void"; a
5259       // typedef of void is not permitted.
5260       if (getLangOpts().CPlusPlus &&
5261           Param->getType().getUnqualifiedType() != Context.VoidTy) {
5262         bool IsTypeAlias = false;
5263         if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5264           IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5265         else if (const TemplateSpecializationType *TST =
5266                    Param->getType()->getAs<TemplateSpecializationType>())
5267           IsTypeAlias = TST->isTypeAlias();
5268         Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5269           << IsTypeAlias;
5270       }
5271     } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5272       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5273         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5274         assert(Param->getDeclContext() != NewFD && "Was set before ?");
5275         Param->setDeclContext(NewFD);
5276         Params.push_back(Param);
5277
5278         if (Param->isInvalidDecl())
5279           NewFD->setInvalidDecl();
5280       }
5281     }
5282
5283   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5284     // When we're declaring a function with a typedef, typeof, etc as in the
5285     // following example, we'll need to synthesize (unnamed)
5286     // parameters for use in the declaration.
5287     //
5288     // @code
5289     // typedef void fn(int);
5290     // fn f;
5291     // @endcode
5292
5293     // Synthesize a parameter for each argument type.
5294     for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5295          AE = FT->arg_type_end(); AI != AE; ++AI) {
5296       ParmVarDecl *Param =
5297         BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5298       Param->setScopeInfo(0, Params.size());
5299       Params.push_back(Param);
5300     }
5301   } else {
5302     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5303            "Should not need args for typedef of non-prototype fn");
5304   }
5305
5306   // Finally, we know we have the right number of parameters, install them.
5307   NewFD->setParams(Params);
5308
5309   // Find all anonymous symbols defined during the declaration of this function
5310   // and add to NewFD. This lets us track decls such 'enum Y' in:
5311   //
5312   //   void f(enum Y {AA} x) {}
5313   //
5314   // which would otherwise incorrectly end up in the translation unit scope.
5315   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5316   DeclsInPrototypeScope.clear();
5317
5318   // Process the non-inheritable attributes on this declaration.
5319   ProcessDeclAttributes(S, NewFD, D,
5320                         /*NonInheritable=*/true, /*Inheritable=*/false);
5321
5322   // Functions returning a variably modified type violate C99 6.7.5.2p2
5323   // because all functions have linkage.
5324   if (!NewFD->isInvalidDecl() &&
5325       NewFD->getResultType()->isVariablyModifiedType()) {
5326     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5327     NewFD->setInvalidDecl();
5328   }
5329
5330   if (!getLangOpts().CPlusPlus) {
5331     // Perform semantic checking on the function declaration.
5332     bool isExplicitSpecialization=false;
5333     if (!NewFD->isInvalidDecl()) {
5334       if (NewFD->isMain())
5335         CheckMain(NewFD, D.getDeclSpec());
5336       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5337                                                   isExplicitSpecialization));
5338     }
5339     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5340             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5341            "previous declaration set still overloaded");
5342   } else {
5343     // If the declarator is a template-id, translate the parser's template 
5344     // argument list into our AST format.
5345     bool HasExplicitTemplateArgs = false;
5346     TemplateArgumentListInfo TemplateArgs;
5347     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5348       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5349       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5350       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5351       ASTTemplateArgsPtr TemplateArgsPtr(*this,
5352                                          TemplateId->getTemplateArgs(),
5353                                          TemplateId->NumArgs);
5354       translateTemplateArguments(TemplateArgsPtr,
5355                                  TemplateArgs);
5356       TemplateArgsPtr.release();
5357     
5358       HasExplicitTemplateArgs = true;
5359     
5360       if (NewFD->isInvalidDecl()) {
5361         HasExplicitTemplateArgs = false;
5362       } else if (FunctionTemplate) {
5363         // Function template with explicit template arguments.
5364         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5365           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5366
5367         HasExplicitTemplateArgs = false;
5368       } else if (!isFunctionTemplateSpecialization && 
5369                  !D.getDeclSpec().isFriendSpecified()) {
5370         // We have encountered something that the user meant to be a 
5371         // specialization (because it has explicitly-specified template
5372         // arguments) but that was not introduced with a "template<>" (or had
5373         // too few of them).
5374         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5375           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5376           << FixItHint::CreateInsertion(
5377                                     D.getDeclSpec().getLocStart(),
5378                                         "template<> ");
5379         isFunctionTemplateSpecialization = true;
5380       } else {
5381         // "friend void foo<>(int);" is an implicit specialization decl.
5382         isFunctionTemplateSpecialization = true;
5383       }
5384     } else if (isFriend && isFunctionTemplateSpecialization) {
5385       // This combination is only possible in a recovery case;  the user
5386       // wrote something like:
5387       //   template <> friend void foo(int);
5388       // which we're recovering from as if the user had written:
5389       //   friend void foo<>(int);
5390       // Go ahead and fake up a template id.
5391       HasExplicitTemplateArgs = true;
5392         TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5393       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5394     }
5395
5396     // If it's a friend (and only if it's a friend), it's possible
5397     // that either the specialized function type or the specialized
5398     // template is dependent, and therefore matching will fail.  In
5399     // this case, don't check the specialization yet.
5400     bool InstantiationDependent = false;
5401     if (isFunctionTemplateSpecialization && isFriend &&
5402         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5403          TemplateSpecializationType::anyDependentTemplateArguments(
5404             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5405             InstantiationDependent))) {
5406       assert(HasExplicitTemplateArgs &&
5407              "friend function specialization without template args");
5408       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5409                                                        Previous))
5410         NewFD->setInvalidDecl();
5411     } else if (isFunctionTemplateSpecialization) {
5412       if (CurContext->isDependentContext() && CurContext->isRecord() 
5413           && !isFriend) {
5414         isDependentClassScopeExplicitSpecialization = true;
5415         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 
5416           diag::ext_function_specialization_in_class :
5417           diag::err_function_specialization_in_class)
5418           << NewFD->getDeclName();
5419       } else if (CheckFunctionTemplateSpecialization(NewFD,
5420                                   (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5421                                                      Previous))
5422         NewFD->setInvalidDecl();
5423       
5424       // C++ [dcl.stc]p1:
5425       //   A storage-class-specifier shall not be specified in an explicit
5426       //   specialization (14.7.3)
5427       if (SC != SC_None) {
5428         if (SC != NewFD->getStorageClass())
5429           Diag(NewFD->getLocation(),
5430                diag::err_explicit_specialization_inconsistent_storage_class)
5431             << SC
5432             << FixItHint::CreateRemoval(
5433                                       D.getDeclSpec().getStorageClassSpecLoc());
5434             
5435         else
5436           Diag(NewFD->getLocation(), 
5437                diag::ext_explicit_specialization_storage_class)
5438             << FixItHint::CreateRemoval(
5439                                       D.getDeclSpec().getStorageClassSpecLoc());
5440       }
5441       
5442     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5443       if (CheckMemberSpecialization(NewFD, Previous))
5444           NewFD->setInvalidDecl();
5445     }
5446
5447     // Perform semantic checking on the function declaration.
5448     if (!isDependentClassScopeExplicitSpecialization) {
5449       if (NewFD->isInvalidDecl()) {
5450         // If this is a class member, mark the class invalid immediately.
5451         // This avoids some consistency errors later.
5452         if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5453           methodDecl->getParent()->setInvalidDecl();
5454       } else {
5455         if (NewFD->isMain()) 
5456           CheckMain(NewFD, D.getDeclSpec());
5457         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5458                                                     isExplicitSpecialization));
5459       }
5460     }
5461
5462     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5463             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5464            "previous declaration set still overloaded");
5465
5466     NamedDecl *PrincipalDecl = (FunctionTemplate
5467                                 ? cast<NamedDecl>(FunctionTemplate)
5468                                 : NewFD);
5469
5470     if (isFriend && D.isRedeclaration()) {
5471       AccessSpecifier Access = AS_public;
5472       if (!NewFD->isInvalidDecl())
5473         Access = NewFD->getPreviousDecl()->getAccess();
5474
5475       NewFD->setAccess(Access);
5476       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5477
5478       PrincipalDecl->setObjectOfFriendDecl(true);
5479     }
5480
5481     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5482         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5483       PrincipalDecl->setNonMemberOperator();
5484
5485     // If we have a function template, check the template parameter
5486     // list. This will check and merge default template arguments.
5487     if (FunctionTemplate) {
5488       FunctionTemplateDecl *PrevTemplate = 
5489                                      FunctionTemplate->getPreviousDecl();
5490       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5491                        PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5492                             D.getDeclSpec().isFriendSpecified()
5493                               ? (D.isFunctionDefinition()
5494                                    ? TPC_FriendFunctionTemplateDefinition
5495                                    : TPC_FriendFunctionTemplate)
5496                               : (D.getCXXScopeSpec().isSet() && 
5497                                  DC && DC->isRecord() && 
5498                                  DC->isDependentContext())
5499                                   ? TPC_ClassTemplateMember
5500                                   : TPC_FunctionTemplate);
5501     }
5502
5503     if (NewFD->isInvalidDecl()) {
5504       // Ignore all the rest of this.
5505     } else if (!D.isRedeclaration()) {
5506       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5507                                        AddToScope };
5508       // Fake up an access specifier if it's supposed to be a class member.
5509       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5510         NewFD->setAccess(AS_public);
5511
5512       // Qualified decls generally require a previous declaration.
5513       if (D.getCXXScopeSpec().isSet()) {
5514         // ...with the major exception of templated-scope or
5515         // dependent-scope friend declarations.
5516
5517         // TODO: we currently also suppress this check in dependent
5518         // contexts because (1) the parameter depth will be off when
5519         // matching friend templates and (2) we might actually be
5520         // selecting a friend based on a dependent factor.  But there
5521         // are situations where these conditions don't apply and we
5522         // can actually do this check immediately.
5523         if (isFriend &&
5524             (TemplateParamLists.size() ||
5525              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5526              CurContext->isDependentContext())) {
5527           // ignore these
5528         } else {
5529           // The user tried to provide an out-of-line definition for a
5530           // function that is a member of a class or namespace, but there
5531           // was no such member function declared (C++ [class.mfct]p2,
5532           // C++ [namespace.memdef]p2). For example:
5533           //
5534           // class X {
5535           //   void f() const;
5536           // };
5537           //
5538           // void X::f() { } // ill-formed
5539           //
5540           // Complain about this problem, and attempt to suggest close
5541           // matches (e.g., those that differ only in cv-qualifiers and
5542           // whether the parameter types are references).
5543
5544           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5545                                                                NewFD,
5546                                                                ExtraArgs)) {
5547             AddToScope = ExtraArgs.AddToScope;
5548             return Result;
5549           }
5550         }
5551
5552         // Unqualified local friend declarations are required to resolve
5553         // to something.
5554       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5555         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5556                                                              NewFD,
5557                                                              ExtraArgs)) {
5558           AddToScope = ExtraArgs.AddToScope;
5559           return Result;
5560         }
5561       }
5562
5563     } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
5564                !isFriend && !isFunctionTemplateSpecialization &&
5565                !isExplicitSpecialization) {
5566       // An out-of-line member function declaration must also be a
5567       // definition (C++ [dcl.meaning]p1).
5568       // Note that this is not the case for explicit specializations of
5569       // function templates or member functions of class templates, per
5570       // C++ [temp.expl.spec]p2. We also allow these declarations as an 
5571       // extension for compatibility with old SWIG code which likes to 
5572       // generate them.
5573       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5574         << D.getCXXScopeSpec().getRange();
5575     }
5576   }
5577  
5578  
5579   // Handle attributes. We need to have merged decls when handling attributes
5580   // (for example to check for conflicts, etc).
5581   // FIXME: This needs to happen before we merge declarations. Then,
5582   // let attribute merging cope with attribute conflicts.
5583   ProcessDeclAttributes(S, NewFD, D,
5584                         /*NonInheritable=*/false, /*Inheritable=*/true);
5585
5586   // attributes declared post-definition are currently ignored
5587   // FIXME: This should happen during attribute merging
5588   if (D.isRedeclaration() && Previous.isSingleResult()) {
5589     const FunctionDecl *Def;
5590     FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
5591     if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
5592       Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
5593       Diag(Def->getLocation(), diag::note_previous_definition);
5594     }
5595   }
5596
5597   AddKnownFunctionAttributes(NewFD);
5598
5599   if (NewFD->hasAttr<OverloadableAttr>() && 
5600       !NewFD->getType()->getAs<FunctionProtoType>()) {
5601     Diag(NewFD->getLocation(),
5602          diag::err_attribute_overloadable_no_prototype)
5603       << NewFD;
5604
5605     // Turn this into a variadic function with no parameters.
5606     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
5607     FunctionProtoType::ExtProtoInfo EPI;
5608     EPI.Variadic = true;
5609     EPI.ExtInfo = FT->getExtInfo();
5610
5611     QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
5612     NewFD->setType(R);
5613   }
5614
5615   // If there's a #pragma GCC visibility in scope, and this isn't a class
5616   // member, set the visibility of this function.
5617   if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5618     AddPushedVisibilityAttribute(NewFD);
5619
5620   // If there's a #pragma clang arc_cf_code_audited in scope, consider
5621   // marking the function.
5622   AddCFAuditedAttribute(NewFD);
5623
5624   // If this is a locally-scoped extern C function, update the
5625   // map of such names.
5626   if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
5627       && !NewFD->isInvalidDecl())
5628     RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
5629
5630   // Set this FunctionDecl's range up to the right paren.
5631   NewFD->setRangeEnd(D.getSourceRange().getEnd());
5632
5633   if (getLangOpts().CPlusPlus) {
5634     if (FunctionTemplate) {
5635       if (NewFD->isInvalidDecl())
5636         FunctionTemplate->setInvalidDecl();
5637       return FunctionTemplate;
5638     }
5639   }
5640
5641   MarkUnusedFileScopedDecl(NewFD);
5642
5643   if (getLangOpts().CUDA)
5644     if (IdentifierInfo *II = NewFD->getIdentifier())
5645       if (!NewFD->isInvalidDecl() &&
5646           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5647         if (II->isStr("cudaConfigureCall")) {
5648           if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5649             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5650
5651           Context.setcudaConfigureCallDecl(NewFD);
5652         }
5653       }
5654   
5655   // Here we have an function template explicit specialization at class scope.
5656   // The actually specialization will be postponed to template instatiation
5657   // time via the ClassScopeFunctionSpecializationDecl node.
5658   if (isDependentClassScopeExplicitSpecialization) {
5659     ClassScopeFunctionSpecializationDecl *NewSpec =
5660                          ClassScopeFunctionSpecializationDecl::Create(
5661                                 Context, CurContext,  SourceLocation(), 
5662                                 cast<CXXMethodDecl>(NewFD));
5663     CurContext->addDecl(NewSpec);
5664     AddToScope = false;
5665   }
5666
5667   return NewFD;
5668 }
5669
5670 /// \brief Perform semantic checking of a new function declaration.
5671 ///
5672 /// Performs semantic analysis of the new function declaration
5673 /// NewFD. This routine performs all semantic checking that does not
5674 /// require the actual declarator involved in the declaration, and is
5675 /// used both for the declaration of functions as they are parsed
5676 /// (called via ActOnDeclarator) and for the declaration of functions
5677 /// that have been instantiated via C++ template instantiation (called
5678 /// via InstantiateDecl).
5679 ///
5680 /// \param IsExplicitSpecialiation whether this new function declaration is
5681 /// an explicit specialization of the previous declaration.
5682 ///
5683 /// This sets NewFD->isInvalidDecl() to true if there was an error.
5684 ///
5685 /// Returns true if the function declaration is a redeclaration.
5686 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
5687                                     LookupResult &Previous,
5688                                     bool IsExplicitSpecialization) {
5689   assert(!NewFD->getResultType()->isVariablyModifiedType() 
5690          && "Variably modified return types are not handled here");
5691
5692   // Check for a previous declaration of this name.
5693   if (Previous.empty() && NewFD->isExternC()) {
5694     // Since we did not find anything by this name and we're declaring
5695     // an extern "C" function, look for a non-visible extern "C"
5696     // declaration with the same name.
5697     llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5698       = findLocallyScopedExternalDecl(NewFD->getDeclName());
5699     if (Pos != LocallyScopedExternalDecls.end())
5700       Previous.addDecl(Pos->second);
5701   }
5702
5703   bool Redeclaration = false;
5704
5705   // Merge or overload the declaration with an existing declaration of
5706   // the same name, if appropriate.
5707   if (!Previous.empty()) {
5708     // Determine whether NewFD is an overload of PrevDecl or
5709     // a declaration that requires merging. If it's an overload,
5710     // there's no more work to do here; we'll just add the new
5711     // function to the scope.
5712
5713     NamedDecl *OldDecl = 0;
5714     if (!AllowOverloadingOfFunction(Previous, Context)) {
5715       Redeclaration = true;
5716       OldDecl = Previous.getFoundDecl();
5717     } else {
5718       switch (CheckOverload(S, NewFD, Previous, OldDecl,
5719                             /*NewIsUsingDecl*/ false)) {
5720       case Ovl_Match:
5721         Redeclaration = true;
5722         break;
5723
5724       case Ovl_NonFunction:
5725         Redeclaration = true;
5726         break;
5727
5728       case Ovl_Overload:
5729         Redeclaration = false;
5730         break;
5731       }
5732
5733       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
5734         // If a function name is overloadable in C, then every function
5735         // with that name must be marked "overloadable".
5736         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5737           << Redeclaration << NewFD;
5738         NamedDecl *OverloadedDecl = 0;
5739         if (Redeclaration)
5740           OverloadedDecl = OldDecl;
5741         else if (!Previous.empty())
5742           OverloadedDecl = Previous.getRepresentativeDecl();
5743         if (OverloadedDecl)
5744           Diag(OverloadedDecl->getLocation(),
5745                diag::note_attribute_overloadable_prev_overload);
5746         NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5747                                                         Context));
5748       }
5749     }
5750
5751     if (Redeclaration) {
5752       // NewFD and OldDecl represent declarations that need to be
5753       // merged.
5754       if (MergeFunctionDecl(NewFD, OldDecl, S)) {
5755         NewFD->setInvalidDecl();
5756         return Redeclaration;
5757       }
5758
5759       Previous.clear();
5760       Previous.addDecl(OldDecl);
5761
5762       if (FunctionTemplateDecl *OldTemplateDecl
5763                                     = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
5764         NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
5765         FunctionTemplateDecl *NewTemplateDecl
5766           = NewFD->getDescribedFunctionTemplate();
5767         assert(NewTemplateDecl && "Template/non-template mismatch");
5768         if (CXXMethodDecl *Method 
5769               = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5770           Method->setAccess(OldTemplateDecl->getAccess());
5771           NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5772         }
5773         
5774         // If this is an explicit specialization of a member that is a function
5775         // template, mark it as a member specialization.
5776         if (IsExplicitSpecialization && 
5777             NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5778           NewTemplateDecl->setMemberSpecialization();
5779           assert(OldTemplateDecl->isMemberSpecialization());
5780         }
5781         
5782       } else {
5783         if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5784           NewFD->setAccess(OldDecl->getAccess());
5785         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
5786       }
5787     }
5788   }
5789
5790   // Semantic checking for this function declaration (in isolation).
5791   if (getLangOpts().CPlusPlus) {
5792     // C++-specific checks.
5793     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5794       CheckConstructor(Constructor);
5795     } else if (CXXDestructorDecl *Destructor = 
5796                 dyn_cast<CXXDestructorDecl>(NewFD)) {
5797       CXXRecordDecl *Record = Destructor->getParent();
5798       QualType ClassType = Context.getTypeDeclType(Record);
5799       
5800       // FIXME: Shouldn't we be able to perform this check even when the class
5801       // type is dependent? Both gcc and edg can handle that.
5802       if (!ClassType->isDependentType()) {
5803         DeclarationName Name
5804           = Context.DeclarationNames.getCXXDestructorName(
5805                                         Context.getCanonicalType(ClassType));
5806         if (NewFD->getDeclName() != Name) {
5807           Diag(NewFD->getLocation(), diag::err_destructor_name);
5808           NewFD->setInvalidDecl();
5809           return Redeclaration;
5810         }
5811       }
5812     } else if (CXXConversionDecl *Conversion
5813                = dyn_cast<CXXConversionDecl>(NewFD)) {
5814       ActOnConversionDeclarator(Conversion);
5815     }
5816
5817     // Find any virtual functions that this function overrides.
5818     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5819       if (!Method->isFunctionTemplateSpecialization() && 
5820           !Method->getDescribedFunctionTemplate()) {
5821         if (AddOverriddenMethods(Method->getParent(), Method)) {
5822           // If the function was marked as "static", we have a problem.
5823           if (NewFD->getStorageClass() == SC_Static) {
5824             Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5825               << NewFD->getDeclName();
5826             for (CXXMethodDecl::method_iterator 
5827                       Overridden = Method->begin_overridden_methods(),
5828                    OverriddenEnd = Method->end_overridden_methods();
5829                  Overridden != OverriddenEnd;
5830                  ++Overridden) {
5831               Diag((*Overridden)->getLocation(), 
5832                    diag::note_overridden_virtual_function);
5833             }
5834           }
5835         }
5836       }
5837     }
5838
5839     // Extra checking for C++ overloaded operators (C++ [over.oper]).
5840     if (NewFD->isOverloadedOperator() &&
5841         CheckOverloadedOperatorDeclaration(NewFD)) {
5842       NewFD->setInvalidDecl();
5843       return Redeclaration;
5844     }
5845
5846     // Extra checking for C++0x literal operators (C++0x [over.literal]).
5847     if (NewFD->getLiteralIdentifier() &&
5848         CheckLiteralOperatorDeclaration(NewFD)) {
5849       NewFD->setInvalidDecl();
5850       return Redeclaration;
5851     }
5852
5853     // In C++, check default arguments now that we have merged decls. Unless
5854     // the lexical context is the class, because in this case this is done
5855     // during delayed parsing anyway.
5856     if (!CurContext->isRecord())
5857       CheckCXXDefaultArguments(NewFD);
5858     
5859     // If this function declares a builtin function, check the type of this
5860     // declaration against the expected type for the builtin. 
5861     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5862       ASTContext::GetBuiltinTypeError Error;
5863       QualType T = Context.GetBuiltinType(BuiltinID, Error);
5864       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5865         // The type of this function differs from the type of the builtin,
5866         // so forget about the builtin entirely.
5867         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5868       }
5869     }
5870   
5871     // If this function is declared as being extern "C", then check to see if 
5872     // the function returns a UDT (class, struct, or union type) that is not C
5873     // compatible, and if it does, warn the user.
5874     if (NewFD->isExternC()) {
5875       QualType R = NewFD->getResultType();
5876       if (!R.isPODType(Context) && 
5877           !R->isVoidType())
5878         Diag( NewFD->getLocation(), diag::warn_return_value_udt ) 
5879           << NewFD << R;
5880     }
5881   }
5882   return Redeclaration;
5883 }
5884
5885 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
5886   // C++11 [basic.start.main]p3:  A program that declares main to be inline,
5887   //   static or constexpr is ill-formed.
5888   // C99 6.7.4p4:  In a hosted environment, the inline function specifier
5889   //   shall not appear in a declaration of main.
5890   // static main is not an error under C99, but we should warn about it.
5891   if (FD->getStorageClass() == SC_Static)
5892     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 
5893          ? diag::err_static_main : diag::warn_static_main) 
5894       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5895   if (FD->isInlineSpecified())
5896     Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 
5897       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
5898   if (FD->isConstexpr()) {
5899     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
5900       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
5901     FD->setConstexpr(false);
5902   }
5903
5904   QualType T = FD->getType();
5905   assert(T->isFunctionType() && "function decl is not of function type");
5906   const FunctionType* FT = T->castAs<FunctionType>();
5907
5908   // All the standards say that main() should should return 'int'.
5909   if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
5910     // In C and C++, main magically returns 0 if you fall off the end;
5911     // set the flag which tells us that.
5912     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5913     FD->setHasImplicitReturnZero(true);
5914
5915   // In C with GNU extensions we allow main() to have non-integer return
5916   // type, but we should warn about the extension, and we disable the
5917   // implicit-return-zero rule.
5918   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
5919     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
5920
5921   // Otherwise, this is just a flat-out error.
5922   } else {
5923     Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
5924     FD->setInvalidDecl(true);
5925   }
5926
5927   // Treat protoless main() as nullary.
5928   if (isa<FunctionNoProtoType>(FT)) return;
5929
5930   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5931   unsigned nparams = FTP->getNumArgs();
5932   assert(FD->getNumParams() == nparams);
5933
5934   bool HasExtraParameters = (nparams > 3);
5935
5936   // Darwin passes an undocumented fourth argument of type char**.  If
5937   // other platforms start sprouting these, the logic below will start
5938   // getting shifty.
5939   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
5940     HasExtraParameters = false;
5941
5942   if (HasExtraParameters) {
5943     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5944     FD->setInvalidDecl(true);
5945     nparams = 3;
5946   }
5947
5948   // FIXME: a lot of the following diagnostics would be improved
5949   // if we had some location information about types.
5950
5951   QualType CharPP =
5952     Context.getPointerType(Context.getPointerType(Context.CharTy));
5953   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
5954
5955   for (unsigned i = 0; i < nparams; ++i) {
5956     QualType AT = FTP->getArgType(i);
5957
5958     bool mismatch = true;
5959
5960     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5961       mismatch = false;
5962     else if (Expected[i] == CharPP) {
5963       // As an extension, the following forms are okay:
5964       //   char const **
5965       //   char const * const *
5966       //   char * const *
5967
5968       QualifierCollector qs;
5969       const PointerType* PT;
5970       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5971           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
5972           (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5973         qs.removeConst();
5974         mismatch = !qs.empty();
5975       }
5976     }
5977
5978     if (mismatch) {
5979       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5980       // TODO: suggest replacing given type with expected type
5981       FD->setInvalidDecl(true);
5982     }
5983   }
5984
5985   if (nparams == 1 && !FD->isInvalidDecl()) {
5986     Diag(FD->getLocation(), diag::warn_main_one_arg);
5987   }
5988   
5989   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5990     Diag(FD->getLocation(), diag::err_main_template_decl);
5991     FD->setInvalidDecl();
5992   }
5993 }
5994
5995 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
5996   // FIXME: Need strict checking.  In C89, we need to check for
5997   // any assignment, increment, decrement, function-calls, or
5998   // commas outside of a sizeof.  In C99, it's the same list,
5999   // except that the aforementioned are allowed in unevaluated
6000   // expressions.  Everything else falls under the
6001   // "may accept other forms of constant expressions" exception.
6002   // (We never end up here for C++, so the constant expression
6003   // rules there don't matter.)
6004   if (Init->isConstantInitializer(Context, false))
6005     return false;
6006   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6007     << Init->getSourceRange();
6008   return true;
6009 }
6010
6011 namespace {
6012   // Visits an initialization expression to see if OrigDecl is evaluated in
6013   // its own initialization and throws a warning if it does.
6014   class SelfReferenceChecker
6015       : public EvaluatedExprVisitor<SelfReferenceChecker> {
6016     Sema &S;
6017     Decl *OrigDecl;
6018     bool isRecordType;
6019     bool isPODType;
6020
6021   public:
6022     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6023
6024     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
6025                                                     S(S), OrigDecl(OrigDecl) {
6026       isPODType = false;
6027       isRecordType = false;
6028       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6029         isPODType = VD->getType().isPODType(S.Context);
6030         isRecordType = VD->getType()->isRecordType();
6031       }
6032     }
6033
6034     void VisitExpr(Expr *E) {
6035       if (isa<ObjCMessageExpr>(*E)) return;
6036       if (isRecordType) {
6037         Expr *expr = E;
6038         if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6039           ValueDecl *VD = ME->getMemberDecl();
6040           if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
6041           expr = ME->getBase();
6042         }
6043         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
6044           HandleDeclRefExpr(DRE);
6045           return;
6046         }
6047       }
6048       Inherited::VisitExpr(E);
6049     }
6050
6051     void VisitMemberExpr(MemberExpr *E) {
6052       if (E->getType()->canDecayToPointerType()) return;
6053       ValueDecl *VD = E->getMemberDecl();
6054       if (isa<FieldDecl>(VD) || isa<CXXMethodDecl>(VD))
6055         if (DeclRefExpr *DRE
6056               = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
6057           HandleDeclRefExpr(DRE);
6058           return;
6059         }
6060       Inherited::VisitMemberExpr(E);
6061     }
6062
6063     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
6064       if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
6065           (isRecordType && E->getCastKind() == CK_NoOp)) {
6066         Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
6067         if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
6068           SubExpr = ME->getBase()->IgnoreParenImpCasts();
6069         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6070           HandleDeclRefExpr(DRE);
6071           return;
6072         }
6073       }
6074       Inherited::VisitImplicitCastExpr(E);
6075     }
6076
6077     void VisitUnaryOperator(UnaryOperator *E) {
6078       // For POD record types, addresses of its own members are well-defined.
6079       if (isRecordType && isPODType) return;
6080       Inherited::VisitUnaryOperator(E);
6081     } 
6082     
6083     void HandleDeclRefExpr(DeclRefExpr *DRE) {
6084       Decl* ReferenceDecl = DRE->getDecl(); 
6085       if (OrigDecl != ReferenceDecl) return;
6086       LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
6087                           Sema::NotForRedeclaration);
6088       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
6089                             S.PDiag(diag::warn_uninit_self_reference_in_init)
6090                               << Result.getLookupName()
6091                               << OrigDecl->getLocation()
6092                               << DRE->getSourceRange());
6093     }
6094   };
6095 }
6096
6097 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
6098 void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
6099   SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
6100 }
6101
6102 /// AddInitializerToDecl - Adds the initializer Init to the
6103 /// declaration dcl. If DirectInit is true, this is C++ direct
6104 /// initialization rather than copy initialization.
6105 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6106                                 bool DirectInit, bool TypeMayContainAuto) {
6107   // If there is no declaration, there was an error parsing it.  Just ignore
6108   // the initializer.
6109   if (RealDecl == 0 || RealDecl->isInvalidDecl())
6110     return;
6111
6112   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6113     // With declarators parsed the way they are, the parser cannot
6114     // distinguish between a normal initializer and a pure-specifier.
6115     // Thus this grotesque test.
6116     IntegerLiteral *IL;
6117     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
6118         Context.getCanonicalType(IL->getType()) == Context.IntTy)
6119       CheckPureMethod(Method, Init->getSourceRange());
6120     else {
6121       Diag(Method->getLocation(), diag::err_member_function_initialization)
6122         << Method->getDeclName() << Init->getSourceRange();
6123       Method->setInvalidDecl();
6124     }
6125     return;
6126   }
6127
6128   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6129   if (!VDecl) {
6130     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6131     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6132     RealDecl->setInvalidDecl();
6133     return;
6134   }
6135
6136   // Check for self-references within variable initializers.
6137   // Variables declared within a function/method body are handled
6138   // by a dataflow analysis.
6139   if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal())
6140     CheckSelfReference(RealDecl, Init);
6141
6142   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6143
6144   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6145   if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
6146     Expr *DeduceInit = Init;
6147     // Initializer could be a C++ direct-initializer. Deduction only works if it
6148     // contains exactly one expression.
6149     if (CXXDirectInit) {
6150       if (CXXDirectInit->getNumExprs() == 0) {
6151         // It isn't possible to write this directly, but it is possible to
6152         // end up in this situation with "auto x(some_pack...);"
6153         Diag(CXXDirectInit->getLocStart(),
6154              diag::err_auto_var_init_no_expression)
6155           << VDecl->getDeclName() << VDecl->getType()
6156           << VDecl->getSourceRange();
6157         RealDecl->setInvalidDecl();
6158         return;
6159       } else if (CXXDirectInit->getNumExprs() > 1) {
6160         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
6161              diag::err_auto_var_init_multiple_expressions)
6162           << VDecl->getDeclName() << VDecl->getType()
6163           << VDecl->getSourceRange();
6164         RealDecl->setInvalidDecl();
6165         return;
6166       } else {
6167         DeduceInit = CXXDirectInit->getExpr(0);
6168       }
6169     }
6170     TypeSourceInfo *DeducedType = 0;
6171     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
6172             DAR_Failed)
6173       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
6174     if (!DeducedType) {
6175       RealDecl->setInvalidDecl();
6176       return;
6177     }
6178     VDecl->setTypeSourceInfo(DeducedType);
6179     VDecl->setType(DeducedType->getType());
6180     VDecl->ClearLinkageCache();
6181     
6182     // In ARC, infer lifetime.
6183     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
6184       VDecl->setInvalidDecl();
6185
6186     // If this is a redeclaration, check that the type we just deduced matches
6187     // the previously declared type.
6188     if (VarDecl *Old = VDecl->getPreviousDecl())
6189       MergeVarDeclTypes(VDecl, Old);
6190   }
6191
6192   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6193     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6194     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6195     VDecl->setInvalidDecl();
6196     return;
6197   }
6198
6199   if (!VDecl->getType()->isDependentType()) {
6200     // A definition must end up with a complete type, which means it must be
6201     // complete with the restriction that an array type might be completed by
6202     // the initializer; note that later code assumes this restriction.
6203     QualType BaseDeclType = VDecl->getType();
6204     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6205       BaseDeclType = Array->getElementType();
6206     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6207                             diag::err_typecheck_decl_incomplete_type)) {
6208       RealDecl->setInvalidDecl();
6209       return;
6210     }
6211
6212     // The variable can not have an abstract class type.
6213     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6214                                diag::err_abstract_type_in_decl,
6215                                AbstractVariableType))
6216       VDecl->setInvalidDecl();
6217   }
6218
6219   const VarDecl *Def;
6220   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
6221     Diag(VDecl->getLocation(), diag::err_redefinition)
6222       << VDecl->getDeclName();
6223     Diag(Def->getLocation(), diag::note_previous_definition);
6224     VDecl->setInvalidDecl();
6225     return;
6226   }
6227   
6228   const VarDecl* PrevInit = 0;
6229   if (getLangOpts().CPlusPlus) {
6230     // C++ [class.static.data]p4
6231     //   If a static data member is of const integral or const
6232     //   enumeration type, its declaration in the class definition can
6233     //   specify a constant-initializer which shall be an integral
6234     //   constant expression (5.19). In that case, the member can appear
6235     //   in integral constant expressions. The member shall still be
6236     //   defined in a namespace scope if it is used in the program and the
6237     //   namespace scope definition shall not contain an initializer.
6238     //
6239     // We already performed a redefinition check above, but for static
6240     // data members we also need to check whether there was an in-class
6241     // declaration with an initializer.
6242     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6243       Diag(VDecl->getLocation(), diag::err_redefinition) 
6244         << VDecl->getDeclName();
6245       Diag(PrevInit->getLocation(), diag::note_previous_definition);
6246       return;
6247     }  
6248
6249     if (VDecl->hasLocalStorage())
6250       getCurFunction()->setHasBranchProtectedScope();
6251
6252     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6253       VDecl->setInvalidDecl();
6254       return;
6255     }
6256   }
6257
6258   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6259   // a kernel function cannot be initialized."
6260   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6261     Diag(VDecl->getLocation(), diag::err_local_cant_init);
6262     VDecl->setInvalidDecl();
6263     return;
6264   }
6265
6266   // Get the decls type and save a reference for later, since
6267   // CheckInitializerTypes may change it.
6268   QualType DclT = VDecl->getType(), SavT = DclT;
6269   
6270   // Top-level message sends default to 'id' when we're in a debugger
6271   // and we are assigning it to a variable of 'id' type.
6272   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
6273     if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6274       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6275       if (Result.isInvalid()) {
6276         VDecl->setInvalidDecl();
6277         return;
6278       }
6279       Init = Result.take();
6280     }
6281
6282   // Perform the initialization.
6283   if (!VDecl->isInvalidDecl()) {
6284     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6285     InitializationKind Kind
6286       = DirectInit ?
6287           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6288                                                            Init->getLocStart(),
6289                                                            Init->getLocEnd())
6290                         : InitializationKind::CreateDirectList(
6291                                                           VDecl->getLocation())
6292                    : InitializationKind::CreateCopy(VDecl->getLocation(),
6293                                                     Init->getLocStart());
6294
6295     Expr **Args = &Init;
6296     unsigned NumArgs = 1;
6297     if (CXXDirectInit) {
6298       Args = CXXDirectInit->getExprs();
6299       NumArgs = CXXDirectInit->getNumExprs();
6300     }
6301     InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
6302     ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6303                                               MultiExprArg(*this, Args,NumArgs),
6304                                               &DclT);
6305     if (Result.isInvalid()) {
6306       VDecl->setInvalidDecl();
6307       return;
6308     }
6309
6310     Init = Result.takeAs<Expr>();
6311   }
6312
6313   // If the type changed, it means we had an incomplete type that was
6314   // completed by the initializer. For example:
6315   //   int ary[] = { 1, 3, 5 };
6316   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
6317   if (!VDecl->isInvalidDecl() && (DclT != SavT))
6318     VDecl->setType(DclT);
6319
6320   // Check any implicit conversions within the expression.
6321   CheckImplicitConversions(Init, VDecl->getLocation());
6322
6323   if (!VDecl->isInvalidDecl())
6324     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6325
6326   Init = MaybeCreateExprWithCleanups(Init);
6327   // Attach the initializer to the decl.
6328   VDecl->setInit(Init);
6329
6330   if (VDecl->isLocalVarDecl()) {
6331     // C99 6.7.8p4: All the expressions in an initializer for an object that has
6332     // static storage duration shall be constant expressions or string literals.
6333     // C++ does not have this restriction.
6334     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
6335         VDecl->getStorageClass() == SC_Static)
6336       CheckForConstantInitializer(Init, DclT);
6337   } else if (VDecl->isStaticDataMember() &&
6338              VDecl->getLexicalDeclContext()->isRecord()) {
6339     // This is an in-class initialization for a static data member, e.g.,
6340     //
6341     // struct S {
6342     //   static const int value = 17;
6343     // };
6344
6345     // C++ [class.mem]p4:
6346     //   A member-declarator can contain a constant-initializer only
6347     //   if it declares a static member (9.4) of const integral or
6348     //   const enumeration type, see 9.4.2.
6349     //
6350     // C++11 [class.static.data]p3:
6351     //   If a non-volatile const static data member is of integral or
6352     //   enumeration type, its declaration in the class definition can
6353     //   specify a brace-or-equal-initializer in which every initalizer-clause
6354     //   that is an assignment-expression is a constant expression. A static
6355     //   data member of literal type can be declared in the class definition
6356     //   with the constexpr specifier; if so, its declaration shall specify a
6357     //   brace-or-equal-initializer in which every initializer-clause that is
6358     //   an assignment-expression is a constant expression.
6359
6360     // Do nothing on dependent types.
6361     if (DclT->isDependentType()) {
6362
6363     // Allow any 'static constexpr' members, whether or not they are of literal
6364     // type. We separately check that every constexpr variable is of literal
6365     // type.
6366     } else if (VDecl->isConstexpr()) {
6367
6368     // Require constness.
6369     } else if (!DclT.isConstQualified()) {
6370       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6371         << Init->getSourceRange();
6372       VDecl->setInvalidDecl();
6373
6374     // We allow integer constant expressions in all cases.
6375     } else if (DclT->isIntegralOrEnumerationType()) {
6376       // Check whether the expression is a constant expression.
6377       SourceLocation Loc;
6378       if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
6379         // In C++11, a non-constexpr const static data member with an
6380         // in-class initializer cannot be volatile.
6381         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6382       else if (Init->isValueDependent())
6383         ; // Nothing to check.
6384       else if (Init->isIntegerConstantExpr(Context, &Loc))
6385         ; // Ok, it's an ICE!
6386       else if (Init->isEvaluatable(Context)) {
6387         // If we can constant fold the initializer through heroics, accept it,
6388         // but report this as a use of an extension for -pedantic.
6389         Diag(Loc, diag::ext_in_class_initializer_non_constant)
6390           << Init->getSourceRange();
6391       } else {
6392         // Otherwise, this is some crazy unknown case.  Report the issue at the
6393         // location provided by the isIntegerConstantExpr failed check.
6394         Diag(Loc, diag::err_in_class_initializer_non_constant)
6395           << Init->getSourceRange();
6396         VDecl->setInvalidDecl();
6397       }
6398
6399     // We allow foldable floating-point constants as an extension.
6400     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
6401       Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6402         << DclT << Init->getSourceRange();
6403       if (getLangOpts().CPlusPlus0x)
6404         Diag(VDecl->getLocation(),
6405              diag::note_in_class_initializer_float_type_constexpr)
6406           << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6407
6408       if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
6409         Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6410           << Init->getSourceRange();
6411         VDecl->setInvalidDecl();
6412       }
6413
6414     // Suggest adding 'constexpr' in C++11 for literal types.
6415     } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
6416       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6417         << DclT << Init->getSourceRange()
6418         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6419       VDecl->setConstexpr(true);
6420
6421     } else {
6422       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6423         << DclT << Init->getSourceRange();
6424       VDecl->setInvalidDecl();
6425     }
6426   } else if (VDecl->isFileVarDecl()) {
6427     if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6428         (!getLangOpts().CPlusPlus ||
6429          !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6430       Diag(VDecl->getLocation(), diag::warn_extern_init);
6431
6432     // C99 6.7.8p4. All file scoped initializers need to be constant.
6433     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
6434       CheckForConstantInitializer(Init, DclT);
6435   }
6436
6437   // We will represent direct-initialization similarly to copy-initialization:
6438   //    int x(1);  -as-> int x = 1;
6439   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6440   //
6441   // Clients that want to distinguish between the two forms, can check for
6442   // direct initializer using VarDecl::getInitStyle().
6443   // A major benefit is that clients that don't particularly care about which
6444   // exactly form was it (like the CodeGen) can handle both cases without
6445   // special case code.
6446
6447   // C++ 8.5p11:
6448   // The form of initialization (using parentheses or '=') is generally
6449   // insignificant, but does matter when the entity being initialized has a
6450   // class type.
6451   if (CXXDirectInit) {
6452     assert(DirectInit && "Call-style initializer must be direct init.");
6453     VDecl->setInitStyle(VarDecl::CallInit);
6454   } else if (DirectInit) {
6455     // This must be list-initialization. No other way is direct-initialization.
6456     VDecl->setInitStyle(VarDecl::ListInit);
6457   }
6458
6459   CheckCompleteVariableDeclaration(VDecl);
6460 }
6461
6462 /// ActOnInitializerError - Given that there was an error parsing an
6463 /// initializer for the given declaration, try to return to some form
6464 /// of sanity.
6465 void Sema::ActOnInitializerError(Decl *D) {
6466   // Our main concern here is re-establishing invariants like "a
6467   // variable's type is either dependent or complete".
6468   if (!D || D->isInvalidDecl()) return;
6469
6470   VarDecl *VD = dyn_cast<VarDecl>(D);
6471   if (!VD) return;
6472
6473   // Auto types are meaningless if we can't make sense of the initializer.
6474   if (ParsingInitForAutoVars.count(D)) {
6475     D->setInvalidDecl();
6476     return;
6477   }
6478
6479   QualType Ty = VD->getType();
6480   if (Ty->isDependentType()) return;
6481
6482   // Require a complete type.
6483   if (RequireCompleteType(VD->getLocation(), 
6484                           Context.getBaseElementType(Ty),
6485                           diag::err_typecheck_decl_incomplete_type)) {
6486     VD->setInvalidDecl();
6487     return;
6488   }
6489
6490   // Require an abstract type.
6491   if (RequireNonAbstractType(VD->getLocation(), Ty,
6492                              diag::err_abstract_type_in_decl,
6493                              AbstractVariableType)) {
6494     VD->setInvalidDecl();
6495     return;
6496   }
6497
6498   // Don't bother complaining about constructors or destructors,
6499   // though.
6500 }
6501
6502 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
6503                                   bool TypeMayContainAuto) {
6504   // If there is no declaration, there was an error parsing it. Just ignore it.
6505   if (RealDecl == 0)
6506     return;
6507
6508   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6509     QualType Type = Var->getType();
6510
6511     // C++11 [dcl.spec.auto]p3
6512     if (TypeMayContainAuto && Type->getContainedAutoType()) {
6513       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6514         << Var->getDeclName() << Type;
6515       Var->setInvalidDecl();
6516       return;
6517     }
6518
6519     // C++11 [class.static.data]p3: A static data member can be declared with
6520     // the constexpr specifier; if so, its declaration shall specify
6521     // a brace-or-equal-initializer.
6522     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6523     // the definition of a variable [...] or the declaration of a static data
6524     // member.
6525     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6526       if (Var->isStaticDataMember())
6527         Diag(Var->getLocation(),
6528              diag::err_constexpr_static_mem_var_requires_init)
6529           << Var->getDeclName();
6530       else
6531         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
6532       Var->setInvalidDecl();
6533       return;
6534     }
6535
6536     switch (Var->isThisDeclarationADefinition()) {
6537     case VarDecl::Definition:
6538       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6539         break;
6540
6541       // We have an out-of-line definition of a static data member
6542       // that has an in-class initializer, so we type-check this like
6543       // a declaration. 
6544       //
6545       // Fall through
6546       
6547     case VarDecl::DeclarationOnly:
6548       // It's only a declaration. 
6549
6550       // Block scope. C99 6.7p7: If an identifier for an object is
6551       // declared with no linkage (C99 6.2.2p6), the type for the
6552       // object shall be complete.
6553       if (!Type->isDependentType() && Var->isLocalVarDecl() && 
6554           !Var->getLinkage() && !Var->isInvalidDecl() &&
6555           RequireCompleteType(Var->getLocation(), Type,
6556                               diag::err_typecheck_decl_incomplete_type))
6557         Var->setInvalidDecl();
6558
6559       // Make sure that the type is not abstract.
6560       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
6561           RequireNonAbstractType(Var->getLocation(), Type,
6562                                  diag::err_abstract_type_in_decl,
6563                                  AbstractVariableType))
6564         Var->setInvalidDecl();
6565       return;
6566
6567     case VarDecl::TentativeDefinition:
6568       // File scope. C99 6.9.2p2: A declaration of an identifier for an
6569       // object that has file scope without an initializer, and without a
6570       // storage-class specifier or with the storage-class specifier "static",
6571       // constitutes a tentative definition. Note: A tentative definition with
6572       // external linkage is valid (C99 6.2.2p5).
6573       if (!Var->isInvalidDecl()) {
6574         if (const IncompleteArrayType *ArrayT
6575                                     = Context.getAsIncompleteArrayType(Type)) {
6576           if (RequireCompleteType(Var->getLocation(),
6577                                   ArrayT->getElementType(),
6578                                   diag::err_illegal_decl_array_incomplete_type))
6579             Var->setInvalidDecl();
6580         } else if (Var->getStorageClass() == SC_Static) {
6581           // C99 6.9.2p3: If the declaration of an identifier for an object is
6582           // a tentative definition and has internal linkage (C99 6.2.2p3), the
6583           // declared type shall not be an incomplete type.
6584           // NOTE: code such as the following
6585           //     static struct s;
6586           //     struct s { int a; };
6587           // is accepted by gcc. Hence here we issue a warning instead of
6588           // an error and we do not invalidate the static declaration.
6589           // NOTE: to avoid multiple warnings, only check the first declaration.
6590           if (Var->getPreviousDecl() == 0)
6591             RequireCompleteType(Var->getLocation(), Type,
6592                                 diag::ext_typecheck_decl_incomplete_type);
6593         }
6594       }
6595
6596       // Record the tentative definition; we're done.
6597       if (!Var->isInvalidDecl())
6598         TentativeDefinitions.push_back(Var);
6599       return;
6600     }
6601
6602     // Provide a specific diagnostic for uninitialized variable
6603     // definitions with incomplete array type.
6604     if (Type->isIncompleteArrayType()) {
6605       Diag(Var->getLocation(),
6606            diag::err_typecheck_incomplete_array_needs_initializer);
6607       Var->setInvalidDecl();
6608       return;
6609     }
6610
6611     // Provide a specific diagnostic for uninitialized variable
6612     // definitions with reference type.
6613     if (Type->isReferenceType()) {
6614       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
6615         << Var->getDeclName()
6616         << SourceRange(Var->getLocation(), Var->getLocation());
6617       Var->setInvalidDecl();
6618       return;
6619     }
6620
6621     // Do not attempt to type-check the default initializer for a
6622     // variable with dependent type.
6623     if (Type->isDependentType())
6624       return;
6625
6626     if (Var->isInvalidDecl())
6627       return;
6628
6629     if (RequireCompleteType(Var->getLocation(), 
6630                             Context.getBaseElementType(Type),
6631                             diag::err_typecheck_decl_incomplete_type)) {
6632       Var->setInvalidDecl();
6633       return;
6634     }
6635
6636     // The variable can not have an abstract class type.
6637     if (RequireNonAbstractType(Var->getLocation(), Type,
6638                                diag::err_abstract_type_in_decl,
6639                                AbstractVariableType)) {
6640       Var->setInvalidDecl();
6641       return;
6642     }
6643
6644     // Check for jumps past the implicit initializer.  C++0x
6645     // clarifies that this applies to a "variable with automatic
6646     // storage duration", not a "local variable".
6647     // C++11 [stmt.dcl]p3
6648     //   A program that jumps from a point where a variable with automatic
6649     //   storage duration is not in scope to a point where it is in scope is
6650     //   ill-formed unless the variable has scalar type, class type with a
6651     //   trivial default constructor and a trivial destructor, a cv-qualified
6652     //   version of one of these types, or an array of one of the preceding
6653     //   types and is declared without an initializer.
6654     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
6655       if (const RecordType *Record
6656             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
6657         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
6658         // Mark the function for further checking even if the looser rules of
6659         // C++11 do not require such checks, so that we can diagnose
6660         // incompatibilities with C++98.
6661         if (!CXXRecord->isPOD())
6662           getCurFunction()->setHasBranchProtectedScope();
6663       }
6664     }
6665     
6666     // C++03 [dcl.init]p9:
6667     //   If no initializer is specified for an object, and the
6668     //   object is of (possibly cv-qualified) non-POD class type (or
6669     //   array thereof), the object shall be default-initialized; if
6670     //   the object is of const-qualified type, the underlying class
6671     //   type shall have a user-declared default
6672     //   constructor. Otherwise, if no initializer is specified for
6673     //   a non- static object, the object and its subobjects, if
6674     //   any, have an indeterminate initial value); if the object
6675     //   or any of its subobjects are of const-qualified type, the
6676     //   program is ill-formed.
6677     // C++0x [dcl.init]p11:
6678     //   If no initializer is specified for an object, the object is
6679     //   default-initialized; [...].
6680     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6681     InitializationKind Kind
6682       = InitializationKind::CreateDefault(Var->getLocation());
6683     
6684     InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6685     ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6686                                       MultiExprArg(*this, 0, 0));
6687     if (Init.isInvalid())
6688       Var->setInvalidDecl();
6689     else if (Init.get()) {
6690       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
6691       // This is important for template substitution.
6692       Var->setInitStyle(VarDecl::CallInit);
6693     }
6694
6695     CheckCompleteVariableDeclaration(Var);
6696   }
6697 }
6698
6699 void Sema::ActOnCXXForRangeDecl(Decl *D) {
6700   VarDecl *VD = dyn_cast<VarDecl>(D);
6701   if (!VD) {
6702     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6703     D->setInvalidDecl();
6704     return;
6705   }
6706
6707   VD->setCXXForRangeDecl(true);
6708
6709   // for-range-declaration cannot be given a storage class specifier.
6710   int Error = -1;
6711   switch (VD->getStorageClassAsWritten()) {
6712   case SC_None:
6713     break;
6714   case SC_Extern:
6715     Error = 0;
6716     break;
6717   case SC_Static:
6718     Error = 1;
6719     break;
6720   case SC_PrivateExtern:
6721     Error = 2;
6722     break;
6723   case SC_Auto:
6724     Error = 3;
6725     break;
6726   case SC_Register:
6727     Error = 4;
6728     break;
6729   case SC_OpenCLWorkGroupLocal:
6730     llvm_unreachable("Unexpected storage class");
6731   }
6732   if (VD->isConstexpr())
6733     Error = 5;
6734   if (Error != -1) {
6735     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6736       << VD->getDeclName() << Error;
6737     D->setInvalidDecl();
6738   }
6739 }
6740
6741 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6742   if (var->isInvalidDecl()) return;
6743
6744   // In ARC, don't allow jumps past the implicit initialization of a
6745   // local retaining variable.
6746   if (getLangOpts().ObjCAutoRefCount &&
6747       var->hasLocalStorage()) {
6748     switch (var->getType().getObjCLifetime()) {
6749     case Qualifiers::OCL_None:
6750     case Qualifiers::OCL_ExplicitNone:
6751     case Qualifiers::OCL_Autoreleasing:
6752       break;
6753
6754     case Qualifiers::OCL_Weak:
6755     case Qualifiers::OCL_Strong:
6756       getCurFunction()->setHasBranchProtectedScope();
6757       break;
6758     }
6759   }
6760
6761   // All the following checks are C++ only.
6762   if (!getLangOpts().CPlusPlus) return;
6763
6764   QualType baseType = Context.getBaseElementType(var->getType());
6765   if (baseType->isDependentType()) return;
6766
6767   // __block variables might require us to capture a copy-initializer.
6768   if (var->hasAttr<BlocksAttr>()) {
6769     // It's currently invalid to ever have a __block variable with an
6770     // array type; should we diagnose that here?
6771
6772     // Regardless, we don't want to ignore array nesting when
6773     // constructing this copy.
6774     QualType type = var->getType();
6775
6776     if (type->isStructureOrClassType()) {
6777       SourceLocation poi = var->getLocation();
6778       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
6779       ExprResult result =
6780         PerformCopyInitialization(
6781                         InitializedEntity::InitializeBlock(poi, type, false),
6782                                   poi, Owned(varRef));
6783       if (!result.isInvalid()) {
6784         result = MaybeCreateExprWithCleanups(result);
6785         Expr *init = result.takeAs<Expr>();
6786         Context.setBlockVarCopyInits(var, init);
6787       }
6788     }
6789   }
6790
6791   Expr *Init = var->getInit();
6792   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
6793
6794   if (!var->getDeclContext()->isDependentContext() && Init) {
6795     if (IsGlobal && !var->isConstexpr() &&
6796         getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
6797                                             var->getLocation())
6798           != DiagnosticsEngine::Ignored &&
6799         !Init->isConstantInitializer(Context, baseType->isReferenceType()))
6800       Diag(var->getLocation(), diag::warn_global_constructor)
6801         << Init->getSourceRange();
6802
6803     if (var->isConstexpr()) {
6804       llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
6805       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
6806         SourceLocation DiagLoc = var->getLocation();
6807         // If the note doesn't add any useful information other than a source
6808         // location, fold it into the primary diagnostic.
6809         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6810               diag::note_invalid_subexpr_in_const_expr) {
6811           DiagLoc = Notes[0].first;
6812           Notes.clear();
6813         }
6814         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
6815           << var << Init->getSourceRange();
6816         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6817           Diag(Notes[I].first, Notes[I].second);
6818       }
6819     } else if (var->isUsableInConstantExpressions(Context)) {
6820       // Check whether the initializer of a const variable of integral or
6821       // enumeration type is an ICE now, since we can't tell whether it was
6822       // initialized by a constant expression if we check later.
6823       var->checkInitIsICE();
6824     }
6825   }
6826
6827   // Require the destructor.
6828   if (const RecordType *recordType = baseType->getAs<RecordType>())
6829     FinalizeVarWithDestructor(var, recordType);
6830 }
6831
6832 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
6833 /// any semantic actions necessary after any initializer has been attached.
6834 void
6835 Sema::FinalizeDeclaration(Decl *ThisDecl) {
6836   // Note that we are no longer parsing the initializer for this declaration.
6837   ParsingInitForAutoVars.erase(ThisDecl);
6838 }
6839
6840 Sema::DeclGroupPtrTy
6841 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
6842                               Decl **Group, unsigned NumDecls) {
6843   SmallVector<Decl*, 8> Decls;
6844
6845   if (DS.isTypeSpecOwned())
6846     Decls.push_back(DS.getRepAsDecl());
6847
6848   for (unsigned i = 0; i != NumDecls; ++i)
6849     if (Decl *D = Group[i])
6850       Decls.push_back(D);
6851
6852   return BuildDeclaratorGroup(Decls.data(), Decls.size(),
6853                               DS.getTypeSpecType() == DeclSpec::TST_auto);
6854 }
6855
6856 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
6857 /// group, performing any necessary semantic checking.
6858 Sema::DeclGroupPtrTy
6859 Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
6860                            bool TypeMayContainAuto) {
6861   // C++0x [dcl.spec.auto]p7:
6862   //   If the type deduced for the template parameter U is not the same in each
6863   //   deduction, the program is ill-formed.
6864   // FIXME: When initializer-list support is added, a distinction is needed
6865   // between the deduced type U and the deduced type which 'auto' stands for.
6866   //   auto a = 0, b = { 1, 2, 3 };
6867   // is legal because the deduced type U is 'int' in both cases.
6868   if (TypeMayContainAuto && NumDecls > 1) {
6869     QualType Deduced;
6870     CanQualType DeducedCanon;
6871     VarDecl *DeducedDecl = 0;
6872     for (unsigned i = 0; i != NumDecls; ++i) {
6873       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
6874         AutoType *AT = D->getType()->getContainedAutoType();
6875         // Don't reissue diagnostics when instantiating a template.
6876         if (AT && D->isInvalidDecl())
6877           break;
6878         if (AT && AT->isDeduced()) {
6879           QualType U = AT->getDeducedType();
6880           CanQualType UCanon = Context.getCanonicalType(U);
6881           if (Deduced.isNull()) {
6882             Deduced = U;
6883             DeducedCanon = UCanon;
6884             DeducedDecl = D;
6885           } else if (DeducedCanon != UCanon) {
6886             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
6887                  diag::err_auto_different_deductions)
6888               << Deduced << DeducedDecl->getDeclName()
6889               << U << D->getDeclName()
6890               << DeducedDecl->getInit()->getSourceRange()
6891               << D->getInit()->getSourceRange();
6892             D->setInvalidDecl();
6893             break;
6894           }
6895         }
6896       }
6897     }
6898   }
6899
6900   return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
6901 }
6902
6903
6904 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
6905 /// to introduce parameters into function prototype scope.
6906 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
6907   const DeclSpec &DS = D.getDeclSpec();
6908
6909   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
6910   // C++03 [dcl.stc]p2 also permits 'auto'.
6911   VarDecl::StorageClass StorageClass = SC_None;
6912   VarDecl::StorageClass StorageClassAsWritten = SC_None;
6913   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
6914     StorageClass = SC_Register;
6915     StorageClassAsWritten = SC_Register;
6916   } else if (getLangOpts().CPlusPlus &&
6917              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
6918     StorageClass = SC_Auto;
6919     StorageClassAsWritten = SC_Auto;
6920   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
6921     Diag(DS.getStorageClassSpecLoc(),
6922          diag::err_invalid_storage_class_in_func_decl);
6923     D.getMutableDeclSpec().ClearStorageClassSpecs();
6924   }
6925
6926   if (D.getDeclSpec().isThreadSpecified())
6927     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
6928   if (D.getDeclSpec().isConstexprSpecified())
6929     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6930       << 0;
6931
6932   DiagnoseFunctionSpecifiers(D);
6933
6934   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6935   QualType parmDeclType = TInfo->getType();
6936
6937   if (getLangOpts().CPlusPlus) {
6938     // Check that there are no default arguments inside the type of this
6939     // parameter.
6940     CheckExtraCXXDefaultArguments(D);
6941     
6942     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6943     if (D.getCXXScopeSpec().isSet()) {
6944       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6945         << D.getCXXScopeSpec().getRange();
6946       D.getCXXScopeSpec().clear();
6947     }
6948   }
6949
6950   // Ensure we have a valid name
6951   IdentifierInfo *II = 0;
6952   if (D.hasName()) {
6953     II = D.getIdentifier();
6954     if (!II) {
6955       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6956         << GetNameForDeclarator(D).getName().getAsString();
6957       D.setInvalidType(true);
6958     }
6959   }
6960
6961   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
6962   if (II) {
6963     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6964                    ForRedeclaration);
6965     LookupName(R, S);
6966     if (R.isSingleResult()) {
6967       NamedDecl *PrevDecl = R.getFoundDecl();
6968       if (PrevDecl->isTemplateParameter()) {
6969         // Maybe we will complain about the shadowed template parameter.
6970         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6971         // Just pretend that we didn't see the previous declaration.
6972         PrevDecl = 0;
6973       } else if (S->isDeclScope(PrevDecl)) {
6974         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
6975         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6976
6977         // Recover by removing the name
6978         II = 0;
6979         D.SetIdentifier(0, D.getIdentifierLoc());
6980         D.setInvalidType(true);
6981       }
6982     }
6983   }
6984
6985   // Temporarily put parameter variables in the translation unit, not
6986   // the enclosing context.  This prevents them from accidentally
6987   // looking like class members in C++.
6988   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
6989                                     D.getLocStart(),
6990                                     D.getIdentifierLoc(), II,
6991                                     parmDeclType, TInfo,
6992                                     StorageClass, StorageClassAsWritten);
6993
6994   if (D.isInvalidType())
6995     New->setInvalidDecl();
6996
6997   assert(S->isFunctionPrototypeScope());
6998   assert(S->getFunctionPrototypeDepth() >= 1);
6999   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7000                     S->getNextFunctionPrototypeIndex());
7001   
7002   // Add the parameter declaration into this scope.
7003   S->AddDecl(New);
7004   if (II)
7005     IdResolver.AddDecl(New);
7006
7007   ProcessDeclAttributes(S, New, D);
7008
7009   if (D.getDeclSpec().isModulePrivateSpecified())
7010     Diag(New->getLocation(), diag::err_module_private_local)
7011       << 1 << New->getDeclName()
7012       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7013       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7014
7015   if (New->hasAttr<BlocksAttr>()) {
7016     Diag(New->getLocation(), diag::err_block_on_nonlocal);
7017   }
7018   return New;
7019 }
7020
7021 /// \brief Synthesizes a variable for a parameter arising from a
7022 /// typedef.
7023 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7024                                               SourceLocation Loc,
7025                                               QualType T) {
7026   /* FIXME: setting StartLoc == Loc.
7027      Would it be worth to modify callers so as to provide proper source
7028      location for the unnamed parameters, embedding the parameter's type? */
7029   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
7030                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
7031                                            SC_None, SC_None, 0);
7032   Param->setImplicit();
7033   return Param;
7034 }
7035
7036 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7037                                     ParmVarDecl * const *ParamEnd) {
7038   // Don't diagnose unused-parameter errors in template instantiations; we
7039   // will already have done so in the template itself.
7040   if (!ActiveTemplateInstantiations.empty())
7041     return;
7042
7043   for (; Param != ParamEnd; ++Param) {
7044     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
7045         !(*Param)->hasAttr<UnusedAttr>()) {
7046       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7047         << (*Param)->getDeclName();
7048     }
7049   }
7050 }
7051
7052 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7053                                                   ParmVarDecl * const *ParamEnd,
7054                                                   QualType ReturnTy,
7055                                                   NamedDecl *D) {
7056   if (LangOpts.NumLargeByValueCopy == 0) // No check.
7057     return;
7058
7059   // Warn if the return value is pass-by-value and larger than the specified
7060   // threshold.
7061   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
7062     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
7063     if (Size > LangOpts.NumLargeByValueCopy)
7064       Diag(D->getLocation(), diag::warn_return_value_size)
7065           << D->getDeclName() << Size;
7066   }
7067
7068   // Warn if any parameter is pass-by-value and larger than the specified
7069   // threshold.
7070   for (; Param != ParamEnd; ++Param) {
7071     QualType T = (*Param)->getType();
7072     if (T->isDependentType() || !T.isPODType(Context))
7073       continue;
7074     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
7075     if (Size > LangOpts.NumLargeByValueCopy)
7076       Diag((*Param)->getLocation(), diag::warn_parameter_size)
7077           << (*Param)->getDeclName() << Size;
7078   }
7079 }
7080
7081 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7082                                   SourceLocation NameLoc, IdentifierInfo *Name,
7083                                   QualType T, TypeSourceInfo *TSInfo,
7084                                   VarDecl::StorageClass StorageClass,
7085                                   VarDecl::StorageClass StorageClassAsWritten) {
7086   // In ARC, infer a lifetime qualifier for appropriate parameter types.
7087   if (getLangOpts().ObjCAutoRefCount &&
7088       T.getObjCLifetime() == Qualifiers::OCL_None &&
7089       T->isObjCLifetimeType()) {
7090
7091     Qualifiers::ObjCLifetime lifetime;
7092
7093     // Special cases for arrays:
7094     //   - if it's const, use __unsafe_unretained
7095     //   - otherwise, it's an error
7096     if (T->isArrayType()) {
7097       if (!T.isConstQualified()) {
7098         DelayedDiagnostics.add(
7099             sema::DelayedDiagnostic::makeForbiddenType(
7100             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
7101       }
7102       lifetime = Qualifiers::OCL_ExplicitNone;
7103     } else {
7104       lifetime = T->getObjCARCImplicitLifetime();
7105     }
7106     T = Context.getLifetimeQualifiedType(T, lifetime);
7107   }
7108
7109   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
7110                                          Context.getAdjustedParameterType(T), 
7111                                          TSInfo,
7112                                          StorageClass, StorageClassAsWritten,
7113                                          0);
7114
7115   // Parameters can not be abstract class types.
7116   // For record types, this is done by the AbstractClassUsageDiagnoser once
7117   // the class has been completely parsed.
7118   if (!CurContext->isRecord() &&
7119       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7120                              AbstractParamType))
7121     New->setInvalidDecl();
7122
7123   // Parameter declarators cannot be interface types. All ObjC objects are
7124   // passed by reference.
7125   if (T->isObjCObjectType()) {
7126     Diag(NameLoc,
7127          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7128       << FixItHint::CreateInsertion(NameLoc, "*");
7129     T = Context.getObjCObjectPointerType(T);
7130     New->setType(T);
7131   }
7132
7133   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 
7134   // duration shall not be qualified by an address-space qualifier."
7135   // Since all parameters have automatic store duration, they can not have
7136   // an address space.
7137   if (T.getAddressSpace() != 0) {
7138     Diag(NameLoc, diag::err_arg_with_address_space);
7139     New->setInvalidDecl();
7140   }   
7141
7142   return New;
7143 }
7144
7145 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7146                                            SourceLocation LocAfterDecls) {
7147   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7148
7149   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7150   // for a K&R function.
7151   if (!FTI.hasPrototype) {
7152     for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7153       --i;
7154       if (FTI.ArgInfo[i].Param == 0) {
7155         SmallString<256> Code;
7156         llvm::raw_svector_ostream(Code) << "  int "
7157                                         << FTI.ArgInfo[i].Ident->getName()
7158                                         << ";\n";
7159         Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
7160           << FTI.ArgInfo[i].Ident
7161           << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
7162
7163         // Implicitly declare the argument as type 'int' for lack of a better
7164         // type.
7165         AttributeFactory attrs;
7166         DeclSpec DS(attrs);
7167         const char* PrevSpec; // unused
7168         unsigned DiagID; // unused
7169         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
7170                            PrevSpec, DiagID);
7171         Declarator ParamD(DS, Declarator::KNRTypeListContext);
7172         ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
7173         FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
7174       }
7175     }
7176   }
7177 }
7178
7179 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
7180                                          Declarator &D) {
7181   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
7182   assert(D.isFunctionDeclarator() && "Not a function declarator!");
7183   Scope *ParentScope = FnBodyScope->getParent();
7184
7185   D.setFunctionDefinitionKind(FDK_Definition);
7186   Decl *DP = HandleDeclarator(ParentScope, D,
7187                               MultiTemplateParamsArg(*this));
7188   return ActOnStartOfFunctionDef(FnBodyScope, DP);
7189 }
7190
7191 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7192   // Don't warn about invalid declarations.
7193   if (FD->isInvalidDecl())
7194     return false;
7195
7196   // Or declarations that aren't global.
7197   if (!FD->isGlobal())
7198     return false;
7199
7200   // Don't warn about C++ member functions.
7201   if (isa<CXXMethodDecl>(FD))
7202     return false;
7203
7204   // Don't warn about 'main'.
7205   if (FD->isMain())
7206     return false;
7207
7208   // Don't warn about inline functions.
7209   if (FD->isInlined())
7210     return false;
7211
7212   // Don't warn about function templates.
7213   if (FD->getDescribedFunctionTemplate())
7214     return false;
7215
7216   // Don't warn about function template specializations.
7217   if (FD->isFunctionTemplateSpecialization())
7218     return false;
7219
7220   bool MissingPrototype = true;
7221   for (const FunctionDecl *Prev = FD->getPreviousDecl();
7222        Prev; Prev = Prev->getPreviousDecl()) {
7223     // Ignore any declarations that occur in function or method
7224     // scope, because they aren't visible from the header.
7225     if (Prev->getDeclContext()->isFunctionOrMethod())
7226       continue;
7227       
7228     MissingPrototype = !Prev->getType()->isFunctionProtoType();
7229     break;
7230   }
7231     
7232   return MissingPrototype;
7233 }
7234
7235 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7236   // Don't complain if we're in GNU89 mode and the previous definition
7237   // was an extern inline function.
7238   const FunctionDecl *Definition;
7239   if (FD->isDefined(Definition) &&
7240       !canRedefineFunction(Definition, getLangOpts())) {
7241     if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
7242         Definition->getStorageClass() == SC_Extern)
7243       Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
7244         << FD->getDeclName() << getLangOpts().CPlusPlus;
7245     else
7246       Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7247     Diag(Definition->getLocation(), diag::note_previous_definition);
7248   }
7249 }
7250
7251 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
7252   // Clear the last template instantiation error context.
7253   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7254   
7255   if (!D)
7256     return D;
7257   FunctionDecl *FD = 0;
7258
7259   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
7260     FD = FunTmpl->getTemplatedDecl();
7261   else
7262     FD = cast<FunctionDecl>(D);
7263
7264   // Enter a new function scope
7265   PushFunctionScope();
7266
7267   // See if this is a redefinition.
7268   if (!FD->isLateTemplateParsed())
7269     CheckForFunctionRedefinition(FD);
7270
7271   // Builtin functions cannot be defined.
7272   if (unsigned BuiltinID = FD->getBuiltinID()) {
7273     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
7274       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
7275       FD->setInvalidDecl();
7276     }
7277   }
7278
7279   // The return type of a function definition must be complete
7280   // (C99 6.9.1p3, C++ [dcl.fct]p6).
7281   QualType ResultType = FD->getResultType();
7282   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
7283       !FD->isInvalidDecl() &&
7284       RequireCompleteType(FD->getLocation(), ResultType,
7285                           diag::err_func_def_incomplete_result))
7286     FD->setInvalidDecl();
7287
7288   // GNU warning -Wmissing-prototypes:
7289   //   Warn if a global function is defined without a previous
7290   //   prototype declaration. This warning is issued even if the
7291   //   definition itself provides a prototype. The aim is to detect
7292   //   global functions that fail to be declared in header files.
7293   if (ShouldWarnAboutMissingPrototype(FD))
7294     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
7295
7296   if (FnBodyScope)
7297     PushDeclContext(FnBodyScope, FD);
7298
7299   // Check the validity of our function parameters
7300   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7301                            /*CheckParameterNames=*/true);
7302
7303   // Introduce our parameters into the function scope
7304   for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7305     ParmVarDecl *Param = FD->getParamDecl(p);
7306     Param->setOwningFunction(FD);
7307
7308     // If this has an identifier, add it to the scope stack.
7309     if (Param->getIdentifier() && FnBodyScope) {
7310       CheckShadow(FnBodyScope, Param);
7311
7312       PushOnScopeChains(Param, FnBodyScope);
7313     }
7314   }
7315
7316   // If we had any tags defined in the function prototype,
7317   // introduce them into the function scope.
7318   if (FnBodyScope) {
7319     for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7320            E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7321       NamedDecl *D = *I;
7322
7323       // Some of these decls (like enums) may have been pinned to the translation unit
7324       // for lack of a real context earlier. If so, remove from the translation unit
7325       // and reattach to the current context.
7326       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7327         // Is the decl actually in the context?
7328         for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7329                DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7330           if (*DI == D) {  
7331             Context.getTranslationUnitDecl()->removeDecl(D);
7332             break;
7333           }
7334         }
7335         // Either way, reassign the lexical decl context to our FunctionDecl.
7336         D->setLexicalDeclContext(CurContext);
7337       }
7338
7339       // If the decl has a non-null name, make accessible in the current scope.
7340       if (!D->getName().empty())
7341         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7342
7343       // Similarly, dive into enums and fish their constants out, making them
7344       // accessible in this scope.
7345       if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7346         for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7347                EE = ED->enumerator_end(); EI != EE; ++EI)
7348           PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
7349       }
7350     }
7351   }
7352
7353   // Checking attributes of current function definition
7354   // dllimport attribute.
7355   DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7356   if (DA && (!FD->getAttr<DLLExportAttr>())) {
7357     // dllimport attribute cannot be directly applied to definition.
7358     // Microsoft accepts dllimport for functions defined within class scope. 
7359     if (!DA->isInherited() &&
7360         !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
7361       Diag(FD->getLocation(),
7362            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7363         << "dllimport";
7364       FD->setInvalidDecl();
7365       return FD;
7366     }
7367
7368     // Visual C++ appears to not think this is an issue, so only issue
7369     // a warning when Microsoft extensions are disabled.
7370     if (!LangOpts.MicrosoftExt) {
7371       // If a symbol previously declared dllimport is later defined, the
7372       // attribute is ignored in subsequent references, and a warning is
7373       // emitted.
7374       Diag(FD->getLocation(),
7375            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7376         << FD->getName() << "dllimport";
7377     }
7378   }
7379   return FD;
7380 }
7381
7382 /// \brief Given the set of return statements within a function body,
7383 /// compute the variables that are subject to the named return value 
7384 /// optimization.
7385 ///
7386 /// Each of the variables that is subject to the named return value 
7387 /// optimization will be marked as NRVO variables in the AST, and any
7388 /// return statement that has a marked NRVO variable as its NRVO candidate can
7389 /// use the named return value optimization.
7390 ///
7391 /// This function applies a very simplistic algorithm for NRVO: if every return
7392 /// statement in the function has the same NRVO candidate, that candidate is
7393 /// the NRVO variable.
7394 ///
7395 /// FIXME: Employ a smarter algorithm that accounts for multiple return 
7396 /// statements and the lifetimes of the NRVO candidates. We should be able to
7397 /// find a maximal set of NRVO variables.
7398 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
7399   ReturnStmt **Returns = Scope->Returns.data();
7400
7401   const VarDecl *NRVOCandidate = 0;
7402   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
7403     if (!Returns[I]->getNRVOCandidate())
7404       return;
7405     
7406     if (!NRVOCandidate)
7407       NRVOCandidate = Returns[I]->getNRVOCandidate();
7408     else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7409       return;
7410   }
7411   
7412   if (NRVOCandidate)
7413     const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7414 }
7415
7416 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
7417   return ActOnFinishFunctionBody(D, move(BodyArg), false);
7418 }
7419
7420 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7421                                     bool IsInstantiation) {
7422   FunctionDecl *FD = 0;
7423   FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7424   if (FunTmpl)
7425     FD = FunTmpl->getTemplatedDecl();
7426   else
7427     FD = dyn_cast_or_null<FunctionDecl>(dcl);
7428
7429   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
7430   sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
7431
7432   if (FD) {
7433     FD->setBody(Body);
7434
7435     // If the function implicitly returns zero (like 'main') or is naked,
7436     // don't complain about missing return statements.
7437     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
7438       WP.disableCheckFallThrough();
7439
7440     // MSVC permits the use of pure specifier (=0) on function definition,
7441     // defined at class scope, warn about this non standard construct.
7442     if (getLangOpts().MicrosoftExt && FD->isPure())
7443       Diag(FD->getLocation(), diag::warn_pure_function_definition);
7444
7445     if (!FD->isInvalidDecl()) {
7446       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
7447       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
7448                                              FD->getResultType(), FD);
7449       
7450       // If this is a constructor, we need a vtable.
7451       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
7452         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
7453       
7454       computeNRVO(Body, getCurFunction());
7455     }
7456     
7457     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
7458            "Function parsing confused");
7459   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
7460     assert(MD == getCurMethodDecl() && "Method parsing confused");
7461     MD->setBody(Body);
7462     if (Body)
7463       MD->setEndLoc(Body->getLocEnd());
7464     if (!MD->isInvalidDecl()) {
7465       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
7466       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
7467                                              MD->getResultType(), MD);
7468       
7469       if (Body)
7470         computeNRVO(Body, getCurFunction());
7471     }
7472     if (ObjCShouldCallSuperDealloc) {
7473       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
7474       ObjCShouldCallSuperDealloc = false;
7475     }
7476     if (ObjCShouldCallSuperFinalize) {
7477       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
7478       ObjCShouldCallSuperFinalize = false;
7479     }
7480   } else {
7481     return 0;
7482   }
7483
7484   assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
7485          "ObjC methods, which should have been handled in the block above.");
7486   assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
7487          "ObjC methods, which should have been handled in the block above.");
7488
7489   // Verify and clean out per-function state.
7490   if (Body) {
7491     // C++ constructors that have function-try-blocks can't have return
7492     // statements in the handlers of that block. (C++ [except.handle]p14)
7493     // Verify this.
7494     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
7495       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
7496     
7497     // Verify that gotos and switch cases don't jump into scopes illegally.
7498     if (getCurFunction()->NeedsScopeChecking() &&
7499         !dcl->isInvalidDecl() &&
7500         !hasAnyUnrecoverableErrorsInThisFunction())
7501       DiagnoseInvalidJumps(Body);
7502
7503     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
7504       if (!Destructor->getParent()->isDependentType())
7505         CheckDestructor(Destructor);
7506
7507       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7508                                              Destructor->getParent());
7509     }
7510     
7511     // If any errors have occurred, clear out any temporaries that may have
7512     // been leftover. This ensures that these temporaries won't be picked up for
7513     // deletion in some later function.
7514     if (PP.getDiagnostics().hasErrorOccurred() ||
7515         PP.getDiagnostics().getSuppressAllDiagnostics()) {
7516       DiscardCleanupsInEvaluationContext();
7517     } else if (!isa<FunctionTemplateDecl>(dcl)) {
7518       // Since the body is valid, issue any analysis-based warnings that are
7519       // enabled.
7520       ActivePolicy = &WP;
7521     }
7522
7523     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
7524         (!CheckConstexprFunctionDecl(FD) ||
7525          !CheckConstexprFunctionBody(FD, Body)))
7526       FD->setInvalidDecl();
7527
7528     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
7529     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
7530     assert(MaybeODRUseExprs.empty() &&
7531            "Leftover expressions for odr-use checking");
7532   }
7533   
7534   if (!IsInstantiation)
7535     PopDeclContext();
7536
7537   PopFunctionScopeInfo(ActivePolicy, dcl);
7538   
7539   // If any errors have occurred, clear out any temporaries that may have
7540   // been leftover. This ensures that these temporaries won't be picked up for
7541   // deletion in some later function.
7542   if (getDiagnostics().hasErrorOccurred()) {
7543     DiscardCleanupsInEvaluationContext();
7544   }
7545
7546   return dcl;
7547 }
7548
7549
7550 /// When we finish delayed parsing of an attribute, we must attach it to the
7551 /// relevant Decl.
7552 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
7553                                        ParsedAttributes &Attrs) {
7554   // Always attach attributes to the underlying decl.
7555   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7556     D = TD->getTemplatedDecl();
7557   ProcessDeclAttributeList(S, D, Attrs.getList());
7558 }
7559
7560
7561 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
7562 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
7563 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
7564                                           IdentifierInfo &II, Scope *S) {
7565   // Before we produce a declaration for an implicitly defined
7566   // function, see whether there was a locally-scoped declaration of
7567   // this name as a function or variable. If so, use that
7568   // (non-visible) declaration, and complain about it.
7569   llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
7570     = findLocallyScopedExternalDecl(&II);
7571   if (Pos != LocallyScopedExternalDecls.end()) {
7572     Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
7573     Diag(Pos->second->getLocation(), diag::note_previous_declaration);
7574     return Pos->second;
7575   }
7576
7577   // Extension in C99.  Legal in C90, but warn about it.
7578   unsigned diag_id;
7579   if (II.getName().startswith("__builtin_"))
7580     diag_id = diag::warn_builtin_unknown;
7581   else if (getLangOpts().C99)
7582     diag_id = diag::ext_implicit_function_decl;
7583   else
7584     diag_id = diag::warn_implicit_function_decl;
7585   Diag(Loc, diag_id) << &II;
7586
7587   // Because typo correction is expensive, only do it if the implicit
7588   // function declaration is going to be treated as an error.
7589   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
7590     TypoCorrection Corrected;
7591     DeclFilterCCC<FunctionDecl> Validator;
7592     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
7593                                       LookupOrdinaryName, S, 0, Validator))) {
7594       std::string CorrectedStr = Corrected.getAsString(getLangOpts());
7595       std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
7596       FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
7597
7598       Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
7599           << FixItHint::CreateReplacement(Loc, CorrectedStr);
7600
7601       if (Func->getLocation().isValid()
7602           && !II.getName().startswith("__builtin_"))
7603         Diag(Func->getLocation(), diag::note_previous_decl)
7604             << CorrectedQuotedStr;
7605     }
7606   }
7607
7608   // Set a Declarator for the implicit definition: int foo();
7609   const char *Dummy;
7610   AttributeFactory attrFactory;
7611   DeclSpec DS(attrFactory);
7612   unsigned DiagID;
7613   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
7614   (void)Error; // Silence warning.
7615   assert(!Error && "Error setting up implicit decl!");
7616   Declarator D(DS, Declarator::BlockContext);
7617   D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
7618                                              0, 0, true, SourceLocation(),
7619                                              SourceLocation(), SourceLocation(),
7620                                              SourceLocation(),
7621                                              EST_None, SourceLocation(),
7622                                              0, 0, 0, 0, Loc, Loc, D),
7623                 DS.getAttributes(),
7624                 SourceLocation());
7625   D.SetIdentifier(&II, Loc);
7626
7627   // Insert this function into translation-unit scope.
7628
7629   DeclContext *PrevDC = CurContext;
7630   CurContext = Context.getTranslationUnitDecl();
7631
7632   FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
7633   FD->setImplicit();
7634
7635   CurContext = PrevDC;
7636
7637   AddKnownFunctionAttributes(FD);
7638
7639   return FD;
7640 }
7641
7642 /// \brief Adds any function attributes that we know a priori based on
7643 /// the declaration of this function.
7644 ///
7645 /// These attributes can apply both to implicitly-declared builtins
7646 /// (like __builtin___printf_chk) or to library-declared functions
7647 /// like NSLog or printf.
7648 ///
7649 /// We need to check for duplicate attributes both here and where user-written
7650 /// attributes are applied to declarations.
7651 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
7652   if (FD->isInvalidDecl())
7653     return;
7654
7655   // If this is a built-in function, map its builtin attributes to
7656   // actual attributes.
7657   if (unsigned BuiltinID = FD->getBuiltinID()) {
7658     // Handle printf-formatting attributes.
7659     unsigned FormatIdx;
7660     bool HasVAListArg;
7661     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
7662       if (!FD->getAttr<FormatAttr>()) {
7663         const char *fmt = "printf";
7664         unsigned int NumParams = FD->getNumParams();
7665         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
7666             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
7667           fmt = "NSString";
7668         FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7669                                                fmt, FormatIdx+1,
7670                                                HasVAListArg ? 0 : FormatIdx+2));
7671       }
7672     }
7673     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
7674                                              HasVAListArg)) {
7675      if (!FD->getAttr<FormatAttr>())
7676        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7677                                               "scanf", FormatIdx+1,
7678                                               HasVAListArg ? 0 : FormatIdx+2));
7679     }
7680
7681     // Mark const if we don't care about errno and that is the only
7682     // thing preventing the function from being const. This allows
7683     // IRgen to use LLVM intrinsics for such functions.
7684     if (!getLangOpts().MathErrno &&
7685         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
7686       if (!FD->getAttr<ConstAttr>())
7687         FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7688     }
7689
7690     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
7691         !FD->getAttr<ReturnsTwiceAttr>())
7692       FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
7693     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
7694       FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
7695     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
7696       FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7697   }
7698
7699   IdentifierInfo *Name = FD->getIdentifier();
7700   if (!Name)
7701     return;
7702   if ((!getLangOpts().CPlusPlus &&
7703        FD->getDeclContext()->isTranslationUnit()) ||
7704       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
7705        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
7706        LinkageSpecDecl::lang_c)) {
7707     // Okay: this could be a libc/libm/Objective-C function we know
7708     // about.
7709   } else
7710     return;
7711
7712   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
7713     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
7714     // target-specific builtins, perhaps?
7715     if (!FD->getAttr<FormatAttr>())
7716       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7717                                              "printf", 2,
7718                                              Name->isStr("vasprintf") ? 0 : 3));
7719   }
7720 }
7721
7722 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
7723                                     TypeSourceInfo *TInfo) {
7724   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
7725   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
7726
7727   if (!TInfo) {
7728     assert(D.isInvalidType() && "no declarator info for valid type");
7729     TInfo = Context.getTrivialTypeSourceInfo(T);
7730   }
7731
7732   // Scope manipulation handled by caller.
7733   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
7734                                            D.getLocStart(),
7735                                            D.getIdentifierLoc(),
7736                                            D.getIdentifier(),
7737                                            TInfo);
7738
7739   // Bail out immediately if we have an invalid declaration.
7740   if (D.isInvalidType()) {
7741     NewTD->setInvalidDecl();
7742     return NewTD;
7743   }
7744
7745   if (D.getDeclSpec().isModulePrivateSpecified()) {
7746     if (CurContext->isFunctionOrMethod())
7747       Diag(NewTD->getLocation(), diag::err_module_private_local)
7748         << 2 << NewTD->getDeclName()
7749         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7750         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7751     else
7752       NewTD->setModulePrivate();
7753   }
7754   
7755   // C++ [dcl.typedef]p8:
7756   //   If the typedef declaration defines an unnamed class (or
7757   //   enum), the first typedef-name declared by the declaration
7758   //   to be that class type (or enum type) is used to denote the
7759   //   class type (or enum type) for linkage purposes only.
7760   // We need to check whether the type was declared in the declaration.
7761   switch (D.getDeclSpec().getTypeSpecType()) {
7762   case TST_enum:
7763   case TST_struct:
7764   case TST_union:
7765   case TST_class: {
7766     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
7767
7768     // Do nothing if the tag is not anonymous or already has an
7769     // associated typedef (from an earlier typedef in this decl group).
7770     if (tagFromDeclSpec->getIdentifier()) break;
7771     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
7772
7773     // A well-formed anonymous tag must always be a TUK_Definition.
7774     assert(tagFromDeclSpec->isThisDeclarationADefinition());
7775
7776     // The type must match the tag exactly;  no qualifiers allowed.
7777     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
7778       break;
7779
7780     // Otherwise, set this is the anon-decl typedef for the tag.
7781     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
7782     break;
7783   }
7784     
7785   default:
7786     break;
7787   }
7788
7789   return NewTD;
7790 }
7791
7792
7793 /// \brief Check that this is a valid underlying type for an enum declaration.
7794 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
7795   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
7796   QualType T = TI->getType();
7797
7798   if (T->isDependentType() || T->isIntegralType(Context))
7799     return false;
7800
7801   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
7802   return true;
7803 }
7804
7805 /// Check whether this is a valid redeclaration of a previous enumeration.
7806 /// \return true if the redeclaration was invalid.
7807 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
7808                                   QualType EnumUnderlyingTy,
7809                                   const EnumDecl *Prev) {
7810   bool IsFixed = !EnumUnderlyingTy.isNull();
7811
7812   if (IsScoped != Prev->isScoped()) {
7813     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
7814       << Prev->isScoped();
7815     Diag(Prev->getLocation(), diag::note_previous_use);
7816     return true;
7817   }
7818
7819   if (IsFixed && Prev->isFixed()) {
7820     if (!EnumUnderlyingTy->isDependentType() &&
7821         !Prev->getIntegerType()->isDependentType() &&
7822         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
7823                                         Prev->getIntegerType())) {
7824       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
7825         << EnumUnderlyingTy << Prev->getIntegerType();
7826       Diag(Prev->getLocation(), diag::note_previous_use);
7827       return true;
7828     }
7829   } else if (IsFixed != Prev->isFixed()) {
7830     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
7831       << Prev->isFixed();
7832     Diag(Prev->getLocation(), diag::note_previous_use);
7833     return true;
7834   }
7835
7836   return false;
7837 }
7838
7839 /// \brief Determine whether a tag with a given kind is acceptable
7840 /// as a redeclaration of the given tag declaration.
7841 ///
7842 /// \returns true if the new tag kind is acceptable, false otherwise.
7843 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
7844                                         TagTypeKind NewTag, bool isDefinition,
7845                                         SourceLocation NewTagLoc,
7846                                         const IdentifierInfo &Name) {
7847   // C++ [dcl.type.elab]p3:
7848   //   The class-key or enum keyword present in the
7849   //   elaborated-type-specifier shall agree in kind with the
7850   //   declaration to which the name in the elaborated-type-specifier
7851   //   refers. This rule also applies to the form of
7852   //   elaborated-type-specifier that declares a class-name or
7853   //   friend class since it can be construed as referring to the
7854   //   definition of the class. Thus, in any
7855   //   elaborated-type-specifier, the enum keyword shall be used to
7856   //   refer to an enumeration (7.2), the union class-key shall be
7857   //   used to refer to a union (clause 9), and either the class or
7858   //   struct class-key shall be used to refer to a class (clause 9)
7859   //   declared using the class or struct class-key.
7860   TagTypeKind OldTag = Previous->getTagKind();
7861   if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
7862     if (OldTag == NewTag)
7863       return true;
7864
7865   if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
7866       (NewTag == TTK_Struct || NewTag == TTK_Class)) {
7867     // Warn about the struct/class tag mismatch.
7868     bool isTemplate = false;
7869     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
7870       isTemplate = Record->getDescribedClassTemplate();
7871
7872     if (!ActiveTemplateInstantiations.empty()) {
7873       // In a template instantiation, do not offer fix-its for tag mismatches
7874       // since they usually mess up the template instead of fixing the problem.
7875       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7876         << (NewTag == TTK_Class) << isTemplate << &Name;
7877       return true;
7878     }
7879
7880     if (isDefinition) {
7881       // On definitions, check previous tags and issue a fix-it for each
7882       // one that doesn't match the current tag.
7883       if (Previous->getDefinition()) {
7884         // Don't suggest fix-its for redefinitions.
7885         return true;
7886       }
7887
7888       bool previousMismatch = false;
7889       for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
7890            E(Previous->redecls_end()); I != E; ++I) {
7891         if (I->getTagKind() != NewTag) {
7892           if (!previousMismatch) {
7893             previousMismatch = true;
7894             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
7895               << (NewTag == TTK_Class) << isTemplate << &Name;
7896           }
7897           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
7898             << (NewTag == TTK_Class)
7899             << FixItHint::CreateReplacement(I->getInnerLocStart(),
7900                                             NewTag == TTK_Class?
7901                                             "class" : "struct");
7902         }
7903       }
7904       return true;
7905     }
7906
7907     // Check for a previous definition.  If current tag and definition
7908     // are same type, do nothing.  If no definition, but disagree with
7909     // with previous tag type, give a warning, but no fix-it.
7910     const TagDecl *Redecl = Previous->getDefinition() ?
7911                             Previous->getDefinition() : Previous;
7912     if (Redecl->getTagKind() == NewTag) {
7913       return true;
7914     }
7915
7916     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7917       << (NewTag == TTK_Class)
7918       << isTemplate << &Name;
7919     Diag(Redecl->getLocation(), diag::note_previous_use);
7920
7921     // If there is a previous defintion, suggest a fix-it.
7922     if (Previous->getDefinition()) {
7923         Diag(NewTagLoc, diag::note_struct_class_suggestion)
7924           << (Redecl->getTagKind() == TTK_Class)
7925           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
7926                         Redecl->getTagKind() == TTK_Class? "class" : "struct");
7927     }
7928
7929     return true;
7930   }
7931   return false;
7932 }
7933
7934 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
7935 /// former case, Name will be non-null.  In the later case, Name will be null.
7936 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
7937 /// reference/declaration/definition of a tag.
7938 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7939                      SourceLocation KWLoc, CXXScopeSpec &SS,
7940                      IdentifierInfo *Name, SourceLocation NameLoc,
7941                      AttributeList *Attr, AccessSpecifier AS,
7942                      SourceLocation ModulePrivateLoc,
7943                      MultiTemplateParamsArg TemplateParameterLists,
7944                      bool &OwnedDecl, bool &IsDependent,
7945                      SourceLocation ScopedEnumKWLoc,
7946                      bool ScopedEnumUsesClassTag,
7947                      TypeResult UnderlyingType) {
7948   // If this is not a definition, it must have a name.
7949   IdentifierInfo *OrigName = Name;
7950   assert((Name != 0 || TUK == TUK_Definition) &&
7951          "Nameless record must be a definition!");
7952   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
7953
7954   OwnedDecl = false;
7955   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7956   bool ScopedEnum = ScopedEnumKWLoc.isValid();
7957
7958   // FIXME: Check explicit specializations more carefully.
7959   bool isExplicitSpecialization = false;
7960   bool Invalid = false;
7961
7962   // We only need to do this matching if we have template parameters
7963   // or a scope specifier, which also conveniently avoids this work
7964   // for non-C++ cases.
7965   if (TemplateParameterLists.size() > 0 ||
7966       (SS.isNotEmpty() && TUK != TUK_Reference)) {
7967     if (TemplateParameterList *TemplateParams
7968           = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
7969                                                 TemplateParameterLists.get(),
7970                                                 TemplateParameterLists.size(),
7971                                                     TUK == TUK_Friend,
7972                                                     isExplicitSpecialization,
7973                                                     Invalid)) {
7974       if (TemplateParams->size() > 0) {
7975         // This is a declaration or definition of a class template (which may
7976         // be a member of another template).
7977
7978         if (Invalid)
7979           return 0;
7980
7981         OwnedDecl = false;
7982         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
7983                                                SS, Name, NameLoc, Attr,
7984                                                TemplateParams, AS,
7985                                                ModulePrivateLoc,
7986                                            TemplateParameterLists.size() - 1,
7987                  (TemplateParameterList**) TemplateParameterLists.release());
7988         return Result.get();
7989       } else {
7990         // The "template<>" header is extraneous.
7991         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7992           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7993         isExplicitSpecialization = true;
7994       }
7995     }
7996   }
7997
7998   // Figure out the underlying type if this a enum declaration. We need to do
7999   // this early, because it's needed to detect if this is an incompatible
8000   // redeclaration.
8001   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8002
8003   if (Kind == TTK_Enum) {
8004     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8005       // No underlying type explicitly specified, or we failed to parse the
8006       // type, default to int.
8007       EnumUnderlying = Context.IntTy.getTypePtr();
8008     else if (UnderlyingType.get()) {
8009       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8010       // integral type; any cv-qualification is ignored.
8011       TypeSourceInfo *TI = 0;
8012       GetTypeFromParser(UnderlyingType.get(), &TI);
8013       EnumUnderlying = TI;
8014
8015       if (CheckEnumUnderlyingType(TI))
8016         // Recover by falling back to int.
8017         EnumUnderlying = Context.IntTy.getTypePtr();
8018
8019       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
8020                                           UPPC_FixedUnderlyingType))
8021         EnumUnderlying = Context.IntTy.getTypePtr();
8022
8023     } else if (getLangOpts().MicrosoftMode)
8024       // Microsoft enums are always of int type.
8025       EnumUnderlying = Context.IntTy.getTypePtr();
8026   }
8027
8028   DeclContext *SearchDC = CurContext;
8029   DeclContext *DC = CurContext;
8030   bool isStdBadAlloc = false;
8031
8032   RedeclarationKind Redecl = ForRedeclaration;
8033   if (TUK == TUK_Friend || TUK == TUK_Reference)
8034     Redecl = NotForRedeclaration;
8035
8036   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
8037
8038   if (Name && SS.isNotEmpty()) {
8039     // We have a nested-name tag ('struct foo::bar').
8040
8041     // Check for invalid 'foo::'.
8042     if (SS.isInvalid()) {
8043       Name = 0;
8044       goto CreateNewDecl;
8045     }
8046
8047     // If this is a friend or a reference to a class in a dependent
8048     // context, don't try to make a decl for it.
8049     if (TUK == TUK_Friend || TUK == TUK_Reference) {
8050       DC = computeDeclContext(SS, false);
8051       if (!DC) {
8052         IsDependent = true;
8053         return 0;
8054       }
8055     } else {
8056       DC = computeDeclContext(SS, true);
8057       if (!DC) {
8058         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8059           << SS.getRange();
8060         return 0;
8061       }
8062     }
8063
8064     if (RequireCompleteDeclContext(SS, DC))
8065       return 0;
8066
8067     SearchDC = DC;
8068     // Look-up name inside 'foo::'.
8069     LookupQualifiedName(Previous, DC);
8070
8071     if (Previous.isAmbiguous())
8072       return 0;
8073
8074     if (Previous.empty()) {
8075       // Name lookup did not find anything. However, if the
8076       // nested-name-specifier refers to the current instantiation,
8077       // and that current instantiation has any dependent base
8078       // classes, we might find something at instantiation time: treat
8079       // this as a dependent elaborated-type-specifier.
8080       // But this only makes any sense for reference-like lookups.
8081       if (Previous.wasNotFoundInCurrentInstantiation() &&
8082           (TUK == TUK_Reference || TUK == TUK_Friend)) {
8083         IsDependent = true;
8084         return 0;
8085       }
8086
8087       // A tag 'foo::bar' must already exist.
8088       Diag(NameLoc, diag::err_not_tag_in_scope) 
8089         << Kind << Name << DC << SS.getRange();
8090       Name = 0;
8091       Invalid = true;
8092       goto CreateNewDecl;
8093     }
8094   } else if (Name) {
8095     // If this is a named struct, check to see if there was a previous forward
8096     // declaration or definition.
8097     // FIXME: We're looking into outer scopes here, even when we
8098     // shouldn't be. Doing so can result in ambiguities that we
8099     // shouldn't be diagnosing.
8100     LookupName(Previous, S);
8101
8102     if (Previous.isAmbiguous() && 
8103         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
8104       LookupResult::Filter F = Previous.makeFilter();
8105       while (F.hasNext()) {
8106         NamedDecl *ND = F.next();
8107         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8108           F.erase();
8109       }
8110       F.done();
8111     }
8112     
8113     // Note:  there used to be some attempt at recovery here.
8114     if (Previous.isAmbiguous())
8115       return 0;
8116
8117     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
8118       // FIXME: This makes sure that we ignore the contexts associated
8119       // with C structs, unions, and enums when looking for a matching
8120       // tag declaration or definition. See the similar lookup tweak
8121       // in Sema::LookupName; is there a better way to deal with this?
8122       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8123         SearchDC = SearchDC->getParent();
8124     }
8125   } else if (S->isFunctionPrototypeScope()) {
8126     // If this is an enum declaration in function prototype scope, set its
8127     // initial context to the translation unit.
8128     // FIXME: [citation needed]
8129     SearchDC = Context.getTranslationUnitDecl();
8130   }
8131
8132   if (Previous.isSingleResult() &&
8133       Previous.getFoundDecl()->isTemplateParameter()) {
8134     // Maybe we will complain about the shadowed template parameter.
8135     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
8136     // Just pretend that we didn't see the previous declaration.
8137     Previous.clear();
8138   }
8139
8140   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
8141       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
8142     // This is a declaration of or a reference to "std::bad_alloc".
8143     isStdBadAlloc = true;
8144     
8145     if (Previous.empty() && StdBadAlloc) {
8146       // std::bad_alloc has been implicitly declared (but made invisible to
8147       // name lookup). Fill in this implicit declaration as the previous 
8148       // declaration, so that the declarations get chained appropriately.
8149       Previous.addDecl(getStdBadAlloc());
8150     }
8151   }
8152
8153   // If we didn't find a previous declaration, and this is a reference
8154   // (or friend reference), move to the correct scope.  In C++, we
8155   // also need to do a redeclaration lookup there, just in case
8156   // there's a shadow friend decl.
8157   if (Name && Previous.empty() &&
8158       (TUK == TUK_Reference || TUK == TUK_Friend)) {
8159     if (Invalid) goto CreateNewDecl;
8160     assert(SS.isEmpty());
8161
8162     if (TUK == TUK_Reference) {
8163       // C++ [basic.scope.pdecl]p5:
8164       //   -- for an elaborated-type-specifier of the form
8165       //
8166       //          class-key identifier
8167       //
8168       //      if the elaborated-type-specifier is used in the
8169       //      decl-specifier-seq or parameter-declaration-clause of a
8170       //      function defined in namespace scope, the identifier is
8171       //      declared as a class-name in the namespace that contains
8172       //      the declaration; otherwise, except as a friend
8173       //      declaration, the identifier is declared in the smallest
8174       //      non-class, non-function-prototype scope that contains the
8175       //      declaration.
8176       //
8177       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8178       // C structs and unions.
8179       //
8180       // It is an error in C++ to declare (rather than define) an enum
8181       // type, including via an elaborated type specifier.  We'll
8182       // diagnose that later; for now, declare the enum in the same
8183       // scope as we would have picked for any other tag type.
8184       //
8185       // GNU C also supports this behavior as part of its incomplete
8186       // enum types extension, while GNU C++ does not.
8187       //
8188       // Find the context where we'll be declaring the tag.
8189       // FIXME: We would like to maintain the current DeclContext as the
8190       // lexical context,
8191       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
8192         SearchDC = SearchDC->getParent();
8193
8194       // Find the scope where we'll be declaring the tag.
8195       while (S->isClassScope() ||
8196              (getLangOpts().CPlusPlus &&
8197               S->isFunctionPrototypeScope()) ||
8198              ((S->getFlags() & Scope::DeclScope) == 0) ||
8199              (S->getEntity() &&
8200               ((DeclContext *)S->getEntity())->isTransparentContext()))
8201         S = S->getParent();
8202     } else {
8203       assert(TUK == TUK_Friend);
8204       // C++ [namespace.memdef]p3:
8205       //   If a friend declaration in a non-local class first declares a
8206       //   class or function, the friend class or function is a member of
8207       //   the innermost enclosing namespace.
8208       SearchDC = SearchDC->getEnclosingNamespaceContext();
8209     }
8210
8211     // In C++, we need to do a redeclaration lookup to properly
8212     // diagnose some problems.
8213     if (getLangOpts().CPlusPlus) {
8214       Previous.setRedeclarationKind(ForRedeclaration);
8215       LookupQualifiedName(Previous, SearchDC);
8216     }
8217   }
8218
8219   if (!Previous.empty()) {
8220     NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
8221
8222     // It's okay to have a tag decl in the same scope as a typedef
8223     // which hides a tag decl in the same scope.  Finding this
8224     // insanity with a redeclaration lookup can only actually happen
8225     // in C++.
8226     //
8227     // This is also okay for elaborated-type-specifiers, which is
8228     // technically forbidden by the current standard but which is
8229     // okay according to the likely resolution of an open issue;
8230     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
8231     if (getLangOpts().CPlusPlus) {
8232       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8233         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8234           TagDecl *Tag = TT->getDecl();
8235           if (Tag->getDeclName() == Name &&
8236               Tag->getDeclContext()->getRedeclContext()
8237                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
8238             PrevDecl = Tag;
8239             Previous.clear();
8240             Previous.addDecl(Tag);
8241             Previous.resolveKind();
8242           }
8243         }
8244       }
8245     }
8246
8247     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
8248       // If this is a use of a previous tag, or if the tag is already declared
8249       // in the same scope (so that the definition/declaration completes or
8250       // rementions the tag), reuse the decl.
8251       if (TUK == TUK_Reference || TUK == TUK_Friend ||
8252           isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
8253         // Make sure that this wasn't declared as an enum and now used as a
8254         // struct or something similar.
8255         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8256                                           TUK == TUK_Definition, KWLoc,
8257                                           *Name)) {
8258           bool SafeToContinue
8259             = (PrevTagDecl->getTagKind() != TTK_Enum &&
8260                Kind != TTK_Enum);
8261           if (SafeToContinue)
8262             Diag(KWLoc, diag::err_use_with_wrong_tag)
8263               << Name
8264               << FixItHint::CreateReplacement(SourceRange(KWLoc),
8265                                               PrevTagDecl->getKindName());
8266           else
8267             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
8268           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8269
8270           if (SafeToContinue)
8271             Kind = PrevTagDecl->getTagKind();
8272           else {
8273             // Recover by making this an anonymous redefinition.
8274             Name = 0;
8275             Previous.clear();
8276             Invalid = true;
8277           }
8278         }
8279
8280         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8281           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8282
8283           // If this is an elaborated-type-specifier for a scoped enumeration,
8284           // the 'class' keyword is not necessary and not permitted.
8285           if (TUK == TUK_Reference || TUK == TUK_Friend) {
8286             if (ScopedEnum)
8287               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8288                 << PrevEnum->isScoped()
8289                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8290             return PrevTagDecl;
8291           }
8292
8293           QualType EnumUnderlyingTy;
8294           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8295             EnumUnderlyingTy = TI->getType();
8296           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8297             EnumUnderlyingTy = QualType(T, 0);
8298
8299           // All conflicts with previous declarations are recovered by
8300           // returning the previous declaration, unless this is a definition,
8301           // in which case we want the caller to bail out.
8302           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8303                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
8304             return TUK == TUK_Declaration ? PrevTagDecl : 0;
8305         }
8306
8307         if (!Invalid) {
8308           // If this is a use, just return the declaration we found.
8309
8310           // FIXME: In the future, return a variant or some other clue
8311           // for the consumer of this Decl to know it doesn't own it.
8312           // For our current ASTs this shouldn't be a problem, but will
8313           // need to be changed with DeclGroups.
8314           if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
8315                getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
8316             return PrevTagDecl;
8317
8318           // Diagnose attempts to redefine a tag.
8319           if (TUK == TUK_Definition) {
8320             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
8321               // If we're defining a specialization and the previous definition
8322               // is from an implicit instantiation, don't emit an error
8323               // here; we'll catch this in the general case below.
8324               bool IsExplicitSpecializationAfterInstantiation = false;
8325               if (isExplicitSpecialization) {
8326                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8327                   IsExplicitSpecializationAfterInstantiation =
8328                     RD->getTemplateSpecializationKind() !=
8329                     TSK_ExplicitSpecialization;
8330                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8331                   IsExplicitSpecializationAfterInstantiation =
8332                     ED->getTemplateSpecializationKind() !=
8333                     TSK_ExplicitSpecialization;
8334               }
8335
8336               if (!IsExplicitSpecializationAfterInstantiation) {
8337                 // A redeclaration in function prototype scope in C isn't
8338                 // visible elsewhere, so merely issue a warning.
8339                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
8340                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
8341                 else
8342                   Diag(NameLoc, diag::err_redefinition) << Name;
8343                 Diag(Def->getLocation(), diag::note_previous_definition);
8344                 // If this is a redefinition, recover by making this
8345                 // struct be anonymous, which will make any later
8346                 // references get the previous definition.
8347                 Name = 0;
8348                 Previous.clear();
8349                 Invalid = true;
8350               }
8351             } else {
8352               // If the type is currently being defined, complain
8353               // about a nested redefinition.
8354               const TagType *Tag
8355                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
8356               if (Tag->isBeingDefined()) {
8357                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
8358                 Diag(PrevTagDecl->getLocation(),
8359                      diag::note_previous_definition);
8360                 Name = 0;
8361                 Previous.clear();
8362                 Invalid = true;
8363               }
8364             }
8365
8366             // Okay, this is definition of a previously declared or referenced
8367             // tag PrevDecl. We're going to create a new Decl for it.
8368           }
8369         }
8370         // If we get here we have (another) forward declaration or we
8371         // have a definition.  Just create a new decl.
8372
8373       } else {
8374         // If we get here, this is a definition of a new tag type in a nested
8375         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
8376         // new decl/type.  We set PrevDecl to NULL so that the entities
8377         // have distinct types.
8378         Previous.clear();
8379       }
8380       // If we get here, we're going to create a new Decl. If PrevDecl
8381       // is non-NULL, it's a definition of the tag declared by
8382       // PrevDecl. If it's NULL, we have a new definition.
8383
8384
8385     // Otherwise, PrevDecl is not a tag, but was found with tag
8386     // lookup.  This is only actually possible in C++, where a few
8387     // things like templates still live in the tag namespace.
8388     } else {
8389       // Use a better diagnostic if an elaborated-type-specifier
8390       // found the wrong kind of type on the first
8391       // (non-redeclaration) lookup.
8392       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
8393           !Previous.isForRedeclaration()) {
8394         unsigned Kind = 0;
8395         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8396         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8397         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8398         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
8399         Diag(PrevDecl->getLocation(), diag::note_declared_at);
8400         Invalid = true;
8401
8402       // Otherwise, only diagnose if the declaration is in scope.
8403       } else if (!isDeclInScope(PrevDecl, SearchDC, S, 
8404                                 isExplicitSpecialization)) {
8405         // do nothing
8406
8407       // Diagnose implicit declarations introduced by elaborated types.
8408       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
8409         unsigned Kind = 0;
8410         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8411         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8412         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8413         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
8414         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8415         Invalid = true;
8416
8417       // Otherwise it's a declaration.  Call out a particularly common
8418       // case here.
8419       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8420         unsigned Kind = 0;
8421         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
8422         Diag(NameLoc, diag::err_tag_definition_of_typedef)
8423           << Name << Kind << TND->getUnderlyingType();
8424         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8425         Invalid = true;
8426
8427       // Otherwise, diagnose.
8428       } else {
8429         // The tag name clashes with something else in the target scope,
8430         // issue an error and recover by making this tag be anonymous.
8431         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
8432         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8433         Name = 0;
8434         Invalid = true;
8435       }
8436
8437       // The existing declaration isn't relevant to us; we're in a
8438       // new scope, so clear out the previous declaration.
8439       Previous.clear();
8440     }
8441   }
8442
8443 CreateNewDecl:
8444
8445   TagDecl *PrevDecl = 0;
8446   if (Previous.isSingleResult())
8447     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
8448
8449   // If there is an identifier, use the location of the identifier as the
8450   // location of the decl, otherwise use the location of the struct/union
8451   // keyword.
8452   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
8453
8454   // Otherwise, create a new declaration. If there is a previous
8455   // declaration of the same entity, the two will be linked via
8456   // PrevDecl.
8457   TagDecl *New;
8458
8459   bool IsForwardReference = false;
8460   if (Kind == TTK_Enum) {
8461     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8462     // enum X { A, B, C } D;    D should chain to X.
8463     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
8464                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
8465                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
8466     // If this is an undefined enum, warn.
8467     if (TUK != TUK_Definition && !Invalid) {
8468       TagDecl *Def;
8469       if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
8470         // C++0x: 7.2p2: opaque-enum-declaration.
8471         // Conflicts are diagnosed above. Do nothing.
8472       }
8473       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
8474         Diag(Loc, diag::ext_forward_ref_enum_def)
8475           << New;
8476         Diag(Def->getLocation(), diag::note_previous_definition);
8477       } else {
8478         unsigned DiagID = diag::ext_forward_ref_enum;
8479         if (getLangOpts().MicrosoftMode)
8480           DiagID = diag::ext_ms_forward_ref_enum;
8481         else if (getLangOpts().CPlusPlus)
8482           DiagID = diag::err_forward_ref_enum;
8483         Diag(Loc, DiagID);
8484         
8485         // If this is a forward-declared reference to an enumeration, make a 
8486         // note of it; we won't actually be introducing the declaration into
8487         // the declaration context.
8488         if (TUK == TUK_Reference)
8489           IsForwardReference = true;
8490       }
8491     }
8492
8493     if (EnumUnderlying) {
8494       EnumDecl *ED = cast<EnumDecl>(New);
8495       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8496         ED->setIntegerTypeSourceInfo(TI);
8497       else
8498         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
8499       ED->setPromotionType(ED->getIntegerType());
8500     }
8501
8502   } else {
8503     // struct/union/class
8504
8505     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8506     // struct X { int A; } D;    D should chain to X.
8507     if (getLangOpts().CPlusPlus) {
8508       // FIXME: Look for a way to use RecordDecl for simple structs.
8509       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8510                                   cast_or_null<CXXRecordDecl>(PrevDecl));
8511
8512       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
8513         StdBadAlloc = cast<CXXRecordDecl>(New);
8514     } else
8515       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8516                                cast_or_null<RecordDecl>(PrevDecl));
8517   }
8518
8519   // Maybe add qualifier info.
8520   if (SS.isNotEmpty()) {
8521     if (SS.isSet()) {
8522       // If this is either a declaration or a definition, check the 
8523       // nested-name-specifier against the current context. We don't do this
8524       // for explicit specializations, because they have similar checking
8525       // (with more specific diagnostics) in the call to 
8526       // CheckMemberSpecialization, below.
8527       if (!isExplicitSpecialization &&
8528           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
8529           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
8530         Invalid = true;
8531
8532       New->setQualifierInfo(SS.getWithLocInContext(Context));
8533       if (TemplateParameterLists.size() > 0) {
8534         New->setTemplateParameterListsInfo(Context,
8535                                            TemplateParameterLists.size(),
8536                     (TemplateParameterList**) TemplateParameterLists.release());
8537       }
8538     }
8539     else
8540       Invalid = true;
8541   }
8542
8543   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
8544     // Add alignment attributes if necessary; these attributes are checked when
8545     // the ASTContext lays out the structure.
8546     //
8547     // It is important for implementing the correct semantics that this
8548     // happen here (in act on tag decl). The #pragma pack stack is
8549     // maintained as a result of parser callbacks which can occur at
8550     // many points during the parsing of a struct declaration (because
8551     // the #pragma tokens are effectively skipped over during the
8552     // parsing of the struct).
8553     AddAlignmentAttributesForRecord(RD);
8554     
8555     AddMsStructLayoutForRecord(RD);
8556   }
8557
8558   if (ModulePrivateLoc.isValid()) {
8559     if (isExplicitSpecialization)
8560       Diag(New->getLocation(), diag::err_module_private_specialization)
8561         << 2
8562         << FixItHint::CreateRemoval(ModulePrivateLoc);
8563     // __module_private__ does not apply to local classes. However, we only
8564     // diagnose this as an error when the declaration specifiers are
8565     // freestanding. Here, we just ignore the __module_private__.
8566     else if (!SearchDC->isFunctionOrMethod())
8567       New->setModulePrivate();
8568   }
8569   
8570   // If this is a specialization of a member class (of a class template),
8571   // check the specialization.
8572   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
8573     Invalid = true;
8574            
8575   if (Invalid)
8576     New->setInvalidDecl();
8577
8578   if (Attr)
8579     ProcessDeclAttributeList(S, New, Attr);
8580
8581   // If we're declaring or defining a tag in function prototype scope
8582   // in C, note that this type can only be used within the function.
8583   if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
8584     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
8585
8586   // Set the lexical context. If the tag has a C++ scope specifier, the
8587   // lexical context will be different from the semantic context.
8588   New->setLexicalDeclContext(CurContext);
8589
8590   // Mark this as a friend decl if applicable.
8591   // In Microsoft mode, a friend declaration also acts as a forward
8592   // declaration so we always pass true to setObjectOfFriendDecl to make
8593   // the tag name visible.
8594   if (TUK == TUK_Friend)
8595     New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
8596                                getLangOpts().MicrosoftExt);
8597
8598   // Set the access specifier.
8599   if (!Invalid && SearchDC->isRecord())
8600     SetMemberAccessSpecifier(New, PrevDecl, AS);
8601
8602   if (TUK == TUK_Definition)
8603     New->startDefinition();
8604
8605   // If this has an identifier, add it to the scope stack.
8606   if (TUK == TUK_Friend) {
8607     // We might be replacing an existing declaration in the lookup tables;
8608     // if so, borrow its access specifier.
8609     if (PrevDecl)
8610       New->setAccess(PrevDecl->getAccess());
8611
8612     DeclContext *DC = New->getDeclContext()->getRedeclContext();
8613     DC->makeDeclVisibleInContext(New);
8614     if (Name) // can be null along some error paths
8615       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8616         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
8617   } else if (Name) {
8618     S = getNonFieldDeclScope(S);
8619     PushOnScopeChains(New, S, !IsForwardReference);
8620     if (IsForwardReference)
8621       SearchDC->makeDeclVisibleInContext(New);
8622
8623   } else {
8624     CurContext->addDecl(New);
8625   }
8626
8627   // If this is the C FILE type, notify the AST context.
8628   if (IdentifierInfo *II = New->getIdentifier())
8629     if (!New->isInvalidDecl() &&
8630         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8631         II->isStr("FILE"))
8632       Context.setFILEDecl(New);
8633
8634   // If we were in function prototype scope (and not in C++ mode), add this
8635   // tag to the list of decls to inject into the function definition scope.
8636   if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
8637       InFunctionDeclarator && Name)
8638     DeclsInPrototypeScope.push_back(New);
8639
8640   OwnedDecl = true;
8641   return New;
8642 }
8643
8644 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
8645   AdjustDeclIfTemplate(TagD);
8646   TagDecl *Tag = cast<TagDecl>(TagD);
8647   
8648   // Enter the tag context.
8649   PushDeclContext(S, Tag);
8650 }
8651
8652 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
8653   assert(isa<ObjCContainerDecl>(IDecl) && 
8654          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
8655   DeclContext *OCD = cast<DeclContext>(IDecl);
8656   assert(getContainingDC(OCD) == CurContext &&
8657       "The next DeclContext should be lexically contained in the current one.");
8658   CurContext = OCD;
8659   return IDecl;
8660 }
8661
8662 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
8663                                            SourceLocation FinalLoc,
8664                                            SourceLocation LBraceLoc) {
8665   AdjustDeclIfTemplate(TagD);
8666   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
8667
8668   FieldCollector->StartClass();
8669
8670   if (!Record->getIdentifier())
8671     return;
8672
8673   if (FinalLoc.isValid())
8674     Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
8675     
8676   // C++ [class]p2:
8677   //   [...] The class-name is also inserted into the scope of the
8678   //   class itself; this is known as the injected-class-name. For
8679   //   purposes of access checking, the injected-class-name is treated
8680   //   as if it were a public member name.
8681   CXXRecordDecl *InjectedClassName
8682     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
8683                             Record->getLocStart(), Record->getLocation(),
8684                             Record->getIdentifier(),
8685                             /*PrevDecl=*/0,
8686                             /*DelayTypeCreation=*/true);
8687   Context.getTypeDeclType(InjectedClassName, Record);
8688   InjectedClassName->setImplicit();
8689   InjectedClassName->setAccess(AS_public);
8690   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
8691       InjectedClassName->setDescribedClassTemplate(Template);
8692   PushOnScopeChains(InjectedClassName, S);
8693   assert(InjectedClassName->isInjectedClassName() &&
8694          "Broken injected-class-name");
8695 }
8696
8697 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
8698                                     SourceLocation RBraceLoc) {
8699   AdjustDeclIfTemplate(TagD);
8700   TagDecl *Tag = cast<TagDecl>(TagD);
8701   Tag->setRBraceLoc(RBraceLoc);
8702
8703   // Make sure we "complete" the definition even it is invalid.
8704   if (Tag->isBeingDefined()) {
8705     assert(Tag->isInvalidDecl() && "We should already have completed it");
8706     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8707       RD->completeDefinition();
8708   }
8709
8710   if (isa<CXXRecordDecl>(Tag))
8711     FieldCollector->FinishClass();
8712
8713   // Exit this scope of this tag's definition.
8714   PopDeclContext();
8715                                           
8716   // Notify the consumer that we've defined a tag.
8717   Consumer.HandleTagDeclDefinition(Tag);
8718 }
8719
8720 void Sema::ActOnObjCContainerFinishDefinition() {
8721   // Exit this scope of this interface definition.
8722   PopDeclContext();
8723 }
8724
8725 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
8726   assert(DC == CurContext && "Mismatch of container contexts");
8727   OriginalLexicalContext = DC;
8728   ActOnObjCContainerFinishDefinition();
8729 }
8730
8731 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
8732   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
8733   OriginalLexicalContext = 0;
8734 }
8735
8736 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
8737   AdjustDeclIfTemplate(TagD);
8738   TagDecl *Tag = cast<TagDecl>(TagD);
8739   Tag->setInvalidDecl();
8740
8741   // Make sure we "complete" the definition even it is invalid.
8742   if (Tag->isBeingDefined()) {
8743     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8744       RD->completeDefinition();
8745   }
8746
8747   // We're undoing ActOnTagStartDefinition here, not
8748   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
8749   // the FieldCollector.
8750
8751   PopDeclContext();  
8752 }
8753
8754 // Note that FieldName may be null for anonymous bitfields.
8755 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
8756                                 IdentifierInfo *FieldName,
8757                                 QualType FieldTy, Expr *BitWidth,
8758                                 bool *ZeroWidth) {
8759   // Default to true; that shouldn't confuse checks for emptiness
8760   if (ZeroWidth)
8761     *ZeroWidth = true;
8762
8763   // C99 6.7.2.1p4 - verify the field type.
8764   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
8765   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
8766     // Handle incomplete types with specific error.
8767     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
8768       return ExprError();
8769     if (FieldName)
8770       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
8771         << FieldName << FieldTy << BitWidth->getSourceRange();
8772     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
8773       << FieldTy << BitWidth->getSourceRange();
8774   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
8775                                              UPPC_BitFieldWidth))
8776     return ExprError();
8777
8778   // If the bit-width is type- or value-dependent, don't try to check
8779   // it now.
8780   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
8781     return Owned(BitWidth);
8782
8783   llvm::APSInt Value;
8784   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
8785   if (ICE.isInvalid())
8786     return ICE;
8787   BitWidth = ICE.take();
8788
8789   if (Value != 0 && ZeroWidth)
8790     *ZeroWidth = false;
8791
8792   // Zero-width bitfield is ok for anonymous field.
8793   if (Value == 0 && FieldName)
8794     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
8795
8796   if (Value.isSigned() && Value.isNegative()) {
8797     if (FieldName)
8798       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
8799                << FieldName << Value.toString(10);
8800     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
8801       << Value.toString(10);
8802   }
8803
8804   if (!FieldTy->isDependentType()) {
8805     uint64_t TypeSize = Context.getTypeSize(FieldTy);
8806     if (Value.getZExtValue() > TypeSize) {
8807       if (!getLangOpts().CPlusPlus) {
8808         if (FieldName) 
8809           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
8810             << FieldName << (unsigned)Value.getZExtValue() 
8811             << (unsigned)TypeSize;
8812         
8813         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
8814           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8815       }
8816       
8817       if (FieldName)
8818         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
8819           << FieldName << (unsigned)Value.getZExtValue() 
8820           << (unsigned)TypeSize;
8821       else
8822         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
8823           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;        
8824     }
8825   }
8826
8827   return Owned(BitWidth);
8828 }
8829
8830 /// ActOnField - Each field of a C struct/union is passed into this in order
8831 /// to create a FieldDecl object for it.
8832 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
8833                        Declarator &D, Expr *BitfieldWidth) {
8834   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
8835                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
8836                                /*HasInit=*/false, AS_public);
8837   return Res;
8838 }
8839
8840 /// HandleField - Analyze a field of a C struct or a C++ data member.
8841 ///
8842 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
8843                              SourceLocation DeclStart,
8844                              Declarator &D, Expr *BitWidth, bool HasInit,
8845                              AccessSpecifier AS) {
8846   IdentifierInfo *II = D.getIdentifier();
8847   SourceLocation Loc = DeclStart;
8848   if (II) Loc = D.getIdentifierLoc();
8849
8850   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8851   QualType T = TInfo->getType();
8852   if (getLangOpts().CPlusPlus) {
8853     CheckExtraCXXDefaultArguments(D);
8854
8855     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8856                                         UPPC_DataMemberType)) {
8857       D.setInvalidType();
8858       T = Context.IntTy;
8859       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
8860     }
8861   }
8862
8863   DiagnoseFunctionSpecifiers(D);
8864
8865   if (D.getDeclSpec().isThreadSpecified())
8866     Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
8867   if (D.getDeclSpec().isConstexprSpecified())
8868     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8869       << 2;
8870   
8871   // Check to see if this name was declared as a member previously
8872   NamedDecl *PrevDecl = 0;
8873   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
8874   LookupName(Previous, S);
8875   switch (Previous.getResultKind()) {
8876     case LookupResult::Found:
8877     case LookupResult::FoundUnresolvedValue:
8878       PrevDecl = Previous.getAsSingle<NamedDecl>();
8879       break;
8880       
8881     case LookupResult::FoundOverloaded:
8882       PrevDecl = Previous.getRepresentativeDecl();
8883       break;
8884       
8885     case LookupResult::NotFound:
8886     case LookupResult::NotFoundInCurrentInstantiation:
8887     case LookupResult::Ambiguous:
8888       break;
8889   }
8890   Previous.suppressDiagnostics();
8891
8892   if (PrevDecl && PrevDecl->isTemplateParameter()) {
8893     // Maybe we will complain about the shadowed template parameter.
8894     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8895     // Just pretend that we didn't see the previous declaration.
8896     PrevDecl = 0;
8897   }
8898
8899   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
8900     PrevDecl = 0;
8901
8902   bool Mutable
8903     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
8904   SourceLocation TSSL = D.getLocStart();
8905   FieldDecl *NewFD
8906     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
8907                      TSSL, AS, PrevDecl, &D);
8908
8909   if (NewFD->isInvalidDecl())
8910     Record->setInvalidDecl();
8911
8912   if (D.getDeclSpec().isModulePrivateSpecified())
8913     NewFD->setModulePrivate();
8914   
8915   if (NewFD->isInvalidDecl() && PrevDecl) {
8916     // Don't introduce NewFD into scope; there's already something
8917     // with the same name in the same scope.
8918   } else if (II) {
8919     PushOnScopeChains(NewFD, S);
8920   } else
8921     Record->addDecl(NewFD);
8922
8923   return NewFD;
8924 }
8925
8926 /// \brief Build a new FieldDecl and check its well-formedness.
8927 ///
8928 /// This routine builds a new FieldDecl given the fields name, type,
8929 /// record, etc. \p PrevDecl should refer to any previous declaration
8930 /// with the same name and in the same scope as the field to be
8931 /// created.
8932 ///
8933 /// \returns a new FieldDecl.
8934 ///
8935 /// \todo The Declarator argument is a hack. It will be removed once
8936 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
8937                                 TypeSourceInfo *TInfo,
8938                                 RecordDecl *Record, SourceLocation Loc,
8939                                 bool Mutable, Expr *BitWidth, bool HasInit,
8940                                 SourceLocation TSSL,
8941                                 AccessSpecifier AS, NamedDecl *PrevDecl,
8942                                 Declarator *D) {
8943   IdentifierInfo *II = Name.getAsIdentifierInfo();
8944   bool InvalidDecl = false;
8945   if (D) InvalidDecl = D->isInvalidType();
8946
8947   // If we receive a broken type, recover by assuming 'int' and
8948   // marking this declaration as invalid.
8949   if (T.isNull()) {
8950     InvalidDecl = true;
8951     T = Context.IntTy;
8952   }
8953
8954   QualType EltTy = Context.getBaseElementType(T);
8955   if (!EltTy->isDependentType()) {
8956     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
8957       // Fields of incomplete type force their record to be invalid.
8958       Record->setInvalidDecl();
8959       InvalidDecl = true;
8960     } else {
8961       NamedDecl *Def;
8962       EltTy->isIncompleteType(&Def);
8963       if (Def && Def->isInvalidDecl()) {
8964         Record->setInvalidDecl();
8965         InvalidDecl = true;
8966       }
8967     }
8968   }
8969
8970   // C99 6.7.2.1p8: A member of a structure or union may have any type other
8971   // than a variably modified type.
8972   if (!InvalidDecl && T->isVariablyModifiedType()) {
8973     bool SizeIsNegative;
8974     llvm::APSInt Oversized;
8975     QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
8976                                                            SizeIsNegative,
8977                                                            Oversized);
8978     if (!FixedTy.isNull()) {
8979       Diag(Loc, diag::warn_illegal_constant_array_size);
8980       T = FixedTy;
8981     } else {
8982       if (SizeIsNegative)
8983         Diag(Loc, diag::err_typecheck_negative_array_size);
8984       else if (Oversized.getBoolValue())
8985         Diag(Loc, diag::err_array_too_large)
8986           << Oversized.toString(10);
8987       else
8988         Diag(Loc, diag::err_typecheck_field_variable_size);
8989       InvalidDecl = true;
8990     }
8991   }
8992
8993   // Fields can not have abstract class types
8994   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
8995                                              diag::err_abstract_type_in_decl,
8996                                              AbstractFieldType))
8997     InvalidDecl = true;
8998
8999   bool ZeroWidth = false;
9000   // If this is declared as a bit-field, check the bit-field.
9001   if (!InvalidDecl && BitWidth) {
9002     BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9003     if (!BitWidth) {
9004       InvalidDecl = true;
9005       BitWidth = 0;
9006       ZeroWidth = false;
9007     }
9008   }
9009
9010   // Check that 'mutable' is consistent with the type of the declaration.
9011   if (!InvalidDecl && Mutable) {
9012     unsigned DiagID = 0;
9013     if (T->isReferenceType())
9014       DiagID = diag::err_mutable_reference;
9015     else if (T.isConstQualified())
9016       DiagID = diag::err_mutable_const;
9017
9018     if (DiagID) {
9019       SourceLocation ErrLoc = Loc;
9020       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9021         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9022       Diag(ErrLoc, DiagID);
9023       Mutable = false;
9024       InvalidDecl = true;
9025     }
9026   }
9027
9028   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
9029                                        BitWidth, Mutable, HasInit);
9030   if (InvalidDecl)
9031     NewFD->setInvalidDecl();
9032
9033   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9034     Diag(Loc, diag::err_duplicate_member) << II;
9035     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9036     NewFD->setInvalidDecl();
9037   }
9038
9039   if (!InvalidDecl && getLangOpts().CPlusPlus) {
9040     if (Record->isUnion()) {
9041       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9042         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9043         if (RDecl->getDefinition()) {
9044           // C++ [class.union]p1: An object of a class with a non-trivial
9045           // constructor, a non-trivial copy constructor, a non-trivial
9046           // destructor, or a non-trivial copy assignment operator
9047           // cannot be a member of a union, nor can an array of such
9048           // objects.
9049           if (CheckNontrivialField(NewFD))
9050             NewFD->setInvalidDecl();
9051         }
9052       }
9053
9054       // C++ [class.union]p1: If a union contains a member of reference type,
9055       // the program is ill-formed.
9056       if (EltTy->isReferenceType()) {
9057         Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9058           << NewFD->getDeclName() << EltTy;
9059         NewFD->setInvalidDecl();
9060       }
9061     }
9062   }
9063
9064   // FIXME: We need to pass in the attributes given an AST
9065   // representation, not a parser representation.
9066   if (D)
9067     // FIXME: What to pass instead of TUScope?
9068     ProcessDeclAttributes(TUScope, NewFD, *D);
9069
9070   // In auto-retain/release, infer strong retension for fields of
9071   // retainable type.
9072   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
9073     NewFD->setInvalidDecl();
9074
9075   if (T.isObjCGCWeak())
9076     Diag(Loc, diag::warn_attribute_weak_on_field);
9077
9078   NewFD->setAccess(AS);
9079   return NewFD;
9080 }
9081
9082 bool Sema::CheckNontrivialField(FieldDecl *FD) {
9083   assert(FD);
9084   assert(getLangOpts().CPlusPlus && "valid check only for C++");
9085
9086   if (FD->isInvalidDecl())
9087     return true;
9088
9089   QualType EltTy = Context.getBaseElementType(FD->getType());
9090   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9091     CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9092     if (RDecl->getDefinition()) {
9093       // We check for copy constructors before constructors
9094       // because otherwise we'll never get complaints about
9095       // copy constructors.
9096
9097       CXXSpecialMember member = CXXInvalid;
9098       if (!RDecl->hasTrivialCopyConstructor())
9099         member = CXXCopyConstructor;
9100       else if (!RDecl->hasTrivialDefaultConstructor())
9101         member = CXXDefaultConstructor;
9102       else if (!RDecl->hasTrivialCopyAssignment())
9103         member = CXXCopyAssignment;
9104       else if (!RDecl->hasTrivialDestructor())
9105         member = CXXDestructor;
9106
9107       if (member != CXXInvalid) {
9108         if (!getLangOpts().CPlusPlus0x &&
9109             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
9110           // Objective-C++ ARC: it is an error to have a non-trivial field of
9111           // a union. However, system headers in Objective-C programs 
9112           // occasionally have Objective-C lifetime objects within unions,
9113           // and rather than cause the program to fail, we make those 
9114           // members unavailable.
9115           SourceLocation Loc = FD->getLocation();
9116           if (getSourceManager().isInSystemHeader(Loc)) {
9117             if (!FD->hasAttr<UnavailableAttr>())
9118               FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
9119                                   "this system field has retaining ownership"));
9120             return false;
9121           }
9122         }
9123
9124         Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
9125                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9126                diag::err_illegal_union_or_anon_struct_member)
9127           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
9128         DiagnoseNontrivial(RT, member);
9129         return !getLangOpts().CPlusPlus0x;
9130       }
9131     }
9132   }
9133   
9134   return false;
9135 }
9136
9137 /// If the given constructor is user-provided, produce a diagnostic explaining
9138 /// that it makes the class non-trivial.
9139 static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT,
9140                                                CXXConstructorDecl *CD,
9141                                                Sema::CXXSpecialMember CSM) {
9142   if (!CD->isUserProvided())
9143     return false;
9144
9145   SourceLocation CtorLoc = CD->getLocation();
9146   S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9147   return true;
9148 }
9149
9150 /// DiagnoseNontrivial - Given that a class has a non-trivial
9151 /// special member, figure out why.
9152 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9153   QualType QT(T, 0U);
9154   CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9155
9156   // Check whether the member was user-declared.
9157   switch (member) {
9158   case CXXInvalid:
9159     break;
9160
9161   case CXXDefaultConstructor:
9162     if (RD->hasUserDeclaredConstructor()) {
9163       typedef CXXRecordDecl::ctor_iterator ctor_iter;
9164       for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
9165         if (DiagnoseNontrivialUserProvidedCtor(*this, QT, *CI, member))
9166           return;
9167
9168       // No user-provided constructors; look for constructor templates.
9169       typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9170           tmpl_iter;
9171       for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9172            TI != TE; ++TI) {
9173         CXXConstructorDecl *CD =
9174             dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
9175         if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member))
9176           return;
9177       }
9178     }
9179     break;
9180
9181   case CXXCopyConstructor:
9182     if (RD->hasUserDeclaredCopyConstructor()) {
9183       SourceLocation CtorLoc =
9184         RD->getCopyConstructor(0)->getLocation();
9185       Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9186       return;
9187     }
9188     break;
9189
9190   case CXXMoveConstructor:
9191     if (RD->hasUserDeclaredMoveConstructor()) {
9192       SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
9193       Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9194       return;
9195     }
9196     break;
9197
9198   case CXXCopyAssignment:
9199     if (RD->hasUserDeclaredCopyAssignment()) {
9200       // FIXME: this should use the location of the copy
9201       // assignment, not the type.
9202       SourceLocation TyLoc = RD->getLocStart();
9203       Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
9204       return;
9205     }
9206     break;
9207
9208   case CXXMoveAssignment:
9209     if (RD->hasUserDeclaredMoveAssignment()) {
9210       SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9211       Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9212       return;
9213     }
9214     break;
9215
9216   case CXXDestructor:
9217     if (RD->hasUserDeclaredDestructor()) {
9218       SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
9219       Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9220       return;
9221     }
9222     break;
9223   }
9224
9225   typedef CXXRecordDecl::base_class_iterator base_iter;
9226
9227   // Virtual bases and members inhibit trivial copying/construction,
9228   // but not trivial destruction.
9229   if (member != CXXDestructor) {
9230     // Check for virtual bases.  vbases includes indirect virtual bases,
9231     // so we just iterate through the direct bases.
9232     for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9233       if (bi->isVirtual()) {
9234         SourceLocation BaseLoc = bi->getLocStart();
9235         Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9236         return;
9237       }
9238
9239     // Check for virtual methods.
9240     typedef CXXRecordDecl::method_iterator meth_iter;
9241     for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9242          ++mi) {
9243       if (mi->isVirtual()) {
9244         SourceLocation MLoc = mi->getLocStart();
9245         Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9246         return;
9247       }
9248     }
9249   }
9250
9251   bool (CXXRecordDecl::*hasTrivial)() const;
9252   switch (member) {
9253   case CXXDefaultConstructor:
9254     hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
9255   case CXXCopyConstructor:
9256     hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
9257   case CXXCopyAssignment:
9258     hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
9259   case CXXDestructor:
9260     hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
9261   default:
9262     llvm_unreachable("unexpected special member");
9263   }
9264
9265   // Check for nontrivial bases (and recurse).
9266   for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
9267     const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
9268     assert(BaseRT && "Don't know how to handle dependent bases");
9269     CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
9270     if (!(BaseRecTy->*hasTrivial)()) {
9271       SourceLocation BaseLoc = bi->getLocStart();
9272       Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9273       DiagnoseNontrivial(BaseRT, member);
9274       return;
9275     }
9276   }
9277
9278   // Check for nontrivial members (and recurse).
9279   typedef RecordDecl::field_iterator field_iter;
9280   for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9281        ++fi) {
9282     QualType EltTy = Context.getBaseElementType((*fi)->getType());
9283     if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
9284       CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9285
9286       if (!(EltRD->*hasTrivial)()) {
9287         SourceLocation FLoc = (*fi)->getLocation();
9288         Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9289         DiagnoseNontrivial(EltRT, member);
9290         return;
9291       }
9292     }
9293     
9294     if (EltTy->isObjCLifetimeType()) {
9295       switch (EltTy.getObjCLifetime()) {
9296       case Qualifiers::OCL_None:
9297       case Qualifiers::OCL_ExplicitNone:
9298         break;
9299           
9300       case Qualifiers::OCL_Autoreleasing:
9301       case Qualifiers::OCL_Weak:
9302       case Qualifiers::OCL_Strong:
9303         Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
9304           << QT << EltTy.getObjCLifetime();
9305         return;
9306       }
9307     }
9308   }
9309
9310   llvm_unreachable("found no explanation for non-trivial member");
9311 }
9312
9313 /// TranslateIvarVisibility - Translate visibility from a token ID to an
9314 ///  AST enum value.
9315 static ObjCIvarDecl::AccessControl
9316 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
9317   switch (ivarVisibility) {
9318   default: llvm_unreachable("Unknown visitibility kind");
9319   case tok::objc_private: return ObjCIvarDecl::Private;
9320   case tok::objc_public: return ObjCIvarDecl::Public;
9321   case tok::objc_protected: return ObjCIvarDecl::Protected;
9322   case tok::objc_package: return ObjCIvarDecl::Package;
9323   }
9324 }
9325
9326 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
9327 /// in order to create an IvarDecl object for it.
9328 Decl *Sema::ActOnIvar(Scope *S,
9329                                 SourceLocation DeclStart,
9330                                 Declarator &D, Expr *BitfieldWidth,
9331                                 tok::ObjCKeywordKind Visibility) {
9332
9333   IdentifierInfo *II = D.getIdentifier();
9334   Expr *BitWidth = (Expr*)BitfieldWidth;
9335   SourceLocation Loc = DeclStart;
9336   if (II) Loc = D.getIdentifierLoc();
9337
9338   // FIXME: Unnamed fields can be handled in various different ways, for
9339   // example, unnamed unions inject all members into the struct namespace!
9340
9341   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9342   QualType T = TInfo->getType();
9343
9344   if (BitWidth) {
9345     // 6.7.2.1p3, 6.7.2.1p4
9346     BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9347     if (!BitWidth)
9348       D.setInvalidType();
9349   } else {
9350     // Not a bitfield.
9351
9352     // validate II.
9353
9354   }
9355   if (T->isReferenceType()) {
9356     Diag(Loc, diag::err_ivar_reference_type);
9357     D.setInvalidType();
9358   }
9359   // C99 6.7.2.1p8: A member of a structure or union may have any type other
9360   // than a variably modified type.
9361   else if (T->isVariablyModifiedType()) {
9362     Diag(Loc, diag::err_typecheck_ivar_variable_size);
9363     D.setInvalidType();
9364   }
9365
9366   // Get the visibility (access control) for this ivar.
9367   ObjCIvarDecl::AccessControl ac =
9368     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9369                                         : ObjCIvarDecl::None;
9370   // Must set ivar's DeclContext to its enclosing interface.
9371   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
9372   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9373     return 0;
9374   ObjCContainerDecl *EnclosingContext;
9375   if (ObjCImplementationDecl *IMPDecl =
9376       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9377     if (!LangOpts.ObjCNonFragileABI2) {
9378     // Case of ivar declared in an implementation. Context is that of its class.
9379       EnclosingContext = IMPDecl->getClassInterface();
9380       assert(EnclosingContext && "Implementation has no class interface!");
9381     }
9382     else
9383       EnclosingContext = EnclosingDecl;
9384   } else {
9385     if (ObjCCategoryDecl *CDecl = 
9386         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9387       if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
9388         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
9389         return 0;
9390       }
9391     }
9392     EnclosingContext = EnclosingDecl;
9393   }
9394
9395   // Construct the decl.
9396   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
9397                                              DeclStart, Loc, II, T,
9398                                              TInfo, ac, (Expr *)BitfieldWidth);
9399
9400   if (II) {
9401     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
9402                                            ForRedeclaration);
9403     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
9404         && !isa<TagDecl>(PrevDecl)) {
9405       Diag(Loc, diag::err_duplicate_member) << II;
9406       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9407       NewID->setInvalidDecl();
9408     }
9409   }
9410
9411   // Process attributes attached to the ivar.
9412   ProcessDeclAttributes(S, NewID, D);
9413
9414   if (D.isInvalidType())
9415     NewID->setInvalidDecl();
9416
9417   // In ARC, infer 'retaining' for ivars of retainable type.
9418   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
9419     NewID->setInvalidDecl();
9420
9421   if (D.getDeclSpec().isModulePrivateSpecified())
9422     NewID->setModulePrivate();
9423   
9424   if (II) {
9425     // FIXME: When interfaces are DeclContexts, we'll need to add
9426     // these to the interface.
9427     S->AddDecl(NewID);
9428     IdResolver.AddDecl(NewID);
9429   }
9430
9431   return NewID;
9432 }
9433
9434 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 
9435 /// class and class extensions. For every class @interface and class 
9436 /// extension @interface, if the last ivar is a bitfield of any type, 
9437 /// then add an implicit `char :0` ivar to the end of that interface.
9438 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
9439                              SmallVectorImpl<Decl *> &AllIvarDecls) {
9440   if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
9441     return;
9442   
9443   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
9444   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
9445   
9446   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
9447     return;
9448   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
9449   if (!ID) {
9450     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
9451       if (!CD->IsClassExtension())
9452         return;
9453     }
9454     // No need to add this to end of @implementation.
9455     else
9456       return;
9457   }
9458   // All conditions are met. Add a new bitfield to the tail end of ivars.
9459   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9460   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
9461
9462   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
9463                               DeclLoc, DeclLoc, 0,
9464                               Context.CharTy, 
9465                               Context.getTrivialTypeSourceInfo(Context.CharTy,
9466                                                                DeclLoc),
9467                               ObjCIvarDecl::Private, BW,
9468                               true);
9469   AllIvarDecls.push_back(Ivar);
9470 }
9471
9472 void Sema::ActOnFields(Scope* S,
9473                        SourceLocation RecLoc, Decl *EnclosingDecl,
9474                        llvm::ArrayRef<Decl *> Fields,
9475                        SourceLocation LBrac, SourceLocation RBrac,
9476                        AttributeList *Attr) {
9477   assert(EnclosingDecl && "missing record or interface decl");
9478
9479   // If the decl this is being inserted into is invalid, then it may be a
9480   // redeclaration or some other bogus case.  Don't try to add fields to it.
9481   if (EnclosingDecl->isInvalidDecl())
9482     return;
9483
9484   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
9485
9486   // Start counting up the number of named members; make sure to include
9487   // members of anonymous structs and unions in the total.
9488   unsigned NumNamedMembers = 0;
9489   if (Record) {
9490     for (RecordDecl::decl_iterator i = Record->decls_begin(),
9491                                    e = Record->decls_end(); i != e; i++) {
9492       if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
9493         if (IFD->getDeclName())
9494           ++NumNamedMembers;
9495     }
9496   }
9497
9498   // Verify that all the fields are okay.
9499   SmallVector<FieldDecl*, 32> RecFields;
9500
9501   bool ARCErrReported = false;
9502   for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
9503        i != end; ++i) {
9504     FieldDecl *FD = cast<FieldDecl>(*i);
9505
9506     // Get the type for the field.
9507     const Type *FDTy = FD->getType().getTypePtr();
9508
9509     if (!FD->isAnonymousStructOrUnion()) {
9510       // Remember all fields written by the user.
9511       RecFields.push_back(FD);
9512     }
9513
9514     // If the field is already invalid for some reason, don't emit more
9515     // diagnostics about it.
9516     if (FD->isInvalidDecl()) {
9517       EnclosingDecl->setInvalidDecl();
9518       continue;
9519     }
9520
9521     // C99 6.7.2.1p2:
9522     //   A structure or union shall not contain a member with
9523     //   incomplete or function type (hence, a structure shall not
9524     //   contain an instance of itself, but may contain a pointer to
9525     //   an instance of itself), except that the last member of a
9526     //   structure with more than one named member may have incomplete
9527     //   array type; such a structure (and any union containing,
9528     //   possibly recursively, a member that is such a structure)
9529     //   shall not be a member of a structure or an element of an
9530     //   array.
9531     if (FDTy->isFunctionType()) {
9532       // Field declared as a function.
9533       Diag(FD->getLocation(), diag::err_field_declared_as_function)
9534         << FD->getDeclName();
9535       FD->setInvalidDecl();
9536       EnclosingDecl->setInvalidDecl();
9537       continue;
9538     } else if (FDTy->isIncompleteArrayType() && Record && 
9539                ((i + 1 == Fields.end() && !Record->isUnion()) ||
9540                 ((getLangOpts().MicrosoftExt ||
9541                   getLangOpts().CPlusPlus) &&
9542                  (i + 1 == Fields.end() || Record->isUnion())))) {
9543       // Flexible array member.
9544       // Microsoft and g++ is more permissive regarding flexible array.
9545       // It will accept flexible array in union and also
9546       // as the sole element of a struct/class.
9547       if (getLangOpts().MicrosoftExt) {
9548         if (Record->isUnion()) 
9549           Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
9550             << FD->getDeclName();
9551         else if (Fields.size() == 1) 
9552           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
9553             << FD->getDeclName() << Record->getTagKind();
9554       } else if (getLangOpts().CPlusPlus) {
9555         if (Record->isUnion()) 
9556           Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9557             << FD->getDeclName();
9558         else if (Fields.size() == 1) 
9559           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
9560             << FD->getDeclName() << Record->getTagKind();
9561       } else if (!getLangOpts().C99) {
9562       if (Record->isUnion())
9563         Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9564           << FD->getDeclName();
9565       else
9566         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
9567           << FD->getDeclName() << Record->getTagKind();
9568       } else if (NumNamedMembers < 1) {
9569         Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
9570           << FD->getDeclName();
9571         FD->setInvalidDecl();
9572         EnclosingDecl->setInvalidDecl();
9573         continue;
9574       }
9575       if (!FD->getType()->isDependentType() &&
9576           !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
9577         Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
9578           << FD->getDeclName() << FD->getType();
9579         FD->setInvalidDecl();
9580         EnclosingDecl->setInvalidDecl();
9581         continue;
9582       }
9583       // Okay, we have a legal flexible array member at the end of the struct.
9584       if (Record)
9585         Record->setHasFlexibleArrayMember(true);
9586     } else if (!FDTy->isDependentType() &&
9587                RequireCompleteType(FD->getLocation(), FD->getType(),
9588                                    diag::err_field_incomplete)) {
9589       // Incomplete type
9590       FD->setInvalidDecl();
9591       EnclosingDecl->setInvalidDecl();
9592       continue;
9593     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
9594       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
9595         // If this is a member of a union, then entire union becomes "flexible".
9596         if (Record && Record->isUnion()) {
9597           Record->setHasFlexibleArrayMember(true);
9598         } else {
9599           // If this is a struct/class and this is not the last element, reject
9600           // it.  Note that GCC supports variable sized arrays in the middle of
9601           // structures.
9602           if (i + 1 != Fields.end())
9603             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
9604               << FD->getDeclName() << FD->getType();
9605           else {
9606             // We support flexible arrays at the end of structs in
9607             // other structs as an extension.
9608             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
9609               << FD->getDeclName();
9610             if (Record)
9611               Record->setHasFlexibleArrayMember(true);
9612           }
9613         }
9614       }
9615       if (Record && FDTTy->getDecl()->hasObjectMember())
9616         Record->setHasObjectMember(true);
9617     } else if (FDTy->isObjCObjectType()) {
9618       /// A field cannot be an Objective-c object
9619       Diag(FD->getLocation(), diag::err_statically_allocated_object)
9620         << FixItHint::CreateInsertion(FD->getLocation(), "*");
9621       QualType T = Context.getObjCObjectPointerType(FD->getType());
9622       FD->setType(T);
9623     } 
9624     else if (!getLangOpts().CPlusPlus) {
9625       if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
9626         // It's an error in ARC if a field has lifetime.
9627         // We don't want to report this in a system header, though,
9628         // so we just make the field unavailable.
9629         // FIXME: that's really not sufficient; we need to make the type
9630         // itself invalid to, say, initialize or copy.
9631         QualType T = FD->getType();
9632         Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
9633         if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
9634           SourceLocation loc = FD->getLocation();
9635           if (getSourceManager().isInSystemHeader(loc)) {
9636             if (!FD->hasAttr<UnavailableAttr>()) {
9637               FD->addAttr(new (Context) UnavailableAttr(loc, Context,
9638                                 "this system field has retaining ownership"));
9639             }
9640           } else {
9641             Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct) 
9642               << T->isBlockPointerType();
9643           }
9644           ARCErrReported = true;
9645         }
9646       }
9647       else if (getLangOpts().ObjC1 &&
9648                getLangOpts().getGC() != LangOptions::NonGC &&
9649                Record && !Record->hasObjectMember()) {
9650         if (FD->getType()->isObjCObjectPointerType() ||
9651             FD->getType().isObjCGCStrong())
9652           Record->setHasObjectMember(true);
9653         else if (Context.getAsArrayType(FD->getType())) {
9654           QualType BaseType = Context.getBaseElementType(FD->getType());
9655           if (BaseType->isRecordType() && 
9656               BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
9657             Record->setHasObjectMember(true);
9658           else if (BaseType->isObjCObjectPointerType() ||
9659                    BaseType.isObjCGCStrong())
9660                  Record->setHasObjectMember(true);
9661         }
9662       }
9663     }
9664     // Keep track of the number of named members.
9665     if (FD->getIdentifier())
9666       ++NumNamedMembers;
9667   }
9668
9669   // Okay, we successfully defined 'Record'.
9670   if (Record) {
9671     bool Completed = false;
9672     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
9673       if (!CXXRecord->isInvalidDecl()) {
9674         // Set access bits correctly on the directly-declared conversions.
9675         UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
9676         for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 
9677              I != E; ++I)
9678           Convs->setAccess(I, (*I)->getAccess());
9679         
9680         if (!CXXRecord->isDependentType()) {
9681           // Objective-C Automatic Reference Counting:
9682           //   If a class has a non-static data member of Objective-C pointer
9683           //   type (or array thereof), it is a non-POD type and its
9684           //   default constructor (if any), copy constructor, copy assignment
9685           //   operator, and destructor are non-trivial.
9686           //
9687           // This rule is also handled by CXXRecordDecl::completeDefinition(). 
9688           // However, here we check whether this particular class is only 
9689           // non-POD because of the presence of an Objective-C pointer member. 
9690           // If so, objects of this type cannot be shared between code compiled 
9691           // with instant objects and code compiled with manual retain/release.
9692           if (getLangOpts().ObjCAutoRefCount &&
9693               CXXRecord->hasObjectMember() && 
9694               CXXRecord->getLinkage() == ExternalLinkage) {
9695             if (CXXRecord->isPOD()) {
9696               Diag(CXXRecord->getLocation(), 
9697                    diag::warn_arc_non_pod_class_with_object_member)
9698                << CXXRecord;
9699             } else {
9700               // FIXME: Fix-Its would be nice here, but finding a good location
9701               // for them is going to be tricky.
9702               if (CXXRecord->hasTrivialCopyConstructor())
9703                 Diag(CXXRecord->getLocation(), 
9704                      diag::warn_arc_trivial_member_function_with_object_member)
9705                   << CXXRecord << 0;
9706               if (CXXRecord->hasTrivialCopyAssignment())
9707                 Diag(CXXRecord->getLocation(), 
9708                      diag::warn_arc_trivial_member_function_with_object_member)
9709                 << CXXRecord << 1;
9710               if (CXXRecord->hasTrivialDestructor())
9711                 Diag(CXXRecord->getLocation(), 
9712                      diag::warn_arc_trivial_member_function_with_object_member)
9713                 << CXXRecord << 2;
9714             }
9715           }
9716           
9717           // Adjust user-defined destructor exception spec.
9718           if (getLangOpts().CPlusPlus0x &&
9719               CXXRecord->hasUserDeclaredDestructor())
9720             AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
9721
9722           // Add any implicitly-declared members to this class.
9723           AddImplicitlyDeclaredMembersToClass(CXXRecord);
9724
9725           // If we have virtual base classes, we may end up finding multiple 
9726           // final overriders for a given virtual function. Check for this 
9727           // problem now.
9728           if (CXXRecord->getNumVBases()) {
9729             CXXFinalOverriderMap FinalOverriders;
9730             CXXRecord->getFinalOverriders(FinalOverriders);
9731             
9732             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 
9733                                              MEnd = FinalOverriders.end();
9734                  M != MEnd; ++M) {
9735               for (OverridingMethods::iterator SO = M->second.begin(), 
9736                                             SOEnd = M->second.end();
9737                    SO != SOEnd; ++SO) {
9738                 assert(SO->second.size() > 0 && 
9739                        "Virtual function without overridding functions?");
9740                 if (SO->second.size() == 1)
9741                   continue;
9742                 
9743                 // C++ [class.virtual]p2:
9744                 //   In a derived class, if a virtual member function of a base
9745                 //   class subobject has more than one final overrider the
9746                 //   program is ill-formed.
9747                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
9748                   << (NamedDecl *)M->first << Record;
9749                 Diag(M->first->getLocation(), 
9750                      diag::note_overridden_virtual_function);
9751                 for (OverridingMethods::overriding_iterator 
9752                           OM = SO->second.begin(), 
9753                        OMEnd = SO->second.end();
9754                      OM != OMEnd; ++OM)
9755                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
9756                     << (NamedDecl *)M->first << OM->Method->getParent();
9757                 
9758                 Record->setInvalidDecl();
9759               }
9760             }
9761             CXXRecord->completeDefinition(&FinalOverriders);
9762             Completed = true;
9763           }
9764         }
9765       }
9766     }
9767     
9768     if (!Completed)
9769       Record->completeDefinition();
9770
9771     // Now that the record is complete, do any delayed exception spec checks
9772     // we were missing.
9773     while (!DelayedDestructorExceptionSpecChecks.empty()) {
9774       const CXXDestructorDecl *Dtor =
9775               DelayedDestructorExceptionSpecChecks.back().first;
9776       if (Dtor->getParent() != Record)
9777         break;
9778
9779       assert(!Dtor->getParent()->isDependentType() &&
9780           "Should not ever add destructors of templates into the list.");
9781       CheckOverridingFunctionExceptionSpec(Dtor,
9782           DelayedDestructorExceptionSpecChecks.back().second);
9783       DelayedDestructorExceptionSpecChecks.pop_back();
9784     }
9785
9786   } else {
9787     ObjCIvarDecl **ClsFields =
9788       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
9789     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
9790       ID->setEndOfDefinitionLoc(RBrac);
9791       // Add ivar's to class's DeclContext.
9792       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9793         ClsFields[i]->setLexicalDeclContext(ID);
9794         ID->addDecl(ClsFields[i]);
9795       }
9796       // Must enforce the rule that ivars in the base classes may not be
9797       // duplicates.
9798       if (ID->getSuperClass())
9799         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
9800     } else if (ObjCImplementationDecl *IMPDecl =
9801                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9802       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
9803       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
9804         // Ivar declared in @implementation never belongs to the implementation.
9805         // Only it is in implementation's lexical context.
9806         ClsFields[I]->setLexicalDeclContext(IMPDecl);
9807       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
9808       IMPDecl->setIvarLBraceLoc(LBrac);
9809       IMPDecl->setIvarRBraceLoc(RBrac);
9810     } else if (ObjCCategoryDecl *CDecl = 
9811                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9812       // case of ivars in class extension; all other cases have been
9813       // reported as errors elsewhere.
9814       // FIXME. Class extension does not have a LocEnd field.
9815       // CDecl->setLocEnd(RBrac);
9816       // Add ivar's to class extension's DeclContext.
9817       // Diagnose redeclaration of private ivars.
9818       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
9819       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9820         if (IDecl) {
9821           if (const ObjCIvarDecl *ClsIvar = 
9822               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9823             Diag(ClsFields[i]->getLocation(), 
9824                  diag::err_duplicate_ivar_declaration); 
9825             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
9826             continue;
9827           }
9828           for (const ObjCCategoryDecl *ClsExtDecl = 
9829                 IDecl->getFirstClassExtension();
9830                ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
9831             if (const ObjCIvarDecl *ClsExtIvar = 
9832                 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9833               Diag(ClsFields[i]->getLocation(), 
9834                    diag::err_duplicate_ivar_declaration); 
9835               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
9836               continue;
9837             }
9838           }
9839         }
9840         ClsFields[i]->setLexicalDeclContext(CDecl);
9841         CDecl->addDecl(ClsFields[i]);
9842       }
9843       CDecl->setIvarLBraceLoc(LBrac);
9844       CDecl->setIvarRBraceLoc(RBrac);
9845     }
9846   }
9847
9848   if (Attr)
9849     ProcessDeclAttributeList(S, Record, Attr);
9850
9851   // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
9852   // set the visibility of this record.
9853   if (Record && !Record->getDeclContext()->isRecord())
9854     AddPushedVisibilityAttribute(Record);
9855 }
9856
9857 /// \brief Determine whether the given integral value is representable within
9858 /// the given type T.
9859 static bool isRepresentableIntegerValue(ASTContext &Context,
9860                                         llvm::APSInt &Value,
9861                                         QualType T) {
9862   assert(T->isIntegralType(Context) && "Integral type required!");
9863   unsigned BitWidth = Context.getIntWidth(T);
9864   
9865   if (Value.isUnsigned() || Value.isNonNegative()) {
9866     if (T->isSignedIntegerOrEnumerationType()) 
9867       --BitWidth;
9868     return Value.getActiveBits() <= BitWidth;
9869   }  
9870   return Value.getMinSignedBits() <= BitWidth;
9871 }
9872
9873 // \brief Given an integral type, return the next larger integral type
9874 // (or a NULL type of no such type exists).
9875 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
9876   // FIXME: Int128/UInt128 support, which also needs to be introduced into 
9877   // enum checking below.
9878   assert(T->isIntegralType(Context) && "Integral type required!");
9879   const unsigned NumTypes = 4;
9880   QualType SignedIntegralTypes[NumTypes] = { 
9881     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
9882   };
9883   QualType UnsignedIntegralTypes[NumTypes] = { 
9884     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 
9885     Context.UnsignedLongLongTy
9886   };
9887   
9888   unsigned BitWidth = Context.getTypeSize(T);
9889   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
9890                                                         : UnsignedIntegralTypes;
9891   for (unsigned I = 0; I != NumTypes; ++I)
9892     if (Context.getTypeSize(Types[I]) > BitWidth)
9893       return Types[I];
9894   
9895   return QualType();
9896 }
9897
9898 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
9899                                           EnumConstantDecl *LastEnumConst,
9900                                           SourceLocation IdLoc,
9901                                           IdentifierInfo *Id,
9902                                           Expr *Val) {
9903   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
9904   llvm::APSInt EnumVal(IntWidth);
9905   QualType EltTy;
9906
9907   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
9908     Val = 0;
9909
9910   if (Val)
9911     Val = DefaultLvalueConversion(Val).take();
9912
9913   if (Val) {
9914     if (Enum->isDependentType() || Val->isTypeDependent())
9915       EltTy = Context.DependentTy;
9916     else {
9917       SourceLocation ExpLoc;
9918       if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
9919           !getLangOpts().MicrosoftMode) {
9920         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
9921         // constant-expression in the enumerator-definition shall be a converted
9922         // constant expression of the underlying type.
9923         EltTy = Enum->getIntegerType();
9924         ExprResult Converted =
9925           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
9926                                            CCEK_Enumerator);
9927         if (Converted.isInvalid())
9928           Val = 0;
9929         else
9930           Val = Converted.take();
9931       } else if (!Val->isValueDependent() &&
9932                  !(Val = VerifyIntegerConstantExpression(Val,
9933                                                          &EnumVal).take())) {
9934         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
9935       } else {
9936         if (Enum->isFixed()) {
9937           EltTy = Enum->getIntegerType();
9938
9939           // In Obj-C and Microsoft mode, require the enumeration value to be
9940           // representable in the underlying type of the enumeration. In C++11,
9941           // we perform a non-narrowing conversion as part of converted constant
9942           // expression checking.
9943           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9944             if (getLangOpts().MicrosoftMode) {
9945               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
9946               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9947             } else
9948               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
9949           } else
9950             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9951         } else if (getLangOpts().CPlusPlus) {
9952           // C++11 [dcl.enum]p5:
9953           //   If the underlying type is not fixed, the type of each enumerator
9954           //   is the type of its initializing value:
9955           //     - If an initializer is specified for an enumerator, the 
9956           //       initializing value has the same type as the expression.
9957           EltTy = Val->getType();
9958         } else {
9959           // C99 6.7.2.2p2:
9960           //   The expression that defines the value of an enumeration constant
9961           //   shall be an integer constant expression that has a value
9962           //   representable as an int.
9963
9964           // Complain if the value is not representable in an int.
9965           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
9966             Diag(IdLoc, diag::ext_enum_value_not_int)
9967               << EnumVal.toString(10) << Val->getSourceRange()
9968               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
9969           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
9970             // Force the type of the expression to 'int'.
9971             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
9972           }
9973           EltTy = Val->getType();
9974         }
9975       }
9976     }
9977   }
9978
9979   if (!Val) {
9980     if (Enum->isDependentType())
9981       EltTy = Context.DependentTy;
9982     else if (!LastEnumConst) {
9983       // C++0x [dcl.enum]p5:
9984       //   If the underlying type is not fixed, the type of each enumerator
9985       //   is the type of its initializing value:
9986       //     - If no initializer is specified for the first enumerator, the 
9987       //       initializing value has an unspecified integral type.
9988       //
9989       // GCC uses 'int' for its unspecified integral type, as does 
9990       // C99 6.7.2.2p3.
9991       if (Enum->isFixed()) {
9992         EltTy = Enum->getIntegerType();
9993       }
9994       else {
9995         EltTy = Context.IntTy;
9996       }
9997     } else {
9998       // Assign the last value + 1.
9999       EnumVal = LastEnumConst->getInitVal();
10000       ++EnumVal;
10001       EltTy = LastEnumConst->getType();
10002
10003       // Check for overflow on increment.
10004       if (EnumVal < LastEnumConst->getInitVal()) {
10005         // C++0x [dcl.enum]p5:
10006         //   If the underlying type is not fixed, the type of each enumerator
10007         //   is the type of its initializing value:
10008         //
10009         //     - Otherwise the type of the initializing value is the same as
10010         //       the type of the initializing value of the preceding enumerator
10011         //       unless the incremented value is not representable in that type,
10012         //       in which case the type is an unspecified integral type 
10013         //       sufficient to contain the incremented value. If no such type
10014         //       exists, the program is ill-formed.
10015         QualType T = getNextLargerIntegralType(Context, EltTy);
10016         if (T.isNull() || Enum->isFixed()) {
10017           // There is no integral type larger enough to represent this 
10018           // value. Complain, then allow the value to wrap around.
10019           EnumVal = LastEnumConst->getInitVal();
10020           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
10021           ++EnumVal;
10022           if (Enum->isFixed())
10023             // When the underlying type is fixed, this is ill-formed.
10024             Diag(IdLoc, diag::err_enumerator_wrapped)
10025               << EnumVal.toString(10)
10026               << EltTy;
10027           else
10028             Diag(IdLoc, diag::warn_enumerator_too_large)
10029               << EnumVal.toString(10);
10030         } else {
10031           EltTy = T;
10032         }
10033         
10034         // Retrieve the last enumerator's value, extent that type to the
10035         // type that is supposed to be large enough to represent the incremented
10036         // value, then increment.
10037         EnumVal = LastEnumConst->getInitVal();
10038         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10039         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
10040         ++EnumVal;        
10041         
10042         // If we're not in C++, diagnose the overflow of enumerator values,
10043         // which in C99 means that the enumerator value is not representable in
10044         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10045         // permits enumerator values that are representable in some larger
10046         // integral type.
10047         if (!getLangOpts().CPlusPlus && !T.isNull())
10048           Diag(IdLoc, diag::warn_enum_value_overflow);
10049       } else if (!getLangOpts().CPlusPlus &&
10050                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10051         // Enforce C99 6.7.2.2p2 even when we compute the next value.
10052         Diag(IdLoc, diag::ext_enum_value_not_int)
10053           << EnumVal.toString(10) << 1;
10054       }
10055     }
10056   }
10057
10058   if (!EltTy->isDependentType()) {
10059     // Make the enumerator value match the signedness and size of the 
10060     // enumerator's type.
10061     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
10062     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10063   }
10064   
10065   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
10066                                   Val, EnumVal);
10067 }
10068
10069
10070 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10071                               SourceLocation IdLoc, IdentifierInfo *Id,
10072                               AttributeList *Attr,
10073                               SourceLocation EqualLoc, Expr *Val) {
10074   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
10075   EnumConstantDecl *LastEnumConst =
10076     cast_or_null<EnumConstantDecl>(lastEnumConst);
10077
10078   // The scope passed in may not be a decl scope.  Zip up the scope tree until
10079   // we find one that is.
10080   S = getNonFieldDeclScope(S);
10081
10082   // Verify that there isn't already something declared with this name in this
10083   // scope.
10084   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
10085                                          ForRedeclaration);
10086   if (PrevDecl && PrevDecl->isTemplateParameter()) {
10087     // Maybe we will complain about the shadowed template parameter.
10088     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10089     // Just pretend that we didn't see the previous declaration.
10090     PrevDecl = 0;
10091   }
10092
10093   if (PrevDecl) {
10094     // When in C++, we may get a TagDecl with the same name; in this case the
10095     // enum constant will 'hide' the tag.
10096     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
10097            "Received TagDecl when not in C++!");
10098     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
10099       if (isa<EnumConstantDecl>(PrevDecl))
10100         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
10101       else
10102         Diag(IdLoc, diag::err_redefinition) << Id;
10103       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10104       return 0;
10105     }
10106   }
10107
10108   // C++ [class.mem]p13:
10109   //   If T is the name of a class, then each of the following shall have a 
10110   //   name different from T:
10111   //     - every enumerator of every member of class T that is an enumerated 
10112   //       type
10113   if (CXXRecordDecl *Record
10114                       = dyn_cast<CXXRecordDecl>(
10115                              TheEnumDecl->getDeclContext()->getRedeclContext()))
10116     if (Record->getIdentifier() && Record->getIdentifier() == Id)
10117       Diag(IdLoc, diag::err_member_name_of_class) << Id;
10118   
10119   EnumConstantDecl *New =
10120     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
10121
10122   if (New) {
10123     // Process attributes.
10124     if (Attr) ProcessDeclAttributeList(S, New, Attr);
10125
10126     // Register this decl in the current scope stack.
10127     New->setAccess(TheEnumDecl->getAccess());
10128     PushOnScopeChains(New, S);
10129   }
10130
10131   return New;
10132 }
10133
10134 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
10135                          SourceLocation RBraceLoc, Decl *EnumDeclX,
10136                          Decl **Elements, unsigned NumElements,
10137                          Scope *S, AttributeList *Attr) {
10138   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
10139   QualType EnumType = Context.getTypeDeclType(Enum);
10140
10141   if (Attr)
10142     ProcessDeclAttributeList(S, Enum, Attr);
10143
10144   if (Enum->isDependentType()) {
10145     for (unsigned i = 0; i != NumElements; ++i) {
10146       EnumConstantDecl *ECD =
10147         cast_or_null<EnumConstantDecl>(Elements[i]);
10148       if (!ECD) continue;
10149
10150       ECD->setType(EnumType);
10151     }
10152
10153     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
10154     return;
10155   }
10156
10157   // TODO: If the result value doesn't fit in an int, it must be a long or long
10158   // long value.  ISO C does not support this, but GCC does as an extension,
10159   // emit a warning.
10160   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10161   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10162   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
10163
10164   // Verify that all the values are okay, compute the size of the values, and
10165   // reverse the list.
10166   unsigned NumNegativeBits = 0;
10167   unsigned NumPositiveBits = 0;
10168
10169   // Keep track of whether all elements have type int.
10170   bool AllElementsInt = true;
10171
10172   for (unsigned i = 0; i != NumElements; ++i) {
10173     EnumConstantDecl *ECD =
10174       cast_or_null<EnumConstantDecl>(Elements[i]);
10175     if (!ECD) continue;  // Already issued a diagnostic.
10176
10177     const llvm::APSInt &InitVal = ECD->getInitVal();
10178
10179     // Keep track of the size of positive and negative values.
10180     if (InitVal.isUnsigned() || InitVal.isNonNegative())
10181       NumPositiveBits = std::max(NumPositiveBits,
10182                                  (unsigned)InitVal.getActiveBits());
10183     else
10184       NumNegativeBits = std::max(NumNegativeBits,
10185                                  (unsigned)InitVal.getMinSignedBits());
10186
10187     // Keep track of whether every enum element has type int (very commmon).
10188     if (AllElementsInt)
10189       AllElementsInt = ECD->getType() == Context.IntTy;
10190   }
10191
10192   // Figure out the type that should be used for this enum.
10193   QualType BestType;
10194   unsigned BestWidth;
10195
10196   // C++0x N3000 [conv.prom]p3:
10197   //   An rvalue of an unscoped enumeration type whose underlying
10198   //   type is not fixed can be converted to an rvalue of the first
10199   //   of the following types that can represent all the values of
10200   //   the enumeration: int, unsigned int, long int, unsigned long
10201   //   int, long long int, or unsigned long long int.
10202   // C99 6.4.4.3p2:
10203   //   An identifier declared as an enumeration constant has type int.
10204   // The C99 rule is modified by a gcc extension 
10205   QualType BestPromotionType;
10206
10207   bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
10208   // -fshort-enums is the equivalent to specifying the packed attribute on all
10209   // enum definitions.
10210   if (LangOpts.ShortEnums)
10211     Packed = true;
10212
10213   if (Enum->isFixed()) {
10214     BestType = Enum->getIntegerType();
10215     if (BestType->isPromotableIntegerType())
10216       BestPromotionType = Context.getPromotedIntegerType(BestType);
10217     else
10218       BestPromotionType = BestType;
10219     // We don't need to set BestWidth, because BestType is going to be the type
10220     // of the enumerators, but we do anyway because otherwise some compilers
10221     // warn that it might be used uninitialized.
10222     BestWidth = CharWidth;
10223   }
10224   else if (NumNegativeBits) {
10225     // If there is a negative value, figure out the smallest integer type (of
10226     // int/long/longlong) that fits.
10227     // If it's packed, check also if it fits a char or a short.
10228     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
10229       BestType = Context.SignedCharTy;
10230       BestWidth = CharWidth;
10231     } else if (Packed && NumNegativeBits <= ShortWidth &&
10232                NumPositiveBits < ShortWidth) {
10233       BestType = Context.ShortTy;
10234       BestWidth = ShortWidth;
10235     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
10236       BestType = Context.IntTy;
10237       BestWidth = IntWidth;
10238     } else {
10239       BestWidth = Context.getTargetInfo().getLongWidth();
10240
10241       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
10242         BestType = Context.LongTy;
10243       } else {
10244         BestWidth = Context.getTargetInfo().getLongLongWidth();
10245
10246         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
10247           Diag(Enum->getLocation(), diag::warn_enum_too_large);
10248         BestType = Context.LongLongTy;
10249       }
10250     }
10251     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
10252   } else {
10253     // If there is no negative value, figure out the smallest type that fits
10254     // all of the enumerator values.
10255     // If it's packed, check also if it fits a char or a short.
10256     if (Packed && NumPositiveBits <= CharWidth) {
10257       BestType = Context.UnsignedCharTy;
10258       BestPromotionType = Context.IntTy;
10259       BestWidth = CharWidth;
10260     } else if (Packed && NumPositiveBits <= ShortWidth) {
10261       BestType = Context.UnsignedShortTy;
10262       BestPromotionType = Context.IntTy;
10263       BestWidth = ShortWidth;
10264     } else if (NumPositiveBits <= IntWidth) {
10265       BestType = Context.UnsignedIntTy;
10266       BestWidth = IntWidth;
10267       BestPromotionType
10268         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10269                            ? Context.UnsignedIntTy : Context.IntTy;
10270     } else if (NumPositiveBits <=
10271                (BestWidth = Context.getTargetInfo().getLongWidth())) {
10272       BestType = Context.UnsignedLongTy;
10273       BestPromotionType
10274         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10275                            ? Context.UnsignedLongTy : Context.LongTy;
10276     } else {
10277       BestWidth = Context.getTargetInfo().getLongLongWidth();
10278       assert(NumPositiveBits <= BestWidth &&
10279              "How could an initializer get larger than ULL?");
10280       BestType = Context.UnsignedLongLongTy;
10281       BestPromotionType
10282         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10283                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
10284     }
10285   }
10286
10287   // Loop over all of the enumerator constants, changing their types to match
10288   // the type of the enum if needed.
10289   for (unsigned i = 0; i != NumElements; ++i) {
10290     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
10291     if (!ECD) continue;  // Already issued a diagnostic.
10292
10293     // Standard C says the enumerators have int type, but we allow, as an
10294     // extension, the enumerators to be larger than int size.  If each
10295     // enumerator value fits in an int, type it as an int, otherwise type it the
10296     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
10297     // that X has type 'int', not 'unsigned'.
10298
10299     // Determine whether the value fits into an int.
10300     llvm::APSInt InitVal = ECD->getInitVal();
10301
10302     // If it fits into an integer type, force it.  Otherwise force it to match
10303     // the enum decl type.
10304     QualType NewTy;
10305     unsigned NewWidth;
10306     bool NewSign;
10307     if (!getLangOpts().CPlusPlus &&
10308         !Enum->isFixed() &&
10309         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
10310       NewTy = Context.IntTy;
10311       NewWidth = IntWidth;
10312       NewSign = true;
10313     } else if (ECD->getType() == BestType) {
10314       // Already the right type!
10315       if (getLangOpts().CPlusPlus)
10316         // C++ [dcl.enum]p4: Following the closing brace of an
10317         // enum-specifier, each enumerator has the type of its
10318         // enumeration.
10319         ECD->setType(EnumType);
10320       continue;
10321     } else {
10322       NewTy = BestType;
10323       NewWidth = BestWidth;
10324       NewSign = BestType->isSignedIntegerOrEnumerationType();
10325     }
10326
10327     // Adjust the APSInt value.
10328     InitVal = InitVal.extOrTrunc(NewWidth);
10329     InitVal.setIsSigned(NewSign);
10330     ECD->setInitVal(InitVal);
10331
10332     // Adjust the Expr initializer and type.
10333     if (ECD->getInitExpr() &&
10334         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
10335       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
10336                                                 CK_IntegralCast,
10337                                                 ECD->getInitExpr(),
10338                                                 /*base paths*/ 0,
10339                                                 VK_RValue));
10340     if (getLangOpts().CPlusPlus)
10341       // C++ [dcl.enum]p4: Following the closing brace of an
10342       // enum-specifier, each enumerator has the type of its
10343       // enumeration.
10344       ECD->setType(EnumType);
10345     else
10346       ECD->setType(NewTy);
10347   }
10348
10349   Enum->completeDefinition(BestType, BestPromotionType,
10350                            NumPositiveBits, NumNegativeBits);
10351
10352   // If we're declaring a function, ensure this decl isn't forgotten about -
10353   // it needs to go into the function scope.
10354   if (InFunctionDeclarator)
10355     DeclsInPrototypeScope.push_back(Enum);
10356
10357 }
10358
10359 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
10360                                   SourceLocation StartLoc,
10361                                   SourceLocation EndLoc) {
10362   StringLiteral *AsmString = cast<StringLiteral>(expr);
10363
10364   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
10365                                                    AsmString, StartLoc,
10366                                                    EndLoc);
10367   CurContext->addDecl(New);
10368   return New;
10369 }
10370
10371 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 
10372                                    SourceLocation ImportLoc, 
10373                                    ModuleIdPath Path) {
10374   Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 
10375                                                 Module::AllVisible,
10376                                                 /*IsIncludeDirective=*/false);
10377   if (!Mod)
10378     return true;
10379   
10380   llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
10381   Module *ModCheck = Mod;
10382   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
10383     // If we've run out of module parents, just drop the remaining identifiers.
10384     // We need the length to be consistent.
10385     if (!ModCheck)
10386       break;
10387     ModCheck = ModCheck->Parent;
10388     
10389     IdentifierLocs.push_back(Path[I].second);
10390   }
10391
10392   ImportDecl *Import = ImportDecl::Create(Context, 
10393                                           Context.getTranslationUnitDecl(),
10394                                           AtLoc.isValid()? AtLoc : ImportLoc, 
10395                                           Mod, IdentifierLocs);
10396   Context.getTranslationUnitDecl()->addDecl(Import);
10397   return Import;
10398 }
10399
10400 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
10401                                       IdentifierInfo* AliasName,
10402                                       SourceLocation PragmaLoc,
10403                                       SourceLocation NameLoc,
10404                                       SourceLocation AliasNameLoc) {
10405   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
10406                                     LookupOrdinaryName);
10407   AsmLabelAttr *Attr =
10408      ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
10409
10410   if (PrevDecl) 
10411     PrevDecl->addAttr(Attr);
10412   else 
10413     (void)ExtnameUndeclaredIdentifiers.insert(
10414       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
10415 }
10416
10417 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
10418                              SourceLocation PragmaLoc,
10419                              SourceLocation NameLoc) {
10420   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
10421
10422   if (PrevDecl) {
10423     PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
10424   } else {
10425     (void)WeakUndeclaredIdentifiers.insert(
10426       std::pair<IdentifierInfo*,WeakInfo>
10427         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
10428   }
10429 }
10430
10431 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
10432                                 IdentifierInfo* AliasName,
10433                                 SourceLocation PragmaLoc,
10434                                 SourceLocation NameLoc,
10435                                 SourceLocation AliasNameLoc) {
10436   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
10437                                     LookupOrdinaryName);
10438   WeakInfo W = WeakInfo(Name, NameLoc);
10439
10440   if (PrevDecl) {
10441     if (!PrevDecl->hasAttr<AliasAttr>())
10442       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
10443         DeclApplyPragmaWeak(TUScope, ND, W);
10444   } else {
10445     (void)WeakUndeclaredIdentifiers.insert(
10446       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
10447   }
10448 }
10449
10450 Decl *Sema::getObjCDeclContext() const {
10451   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
10452 }
10453
10454 AvailabilityResult Sema::getCurContextAvailability() const {
10455   const Decl *D = cast<Decl>(getCurLexicalContext());
10456   // A category implicitly has the availability of the interface.
10457   if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
10458     D = CatD->getClassInterface();
10459   
10460   return D->getAvailability();
10461 }