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