1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
32 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
34 #include "clang/Parse/ParseDiagnostic.h"
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 using namespace clang;
50 using namespace sema;
51 
52 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
53   if (OwnedType) {
54     Decl *Group[2] = { OwnedType, Ptr };
55     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
56   }
57 
58   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
59 }
60 
61 namespace {
62 
63 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64  public:
65   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
66                        bool AllowTemplates=false)
67       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
68         AllowClassTemplates(AllowTemplates) {
69     WantExpressionKeywords = false;
70     WantCXXNamedCasts = false;
71     WantRemainingKeywords = false;
72   }
73 
74   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
75     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
76       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
77       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
78       return (IsType || AllowedTemplate) &&
79              (AllowInvalidDecl || !ND->isInvalidDecl());
80     }
81     return !WantClassName && candidate.isKeyword();
82   }
83 
84  private:
85   bool AllowInvalidDecl;
86   bool WantClassName;
87   bool AllowClassTemplates;
88 };
89 
90 }
91 
92 /// \brief Determine whether the token kind starts a simple-type-specifier.
93 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
94   switch (Kind) {
95   // FIXME: Take into account the current language when deciding whether a
96   // token kind is a valid type specifier
97   case tok::kw_short:
98   case tok::kw_long:
99   case tok::kw___int64:
100   case tok::kw___int128:
101   case tok::kw_signed:
102   case tok::kw_unsigned:
103   case tok::kw_void:
104   case tok::kw_char:
105   case tok::kw_int:
106   case tok::kw_half:
107   case tok::kw_float:
108   case tok::kw_double:
109   case tok::kw_wchar_t:
110   case tok::kw_bool:
111   case tok::kw___underlying_type:
112     return true;
113 
114   case tok::annot_typename:
115   case tok::kw_char16_t:
116   case tok::kw_char32_t:
117   case tok::kw_typeof:
118   case tok::annot_decltype:
119   case tok::kw_decltype:
120     return getLangOpts().CPlusPlus;
121 
122   default:
123     break;
124   }
125 
126   return false;
127 }
128 
129 /// \brief If the identifier refers to a type name within this scope,
130 /// return the declaration of that type.
131 ///
132 /// This routine performs ordinary name lookup of the identifier II
133 /// within the given scope, with optional C++ scope specifier SS, to
134 /// determine whether the name refers to a type. If so, returns an
135 /// opaque pointer (actually a QualType) corresponding to that
136 /// type. Otherwise, returns NULL.
137 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
138                              Scope *S, CXXScopeSpec *SS,
139                              bool isClassName, bool HasTrailingDot,
140                              ParsedType ObjectTypePtr,
141                              bool IsCtorOrDtorName,
142                              bool WantNontrivialTypeSourceInfo,
143                              IdentifierInfo **CorrectedII) {
144   // Determine where we will perform name lookup.
145   DeclContext *LookupCtx = 0;
146   if (ObjectTypePtr) {
147     QualType ObjectType = ObjectTypePtr.get();
148     if (ObjectType->isRecordType())
149       LookupCtx = computeDeclContext(ObjectType);
150   } else if (SS && SS->isNotEmpty()) {
151     LookupCtx = computeDeclContext(*SS, false);
152 
153     if (!LookupCtx) {
154       if (isDependentScopeSpecifier(*SS)) {
155         // C++ [temp.res]p3:
156         //   A qualified-id that refers to a type and in which the
157         //   nested-name-specifier depends on a template-parameter (14.6.2)
158         //   shall be prefixed by the keyword typename to indicate that the
159         //   qualified-id denotes a type, forming an
160         //   elaborated-type-specifier (7.1.5.3).
161         //
162         // We therefore do not perform any name lookup if the result would
163         // refer to a member of an unknown specialization.
164         if (!isClassName && !IsCtorOrDtorName)
165           return ParsedType();
166 
167         // We know from the grammar that this name refers to a type,
168         // so build a dependent node to describe the type.
169         if (WantNontrivialTypeSourceInfo)
170           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
171 
172         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
173         QualType T =
174           CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
175                             II, NameLoc);
176 
177           return ParsedType::make(T);
178       }
179 
180       return ParsedType();
181     }
182 
183     if (!LookupCtx->isDependentContext() &&
184         RequireCompleteDeclContext(*SS, LookupCtx))
185       return ParsedType();
186   }
187 
188   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
189   // lookup for class-names.
190   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
191                                       LookupOrdinaryName;
192   LookupResult Result(*this, &II, NameLoc, Kind);
193   if (LookupCtx) {
194     // Perform "qualified" name lookup into the declaration context we
195     // computed, which is either the type of the base of a member access
196     // expression or the declaration context associated with a prior
197     // nested-name-specifier.
198     LookupQualifiedName(Result, LookupCtx);
199 
200     if (ObjectTypePtr && Result.empty()) {
201       // C++ [basic.lookup.classref]p3:
202       //   If the unqualified-id is ~type-name, the type-name is looked up
203       //   in the context of the entire postfix-expression. If the type T of
204       //   the object expression is of a class type C, the type-name is also
205       //   looked up in the scope of class C. At least one of the lookups shall
206       //   find a name that refers to (possibly cv-qualified) T.
207       LookupName(Result, S);
208     }
209   } else {
210     // Perform unqualified name lookup.
211     LookupName(Result, S);
212   }
213 
214   NamedDecl *IIDecl = 0;
215   switch (Result.getResultKind()) {
216   case LookupResult::NotFound:
217   case LookupResult::NotFoundInCurrentInstantiation:
218     if (CorrectedII) {
219       TypeNameValidatorCCC Validator(true, isClassName);
220       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
221                                               Kind, S, SS, Validator);
222       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
223       TemplateTy Template;
224       bool MemberOfUnknownSpecialization;
225       UnqualifiedId TemplateName;
226       TemplateName.setIdentifier(NewII, NameLoc);
227       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
228       CXXScopeSpec NewSS, *NewSSPtr = SS;
229       if (SS && NNS) {
230         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
231         NewSSPtr = &NewSS;
232       }
233       if (Correction && (NNS || NewII != &II) &&
234           // Ignore a correction to a template type as the to-be-corrected
235           // identifier is not a template (typo correction for template names
236           // is handled elsewhere).
237           !(getLangOpts().CPlusPlus && NewSSPtr &&
238             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
239                            false, Template, MemberOfUnknownSpecialization))) {
240         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
241                                     isClassName, HasTrailingDot, ObjectTypePtr,
242                                     IsCtorOrDtorName,
243                                     WantNontrivialTypeSourceInfo);
244         if (Ty) {
245           diagnoseTypo(Correction,
246                        PDiag(diag::err_unknown_type_or_class_name_suggest)
247                          << Result.getLookupName() << isClassName);
248           if (SS && NNS)
249             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
250           *CorrectedII = NewII;
251           return Ty;
252         }
253       }
254     }
255     // If typo correction failed or was not performed, fall through
256   case LookupResult::FoundOverloaded:
257   case LookupResult::FoundUnresolvedValue:
258     Result.suppressDiagnostics();
259     return ParsedType();
260 
261   case LookupResult::Ambiguous:
262     // Recover from type-hiding ambiguities by hiding the type.  We'll
263     // do the lookup again when looking for an object, and we can
264     // diagnose the error then.  If we don't do this, then the error
265     // about hiding the type will be immediately followed by an error
266     // that only makes sense if the identifier was treated like a type.
267     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
268       Result.suppressDiagnostics();
269       return ParsedType();
270     }
271 
272     // Look to see if we have a type anywhere in the list of results.
273     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
274          Res != ResEnd; ++Res) {
275       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
276         if (!IIDecl ||
277             (*Res)->getLocation().getRawEncoding() <
278               IIDecl->getLocation().getRawEncoding())
279           IIDecl = *Res;
280       }
281     }
282 
283     if (!IIDecl) {
284       // None of the entities we found is a type, so there is no way
285       // to even assume that the result is a type. In this case, don't
286       // complain about the ambiguity. The parser will either try to
287       // perform this lookup again (e.g., as an object name), which
288       // will produce the ambiguity, or will complain that it expected
289       // a type name.
290       Result.suppressDiagnostics();
291       return ParsedType();
292     }
293 
294     // We found a type within the ambiguous lookup; diagnose the
295     // ambiguity and then return that type. This might be the right
296     // answer, or it might not be, but it suppresses any attempt to
297     // perform the name lookup again.
298     break;
299 
300   case LookupResult::Found:
301     IIDecl = Result.getFoundDecl();
302     break;
303   }
304 
305   assert(IIDecl && "Didn't find decl");
306 
307   QualType T;
308   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
309     DiagnoseUseOfDecl(IIDecl, NameLoc);
310 
311     if (T.isNull())
312       T = Context.getTypeDeclType(TD);
313 
314     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
315     // constructor or destructor name (in such a case, the scope specifier
316     // will be attached to the enclosing Expr or Decl node).
317     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
318       if (WantNontrivialTypeSourceInfo) {
319         // Construct a type with type-source information.
320         TypeLocBuilder Builder;
321         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
322 
323         T = getElaboratedType(ETK_None, *SS, T);
324         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
325         ElabTL.setElaboratedKeywordLoc(SourceLocation());
326         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
327         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
328       } else {
329         T = getElaboratedType(ETK_None, *SS, T);
330       }
331     }
332   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
333     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
334     if (!HasTrailingDot)
335       T = Context.getObjCInterfaceType(IDecl);
336   }
337 
338   if (T.isNull()) {
339     // If it's not plausibly a type, suppress diagnostics.
340     Result.suppressDiagnostics();
341     return ParsedType();
342   }
343   return ParsedType::make(T);
344 }
345 
346 /// isTagName() - This method is called *for error recovery purposes only*
347 /// to determine if the specified name is a valid tag name ("struct foo").  If
348 /// so, this returns the TST for the tag corresponding to it (TST_enum,
349 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
350 /// cases in C where the user forgot to specify the tag.
351 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
352   // Do a tag name lookup in this scope.
353   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
354   LookupName(R, S, false);
355   R.suppressDiagnostics();
356   if (R.getResultKind() == LookupResult::Found)
357     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
358       switch (TD->getTagKind()) {
359       case TTK_Struct: return DeclSpec::TST_struct;
360       case TTK_Interface: return DeclSpec::TST_interface;
361       case TTK_Union:  return DeclSpec::TST_union;
362       case TTK_Class:  return DeclSpec::TST_class;
363       case TTK_Enum:   return DeclSpec::TST_enum;
364       }
365     }
366 
367   return DeclSpec::TST_unspecified;
368 }
369 
370 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
371 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
372 /// then downgrade the missing typename error to a warning.
373 /// This is needed for MSVC compatibility; Example:
374 /// @code
375 /// template<class T> class A {
376 /// public:
377 ///   typedef int TYPE;
378 /// };
379 /// template<class T> class B : public A<T> {
380 /// public:
381 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
382 /// };
383 /// @endcode
384 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
385   if (CurContext->isRecord()) {
386     const Type *Ty = SS->getScopeRep()->getAsType();
387 
388     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
389     for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
390           BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
391       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
392         return true;
393     return S->isFunctionPrototypeScope();
394   }
395   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
396 }
397 
398 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
399                                    SourceLocation IILoc,
400                                    Scope *S,
401                                    CXXScopeSpec *SS,
402                                    ParsedType &SuggestedType,
403                                    bool AllowClassTemplates) {
404   // We don't have anything to suggest (yet).
405   SuggestedType = ParsedType();
406 
407   // There may have been a typo in the name of the type. Look up typo
408   // results, in case we have something that we can suggest.
409   TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
410   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
411                                              LookupOrdinaryName, S, SS,
412                                              Validator)) {
413     if (Corrected.isKeyword()) {
414       // We corrected to a keyword.
415       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
416       II = Corrected.getCorrectionAsIdentifierInfo();
417     } else {
418       // We found a similarly-named type or interface; suggest that.
419       if (!SS || !SS->isSet()) {
420         diagnoseTypo(Corrected,
421                      PDiag(diag::err_unknown_typename_suggest) << II);
422       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
423         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
424         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
425                                 II->getName().equals(CorrectedStr);
426         diagnoseTypo(Corrected,
427                      PDiag(diag::err_unknown_nested_typename_suggest)
428                        << II << DC << DroppedSpecifier << SS->getRange());
429       } else {
430         llvm_unreachable("could not have corrected a typo here");
431       }
432 
433       CXXScopeSpec tmpSS;
434       if (Corrected.getCorrectionSpecifier())
435         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
436                           SourceRange(IILoc));
437       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
438                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
439                                   false, ParsedType(),
440                                   /*IsCtorOrDtorName=*/false,
441                                   /*NonTrivialTypeSourceInfo=*/true);
442     }
443     return true;
444   }
445 
446   if (getLangOpts().CPlusPlus) {
447     // See if II is a class template that the user forgot to pass arguments to.
448     UnqualifiedId Name;
449     Name.setIdentifier(II, IILoc);
450     CXXScopeSpec EmptySS;
451     TemplateTy TemplateResult;
452     bool MemberOfUnknownSpecialization;
453     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
454                        Name, ParsedType(), true, TemplateResult,
455                        MemberOfUnknownSpecialization) == TNK_Type_template) {
456       TemplateName TplName = TemplateResult.get();
457       Diag(IILoc, diag::err_template_missing_args) << TplName;
458       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
459         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
460           << TplDecl->getTemplateParameters()->getSourceRange();
461       }
462       return true;
463     }
464   }
465 
466   // FIXME: Should we move the logic that tries to recover from a missing tag
467   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
468 
469   if (!SS || (!SS->isSet() && !SS->isInvalid()))
470     Diag(IILoc, diag::err_unknown_typename) << II;
471   else if (DeclContext *DC = computeDeclContext(*SS, false))
472     Diag(IILoc, diag::err_typename_nested_not_found)
473       << II << DC << SS->getRange();
474   else if (isDependentScopeSpecifier(*SS)) {
475     unsigned DiagID = diag::err_typename_missing;
476     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
477       DiagID = diag::warn_typename_missing;
478 
479     Diag(SS->getRange().getBegin(), DiagID)
480       << SS->getScopeRep() << II->getName()
481       << SourceRange(SS->getRange().getBegin(), IILoc)
482       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
483     SuggestedType = ActOnTypenameType(S, SourceLocation(),
484                                       *SS, *II, IILoc).get();
485   } else {
486     assert(SS && SS->isInvalid() &&
487            "Invalid scope specifier has already been diagnosed");
488   }
489 
490   return true;
491 }
492 
493 /// \brief Determine whether the given result set contains either a type name
494 /// or
495 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
496   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
497                        NextToken.is(tok::less);
498 
499   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
500     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
501       return true;
502 
503     if (CheckTemplate && isa<TemplateDecl>(*I))
504       return true;
505   }
506 
507   return false;
508 }
509 
510 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
511                                     Scope *S, CXXScopeSpec &SS,
512                                     IdentifierInfo *&Name,
513                                     SourceLocation NameLoc) {
514   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
515   SemaRef.LookupParsedName(R, S, &SS);
516   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
517     const char *TagName = 0;
518     const char *FixItTagName = 0;
519     switch (Tag->getTagKind()) {
520       case TTK_Class:
521         TagName = "class";
522         FixItTagName = "class ";
523         break;
524 
525       case TTK_Enum:
526         TagName = "enum";
527         FixItTagName = "enum ";
528         break;
529 
530       case TTK_Struct:
531         TagName = "struct";
532         FixItTagName = "struct ";
533         break;
534 
535       case TTK_Interface:
536         TagName = "__interface";
537         FixItTagName = "__interface ";
538         break;
539 
540       case TTK_Union:
541         TagName = "union";
542         FixItTagName = "union ";
543         break;
544     }
545 
546     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
547       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
548       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
549 
550     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
551          I != IEnd; ++I)
552       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
553         << Name << TagName;
554 
555     // Replace lookup results with just the tag decl.
556     Result.clear(Sema::LookupTagName);
557     SemaRef.LookupParsedName(Result, S, &SS);
558     return true;
559   }
560 
561   return false;
562 }
563 
564 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
565 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
566                                   QualType T, SourceLocation NameLoc) {
567   ASTContext &Context = S.Context;
568 
569   TypeLocBuilder Builder;
570   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
571 
572   T = S.getElaboratedType(ETK_None, SS, T);
573   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
574   ElabTL.setElaboratedKeywordLoc(SourceLocation());
575   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
576   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
577 }
578 
579 Sema::NameClassification Sema::ClassifyName(Scope *S,
580                                             CXXScopeSpec &SS,
581                                             IdentifierInfo *&Name,
582                                             SourceLocation NameLoc,
583                                             const Token &NextToken,
584                                             bool IsAddressOfOperand,
585                                             CorrectionCandidateCallback *CCC) {
586   DeclarationNameInfo NameInfo(Name, NameLoc);
587   ObjCMethodDecl *CurMethod = getCurMethodDecl();
588 
589   if (NextToken.is(tok::coloncolon)) {
590     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
591                                 QualType(), false, SS, 0, false);
592 
593   }
594 
595   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
596   LookupParsedName(Result, S, &SS, !CurMethod);
597 
598   // Perform lookup for Objective-C instance variables (including automatically
599   // synthesized instance variables), if we're in an Objective-C method.
600   // FIXME: This lookup really, really needs to be folded in to the normal
601   // unqualified lookup mechanism.
602   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
603     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
604     if (E.get() || E.isInvalid())
605       return E;
606   }
607 
608   bool SecondTry = false;
609   bool IsFilteredTemplateName = false;
610 
611 Corrected:
612   switch (Result.getResultKind()) {
613   case LookupResult::NotFound:
614     // If an unqualified-id is followed by a '(', then we have a function
615     // call.
616     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
617       // In C++, this is an ADL-only call.
618       // FIXME: Reference?
619       if (getLangOpts().CPlusPlus)
620         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
621 
622       // C90 6.3.2.2:
623       //   If the expression that precedes the parenthesized argument list in a
624       //   function call consists solely of an identifier, and if no
625       //   declaration is visible for this identifier, the identifier is
626       //   implicitly declared exactly as if, in the innermost block containing
627       //   the function call, the declaration
628       //
629       //     extern int identifier ();
630       //
631       //   appeared.
632       //
633       // We also allow this in C99 as an extension.
634       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
635         Result.addDecl(D);
636         Result.resolveKind();
637         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
638       }
639     }
640 
641     // In C, we first see whether there is a tag type by the same name, in
642     // which case it's likely that the user just forget to write "enum",
643     // "struct", or "union".
644     if (!getLangOpts().CPlusPlus && !SecondTry &&
645         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
646       break;
647     }
648 
649     // Perform typo correction to determine if there is another name that is
650     // close to this name.
651     if (!SecondTry && CCC) {
652       SecondTry = true;
653       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
654                                                  Result.getLookupKind(), S,
655                                                  &SS, *CCC)) {
656         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
657         unsigned QualifiedDiag = diag::err_no_member_suggest;
658 
659         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
660         NamedDecl *UnderlyingFirstDecl
661           = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
662         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
663             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
664           UnqualifiedDiag = diag::err_no_template_suggest;
665           QualifiedDiag = diag::err_no_member_template_suggest;
666         } else if (UnderlyingFirstDecl &&
667                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
668                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
669                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
670           UnqualifiedDiag = diag::err_unknown_typename_suggest;
671           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
672         }
673 
674         if (SS.isEmpty()) {
675           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
676         } else {// FIXME: is this even reachable? Test it.
677           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
678           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
679                                   Name->getName().equals(CorrectedStr);
680           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
681                                     << Name << computeDeclContext(SS, false)
682                                     << DroppedSpecifier << SS.getRange());
683         }
684 
685         // Update the name, so that the caller has the new name.
686         Name = Corrected.getCorrectionAsIdentifierInfo();
687 
688         // Typo correction corrected to a keyword.
689         if (Corrected.isKeyword())
690           return Name;
691 
692         // Also update the LookupResult...
693         // FIXME: This should probably go away at some point
694         Result.clear();
695         Result.setLookupName(Corrected.getCorrection());
696         if (FirstDecl)
697           Result.addDecl(FirstDecl);
698 
699         // If we found an Objective-C instance variable, let
700         // LookupInObjCMethod build the appropriate expression to
701         // reference the ivar.
702         // FIXME: This is a gross hack.
703         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
704           Result.clear();
705           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
706           return E;
707         }
708 
709         goto Corrected;
710       }
711     }
712 
713     // We failed to correct; just fall through and let the parser deal with it.
714     Result.suppressDiagnostics();
715     return NameClassification::Unknown();
716 
717   case LookupResult::NotFoundInCurrentInstantiation: {
718     // We performed name lookup into the current instantiation, and there were
719     // dependent bases, so we treat this result the same way as any other
720     // dependent nested-name-specifier.
721 
722     // C++ [temp.res]p2:
723     //   A name used in a template declaration or definition and that is
724     //   dependent on a template-parameter is assumed not to name a type
725     //   unless the applicable name lookup finds a type name or the name is
726     //   qualified by the keyword typename.
727     //
728     // FIXME: If the next token is '<', we might want to ask the parser to
729     // perform some heroics to see if we actually have a
730     // template-argument-list, which would indicate a missing 'template'
731     // keyword here.
732     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
733                                       NameInfo, IsAddressOfOperand,
734                                       /*TemplateArgs=*/0);
735   }
736 
737   case LookupResult::Found:
738   case LookupResult::FoundOverloaded:
739   case LookupResult::FoundUnresolvedValue:
740     break;
741 
742   case LookupResult::Ambiguous:
743     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
744         hasAnyAcceptableTemplateNames(Result)) {
745       // C++ [temp.local]p3:
746       //   A lookup that finds an injected-class-name (10.2) can result in an
747       //   ambiguity in certain cases (for example, if it is found in more than
748       //   one base class). If all of the injected-class-names that are found
749       //   refer to specializations of the same class template, and if the name
750       //   is followed by a template-argument-list, the reference refers to the
751       //   class template itself and not a specialization thereof, and is not
752       //   ambiguous.
753       //
754       // This filtering can make an ambiguous result into an unambiguous one,
755       // so try again after filtering out template names.
756       FilterAcceptableTemplateNames(Result);
757       if (!Result.isAmbiguous()) {
758         IsFilteredTemplateName = true;
759         break;
760       }
761     }
762 
763     // Diagnose the ambiguity and return an error.
764     return NameClassification::Error();
765   }
766 
767   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
768       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
769     // C++ [temp.names]p3:
770     //   After name lookup (3.4) finds that a name is a template-name or that
771     //   an operator-function-id or a literal- operator-id refers to a set of
772     //   overloaded functions any member of which is a function template if
773     //   this is followed by a <, the < is always taken as the delimiter of a
774     //   template-argument-list and never as the less-than operator.
775     if (!IsFilteredTemplateName)
776       FilterAcceptableTemplateNames(Result);
777 
778     if (!Result.empty()) {
779       bool IsFunctionTemplate;
780       bool IsVarTemplate;
781       TemplateName Template;
782       if (Result.end() - Result.begin() > 1) {
783         IsFunctionTemplate = true;
784         Template = Context.getOverloadedTemplateName(Result.begin(),
785                                                      Result.end());
786       } else {
787         TemplateDecl *TD
788           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
789         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
790         IsVarTemplate = isa<VarTemplateDecl>(TD);
791 
792         if (SS.isSet() && !SS.isInvalid())
793           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
794                                                     /*TemplateKeyword=*/false,
795                                                       TD);
796         else
797           Template = TemplateName(TD);
798       }
799 
800       if (IsFunctionTemplate) {
801         // Function templates always go through overload resolution, at which
802         // point we'll perform the various checks (e.g., accessibility) we need
803         // to based on which function we selected.
804         Result.suppressDiagnostics();
805 
806         return NameClassification::FunctionTemplate(Template);
807       }
808 
809       return IsVarTemplate ? NameClassification::VarTemplate(Template)
810                            : NameClassification::TypeTemplate(Template);
811     }
812   }
813 
814   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
815   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
816     DiagnoseUseOfDecl(Type, NameLoc);
817     QualType T = Context.getTypeDeclType(Type);
818     if (SS.isNotEmpty())
819       return buildNestedType(*this, SS, T, NameLoc);
820     return ParsedType::make(T);
821   }
822 
823   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
824   if (!Class) {
825     // FIXME: It's unfortunate that we don't have a Type node for handling this.
826     if (ObjCCompatibleAliasDecl *Alias
827                                 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
828       Class = Alias->getClassInterface();
829   }
830 
831   if (Class) {
832     DiagnoseUseOfDecl(Class, NameLoc);
833 
834     if (NextToken.is(tok::period)) {
835       // Interface. <something> is parsed as a property reference expression.
836       // Just return "unknown" as a fall-through for now.
837       Result.suppressDiagnostics();
838       return NameClassification::Unknown();
839     }
840 
841     QualType T = Context.getObjCInterfaceType(Class);
842     return ParsedType::make(T);
843   }
844 
845   // We can have a type template here if we're classifying a template argument.
846   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
847     return NameClassification::TypeTemplate(
848         TemplateName(cast<TemplateDecl>(FirstDecl)));
849 
850   // Check for a tag type hidden by a non-type decl in a few cases where it
851   // seems likely a type is wanted instead of the non-type that was found.
852   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
853   if ((NextToken.is(tok::identifier) ||
854        (NextIsOp &&
855         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
856       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
857     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
858     DiagnoseUseOfDecl(Type, NameLoc);
859     QualType T = Context.getTypeDeclType(Type);
860     if (SS.isNotEmpty())
861       return buildNestedType(*this, SS, T, NameLoc);
862     return ParsedType::make(T);
863   }
864 
865   if (FirstDecl->isCXXClassMember())
866     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
867 
868   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
869   return BuildDeclarationNameExpr(SS, Result, ADL);
870 }
871 
872 // Determines the context to return to after temporarily entering a
873 // context.  This depends in an unnecessarily complicated way on the
874 // exact ordering of callbacks from the parser.
875 DeclContext *Sema::getContainingDC(DeclContext *DC) {
876 
877   // Functions defined inline within classes aren't parsed until we've
878   // finished parsing the top-level class, so the top-level class is
879   // the context we'll need to return to.
880   // A Lambda call operator whose parent is a class must not be treated
881   // as an inline member function.  A Lambda can be used legally
882   // either as an in-class member initializer or a default argument.  These
883   // are parsed once the class has been marked complete and so the containing
884   // context would be the nested class (when the lambda is defined in one);
885   // If the class is not complete, then the lambda is being used in an
886   // ill-formed fashion (such as to specify the width of a bit-field, or
887   // in an array-bound) - in which case we still want to return the
888   // lexically containing DC (which could be a nested class).
889   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
890     DC = DC->getLexicalParent();
891 
892     // A function not defined within a class will always return to its
893     // lexical context.
894     if (!isa<CXXRecordDecl>(DC))
895       return DC;
896 
897     // A C++ inline method/friend is parsed *after* the topmost class
898     // it was declared in is fully parsed ("complete");  the topmost
899     // class is the context we need to return to.
900     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
901       DC = RD;
902 
903     // Return the declaration context of the topmost class the inline method is
904     // declared in.
905     return DC;
906   }
907 
908   return DC->getLexicalParent();
909 }
910 
911 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
912   assert(getContainingDC(DC) == CurContext &&
913       "The next DeclContext should be lexically contained in the current one.");
914   CurContext = DC;
915   S->setEntity(DC);
916 }
917 
918 void Sema::PopDeclContext() {
919   assert(CurContext && "DeclContext imbalance!");
920 
921   CurContext = getContainingDC(CurContext);
922   assert(CurContext && "Popped translation unit!");
923 }
924 
925 /// EnterDeclaratorContext - Used when we must lookup names in the context
926 /// of a declarator's nested name specifier.
927 ///
928 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
929   // C++0x [basic.lookup.unqual]p13:
930   //   A name used in the definition of a static data member of class
931   //   X (after the qualified-id of the static member) is looked up as
932   //   if the name was used in a member function of X.
933   // C++0x [basic.lookup.unqual]p14:
934   //   If a variable member of a namespace is defined outside of the
935   //   scope of its namespace then any name used in the definition of
936   //   the variable member (after the declarator-id) is looked up as
937   //   if the definition of the variable member occurred in its
938   //   namespace.
939   // Both of these imply that we should push a scope whose context
940   // is the semantic context of the declaration.  We can't use
941   // PushDeclContext here because that context is not necessarily
942   // lexically contained in the current context.  Fortunately,
943   // the containing scope should have the appropriate information.
944 
945   assert(!S->getEntity() && "scope already has entity");
946 
947 #ifndef NDEBUG
948   Scope *Ancestor = S->getParent();
949   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
950   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
951 #endif
952 
953   CurContext = DC;
954   S->setEntity(DC);
955 }
956 
957 void Sema::ExitDeclaratorContext(Scope *S) {
958   assert(S->getEntity() == CurContext && "Context imbalance!");
959 
960   // Switch back to the lexical context.  The safety of this is
961   // enforced by an assert in EnterDeclaratorContext.
962   Scope *Ancestor = S->getParent();
963   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
964   CurContext = Ancestor->getEntity();
965 
966   // We don't need to do anything with the scope, which is going to
967   // disappear.
968 }
969 
970 
971 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
972   // We assume that the caller has already called
973   // ActOnReenterTemplateScope so getTemplatedDecl() works.
974   FunctionDecl *FD = D->getAsFunction();
975   if (!FD)
976     return;
977 
978   // Same implementation as PushDeclContext, but enters the context
979   // from the lexical parent, rather than the top-level class.
980   assert(CurContext == FD->getLexicalParent() &&
981     "The next DeclContext should be lexically contained in the current one.");
982   CurContext = FD;
983   S->setEntity(CurContext);
984 
985   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
986     ParmVarDecl *Param = FD->getParamDecl(P);
987     // If the parameter has an identifier, then add it to the scope
988     if (Param->getIdentifier()) {
989       S->AddDecl(Param);
990       IdResolver.AddDecl(Param);
991     }
992   }
993 }
994 
995 
996 void Sema::ActOnExitFunctionContext() {
997   // Same implementation as PopDeclContext, but returns to the lexical parent,
998   // rather than the top-level class.
999   assert(CurContext && "DeclContext imbalance!");
1000   CurContext = CurContext->getLexicalParent();
1001   assert(CurContext && "Popped translation unit!");
1002 }
1003 
1004 
1005 /// \brief Determine whether we allow overloading of the function
1006 /// PrevDecl with another declaration.
1007 ///
1008 /// This routine determines whether overloading is possible, not
1009 /// whether some new function is actually an overload. It will return
1010 /// true in C++ (where we can always provide overloads) or, as an
1011 /// extension, in C when the previous function is already an
1012 /// overloaded function declaration or has the "overloadable"
1013 /// attribute.
1014 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1015                                        ASTContext &Context) {
1016   if (Context.getLangOpts().CPlusPlus)
1017     return true;
1018 
1019   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1020     return true;
1021 
1022   return (Previous.getResultKind() == LookupResult::Found
1023           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1024 }
1025 
1026 /// Add this decl to the scope shadowed decl chains.
1027 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1028   // Move up the scope chain until we find the nearest enclosing
1029   // non-transparent context. The declaration will be introduced into this
1030   // scope.
1031   while (S->getEntity() && S->getEntity()->isTransparentContext())
1032     S = S->getParent();
1033 
1034   // Add scoped declarations into their context, so that they can be
1035   // found later. Declarations without a context won't be inserted
1036   // into any context.
1037   if (AddToContext)
1038     CurContext->addDecl(D);
1039 
1040   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1041   // are function-local declarations.
1042   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1043       !D->getDeclContext()->getRedeclContext()->Equals(
1044         D->getLexicalDeclContext()->getRedeclContext()) &&
1045       !D->getLexicalDeclContext()->isFunctionOrMethod())
1046     return;
1047 
1048   // Template instantiations should also not be pushed into scope.
1049   if (isa<FunctionDecl>(D) &&
1050       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1051     return;
1052 
1053   // If this replaces anything in the current scope,
1054   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1055                                IEnd = IdResolver.end();
1056   for (; I != IEnd; ++I) {
1057     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1058       S->RemoveDecl(*I);
1059       IdResolver.RemoveDecl(*I);
1060 
1061       // Should only need to replace one decl.
1062       break;
1063     }
1064   }
1065 
1066   S->AddDecl(D);
1067 
1068   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1069     // Implicitly-generated labels may end up getting generated in an order that
1070     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1071     // the label at the appropriate place in the identifier chain.
1072     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1073       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1074       if (IDC == CurContext) {
1075         if (!S->isDeclScope(*I))
1076           continue;
1077       } else if (IDC->Encloses(CurContext))
1078         break;
1079     }
1080 
1081     IdResolver.InsertDeclAfter(I, D);
1082   } else {
1083     IdResolver.AddDecl(D);
1084   }
1085 }
1086 
1087 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1088   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1089     TUScope->AddDecl(D);
1090 }
1091 
1092 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1093                          bool AllowInlineNamespace) {
1094   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1095 }
1096 
1097 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1098   DeclContext *TargetDC = DC->getPrimaryContext();
1099   do {
1100     if (DeclContext *ScopeDC = S->getEntity())
1101       if (ScopeDC->getPrimaryContext() == TargetDC)
1102         return S;
1103   } while ((S = S->getParent()));
1104 
1105   return 0;
1106 }
1107 
1108 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1109                                             DeclContext*,
1110                                             ASTContext&);
1111 
1112 /// Filters out lookup results that don't fall within the given scope
1113 /// as determined by isDeclInScope.
1114 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1115                                 bool ConsiderLinkage,
1116                                 bool AllowInlineNamespace) {
1117   LookupResult::Filter F = R.makeFilter();
1118   while (F.hasNext()) {
1119     NamedDecl *D = F.next();
1120 
1121     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1122       continue;
1123 
1124     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1125       continue;
1126 
1127     F.erase();
1128   }
1129 
1130   F.done();
1131 }
1132 
1133 static bool isUsingDecl(NamedDecl *D) {
1134   return isa<UsingShadowDecl>(D) ||
1135          isa<UnresolvedUsingTypenameDecl>(D) ||
1136          isa<UnresolvedUsingValueDecl>(D);
1137 }
1138 
1139 /// Removes using shadow declarations from the lookup results.
1140 static void RemoveUsingDecls(LookupResult &R) {
1141   LookupResult::Filter F = R.makeFilter();
1142   while (F.hasNext())
1143     if (isUsingDecl(F.next()))
1144       F.erase();
1145 
1146   F.done();
1147 }
1148 
1149 /// \brief Check for this common pattern:
1150 /// @code
1151 /// class S {
1152 ///   S(const S&); // DO NOT IMPLEMENT
1153 ///   void operator=(const S&); // DO NOT IMPLEMENT
1154 /// };
1155 /// @endcode
1156 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1157   // FIXME: Should check for private access too but access is set after we get
1158   // the decl here.
1159   if (D->doesThisDeclarationHaveABody())
1160     return false;
1161 
1162   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1163     return CD->isCopyConstructor();
1164   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1165     return Method->isCopyAssignmentOperator();
1166   return false;
1167 }
1168 
1169 // We need this to handle
1170 //
1171 // typedef struct {
1172 //   void *foo() { return 0; }
1173 // } A;
1174 //
1175 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1176 // for example. If 'A', foo will have external linkage. If we have '*A',
1177 // foo will have no linkage. Since we can't know until we get to the end
1178 // of the typedef, this function finds out if D might have non-external linkage.
1179 // Callers should verify at the end of the TU if it D has external linkage or
1180 // not.
1181 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1182   const DeclContext *DC = D->getDeclContext();
1183   while (!DC->isTranslationUnit()) {
1184     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1185       if (!RD->hasNameForLinkage())
1186         return true;
1187     }
1188     DC = DC->getParent();
1189   }
1190 
1191   return !D->isExternallyVisible();
1192 }
1193 
1194 // FIXME: This needs to be refactored; some other isInMainFile users want
1195 // these semantics.
1196 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1197   if (S.TUKind != TU_Complete)
1198     return false;
1199   return S.SourceMgr.isInMainFile(Loc);
1200 }
1201 
1202 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1203   assert(D);
1204 
1205   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1206     return false;
1207 
1208   // Ignore class templates.
1209   if (D->getDeclContext()->isDependentContext() ||
1210       D->getLexicalDeclContext()->isDependentContext())
1211     return false;
1212 
1213   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1214     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1215       return false;
1216 
1217     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1218       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1219         return false;
1220     } else {
1221       // 'static inline' functions are defined in headers; don't warn.
1222       if (FD->isInlineSpecified() &&
1223           !isMainFileLoc(*this, FD->getLocation()))
1224         return false;
1225     }
1226 
1227     if (FD->doesThisDeclarationHaveABody() &&
1228         Context.DeclMustBeEmitted(FD))
1229       return false;
1230   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1231     // Constants and utility variables are defined in headers with internal
1232     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1233     // like "inline".)
1234     if (!isMainFileLoc(*this, VD->getLocation()))
1235       return false;
1236 
1237     if (Context.DeclMustBeEmitted(VD))
1238       return false;
1239 
1240     if (VD->isStaticDataMember() &&
1241         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1242       return false;
1243   } else {
1244     return false;
1245   }
1246 
1247   // Only warn for unused decls internal to the translation unit.
1248   return mightHaveNonExternalLinkage(D);
1249 }
1250 
1251 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1252   if (!D)
1253     return;
1254 
1255   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1256     const FunctionDecl *First = FD->getFirstDecl();
1257     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1258       return; // First should already be in the vector.
1259   }
1260 
1261   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1262     const VarDecl *First = VD->getFirstDecl();
1263     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1264       return; // First should already be in the vector.
1265   }
1266 
1267   if (ShouldWarnIfUnusedFileScopedDecl(D))
1268     UnusedFileScopedDecls.push_back(D);
1269 }
1270 
1271 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1272   if (D->isInvalidDecl())
1273     return false;
1274 
1275   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1276       D->hasAttr<ObjCPreciseLifetimeAttr>())
1277     return false;
1278 
1279   if (isa<LabelDecl>(D))
1280     return true;
1281 
1282   // White-list anything that isn't a local variable.
1283   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1284       !D->getDeclContext()->isFunctionOrMethod())
1285     return false;
1286 
1287   // Types of valid local variables should be complete, so this should succeed.
1288   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1289 
1290     // White-list anything with an __attribute__((unused)) type.
1291     QualType Ty = VD->getType();
1292 
1293     // Only look at the outermost level of typedef.
1294     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1295       if (TT->getDecl()->hasAttr<UnusedAttr>())
1296         return false;
1297     }
1298 
1299     // If we failed to complete the type for some reason, or if the type is
1300     // dependent, don't diagnose the variable.
1301     if (Ty->isIncompleteType() || Ty->isDependentType())
1302       return false;
1303 
1304     if (const TagType *TT = Ty->getAs<TagType>()) {
1305       const TagDecl *Tag = TT->getDecl();
1306       if (Tag->hasAttr<UnusedAttr>())
1307         return false;
1308 
1309       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1310         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1311           return false;
1312 
1313         if (const Expr *Init = VD->getInit()) {
1314           if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1315             Init = Cleanups->getSubExpr();
1316           const CXXConstructExpr *Construct =
1317             dyn_cast<CXXConstructExpr>(Init);
1318           if (Construct && !Construct->isElidable()) {
1319             CXXConstructorDecl *CD = Construct->getConstructor();
1320             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1321               return false;
1322           }
1323         }
1324       }
1325     }
1326 
1327     // TODO: __attribute__((unused)) templates?
1328   }
1329 
1330   return true;
1331 }
1332 
1333 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1334                                      FixItHint &Hint) {
1335   if (isa<LabelDecl>(D)) {
1336     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1337                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1338     if (AfterColon.isInvalid())
1339       return;
1340     Hint = FixItHint::CreateRemoval(CharSourceRange::
1341                                     getCharRange(D->getLocStart(), AfterColon));
1342   }
1343   return;
1344 }
1345 
1346 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1347 /// unless they are marked attr(unused).
1348 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1349   FixItHint Hint;
1350   if (!ShouldDiagnoseUnusedDecl(D))
1351     return;
1352 
1353   GenerateFixForUnusedDecl(D, Context, Hint);
1354 
1355   unsigned DiagID;
1356   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1357     DiagID = diag::warn_unused_exception_param;
1358   else if (isa<LabelDecl>(D))
1359     DiagID = diag::warn_unused_label;
1360   else
1361     DiagID = diag::warn_unused_variable;
1362 
1363   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1364 }
1365 
1366 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1367   // Verify that we have no forward references left.  If so, there was a goto
1368   // or address of a label taken, but no definition of it.  Label fwd
1369   // definitions are indicated with a null substmt.
1370   if (L->getStmt() == 0)
1371     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1372 }
1373 
1374 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1375   if (S->decl_empty()) return;
1376   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1377          "Scope shouldn't contain decls!");
1378 
1379   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1380        I != E; ++I) {
1381     Decl *TmpD = (*I);
1382     assert(TmpD && "This decl didn't get pushed??");
1383 
1384     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1385     NamedDecl *D = cast<NamedDecl>(TmpD);
1386 
1387     if (!D->getDeclName()) continue;
1388 
1389     // Diagnose unused variables in this scope.
1390     if (!S->hasUnrecoverableErrorOccurred())
1391       DiagnoseUnusedDecl(D);
1392 
1393     // If this was a forward reference to a label, verify it was defined.
1394     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1395       CheckPoppedLabel(LD, *this);
1396 
1397     // Remove this name from our lexical scope.
1398     IdResolver.RemoveDecl(D);
1399   }
1400 }
1401 
1402 /// \brief Look for an Objective-C class in the translation unit.
1403 ///
1404 /// \param Id The name of the Objective-C class we're looking for. If
1405 /// typo-correction fixes this name, the Id will be updated
1406 /// to the fixed name.
1407 ///
1408 /// \param IdLoc The location of the name in the translation unit.
1409 ///
1410 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1411 /// if there is no class with the given name.
1412 ///
1413 /// \returns The declaration of the named Objective-C class, or NULL if the
1414 /// class could not be found.
1415 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1416                                               SourceLocation IdLoc,
1417                                               bool DoTypoCorrection) {
1418   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1419   // creation from this context.
1420   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1421 
1422   if (!IDecl && DoTypoCorrection) {
1423     // Perform typo correction at the given location, but only if we
1424     // find an Objective-C class name.
1425     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1426     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1427                                        LookupOrdinaryName, TUScope, NULL,
1428                                        Validator)) {
1429       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1430       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1431       Id = IDecl->getIdentifier();
1432     }
1433   }
1434   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1435   // This routine must always return a class definition, if any.
1436   if (Def && Def->getDefinition())
1437       Def = Def->getDefinition();
1438   return Def;
1439 }
1440 
1441 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1442 /// from S, where a non-field would be declared. This routine copes
1443 /// with the difference between C and C++ scoping rules in structs and
1444 /// unions. For example, the following code is well-formed in C but
1445 /// ill-formed in C++:
1446 /// @code
1447 /// struct S6 {
1448 ///   enum { BAR } e;
1449 /// };
1450 ///
1451 /// void test_S6() {
1452 ///   struct S6 a;
1453 ///   a.e = BAR;
1454 /// }
1455 /// @endcode
1456 /// For the declaration of BAR, this routine will return a different
1457 /// scope. The scope S will be the scope of the unnamed enumeration
1458 /// within S6. In C++, this routine will return the scope associated
1459 /// with S6, because the enumeration's scope is a transparent
1460 /// context but structures can contain non-field names. In C, this
1461 /// routine will return the translation unit scope, since the
1462 /// enumeration's scope is a transparent context and structures cannot
1463 /// contain non-field names.
1464 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1465   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1466          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1467          (S->isClassScope() && !getLangOpts().CPlusPlus))
1468     S = S->getParent();
1469   return S;
1470 }
1471 
1472 /// \brief Looks up the declaration of "struct objc_super" and
1473 /// saves it for later use in building builtin declaration of
1474 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1475 /// pre-existing declaration exists no action takes place.
1476 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1477                                         IdentifierInfo *II) {
1478   if (!II->isStr("objc_msgSendSuper"))
1479     return;
1480   ASTContext &Context = ThisSema.Context;
1481 
1482   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1483                       SourceLocation(), Sema::LookupTagName);
1484   ThisSema.LookupName(Result, S);
1485   if (Result.getResultKind() == LookupResult::Found)
1486     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1487       Context.setObjCSuperType(Context.getTagDeclType(TD));
1488 }
1489 
1490 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1491 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1492 /// if we're creating this built-in in anticipation of redeclaring the
1493 /// built-in.
1494 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1495                                      Scope *S, bool ForRedeclaration,
1496                                      SourceLocation Loc) {
1497   LookupPredefedObjCSuperType(*this, S, II);
1498 
1499   Builtin::ID BID = (Builtin::ID)bid;
1500 
1501   ASTContext::GetBuiltinTypeError Error;
1502   QualType R = Context.GetBuiltinType(BID, Error);
1503   switch (Error) {
1504   case ASTContext::GE_None:
1505     // Okay
1506     break;
1507 
1508   case ASTContext::GE_Missing_stdio:
1509     if (ForRedeclaration)
1510       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1511         << Context.BuiltinInfo.GetName(BID);
1512     return 0;
1513 
1514   case ASTContext::GE_Missing_setjmp:
1515     if (ForRedeclaration)
1516       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1517         << Context.BuiltinInfo.GetName(BID);
1518     return 0;
1519 
1520   case ASTContext::GE_Missing_ucontext:
1521     if (ForRedeclaration)
1522       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1523         << Context.BuiltinInfo.GetName(BID);
1524     return 0;
1525   }
1526 
1527   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1528     Diag(Loc, diag::ext_implicit_lib_function_decl)
1529       << Context.BuiltinInfo.GetName(BID)
1530       << R;
1531     if (Context.BuiltinInfo.getHeaderName(BID) &&
1532         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1533           != DiagnosticsEngine::Ignored)
1534       Diag(Loc, diag::note_please_include_header)
1535         << Context.BuiltinInfo.getHeaderName(BID)
1536         << Context.BuiltinInfo.GetName(BID);
1537   }
1538 
1539   DeclContext *Parent = Context.getTranslationUnitDecl();
1540   if (getLangOpts().CPlusPlus) {
1541     LinkageSpecDecl *CLinkageDecl =
1542         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1543                                 LinkageSpecDecl::lang_c, false);
1544     CLinkageDecl->setImplicit();
1545     Parent->addDecl(CLinkageDecl);
1546     Parent = CLinkageDecl;
1547   }
1548 
1549   FunctionDecl *New = FunctionDecl::Create(Context,
1550                                            Parent,
1551                                            Loc, Loc, II, R, /*TInfo=*/0,
1552                                            SC_Extern,
1553                                            false,
1554                                            /*hasPrototype=*/true);
1555   New->setImplicit();
1556 
1557   // Create Decl objects for each parameter, adding them to the
1558   // FunctionDecl.
1559   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1560     SmallVector<ParmVarDecl*, 16> Params;
1561     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1562       ParmVarDecl *parm =
1563           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1564                               0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0);
1565       parm->setScopeInfo(0, i);
1566       Params.push_back(parm);
1567     }
1568     New->setParams(Params);
1569   }
1570 
1571   AddKnownFunctionAttributes(New);
1572   RegisterLocallyScopedExternCDecl(New, S);
1573 
1574   // TUScope is the translation-unit scope to insert this function into.
1575   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1576   // relate Scopes to DeclContexts, and probably eliminate CurContext
1577   // entirely, but we're not there yet.
1578   DeclContext *SavedContext = CurContext;
1579   CurContext = Parent;
1580   PushOnScopeChains(New, TUScope);
1581   CurContext = SavedContext;
1582   return New;
1583 }
1584 
1585 /// \brief Filter out any previous declarations that the given declaration
1586 /// should not consider because they are not permitted to conflict, e.g.,
1587 /// because they come from hidden sub-modules and do not refer to the same
1588 /// entity.
1589 static void filterNonConflictingPreviousDecls(ASTContext &context,
1590                                               NamedDecl *decl,
1591                                               LookupResult &previous){
1592   // This is only interesting when modules are enabled.
1593   if (!context.getLangOpts().Modules)
1594     return;
1595 
1596   // Empty sets are uninteresting.
1597   if (previous.empty())
1598     return;
1599 
1600   LookupResult::Filter filter = previous.makeFilter();
1601   while (filter.hasNext()) {
1602     NamedDecl *old = filter.next();
1603 
1604     // Non-hidden declarations are never ignored.
1605     if (!old->isHidden())
1606       continue;
1607 
1608     if (!old->isExternallyVisible())
1609       filter.erase();
1610   }
1611 
1612   filter.done();
1613 }
1614 
1615 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1616   QualType OldType;
1617   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1618     OldType = OldTypedef->getUnderlyingType();
1619   else
1620     OldType = Context.getTypeDeclType(Old);
1621   QualType NewType = New->getUnderlyingType();
1622 
1623   if (NewType->isVariablyModifiedType()) {
1624     // Must not redefine a typedef with a variably-modified type.
1625     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1626     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1627       << Kind << NewType;
1628     if (Old->getLocation().isValid())
1629       Diag(Old->getLocation(), diag::note_previous_definition);
1630     New->setInvalidDecl();
1631     return true;
1632   }
1633 
1634   if (OldType != NewType &&
1635       !OldType->isDependentType() &&
1636       !NewType->isDependentType() &&
1637       !Context.hasSameType(OldType, NewType)) {
1638     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1639     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1640       << Kind << NewType << OldType;
1641     if (Old->getLocation().isValid())
1642       Diag(Old->getLocation(), diag::note_previous_definition);
1643     New->setInvalidDecl();
1644     return true;
1645   }
1646   return false;
1647 }
1648 
1649 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1650 /// same name and scope as a previous declaration 'Old'.  Figure out
1651 /// how to resolve this situation, merging decls or emitting
1652 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1653 ///
1654 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1655   // If the new decl is known invalid already, don't bother doing any
1656   // merging checks.
1657   if (New->isInvalidDecl()) return;
1658 
1659   // Allow multiple definitions for ObjC built-in typedefs.
1660   // FIXME: Verify the underlying types are equivalent!
1661   if (getLangOpts().ObjC1) {
1662     const IdentifierInfo *TypeID = New->getIdentifier();
1663     switch (TypeID->getLength()) {
1664     default: break;
1665     case 2:
1666       {
1667         if (!TypeID->isStr("id"))
1668           break;
1669         QualType T = New->getUnderlyingType();
1670         if (!T->isPointerType())
1671           break;
1672         if (!T->isVoidPointerType()) {
1673           QualType PT = T->getAs<PointerType>()->getPointeeType();
1674           if (!PT->isStructureType())
1675             break;
1676         }
1677         Context.setObjCIdRedefinitionType(T);
1678         // Install the built-in type for 'id', ignoring the current definition.
1679         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1680         return;
1681       }
1682     case 5:
1683       if (!TypeID->isStr("Class"))
1684         break;
1685       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1686       // Install the built-in type for 'Class', ignoring the current definition.
1687       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1688       return;
1689     case 3:
1690       if (!TypeID->isStr("SEL"))
1691         break;
1692       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1693       // Install the built-in type for 'SEL', ignoring the current definition.
1694       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1695       return;
1696     }
1697     // Fall through - the typedef name was not a builtin type.
1698   }
1699 
1700   // Verify the old decl was also a type.
1701   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1702   if (!Old) {
1703     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1704       << New->getDeclName();
1705 
1706     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1707     if (OldD->getLocation().isValid())
1708       Diag(OldD->getLocation(), diag::note_previous_definition);
1709 
1710     return New->setInvalidDecl();
1711   }
1712 
1713   // If the old declaration is invalid, just give up here.
1714   if (Old->isInvalidDecl())
1715     return New->setInvalidDecl();
1716 
1717   // If the typedef types are not identical, reject them in all languages and
1718   // with any extensions enabled.
1719   if (isIncompatibleTypedef(Old, New))
1720     return;
1721 
1722   // The types match.  Link up the redeclaration chain and merge attributes if
1723   // the old declaration was a typedef.
1724   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1725     New->setPreviousDecl(Typedef);
1726     mergeDeclAttributes(New, Old);
1727   }
1728 
1729   if (getLangOpts().MicrosoftExt)
1730     return;
1731 
1732   if (getLangOpts().CPlusPlus) {
1733     // C++ [dcl.typedef]p2:
1734     //   In a given non-class scope, a typedef specifier can be used to
1735     //   redefine the name of any type declared in that scope to refer
1736     //   to the type to which it already refers.
1737     if (!isa<CXXRecordDecl>(CurContext))
1738       return;
1739 
1740     // C++0x [dcl.typedef]p4:
1741     //   In a given class scope, a typedef specifier can be used to redefine
1742     //   any class-name declared in that scope that is not also a typedef-name
1743     //   to refer to the type to which it already refers.
1744     //
1745     // This wording came in via DR424, which was a correction to the
1746     // wording in DR56, which accidentally banned code like:
1747     //
1748     //   struct S {
1749     //     typedef struct A { } A;
1750     //   };
1751     //
1752     // in the C++03 standard. We implement the C++0x semantics, which
1753     // allow the above but disallow
1754     //
1755     //   struct S {
1756     //     typedef int I;
1757     //     typedef int I;
1758     //   };
1759     //
1760     // since that was the intent of DR56.
1761     if (!isa<TypedefNameDecl>(Old))
1762       return;
1763 
1764     Diag(New->getLocation(), diag::err_redefinition)
1765       << New->getDeclName();
1766     Diag(Old->getLocation(), diag::note_previous_definition);
1767     return New->setInvalidDecl();
1768   }
1769 
1770   // Modules always permit redefinition of typedefs, as does C11.
1771   if (getLangOpts().Modules || getLangOpts().C11)
1772     return;
1773 
1774   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1775   // is normally mapped to an error, but can be controlled with
1776   // -Wtypedef-redefinition.  If either the original or the redefinition is
1777   // in a system header, don't emit this for compatibility with GCC.
1778   if (getDiagnostics().getSuppressSystemWarnings() &&
1779       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1780        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1781     return;
1782 
1783   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1784     << New->getDeclName();
1785   Diag(Old->getLocation(), diag::note_previous_definition);
1786   return;
1787 }
1788 
1789 /// DeclhasAttr - returns true if decl Declaration already has the target
1790 /// attribute.
1791 static bool DeclHasAttr(const Decl *D, const Attr *A) {
1792   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1793   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1794   for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1795     if ((*i)->getKind() == A->getKind()) {
1796       if (Ann) {
1797         if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1798           return true;
1799         continue;
1800       }
1801       // FIXME: Don't hardcode this check
1802       if (OA && isa<OwnershipAttr>(*i))
1803         return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1804       return true;
1805     }
1806 
1807   return false;
1808 }
1809 
1810 static bool isAttributeTargetADefinition(Decl *D) {
1811   if (VarDecl *VD = dyn_cast<VarDecl>(D))
1812     return VD->isThisDeclarationADefinition();
1813   if (TagDecl *TD = dyn_cast<TagDecl>(D))
1814     return TD->isCompleteDefinition() || TD->isBeingDefined();
1815   return true;
1816 }
1817 
1818 /// Merge alignment attributes from \p Old to \p New, taking into account the
1819 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1820 ///
1821 /// \return \c true if any attributes were added to \p New.
1822 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1823   // Look for alignas attributes on Old, and pick out whichever attribute
1824   // specifies the strictest alignment requirement.
1825   AlignedAttr *OldAlignasAttr = 0;
1826   AlignedAttr *OldStrictestAlignAttr = 0;
1827   unsigned OldAlign = 0;
1828   for (specific_attr_iterator<AlignedAttr>
1829          I = Old->specific_attr_begin<AlignedAttr>(),
1830          E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1831     // FIXME: We have no way of representing inherited dependent alignments
1832     // in a case like:
1833     //   template<int A, int B> struct alignas(A) X;
1834     //   template<int A, int B> struct alignas(B) X {};
1835     // For now, we just ignore any alignas attributes which are not on the
1836     // definition in such a case.
1837     if (I->isAlignmentDependent())
1838       return false;
1839 
1840     if (I->isAlignas())
1841       OldAlignasAttr = *I;
1842 
1843     unsigned Align = I->getAlignment(S.Context);
1844     if (Align > OldAlign) {
1845       OldAlign = Align;
1846       OldStrictestAlignAttr = *I;
1847     }
1848   }
1849 
1850   // Look for alignas attributes on New.
1851   AlignedAttr *NewAlignasAttr = 0;
1852   unsigned NewAlign = 0;
1853   for (specific_attr_iterator<AlignedAttr>
1854          I = New->specific_attr_begin<AlignedAttr>(),
1855          E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1856     if (I->isAlignmentDependent())
1857       return false;
1858 
1859     if (I->isAlignas())
1860       NewAlignasAttr = *I;
1861 
1862     unsigned Align = I->getAlignment(S.Context);
1863     if (Align > NewAlign)
1864       NewAlign = Align;
1865   }
1866 
1867   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1868     // Both declarations have 'alignas' attributes. We require them to match.
1869     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1870     // fall short. (If two declarations both have alignas, they must both match
1871     // every definition, and so must match each other if there is a definition.)
1872 
1873     // If either declaration only contains 'alignas(0)' specifiers, then it
1874     // specifies the natural alignment for the type.
1875     if (OldAlign == 0 || NewAlign == 0) {
1876       QualType Ty;
1877       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1878         Ty = VD->getType();
1879       else
1880         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1881 
1882       if (OldAlign == 0)
1883         OldAlign = S.Context.getTypeAlign(Ty);
1884       if (NewAlign == 0)
1885         NewAlign = S.Context.getTypeAlign(Ty);
1886     }
1887 
1888     if (OldAlign != NewAlign) {
1889       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1890         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1891         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1892       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1893     }
1894   }
1895 
1896   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1897     // C++11 [dcl.align]p6:
1898     //   if any declaration of an entity has an alignment-specifier,
1899     //   every defining declaration of that entity shall specify an
1900     //   equivalent alignment.
1901     // C11 6.7.5/7:
1902     //   If the definition of an object does not have an alignment
1903     //   specifier, any other declaration of that object shall also
1904     //   have no alignment specifier.
1905     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1906       << OldAlignasAttr;
1907     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1908       << OldAlignasAttr;
1909   }
1910 
1911   bool AnyAdded = false;
1912 
1913   // Ensure we have an attribute representing the strictest alignment.
1914   if (OldAlign > NewAlign) {
1915     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1916     Clone->setInherited(true);
1917     New->addAttr(Clone);
1918     AnyAdded = true;
1919   }
1920 
1921   // Ensure we have an alignas attribute if the old declaration had one.
1922   if (OldAlignasAttr && !NewAlignasAttr &&
1923       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1924     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1925     Clone->setInherited(true);
1926     New->addAttr(Clone);
1927     AnyAdded = true;
1928   }
1929 
1930   return AnyAdded;
1931 }
1932 
1933 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1934                                bool Override) {
1935   InheritableAttr *NewAttr = NULL;
1936   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1937   if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1938     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1939                                       AA->getIntroduced(), AA->getDeprecated(),
1940                                       AA->getObsoleted(), AA->getUnavailable(),
1941                                       AA->getMessage(), Override,
1942                                       AttrSpellingListIndex);
1943   else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1944     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1945                                     AttrSpellingListIndex);
1946   else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1947     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1948                                         AttrSpellingListIndex);
1949   else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1950     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1951                                    AttrSpellingListIndex);
1952   else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1953     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1954                                    AttrSpellingListIndex);
1955   else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1956     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1957                                 FA->getFormatIdx(), FA->getFirstArg(),
1958                                 AttrSpellingListIndex);
1959   else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1960     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1961                                  AttrSpellingListIndex);
1962   else if (MSInheritanceAttr *IA = dyn_cast<MSInheritanceAttr>(Attr))
1963     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
1964                                        AttrSpellingListIndex,
1965                                        IA->getSemanticSpelling());
1966   else if (isa<AlignedAttr>(Attr))
1967     // AlignedAttrs are handled separately, because we need to handle all
1968     // such attributes on a declaration at the same time.
1969     NewAttr = 0;
1970   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
1971     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
1972 
1973   if (NewAttr) {
1974     NewAttr->setInherited(true);
1975     D->addAttr(NewAttr);
1976     return true;
1977   }
1978 
1979   return false;
1980 }
1981 
1982 static const Decl *getDefinition(const Decl *D) {
1983   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
1984     return TD->getDefinition();
1985   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1986     const VarDecl *Def = VD->getDefinition();
1987     if (Def)
1988       return Def;
1989     return VD->getActingDefinition();
1990   }
1991   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1992     const FunctionDecl* Def;
1993     if (FD->isDefined(Def))
1994       return Def;
1995   }
1996   return NULL;
1997 }
1998 
1999 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2000   for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2001        I != E; ++I) {
2002     Attr *Attribute = *I;
2003     if (Attribute->getKind() == Kind)
2004       return true;
2005   }
2006   return false;
2007 }
2008 
2009 /// checkNewAttributesAfterDef - If we already have a definition, check that
2010 /// there are no new attributes in this declaration.
2011 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2012   if (!New->hasAttrs())
2013     return;
2014 
2015   const Decl *Def = getDefinition(Old);
2016   if (!Def || Def == New)
2017     return;
2018 
2019   AttrVec &NewAttributes = New->getAttrs();
2020   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2021     const Attr *NewAttribute = NewAttributes[I];
2022 
2023     if (isa<AliasAttr>(NewAttribute)) {
2024       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2025         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2026       else {
2027         VarDecl *VD = cast<VarDecl>(New);
2028         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2029                                 VarDecl::TentativeDefinition
2030                             ? diag::err_alias_after_tentative
2031                             : diag::err_redefinition;
2032         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2033         S.Diag(Def->getLocation(), diag::note_previous_definition);
2034         VD->setInvalidDecl();
2035       }
2036       ++I;
2037       continue;
2038     }
2039 
2040     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2041       // Tentative definitions are only interesting for the alias check above.
2042       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2043         ++I;
2044         continue;
2045       }
2046     }
2047 
2048     if (hasAttribute(Def, NewAttribute->getKind())) {
2049       ++I;
2050       continue; // regular attr merging will take care of validating this.
2051     }
2052 
2053     if (isa<C11NoReturnAttr>(NewAttribute)) {
2054       // C's _Noreturn is allowed to be added to a function after it is defined.
2055       ++I;
2056       continue;
2057     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2058       if (AA->isAlignas()) {
2059         // C++11 [dcl.align]p6:
2060         //   if any declaration of an entity has an alignment-specifier,
2061         //   every defining declaration of that entity shall specify an
2062         //   equivalent alignment.
2063         // C11 6.7.5/7:
2064         //   If the definition of an object does not have an alignment
2065         //   specifier, any other declaration of that object shall also
2066         //   have no alignment specifier.
2067         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2068           << AA;
2069         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2070           << AA;
2071         NewAttributes.erase(NewAttributes.begin() + I);
2072         --E;
2073         continue;
2074       }
2075     }
2076 
2077     S.Diag(NewAttribute->getLocation(),
2078            diag::warn_attribute_precede_definition);
2079     S.Diag(Def->getLocation(), diag::note_previous_definition);
2080     NewAttributes.erase(NewAttributes.begin() + I);
2081     --E;
2082   }
2083 }
2084 
2085 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2086 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2087                                AvailabilityMergeKind AMK) {
2088   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2089     UsedAttr *NewAttr = OldAttr->clone(Context);
2090     NewAttr->setInherited(true);
2091     New->addAttr(NewAttr);
2092   }
2093 
2094   if (!Old->hasAttrs() && !New->hasAttrs())
2095     return;
2096 
2097   // attributes declared post-definition are currently ignored
2098   checkNewAttributesAfterDef(*this, New, Old);
2099 
2100   if (!Old->hasAttrs())
2101     return;
2102 
2103   bool foundAny = New->hasAttrs();
2104 
2105   // Ensure that any moving of objects within the allocated map is done before
2106   // we process them.
2107   if (!foundAny) New->setAttrs(AttrVec());
2108 
2109   for (specific_attr_iterator<InheritableAttr>
2110          i = Old->specific_attr_begin<InheritableAttr>(),
2111          e = Old->specific_attr_end<InheritableAttr>();
2112        i != e; ++i) {
2113     bool Override = false;
2114     // Ignore deprecated/unavailable/availability attributes if requested.
2115     if (isa<DeprecatedAttr>(*i) ||
2116         isa<UnavailableAttr>(*i) ||
2117         isa<AvailabilityAttr>(*i)) {
2118       switch (AMK) {
2119       case AMK_None:
2120         continue;
2121 
2122       case AMK_Redeclaration:
2123         break;
2124 
2125       case AMK_Override:
2126         Override = true;
2127         break;
2128       }
2129     }
2130 
2131     // Already handled.
2132     if (isa<UsedAttr>(*i))
2133       continue;
2134 
2135     if (mergeDeclAttribute(*this, New, *i, Override))
2136       foundAny = true;
2137   }
2138 
2139   if (mergeAlignedAttrs(*this, New, Old))
2140     foundAny = true;
2141 
2142   if (!foundAny) New->dropAttrs();
2143 }
2144 
2145 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2146 /// to the new one.
2147 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2148                                      const ParmVarDecl *oldDecl,
2149                                      Sema &S) {
2150   // C++11 [dcl.attr.depend]p2:
2151   //   The first declaration of a function shall specify the
2152   //   carries_dependency attribute for its declarator-id if any declaration
2153   //   of the function specifies the carries_dependency attribute.
2154   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2155   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2156     S.Diag(CDA->getLocation(),
2157            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2158     // Find the first declaration of the parameter.
2159     // FIXME: Should we build redeclaration chains for function parameters?
2160     const FunctionDecl *FirstFD =
2161       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2162     const ParmVarDecl *FirstVD =
2163       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2164     S.Diag(FirstVD->getLocation(),
2165            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2166   }
2167 
2168   if (!oldDecl->hasAttrs())
2169     return;
2170 
2171   bool foundAny = newDecl->hasAttrs();
2172 
2173   // Ensure that any moving of objects within the allocated map is
2174   // done before we process them.
2175   if (!foundAny) newDecl->setAttrs(AttrVec());
2176 
2177   for (specific_attr_iterator<InheritableParamAttr>
2178        i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2179        e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2180     if (!DeclHasAttr(newDecl, *i)) {
2181       InheritableAttr *newAttr =
2182         cast<InheritableParamAttr>((*i)->clone(S.Context));
2183       newAttr->setInherited(true);
2184       newDecl->addAttr(newAttr);
2185       foundAny = true;
2186     }
2187   }
2188 
2189   if (!foundAny) newDecl->dropAttrs();
2190 }
2191 
2192 namespace {
2193 
2194 /// Used in MergeFunctionDecl to keep track of function parameters in
2195 /// C.
2196 struct GNUCompatibleParamWarning {
2197   ParmVarDecl *OldParm;
2198   ParmVarDecl *NewParm;
2199   QualType PromotedType;
2200 };
2201 
2202 }
2203 
2204 /// getSpecialMember - get the special member enum for a method.
2205 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2206   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2207     if (Ctor->isDefaultConstructor())
2208       return Sema::CXXDefaultConstructor;
2209 
2210     if (Ctor->isCopyConstructor())
2211       return Sema::CXXCopyConstructor;
2212 
2213     if (Ctor->isMoveConstructor())
2214       return Sema::CXXMoveConstructor;
2215   } else if (isa<CXXDestructorDecl>(MD)) {
2216     return Sema::CXXDestructor;
2217   } else if (MD->isCopyAssignmentOperator()) {
2218     return Sema::CXXCopyAssignment;
2219   } else if (MD->isMoveAssignmentOperator()) {
2220     return Sema::CXXMoveAssignment;
2221   }
2222 
2223   return Sema::CXXInvalid;
2224 }
2225 
2226 /// canRedefineFunction - checks if a function can be redefined. Currently,
2227 /// only extern inline functions can be redefined, and even then only in
2228 /// GNU89 mode.
2229 static bool canRedefineFunction(const FunctionDecl *FD,
2230                                 const LangOptions& LangOpts) {
2231   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2232           !LangOpts.CPlusPlus &&
2233           FD->isInlineSpecified() &&
2234           FD->getStorageClass() == SC_Extern);
2235 }
2236 
2237 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2238   const AttributedType *AT = T->getAs<AttributedType>();
2239   while (AT && !AT->isCallingConv())
2240     AT = AT->getModifiedType()->getAs<AttributedType>();
2241   return AT;
2242 }
2243 
2244 template <typename T>
2245 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2246   const DeclContext *DC = Old->getDeclContext();
2247   if (DC->isRecord())
2248     return false;
2249 
2250   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2251   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2252     return true;
2253   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2254     return true;
2255   return false;
2256 }
2257 
2258 /// MergeFunctionDecl - We just parsed a function 'New' from
2259 /// declarator D which has the same name and scope as a previous
2260 /// declaration 'Old'.  Figure out how to resolve this situation,
2261 /// merging decls or emitting diagnostics as appropriate.
2262 ///
2263 /// In C++, New and Old must be declarations that are not
2264 /// overloaded. Use IsOverload to determine whether New and Old are
2265 /// overloaded, and to select the Old declaration that New should be
2266 /// merged with.
2267 ///
2268 /// Returns true if there was an error, false otherwise.
2269 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2270                              Scope *S, bool MergeTypeWithOld) {
2271   // Verify the old decl was also a function.
2272   FunctionDecl *Old = OldD->getAsFunction();
2273   if (!Old) {
2274     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2275       if (New->getFriendObjectKind()) {
2276         Diag(New->getLocation(), diag::err_using_decl_friend);
2277         Diag(Shadow->getTargetDecl()->getLocation(),
2278              diag::note_using_decl_target);
2279         Diag(Shadow->getUsingDecl()->getLocation(),
2280              diag::note_using_decl) << 0;
2281         return true;
2282       }
2283 
2284       // C++11 [namespace.udecl]p14:
2285       //   If a function declaration in namespace scope or block scope has the
2286       //   same name and the same parameter-type-list as a function introduced
2287       //   by a using-declaration, and the declarations do not declare the same
2288       //   function, the program is ill-formed.
2289 
2290       // Check whether the two declarations might declare the same function.
2291       Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
2292       if (Old &&
2293           !Old->getDeclContext()->getRedeclContext()->Equals(
2294               New->getDeclContext()->getRedeclContext()) &&
2295           !(Old->isExternC() && New->isExternC()))
2296         Old = 0;
2297 
2298       if (!Old) {
2299         Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2300         Diag(Shadow->getTargetDecl()->getLocation(),
2301              diag::note_using_decl_target);
2302         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2303         return true;
2304       }
2305       OldD = Old;
2306     } else {
2307       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2308         << New->getDeclName();
2309       Diag(OldD->getLocation(), diag::note_previous_definition);
2310       return true;
2311     }
2312   }
2313 
2314   // If the old declaration is invalid, just give up here.
2315   if (Old->isInvalidDecl())
2316     return true;
2317 
2318   // Determine whether the previous declaration was a definition,
2319   // implicit declaration, or a declaration.
2320   diag::kind PrevDiag;
2321   SourceLocation OldLocation = Old->getLocation();
2322   if (Old->isThisDeclarationADefinition())
2323     PrevDiag = diag::note_previous_definition;
2324   else if (Old->isImplicit()) {
2325     PrevDiag = diag::note_previous_implicit_declaration;
2326     if (OldLocation.isInvalid())
2327       OldLocation = New->getLocation();
2328   } else
2329     PrevDiag = diag::note_previous_declaration;
2330 
2331   // Don't complain about this if we're in GNU89 mode and the old function
2332   // is an extern inline function.
2333   // Don't complain about specializations. They are not supposed to have
2334   // storage classes.
2335   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2336       New->getStorageClass() == SC_Static &&
2337       Old->hasExternalFormalLinkage() &&
2338       !New->getTemplateSpecializationInfo() &&
2339       !canRedefineFunction(Old, getLangOpts())) {
2340     if (getLangOpts().MicrosoftExt) {
2341       Diag(New->getLocation(), diag::warn_static_non_static) << New;
2342       Diag(OldLocation, PrevDiag);
2343     } else {
2344       Diag(New->getLocation(), diag::err_static_non_static) << New;
2345       Diag(OldLocation, PrevDiag);
2346       return true;
2347     }
2348   }
2349 
2350 
2351   // If a function is first declared with a calling convention, but is later
2352   // declared or defined without one, all following decls assume the calling
2353   // convention of the first.
2354   //
2355   // It's OK if a function is first declared without a calling convention,
2356   // but is later declared or defined with the default calling convention.
2357   //
2358   // To test if either decl has an explicit calling convention, we look for
2359   // AttributedType sugar nodes on the type as written.  If they are missing or
2360   // were canonicalized away, we assume the calling convention was implicit.
2361   //
2362   // Note also that we DO NOT return at this point, because we still have
2363   // other tests to run.
2364   QualType OldQType = Context.getCanonicalType(Old->getType());
2365   QualType NewQType = Context.getCanonicalType(New->getType());
2366   const FunctionType *OldType = cast<FunctionType>(OldQType);
2367   const FunctionType *NewType = cast<FunctionType>(NewQType);
2368   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2369   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2370   bool RequiresAdjustment = false;
2371 
2372   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2373     FunctionDecl *First = Old->getFirstDecl();
2374     const FunctionType *FT =
2375         First->getType().getCanonicalType()->castAs<FunctionType>();
2376     FunctionType::ExtInfo FI = FT->getExtInfo();
2377     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2378     if (!NewCCExplicit) {
2379       // Inherit the CC from the previous declaration if it was specified
2380       // there but not here.
2381       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2382       RequiresAdjustment = true;
2383     } else {
2384       // Calling conventions aren't compatible, so complain.
2385       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2386       Diag(New->getLocation(), diag::err_cconv_change)
2387         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2388         << !FirstCCExplicit
2389         << (!FirstCCExplicit ? "" :
2390             FunctionType::getNameForCallConv(FI.getCC()));
2391 
2392       // Put the note on the first decl, since it is the one that matters.
2393       Diag(First->getLocation(), diag::note_previous_declaration);
2394       return true;
2395     }
2396   }
2397 
2398   // FIXME: diagnose the other way around?
2399   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2400     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2401     RequiresAdjustment = true;
2402   }
2403 
2404   // Merge regparm attribute.
2405   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2406       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2407     if (NewTypeInfo.getHasRegParm()) {
2408       Diag(New->getLocation(), diag::err_regparm_mismatch)
2409         << NewType->getRegParmType()
2410         << OldType->getRegParmType();
2411       Diag(OldLocation, diag::note_previous_declaration);
2412       return true;
2413     }
2414 
2415     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2416     RequiresAdjustment = true;
2417   }
2418 
2419   // Merge ns_returns_retained attribute.
2420   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2421     if (NewTypeInfo.getProducesResult()) {
2422       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2423       Diag(OldLocation, diag::note_previous_declaration);
2424       return true;
2425     }
2426 
2427     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2428     RequiresAdjustment = true;
2429   }
2430 
2431   if (RequiresAdjustment) {
2432     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2433     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2434     New->setType(QualType(AdjustedType, 0));
2435     NewQType = Context.getCanonicalType(New->getType());
2436     NewType = cast<FunctionType>(NewQType);
2437   }
2438 
2439   // If this redeclaration makes the function inline, we may need to add it to
2440   // UndefinedButUsed.
2441   if (!Old->isInlined() && New->isInlined() &&
2442       !New->hasAttr<GNUInlineAttr>() &&
2443       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2444       Old->isUsed(false) &&
2445       !Old->isDefined() && !New->isThisDeclarationADefinition())
2446     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2447                                            SourceLocation()));
2448 
2449   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2450   // about it.
2451   if (New->hasAttr<GNUInlineAttr>() &&
2452       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2453     UndefinedButUsed.erase(Old->getCanonicalDecl());
2454   }
2455 
2456   if (getLangOpts().CPlusPlus) {
2457     // (C++98 13.1p2):
2458     //   Certain function declarations cannot be overloaded:
2459     //     -- Function declarations that differ only in the return type
2460     //        cannot be overloaded.
2461 
2462     // Go back to the type source info to compare the declared return types,
2463     // per C++1y [dcl.type.auto]p13:
2464     //   Redeclarations or specializations of a function or function template
2465     //   with a declared return type that uses a placeholder type shall also
2466     //   use that placeholder, not a deduced type.
2467     QualType OldDeclaredReturnType =
2468         (Old->getTypeSourceInfo()
2469              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2470              : OldType)->getReturnType();
2471     QualType NewDeclaredReturnType =
2472         (New->getTypeSourceInfo()
2473              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2474              : NewType)->getReturnType();
2475     QualType ResQT;
2476     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2477         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2478           New->isLocalExternDecl())) {
2479       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2480           OldDeclaredReturnType->isObjCObjectPointerType())
2481         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2482       if (ResQT.isNull()) {
2483         if (New->isCXXClassMember() && New->isOutOfLine())
2484           Diag(New->getLocation(),
2485                diag::err_member_def_does_not_match_ret_type) << New;
2486         else
2487           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2488         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2489         return true;
2490       }
2491       else
2492         NewQType = ResQT;
2493     }
2494 
2495     QualType OldReturnType = OldType->getReturnType();
2496     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2497     if (OldReturnType != NewReturnType) {
2498       // If this function has a deduced return type and has already been
2499       // defined, copy the deduced value from the old declaration.
2500       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2501       if (OldAT && OldAT->isDeduced()) {
2502         New->setType(
2503             SubstAutoType(New->getType(),
2504                           OldAT->isDependentType() ? Context.DependentTy
2505                                                    : OldAT->getDeducedType()));
2506         NewQType = Context.getCanonicalType(
2507             SubstAutoType(NewQType,
2508                           OldAT->isDependentType() ? Context.DependentTy
2509                                                    : OldAT->getDeducedType()));
2510       }
2511     }
2512 
2513     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2514     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2515     if (OldMethod && NewMethod) {
2516       // Preserve triviality.
2517       NewMethod->setTrivial(OldMethod->isTrivial());
2518 
2519       // MSVC allows explicit template specialization at class scope:
2520       // 2 CXXMethodDecls referring to the same function will be injected.
2521       // We don't want a redeclaration error.
2522       bool IsClassScopeExplicitSpecialization =
2523                               OldMethod->isFunctionTemplateSpecialization() &&
2524                               NewMethod->isFunctionTemplateSpecialization();
2525       bool isFriend = NewMethod->getFriendObjectKind();
2526 
2527       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2528           !IsClassScopeExplicitSpecialization) {
2529         //    -- Member function declarations with the same name and the
2530         //       same parameter types cannot be overloaded if any of them
2531         //       is a static member function declaration.
2532         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2533           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2534           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2535           return true;
2536         }
2537 
2538         // C++ [class.mem]p1:
2539         //   [...] A member shall not be declared twice in the
2540         //   member-specification, except that a nested class or member
2541         //   class template can be declared and then later defined.
2542         if (ActiveTemplateInstantiations.empty()) {
2543           unsigned NewDiag;
2544           if (isa<CXXConstructorDecl>(OldMethod))
2545             NewDiag = diag::err_constructor_redeclared;
2546           else if (isa<CXXDestructorDecl>(NewMethod))
2547             NewDiag = diag::err_destructor_redeclared;
2548           else if (isa<CXXConversionDecl>(NewMethod))
2549             NewDiag = diag::err_conv_function_redeclared;
2550           else
2551             NewDiag = diag::err_member_redeclared;
2552 
2553           Diag(New->getLocation(), NewDiag);
2554         } else {
2555           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2556             << New << New->getType();
2557         }
2558         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2559 
2560       // Complain if this is an explicit declaration of a special
2561       // member that was initially declared implicitly.
2562       //
2563       // As an exception, it's okay to befriend such methods in order
2564       // to permit the implicit constructor/destructor/operator calls.
2565       } else if (OldMethod->isImplicit()) {
2566         if (isFriend) {
2567           NewMethod->setImplicit();
2568         } else {
2569           Diag(NewMethod->getLocation(),
2570                diag::err_definition_of_implicitly_declared_member)
2571             << New << getSpecialMember(OldMethod);
2572           return true;
2573         }
2574       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2575         Diag(NewMethod->getLocation(),
2576              diag::err_definition_of_explicitly_defaulted_member)
2577           << getSpecialMember(OldMethod);
2578         return true;
2579       }
2580     }
2581 
2582     // C++11 [dcl.attr.noreturn]p1:
2583     //   The first declaration of a function shall specify the noreturn
2584     //   attribute if any declaration of that function specifies the noreturn
2585     //   attribute.
2586     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2587     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2588       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2589       Diag(Old->getFirstDecl()->getLocation(),
2590            diag::note_noreturn_missing_first_decl);
2591     }
2592 
2593     // C++11 [dcl.attr.depend]p2:
2594     //   The first declaration of a function shall specify the
2595     //   carries_dependency attribute for its declarator-id if any declaration
2596     //   of the function specifies the carries_dependency attribute.
2597     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2598     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2599       Diag(CDA->getLocation(),
2600            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2601       Diag(Old->getFirstDecl()->getLocation(),
2602            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2603     }
2604 
2605     // (C++98 8.3.5p3):
2606     //   All declarations for a function shall agree exactly in both the
2607     //   return type and the parameter-type-list.
2608     // We also want to respect all the extended bits except noreturn.
2609 
2610     // noreturn should now match unless the old type info didn't have it.
2611     QualType OldQTypeForComparison = OldQType;
2612     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2613       assert(OldQType == QualType(OldType, 0));
2614       const FunctionType *OldTypeForComparison
2615         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2616       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2617       assert(OldQTypeForComparison.isCanonical());
2618     }
2619 
2620     if (haveIncompatibleLanguageLinkages(Old, New)) {
2621       // As a special case, retain the language linkage from previous
2622       // declarations of a friend function as an extension.
2623       //
2624       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2625       // and is useful because there's otherwise no way to specify language
2626       // linkage within class scope.
2627       //
2628       // Check cautiously as the friend object kind isn't yet complete.
2629       if (New->getFriendObjectKind() != Decl::FOK_None) {
2630         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2631         Diag(OldLocation, PrevDiag);
2632       } else {
2633         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2634         Diag(OldLocation, PrevDiag);
2635         return true;
2636       }
2637     }
2638 
2639     if (OldQTypeForComparison == NewQType)
2640       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2641 
2642     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2643         New->isLocalExternDecl()) {
2644       // It's OK if we couldn't merge types for a local function declaraton
2645       // if either the old or new type is dependent. We'll merge the types
2646       // when we instantiate the function.
2647       return false;
2648     }
2649 
2650     // Fall through for conflicting redeclarations and redefinitions.
2651   }
2652 
2653   // C: Function types need to be compatible, not identical. This handles
2654   // duplicate function decls like "void f(int); void f(enum X);" properly.
2655   if (!getLangOpts().CPlusPlus &&
2656       Context.typesAreCompatible(OldQType, NewQType)) {
2657     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2658     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2659     const FunctionProtoType *OldProto = 0;
2660     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2661         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2662       // The old declaration provided a function prototype, but the
2663       // new declaration does not. Merge in the prototype.
2664       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2665       SmallVector<QualType, 16> ParamTypes(OldProto->param_type_begin(),
2666                                            OldProto->param_type_end());
2667       NewQType =
2668           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
2669                                   OldProto->getExtProtoInfo());
2670       New->setType(NewQType);
2671       New->setHasInheritedPrototype();
2672 
2673       // Synthesize a parameter for each argument type.
2674       SmallVector<ParmVarDecl*, 16> Params;
2675       for (FunctionProtoType::param_type_iterator
2676                ParamType = OldProto->param_type_begin(),
2677                ParamEnd = OldProto->param_type_end();
2678            ParamType != ParamEnd; ++ParamType) {
2679         ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2680                                                  SourceLocation(),
2681                                                  SourceLocation(), 0,
2682                                                  *ParamType, /*TInfo=*/0,
2683                                                  SC_None,
2684                                                  0);
2685         Param->setScopeInfo(0, Params.size());
2686         Param->setImplicit();
2687         Params.push_back(Param);
2688       }
2689 
2690       New->setParams(Params);
2691     }
2692 
2693     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2694   }
2695 
2696   // GNU C permits a K&R definition to follow a prototype declaration
2697   // if the declared types of the parameters in the K&R definition
2698   // match the types in the prototype declaration, even when the
2699   // promoted types of the parameters from the K&R definition differ
2700   // from the types in the prototype. GCC then keeps the types from
2701   // the prototype.
2702   //
2703   // If a variadic prototype is followed by a non-variadic K&R definition,
2704   // the K&R definition becomes variadic.  This is sort of an edge case, but
2705   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2706   // C99 6.9.1p8.
2707   if (!getLangOpts().CPlusPlus &&
2708       Old->hasPrototype() && !New->hasPrototype() &&
2709       New->getType()->getAs<FunctionProtoType>() &&
2710       Old->getNumParams() == New->getNumParams()) {
2711     SmallVector<QualType, 16> ArgTypes;
2712     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2713     const FunctionProtoType *OldProto
2714       = Old->getType()->getAs<FunctionProtoType>();
2715     const FunctionProtoType *NewProto
2716       = New->getType()->getAs<FunctionProtoType>();
2717 
2718     // Determine whether this is the GNU C extension.
2719     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
2720                                                NewProto->getReturnType());
2721     bool LooseCompatible = !MergedReturn.isNull();
2722     for (unsigned Idx = 0, End = Old->getNumParams();
2723          LooseCompatible && Idx != End; ++Idx) {
2724       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2725       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2726       if (Context.typesAreCompatible(OldParm->getType(),
2727                                      NewProto->getParamType(Idx))) {
2728         ArgTypes.push_back(NewParm->getType());
2729       } else if (Context.typesAreCompatible(OldParm->getType(),
2730                                             NewParm->getType(),
2731                                             /*CompareUnqualified=*/true)) {
2732         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
2733                                            NewProto->getParamType(Idx) };
2734         Warnings.push_back(Warn);
2735         ArgTypes.push_back(NewParm->getType());
2736       } else
2737         LooseCompatible = false;
2738     }
2739 
2740     if (LooseCompatible) {
2741       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2742         Diag(Warnings[Warn].NewParm->getLocation(),
2743              diag::ext_param_promoted_not_compatible_with_prototype)
2744           << Warnings[Warn].PromotedType
2745           << Warnings[Warn].OldParm->getType();
2746         if (Warnings[Warn].OldParm->getLocation().isValid())
2747           Diag(Warnings[Warn].OldParm->getLocation(),
2748                diag::note_previous_declaration);
2749       }
2750 
2751       if (MergeTypeWithOld)
2752         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2753                                              OldProto->getExtProtoInfo()));
2754       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2755     }
2756 
2757     // Fall through to diagnose conflicting types.
2758   }
2759 
2760   // A function that has already been declared has been redeclared or
2761   // defined with a different type; show an appropriate diagnostic.
2762 
2763   // If the previous declaration was an implicitly-generated builtin
2764   // declaration, then at the very least we should use a specialized note.
2765   unsigned BuiltinID;
2766   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2767     // If it's actually a library-defined builtin function like 'malloc'
2768     // or 'printf', just warn about the incompatible redeclaration.
2769     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2770       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2771       Diag(OldLocation, diag::note_previous_builtin_declaration)
2772         << Old << Old->getType();
2773 
2774       // If this is a global redeclaration, just forget hereafter
2775       // about the "builtin-ness" of the function.
2776       //
2777       // Doing this for local extern declarations is problematic.  If
2778       // the builtin declaration remains visible, a second invalid
2779       // local declaration will produce a hard error; if it doesn't
2780       // remain visible, a single bogus local redeclaration (which is
2781       // actually only a warning) could break all the downstream code.
2782       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2783         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2784 
2785       return false;
2786     }
2787 
2788     PrevDiag = diag::note_previous_builtin_declaration;
2789   }
2790 
2791   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2792   Diag(OldLocation, PrevDiag) << Old << Old->getType();
2793   return true;
2794 }
2795 
2796 /// \brief Completes the merge of two function declarations that are
2797 /// known to be compatible.
2798 ///
2799 /// This routine handles the merging of attributes and other
2800 /// properties of function declarations from the old declaration to
2801 /// the new declaration, once we know that New is in fact a
2802 /// redeclaration of Old.
2803 ///
2804 /// \returns false
2805 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2806                                         Scope *S, bool MergeTypeWithOld) {
2807   // Merge the attributes
2808   mergeDeclAttributes(New, Old);
2809 
2810   // Merge "pure" flag.
2811   if (Old->isPure())
2812     New->setPure();
2813 
2814   // Merge "used" flag.
2815   if (Old->getMostRecentDecl()->isUsed(false))
2816     New->setIsUsed();
2817 
2818   // Merge attributes from the parameters.  These can mismatch with K&R
2819   // declarations.
2820   if (New->getNumParams() == Old->getNumParams())
2821     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2822       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2823                                *this);
2824 
2825   if (getLangOpts().CPlusPlus)
2826     return MergeCXXFunctionDecl(New, Old, S);
2827 
2828   // Merge the function types so the we get the composite types for the return
2829   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2830   // was visible.
2831   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2832   if (!Merged.isNull() && MergeTypeWithOld)
2833     New->setType(Merged);
2834 
2835   return false;
2836 }
2837 
2838 
2839 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2840                                 ObjCMethodDecl *oldMethod) {
2841 
2842   // Merge the attributes, including deprecated/unavailable
2843   AvailabilityMergeKind MergeKind =
2844     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2845                                                    : AMK_Override;
2846   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
2847 
2848   // Merge attributes from the parameters.
2849   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2850                                        oe = oldMethod->param_end();
2851   for (ObjCMethodDecl::param_iterator
2852          ni = newMethod->param_begin(), ne = newMethod->param_end();
2853        ni != ne && oi != oe; ++ni, ++oi)
2854     mergeParamDeclAttributes(*ni, *oi, *this);
2855 
2856   CheckObjCMethodOverride(newMethod, oldMethod);
2857 }
2858 
2859 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2860 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2861 /// emitting diagnostics as appropriate.
2862 ///
2863 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2864 /// to here in AddInitializerToDecl. We can't check them before the initializer
2865 /// is attached.
2866 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2867                              bool MergeTypeWithOld) {
2868   if (New->isInvalidDecl() || Old->isInvalidDecl())
2869     return;
2870 
2871   QualType MergedT;
2872   if (getLangOpts().CPlusPlus) {
2873     if (New->getType()->isUndeducedType()) {
2874       // We don't know what the new type is until the initializer is attached.
2875       return;
2876     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2877       // These could still be something that needs exception specs checked.
2878       return MergeVarDeclExceptionSpecs(New, Old);
2879     }
2880     // C++ [basic.link]p10:
2881     //   [...] the types specified by all declarations referring to a given
2882     //   object or function shall be identical, except that declarations for an
2883     //   array object can specify array types that differ by the presence or
2884     //   absence of a major array bound (8.3.4).
2885     else if (Old->getType()->isIncompleteArrayType() &&
2886              New->getType()->isArrayType()) {
2887       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2888       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2889       if (Context.hasSameType(OldArray->getElementType(),
2890                               NewArray->getElementType()))
2891         MergedT = New->getType();
2892     } else if (Old->getType()->isArrayType() &&
2893                New->getType()->isIncompleteArrayType()) {
2894       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2895       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2896       if (Context.hasSameType(OldArray->getElementType(),
2897                               NewArray->getElementType()))
2898         MergedT = Old->getType();
2899     } else if (New->getType()->isObjCObjectPointerType() &&
2900                Old->getType()->isObjCObjectPointerType()) {
2901       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2902                                               Old->getType());
2903     }
2904   } else {
2905     // C 6.2.7p2:
2906     //   All declarations that refer to the same object or function shall have
2907     //   compatible type.
2908     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2909   }
2910   if (MergedT.isNull()) {
2911     // It's OK if we couldn't merge types if either type is dependent, for a
2912     // block-scope variable. In other cases (static data members of class
2913     // templates, variable templates, ...), we require the types to be
2914     // equivalent.
2915     // FIXME: The C++ standard doesn't say anything about this.
2916     if ((New->getType()->isDependentType() ||
2917          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2918       // If the old type was dependent, we can't merge with it, so the new type
2919       // becomes dependent for now. We'll reproduce the original type when we
2920       // instantiate the TypeSourceInfo for the variable.
2921       if (!New->getType()->isDependentType() && MergeTypeWithOld)
2922         New->setType(Context.DependentTy);
2923       return;
2924     }
2925 
2926     // FIXME: Even if this merging succeeds, some other non-visible declaration
2927     // of this variable might have an incompatible type. For instance:
2928     //
2929     //   extern int arr[];
2930     //   void f() { extern int arr[2]; }
2931     //   void g() { extern int arr[3]; }
2932     //
2933     // Neither C nor C++ requires a diagnostic for this, but we should still try
2934     // to diagnose it.
2935     Diag(New->getLocation(), diag::err_redefinition_different_type)
2936       << New->getDeclName() << New->getType() << Old->getType();
2937     Diag(Old->getLocation(), diag::note_previous_definition);
2938     return New->setInvalidDecl();
2939   }
2940 
2941   // Don't actually update the type on the new declaration if the old
2942   // declaration was an extern declaration in a different scope.
2943   if (MergeTypeWithOld)
2944     New->setType(MergedT);
2945 }
2946 
2947 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2948                                   LookupResult &Previous) {
2949   // C11 6.2.7p4:
2950   //   For an identifier with internal or external linkage declared
2951   //   in a scope in which a prior declaration of that identifier is
2952   //   visible, if the prior declaration specifies internal or
2953   //   external linkage, the type of the identifier at the later
2954   //   declaration becomes the composite type.
2955   //
2956   // If the variable isn't visible, we do not merge with its type.
2957   if (Previous.isShadowed())
2958     return false;
2959 
2960   if (S.getLangOpts().CPlusPlus) {
2961     // C++11 [dcl.array]p3:
2962     //   If there is a preceding declaration of the entity in the same
2963     //   scope in which the bound was specified, an omitted array bound
2964     //   is taken to be the same as in that earlier declaration.
2965     return NewVD->isPreviousDeclInSameBlockScope() ||
2966            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2967             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2968   } else {
2969     // If the old declaration was function-local, don't merge with its
2970     // type unless we're in the same function.
2971     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2972            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2973   }
2974 }
2975 
2976 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2977 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2978 /// situation, merging decls or emitting diagnostics as appropriate.
2979 ///
2980 /// Tentative definition rules (C99 6.9.2p2) are checked by
2981 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2982 /// definitions here, since the initializer hasn't been attached.
2983 ///
2984 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2985   // If the new decl is already invalid, don't do any other checking.
2986   if (New->isInvalidDecl())
2987     return;
2988 
2989   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
2990 
2991   // Verify the old decl was also a variable or variable template.
2992   VarDecl *Old = 0;
2993   VarTemplateDecl *OldTemplate = 0;
2994   if (Previous.isSingleResult()) {
2995     if (NewTemplate) {
2996       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
2997       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
2998     } else
2999       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3000   }
3001   if (!Old) {
3002     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3003       << New->getDeclName();
3004     Diag(Previous.getRepresentativeDecl()->getLocation(),
3005          diag::note_previous_definition);
3006     return New->setInvalidDecl();
3007   }
3008 
3009   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3010     return;
3011 
3012   // Ensure the template parameters are compatible.
3013   if (NewTemplate &&
3014       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3015                                       OldTemplate->getTemplateParameters(),
3016                                       /*Complain=*/true, TPL_TemplateMatch))
3017     return;
3018 
3019   // C++ [class.mem]p1:
3020   //   A member shall not be declared twice in the member-specification [...]
3021   //
3022   // Here, we need only consider static data members.
3023   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3024     Diag(New->getLocation(), diag::err_duplicate_member)
3025       << New->getIdentifier();
3026     Diag(Old->getLocation(), diag::note_previous_declaration);
3027     New->setInvalidDecl();
3028   }
3029 
3030   mergeDeclAttributes(New, Old);
3031   // Warn if an already-declared variable is made a weak_import in a subsequent
3032   // declaration
3033   if (New->hasAttr<WeakImportAttr>() &&
3034       Old->getStorageClass() == SC_None &&
3035       !Old->hasAttr<WeakImportAttr>()) {
3036     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3037     Diag(Old->getLocation(), diag::note_previous_definition);
3038     // Remove weak_import attribute on new declaration.
3039     New->dropAttr<WeakImportAttr>();
3040   }
3041 
3042   // Merge the types.
3043   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3044 
3045   if (New->isInvalidDecl())
3046     return;
3047 
3048   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3049   if (New->getStorageClass() == SC_Static &&
3050       !New->isStaticDataMember() &&
3051       Old->hasExternalFormalLinkage()) {
3052     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
3053     Diag(Old->getLocation(), diag::note_previous_definition);
3054     return New->setInvalidDecl();
3055   }
3056   // C99 6.2.2p4:
3057   //   For an identifier declared with the storage-class specifier
3058   //   extern in a scope in which a prior declaration of that
3059   //   identifier is visible,23) if the prior declaration specifies
3060   //   internal or external linkage, the linkage of the identifier at
3061   //   the later declaration is the same as the linkage specified at
3062   //   the prior declaration. If no prior declaration is visible, or
3063   //   if the prior declaration specifies no linkage, then the
3064   //   identifier has external linkage.
3065   if (New->hasExternalStorage() && Old->hasLinkage())
3066     /* Okay */;
3067   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3068            !New->isStaticDataMember() &&
3069            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3070     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3071     Diag(Old->getLocation(), diag::note_previous_definition);
3072     return New->setInvalidDecl();
3073   }
3074 
3075   // Check if extern is followed by non-extern and vice-versa.
3076   if (New->hasExternalStorage() &&
3077       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3078     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3079     Diag(Old->getLocation(), diag::note_previous_definition);
3080     return New->setInvalidDecl();
3081   }
3082   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3083       !New->hasExternalStorage()) {
3084     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3085     Diag(Old->getLocation(), diag::note_previous_definition);
3086     return New->setInvalidDecl();
3087   }
3088 
3089   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3090 
3091   // FIXME: The test for external storage here seems wrong? We still
3092   // need to check for mismatches.
3093   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3094       // Don't complain about out-of-line definitions of static members.
3095       !(Old->getLexicalDeclContext()->isRecord() &&
3096         !New->getLexicalDeclContext()->isRecord())) {
3097     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3098     Diag(Old->getLocation(), diag::note_previous_definition);
3099     return New->setInvalidDecl();
3100   }
3101 
3102   if (New->getTLSKind() != Old->getTLSKind()) {
3103     if (!Old->getTLSKind()) {
3104       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3105       Diag(Old->getLocation(), diag::note_previous_declaration);
3106     } else if (!New->getTLSKind()) {
3107       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3108       Diag(Old->getLocation(), diag::note_previous_declaration);
3109     } else {
3110       // Do not allow redeclaration to change the variable between requiring
3111       // static and dynamic initialization.
3112       // FIXME: GCC allows this, but uses the TLS keyword on the first
3113       // declaration to determine the kind. Do we need to be compatible here?
3114       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3115         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3116       Diag(Old->getLocation(), diag::note_previous_declaration);
3117     }
3118   }
3119 
3120   // C++ doesn't have tentative definitions, so go right ahead and check here.
3121   const VarDecl *Def;
3122   if (getLangOpts().CPlusPlus &&
3123       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3124       (Def = Old->getDefinition())) {
3125     Diag(New->getLocation(), diag::err_redefinition) << New;
3126     Diag(Def->getLocation(), diag::note_previous_definition);
3127     New->setInvalidDecl();
3128     return;
3129   }
3130 
3131   if (haveIncompatibleLanguageLinkages(Old, New)) {
3132     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3133     Diag(Old->getLocation(), diag::note_previous_definition);
3134     New->setInvalidDecl();
3135     return;
3136   }
3137 
3138   // Merge "used" flag.
3139   if (Old->getMostRecentDecl()->isUsed(false))
3140     New->setIsUsed();
3141 
3142   // Keep a chain of previous declarations.
3143   New->setPreviousDecl(Old);
3144   if (NewTemplate)
3145     NewTemplate->setPreviousDecl(OldTemplate);
3146 
3147   // Inherit access appropriately.
3148   New->setAccess(Old->getAccess());
3149   if (NewTemplate)
3150     NewTemplate->setAccess(New->getAccess());
3151 }
3152 
3153 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3154 /// no declarator (e.g. "struct foo;") is parsed.
3155 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3156                                        DeclSpec &DS) {
3157   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3158 }
3159 
3160 static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
3161   if (!S.Context.getLangOpts().CPlusPlus)
3162     return;
3163 
3164   if (isa<CXXRecordDecl>(Tag->getParent())) {
3165     // If this tag is the direct child of a class, number it if
3166     // it is anonymous.
3167     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3168       return;
3169     MangleNumberingContext &MCtx =
3170         S.Context.getManglingNumberContext(Tag->getParent());
3171     S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3172     return;
3173   }
3174 
3175   // If this tag isn't a direct child of a class, number it if it is local.
3176   Decl *ManglingContextDecl;
3177   if (MangleNumberingContext *MCtx =
3178           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3179                                           ManglingContextDecl)) {
3180     S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3181   }
3182 }
3183 
3184 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3185 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3186 /// parameters to cope with template friend declarations.
3187 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3188                                        DeclSpec &DS,
3189                                        MultiTemplateParamsArg TemplateParams,
3190                                        bool IsExplicitInstantiation) {
3191   Decl *TagD = 0;
3192   TagDecl *Tag = 0;
3193   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3194       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3195       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3196       DS.getTypeSpecType() == DeclSpec::TST_union ||
3197       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3198     TagD = DS.getRepAsDecl();
3199 
3200     if (!TagD) // We probably had an error
3201       return 0;
3202 
3203     // Note that the above type specs guarantee that the
3204     // type rep is a Decl, whereas in many of the others
3205     // it's a Type.
3206     if (isa<TagDecl>(TagD))
3207       Tag = cast<TagDecl>(TagD);
3208     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3209       Tag = CTD->getTemplatedDecl();
3210   }
3211 
3212   if (Tag) {
3213     HandleTagNumbering(*this, Tag);
3214     Tag->setFreeStanding();
3215     if (Tag->isInvalidDecl())
3216       return Tag;
3217   }
3218 
3219   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3220     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3221     // or incomplete types shall not be restrict-qualified."
3222     if (TypeQuals & DeclSpec::TQ_restrict)
3223       Diag(DS.getRestrictSpecLoc(),
3224            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3225            << DS.getSourceRange();
3226   }
3227 
3228   if (DS.isConstexprSpecified()) {
3229     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3230     // and definitions of functions and variables.
3231     if (Tag)
3232       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3233         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3234             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3235             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3236             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3237     else
3238       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3239     // Don't emit warnings after this error.
3240     return TagD;
3241   }
3242 
3243   DiagnoseFunctionSpecifiers(DS);
3244 
3245   if (DS.isFriendSpecified()) {
3246     // If we're dealing with a decl but not a TagDecl, assume that
3247     // whatever routines created it handled the friendship aspect.
3248     if (TagD && !Tag)
3249       return 0;
3250     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3251   }
3252 
3253   CXXScopeSpec &SS = DS.getTypeSpecScope();
3254   bool IsExplicitSpecialization =
3255     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3256   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3257       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3258     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3259     // nested-name-specifier unless it is an explicit instantiation
3260     // or an explicit specialization.
3261     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3262     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3263       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3264           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3265           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3266           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3267       << SS.getRange();
3268     return 0;
3269   }
3270 
3271   // Track whether this decl-specifier declares anything.
3272   bool DeclaresAnything = true;
3273 
3274   // Handle anonymous struct definitions.
3275   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3276     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3277         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3278       if (getLangOpts().CPlusPlus ||
3279           Record->getDeclContext()->isRecord())
3280         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
3281 
3282       DeclaresAnything = false;
3283     }
3284   }
3285 
3286   // Check for Microsoft C extension: anonymous struct member.
3287   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3288       CurContext->isRecord() &&
3289       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3290     // Handle 2 kinds of anonymous struct:
3291     //   struct STRUCT;
3292     // and
3293     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3294     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3295     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3296         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3297          DS.getRepAsType().get()->isStructureType())) {
3298       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3299         << DS.getSourceRange();
3300       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3301     }
3302   }
3303 
3304   // Skip all the checks below if we have a type error.
3305   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3306       (TagD && TagD->isInvalidDecl()))
3307     return TagD;
3308 
3309   if (getLangOpts().CPlusPlus &&
3310       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3311     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3312       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3313           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3314         DeclaresAnything = false;
3315 
3316   if (!DS.isMissingDeclaratorOk()) {
3317     // Customize diagnostic for a typedef missing a name.
3318     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3319       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3320         << DS.getSourceRange();
3321     else
3322       DeclaresAnything = false;
3323   }
3324 
3325   if (DS.isModulePrivateSpecified() &&
3326       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3327     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3328       << Tag->getTagKind()
3329       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3330 
3331   ActOnDocumentableDecl(TagD);
3332 
3333   // C 6.7/2:
3334   //   A declaration [...] shall declare at least a declarator [...], a tag,
3335   //   or the members of an enumeration.
3336   // C++ [dcl.dcl]p3:
3337   //   [If there are no declarators], and except for the declaration of an
3338   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3339   //   names into the program, or shall redeclare a name introduced by a
3340   //   previous declaration.
3341   if (!DeclaresAnything) {
3342     // In C, we allow this as a (popular) extension / bug. Don't bother
3343     // producing further diagnostics for redundant qualifiers after this.
3344     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3345     return TagD;
3346   }
3347 
3348   // C++ [dcl.stc]p1:
3349   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3350   //   init-declarator-list of the declaration shall not be empty.
3351   // C++ [dcl.fct.spec]p1:
3352   //   If a cv-qualifier appears in a decl-specifier-seq, the
3353   //   init-declarator-list of the declaration shall not be empty.
3354   //
3355   // Spurious qualifiers here appear to be valid in C.
3356   unsigned DiagID = diag::warn_standalone_specifier;
3357   if (getLangOpts().CPlusPlus)
3358     DiagID = diag::ext_standalone_specifier;
3359 
3360   // Note that a linkage-specification sets a storage class, but
3361   // 'extern "C" struct foo;' is actually valid and not theoretically
3362   // useless.
3363   if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3364     if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3365       Diag(DS.getStorageClassSpecLoc(), DiagID)
3366         << DeclSpec::getSpecifierName(SCS);
3367 
3368   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3369     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3370       << DeclSpec::getSpecifierName(TSCS);
3371   if (DS.getTypeQualifiers()) {
3372     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3373       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3374     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3375       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3376     // Restrict is covered above.
3377     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3378       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3379   }
3380 
3381   // Warn about ignored type attributes, for example:
3382   // __attribute__((aligned)) struct A;
3383   // Attributes should be placed after tag to apply to type declaration.
3384   if (!DS.getAttributes().empty()) {
3385     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3386     if (TypeSpecType == DeclSpec::TST_class ||
3387         TypeSpecType == DeclSpec::TST_struct ||
3388         TypeSpecType == DeclSpec::TST_interface ||
3389         TypeSpecType == DeclSpec::TST_union ||
3390         TypeSpecType == DeclSpec::TST_enum) {
3391       AttributeList* attrs = DS.getAttributes().getList();
3392       while (attrs) {
3393         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3394         << attrs->getName()
3395         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3396             TypeSpecType == DeclSpec::TST_struct ? 1 :
3397             TypeSpecType == DeclSpec::TST_union ? 2 :
3398             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3399         attrs = attrs->getNext();
3400       }
3401     }
3402   }
3403 
3404   return TagD;
3405 }
3406 
3407 /// We are trying to inject an anonymous member into the given scope;
3408 /// check if there's an existing declaration that can't be overloaded.
3409 ///
3410 /// \return true if this is a forbidden redeclaration
3411 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3412                                          Scope *S,
3413                                          DeclContext *Owner,
3414                                          DeclarationName Name,
3415                                          SourceLocation NameLoc,
3416                                          unsigned diagnostic) {
3417   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3418                  Sema::ForRedeclaration);
3419   if (!SemaRef.LookupName(R, S)) return false;
3420 
3421   if (R.getAsSingle<TagDecl>())
3422     return false;
3423 
3424   // Pick a representative declaration.
3425   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3426   assert(PrevDecl && "Expected a non-null Decl");
3427 
3428   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3429     return false;
3430 
3431   SemaRef.Diag(NameLoc, diagnostic) << Name;
3432   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3433 
3434   return true;
3435 }
3436 
3437 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3438 /// anonymous struct or union AnonRecord into the owning context Owner
3439 /// and scope S. This routine will be invoked just after we realize
3440 /// that an unnamed union or struct is actually an anonymous union or
3441 /// struct, e.g.,
3442 ///
3443 /// @code
3444 /// union {
3445 ///   int i;
3446 ///   float f;
3447 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3448 ///    // f into the surrounding scope.x
3449 /// @endcode
3450 ///
3451 /// This routine is recursive, injecting the names of nested anonymous
3452 /// structs/unions into the owning context and scope as well.
3453 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3454                                          DeclContext *Owner,
3455                                          RecordDecl *AnonRecord,
3456                                          AccessSpecifier AS,
3457                                          SmallVectorImpl<NamedDecl *> &Chaining,
3458                                          bool MSAnonStruct) {
3459   unsigned diagKind
3460     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3461                             : diag::err_anonymous_struct_member_redecl;
3462 
3463   bool Invalid = false;
3464 
3465   // Look every FieldDecl and IndirectFieldDecl with a name.
3466   for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3467                                DEnd = AnonRecord->decls_end();
3468        D != DEnd; ++D) {
3469     if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3470         cast<NamedDecl>(*D)->getDeclName()) {
3471       ValueDecl *VD = cast<ValueDecl>(*D);
3472       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3473                                        VD->getLocation(), diagKind)) {
3474         // C++ [class.union]p2:
3475         //   The names of the members of an anonymous union shall be
3476         //   distinct from the names of any other entity in the
3477         //   scope in which the anonymous union is declared.
3478         Invalid = true;
3479       } else {
3480         // C++ [class.union]p2:
3481         //   For the purpose of name lookup, after the anonymous union
3482         //   definition, the members of the anonymous union are
3483         //   considered to have been defined in the scope in which the
3484         //   anonymous union is declared.
3485         unsigned OldChainingSize = Chaining.size();
3486         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3487           for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3488                PE = IF->chain_end(); PI != PE; ++PI)
3489             Chaining.push_back(*PI);
3490         else
3491           Chaining.push_back(VD);
3492 
3493         assert(Chaining.size() >= 2);
3494         NamedDecl **NamedChain =
3495           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3496         for (unsigned i = 0; i < Chaining.size(); i++)
3497           NamedChain[i] = Chaining[i];
3498 
3499         IndirectFieldDecl* IndirectField =
3500           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3501                                     VD->getIdentifier(), VD->getType(),
3502                                     NamedChain, Chaining.size());
3503 
3504         IndirectField->setAccess(AS);
3505         IndirectField->setImplicit();
3506         SemaRef.PushOnScopeChains(IndirectField, S);
3507 
3508         // That includes picking up the appropriate access specifier.
3509         if (AS != AS_none) IndirectField->setAccess(AS);
3510 
3511         Chaining.resize(OldChainingSize);
3512       }
3513     }
3514   }
3515 
3516   return Invalid;
3517 }
3518 
3519 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3520 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3521 /// illegal input values are mapped to SC_None.
3522 static StorageClass
3523 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3524   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3525   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3526          "Parser allowed 'typedef' as storage class VarDecl.");
3527   switch (StorageClassSpec) {
3528   case DeclSpec::SCS_unspecified:    return SC_None;
3529   case DeclSpec::SCS_extern:
3530     if (DS.isExternInLinkageSpec())
3531       return SC_None;
3532     return SC_Extern;
3533   case DeclSpec::SCS_static:         return SC_Static;
3534   case DeclSpec::SCS_auto:           return SC_Auto;
3535   case DeclSpec::SCS_register:       return SC_Register;
3536   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3537     // Illegal SCSs map to None: error reporting is up to the caller.
3538   case DeclSpec::SCS_mutable:        // Fall through.
3539   case DeclSpec::SCS_typedef:        return SC_None;
3540   }
3541   llvm_unreachable("unknown storage class specifier");
3542 }
3543 
3544 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3545   assert(Record->hasInClassInitializer());
3546 
3547   for (DeclContext::decl_iterator I = Record->decls_begin(),
3548                                   E = Record->decls_end();
3549        I != E; ++I) {
3550     FieldDecl *FD = dyn_cast<FieldDecl>(*I);
3551     if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
3552       FD = IFD->getAnonField();
3553     if (FD && FD->hasInClassInitializer())
3554       return FD->getLocation();
3555   }
3556 
3557   llvm_unreachable("couldn't find in-class initializer");
3558 }
3559 
3560 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3561                                       SourceLocation DefaultInitLoc) {
3562   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3563     return;
3564 
3565   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3566   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3567 }
3568 
3569 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3570                                       CXXRecordDecl *AnonUnion) {
3571   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3572     return;
3573 
3574   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3575 }
3576 
3577 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3578 /// anonymous structure or union. Anonymous unions are a C++ feature
3579 /// (C++ [class.union]) and a C11 feature; anonymous structures
3580 /// are a C11 feature and GNU C++ extension.
3581 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3582                                         AccessSpecifier AS,
3583                                         RecordDecl *Record,
3584                                         const PrintingPolicy &Policy) {
3585   DeclContext *Owner = Record->getDeclContext();
3586 
3587   // Diagnose whether this anonymous struct/union is an extension.
3588   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3589     Diag(Record->getLocation(), diag::ext_anonymous_union);
3590   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3591     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3592   else if (!Record->isUnion() && !getLangOpts().C11)
3593     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3594 
3595   // C and C++ require different kinds of checks for anonymous
3596   // structs/unions.
3597   bool Invalid = false;
3598   if (getLangOpts().CPlusPlus) {
3599     const char* PrevSpec = 0;
3600     unsigned DiagID;
3601     if (Record->isUnion()) {
3602       // C++ [class.union]p6:
3603       //   Anonymous unions declared in a named namespace or in the
3604       //   global namespace shall be declared static.
3605       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3606           (isa<TranslationUnitDecl>(Owner) ||
3607            (isa<NamespaceDecl>(Owner) &&
3608             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3609         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3610           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3611 
3612         // Recover by adding 'static'.
3613         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3614                                PrevSpec, DiagID, Policy);
3615       }
3616       // C++ [class.union]p6:
3617       //   A storage class is not allowed in a declaration of an
3618       //   anonymous union in a class scope.
3619       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3620                isa<RecordDecl>(Owner)) {
3621         Diag(DS.getStorageClassSpecLoc(),
3622              diag::err_anonymous_union_with_storage_spec)
3623           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3624 
3625         // Recover by removing the storage specifier.
3626         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3627                                SourceLocation(),
3628                                PrevSpec, DiagID, Context.getPrintingPolicy());
3629       }
3630     }
3631 
3632     // Ignore const/volatile/restrict qualifiers.
3633     if (DS.getTypeQualifiers()) {
3634       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3635         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3636           << Record->isUnion() << "const"
3637           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3638       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3639         Diag(DS.getVolatileSpecLoc(),
3640              diag::ext_anonymous_struct_union_qualified)
3641           << Record->isUnion() << "volatile"
3642           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3643       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3644         Diag(DS.getRestrictSpecLoc(),
3645              diag::ext_anonymous_struct_union_qualified)
3646           << Record->isUnion() << "restrict"
3647           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3648       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3649         Diag(DS.getAtomicSpecLoc(),
3650              diag::ext_anonymous_struct_union_qualified)
3651           << Record->isUnion() << "_Atomic"
3652           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3653 
3654       DS.ClearTypeQualifiers();
3655     }
3656 
3657     // C++ [class.union]p2:
3658     //   The member-specification of an anonymous union shall only
3659     //   define non-static data members. [Note: nested types and
3660     //   functions cannot be declared within an anonymous union. ]
3661     for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3662                                  MemEnd = Record->decls_end();
3663          Mem != MemEnd; ++Mem) {
3664       if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3665         // C++ [class.union]p3:
3666         //   An anonymous union shall not have private or protected
3667         //   members (clause 11).
3668         assert(FD->getAccess() != AS_none);
3669         if (FD->getAccess() != AS_public) {
3670           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3671             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3672           Invalid = true;
3673         }
3674 
3675         // C++ [class.union]p1
3676         //   An object of a class with a non-trivial constructor, a non-trivial
3677         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3678         //   assignment operator cannot be a member of a union, nor can an
3679         //   array of such objects.
3680         if (CheckNontrivialField(FD))
3681           Invalid = true;
3682       } else if ((*Mem)->isImplicit()) {
3683         // Any implicit members are fine.
3684       } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3685         // This is a type that showed up in an
3686         // elaborated-type-specifier inside the anonymous struct or
3687         // union, but which actually declares a type outside of the
3688         // anonymous struct or union. It's okay.
3689       } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3690         if (!MemRecord->isAnonymousStructOrUnion() &&
3691             MemRecord->getDeclName()) {
3692           // Visual C++ allows type definition in anonymous struct or union.
3693           if (getLangOpts().MicrosoftExt)
3694             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3695               << (int)Record->isUnion();
3696           else {
3697             // This is a nested type declaration.
3698             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3699               << (int)Record->isUnion();
3700             Invalid = true;
3701           }
3702         } else {
3703           // This is an anonymous type definition within another anonymous type.
3704           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3705           // not part of standard C++.
3706           Diag(MemRecord->getLocation(),
3707                diag::ext_anonymous_record_with_anonymous_type)
3708             << (int)Record->isUnion();
3709         }
3710       } else if (isa<AccessSpecDecl>(*Mem)) {
3711         // Any access specifier is fine.
3712       } else {
3713         // We have something that isn't a non-static data
3714         // member. Complain about it.
3715         unsigned DK = diag::err_anonymous_record_bad_member;
3716         if (isa<TypeDecl>(*Mem))
3717           DK = diag::err_anonymous_record_with_type;
3718         else if (isa<FunctionDecl>(*Mem))
3719           DK = diag::err_anonymous_record_with_function;
3720         else if (isa<VarDecl>(*Mem))
3721           DK = diag::err_anonymous_record_with_static;
3722 
3723         // Visual C++ allows type definition in anonymous struct or union.
3724         if (getLangOpts().MicrosoftExt &&
3725             DK == diag::err_anonymous_record_with_type)
3726           Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3727             << (int)Record->isUnion();
3728         else {
3729           Diag((*Mem)->getLocation(), DK)
3730               << (int)Record->isUnion();
3731           Invalid = true;
3732         }
3733       }
3734     }
3735 
3736     // C++11 [class.union]p8 (DR1460):
3737     //   At most one variant member of a union may have a
3738     //   brace-or-equal-initializer.
3739     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3740         Owner->isRecord())
3741       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3742                                 cast<CXXRecordDecl>(Record));
3743   }
3744 
3745   if (!Record->isUnion() && !Owner->isRecord()) {
3746     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3747       << (int)getLangOpts().CPlusPlus;
3748     Invalid = true;
3749   }
3750 
3751   // Mock up a declarator.
3752   Declarator Dc(DS, Declarator::MemberContext);
3753   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3754   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3755 
3756   // Create a declaration for this anonymous struct/union.
3757   NamedDecl *Anon = 0;
3758   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3759     Anon = FieldDecl::Create(Context, OwningClass,
3760                              DS.getLocStart(),
3761                              Record->getLocation(),
3762                              /*IdentifierInfo=*/0,
3763                              Context.getTypeDeclType(Record),
3764                              TInfo,
3765                              /*BitWidth=*/0, /*Mutable=*/false,
3766                              /*InitStyle=*/ICIS_NoInit);
3767     Anon->setAccess(AS);
3768     if (getLangOpts().CPlusPlus)
3769       FieldCollector->Add(cast<FieldDecl>(Anon));
3770   } else {
3771     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3772     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3773     if (SCSpec == DeclSpec::SCS_mutable) {
3774       // mutable can only appear on non-static class members, so it's always
3775       // an error here
3776       Diag(Record->getLocation(), diag::err_mutable_nonmember);
3777       Invalid = true;
3778       SC = SC_None;
3779     }
3780 
3781     Anon = VarDecl::Create(Context, Owner,
3782                            DS.getLocStart(),
3783                            Record->getLocation(), /*IdentifierInfo=*/0,
3784                            Context.getTypeDeclType(Record),
3785                            TInfo, SC);
3786 
3787     // Default-initialize the implicit variable. This initialization will be
3788     // trivial in almost all cases, except if a union member has an in-class
3789     // initializer:
3790     //   union { int n = 0; };
3791     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3792   }
3793   Anon->setImplicit();
3794 
3795   // Mark this as an anonymous struct/union type.
3796   Record->setAnonymousStructOrUnion(true);
3797 
3798   // Add the anonymous struct/union object to the current
3799   // context. We'll be referencing this object when we refer to one of
3800   // its members.
3801   Owner->addDecl(Anon);
3802 
3803   // Inject the members of the anonymous struct/union into the owning
3804   // context and into the identifier resolver chain for name lookup
3805   // purposes.
3806   SmallVector<NamedDecl*, 2> Chain;
3807   Chain.push_back(Anon);
3808 
3809   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3810                                           Chain, false))
3811     Invalid = true;
3812 
3813   if (Invalid)
3814     Anon->setInvalidDecl();
3815 
3816   return Anon;
3817 }
3818 
3819 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3820 /// Microsoft C anonymous structure.
3821 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3822 /// Example:
3823 ///
3824 /// struct A { int a; };
3825 /// struct B { struct A; int b; };
3826 ///
3827 /// void foo() {
3828 ///   B var;
3829 ///   var.a = 3;
3830 /// }
3831 ///
3832 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3833                                            RecordDecl *Record) {
3834 
3835   // If there is no Record, get the record via the typedef.
3836   if (!Record)
3837     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3838 
3839   // Mock up a declarator.
3840   Declarator Dc(DS, Declarator::TypeNameContext);
3841   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3842   assert(TInfo && "couldn't build declarator info for anonymous struct");
3843 
3844   // Create a declaration for this anonymous struct.
3845   NamedDecl* Anon = FieldDecl::Create(Context,
3846                              cast<RecordDecl>(CurContext),
3847                              DS.getLocStart(),
3848                              DS.getLocStart(),
3849                              /*IdentifierInfo=*/0,
3850                              Context.getTypeDeclType(Record),
3851                              TInfo,
3852                              /*BitWidth=*/0, /*Mutable=*/false,
3853                              /*InitStyle=*/ICIS_NoInit);
3854   Anon->setImplicit();
3855 
3856   // Add the anonymous struct object to the current context.
3857   CurContext->addDecl(Anon);
3858 
3859   // Inject the members of the anonymous struct into the current
3860   // context and into the identifier resolver chain for name lookup
3861   // purposes.
3862   SmallVector<NamedDecl*, 2> Chain;
3863   Chain.push_back(Anon);
3864 
3865   RecordDecl *RecordDef = Record->getDefinition();
3866   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3867                                                         RecordDef, AS_none,
3868                                                         Chain, true))
3869     Anon->setInvalidDecl();
3870 
3871   return Anon;
3872 }
3873 
3874 /// GetNameForDeclarator - Determine the full declaration name for the
3875 /// given Declarator.
3876 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3877   return GetNameFromUnqualifiedId(D.getName());
3878 }
3879 
3880 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3881 DeclarationNameInfo
3882 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3883   DeclarationNameInfo NameInfo;
3884   NameInfo.setLoc(Name.StartLocation);
3885 
3886   switch (Name.getKind()) {
3887 
3888   case UnqualifiedId::IK_ImplicitSelfParam:
3889   case UnqualifiedId::IK_Identifier:
3890     NameInfo.setName(Name.Identifier);
3891     NameInfo.setLoc(Name.StartLocation);
3892     return NameInfo;
3893 
3894   case UnqualifiedId::IK_OperatorFunctionId:
3895     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3896                                            Name.OperatorFunctionId.Operator));
3897     NameInfo.setLoc(Name.StartLocation);
3898     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3899       = Name.OperatorFunctionId.SymbolLocations[0];
3900     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3901       = Name.EndLocation.getRawEncoding();
3902     return NameInfo;
3903 
3904   case UnqualifiedId::IK_LiteralOperatorId:
3905     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3906                                                            Name.Identifier));
3907     NameInfo.setLoc(Name.StartLocation);
3908     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3909     return NameInfo;
3910 
3911   case UnqualifiedId::IK_ConversionFunctionId: {
3912     TypeSourceInfo *TInfo;
3913     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3914     if (Ty.isNull())
3915       return DeclarationNameInfo();
3916     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3917                                                Context.getCanonicalType(Ty)));
3918     NameInfo.setLoc(Name.StartLocation);
3919     NameInfo.setNamedTypeInfo(TInfo);
3920     return NameInfo;
3921   }
3922 
3923   case UnqualifiedId::IK_ConstructorName: {
3924     TypeSourceInfo *TInfo;
3925     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3926     if (Ty.isNull())
3927       return DeclarationNameInfo();
3928     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3929                                               Context.getCanonicalType(Ty)));
3930     NameInfo.setLoc(Name.StartLocation);
3931     NameInfo.setNamedTypeInfo(TInfo);
3932     return NameInfo;
3933   }
3934 
3935   case UnqualifiedId::IK_ConstructorTemplateId: {
3936     // In well-formed code, we can only have a constructor
3937     // template-id that refers to the current context, so go there
3938     // to find the actual type being constructed.
3939     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3940     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3941       return DeclarationNameInfo();
3942 
3943     // Determine the type of the class being constructed.
3944     QualType CurClassType = Context.getTypeDeclType(CurClass);
3945 
3946     // FIXME: Check two things: that the template-id names the same type as
3947     // CurClassType, and that the template-id does not occur when the name
3948     // was qualified.
3949 
3950     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3951                                     Context.getCanonicalType(CurClassType)));
3952     NameInfo.setLoc(Name.StartLocation);
3953     // FIXME: should we retrieve TypeSourceInfo?
3954     NameInfo.setNamedTypeInfo(0);
3955     return NameInfo;
3956   }
3957 
3958   case UnqualifiedId::IK_DestructorName: {
3959     TypeSourceInfo *TInfo;
3960     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3961     if (Ty.isNull())
3962       return DeclarationNameInfo();
3963     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3964                                               Context.getCanonicalType(Ty)));
3965     NameInfo.setLoc(Name.StartLocation);
3966     NameInfo.setNamedTypeInfo(TInfo);
3967     return NameInfo;
3968   }
3969 
3970   case UnqualifiedId::IK_TemplateId: {
3971     TemplateName TName = Name.TemplateId->Template.get();
3972     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3973     return Context.getNameForTemplate(TName, TNameLoc);
3974   }
3975 
3976   } // switch (Name.getKind())
3977 
3978   llvm_unreachable("Unknown name kind");
3979 }
3980 
3981 static QualType getCoreType(QualType Ty) {
3982   do {
3983     if (Ty->isPointerType() || Ty->isReferenceType())
3984       Ty = Ty->getPointeeType();
3985     else if (Ty->isArrayType())
3986       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3987     else
3988       return Ty.withoutLocalFastQualifiers();
3989   } while (true);
3990 }
3991 
3992 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3993 /// and Definition have "nearly" matching parameters. This heuristic is
3994 /// used to improve diagnostics in the case where an out-of-line function
3995 /// definition doesn't match any declaration within the class or namespace.
3996 /// Also sets Params to the list of indices to the parameters that differ
3997 /// between the declaration and the definition. If hasSimilarParameters
3998 /// returns true and Params is empty, then all of the parameters match.
3999 static bool hasSimilarParameters(ASTContext &Context,
4000                                      FunctionDecl *Declaration,
4001                                      FunctionDecl *Definition,
4002                                      SmallVectorImpl<unsigned> &Params) {
4003   Params.clear();
4004   if (Declaration->param_size() != Definition->param_size())
4005     return false;
4006   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4007     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4008     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4009 
4010     // The parameter types are identical
4011     if (Context.hasSameType(DefParamTy, DeclParamTy))
4012       continue;
4013 
4014     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4015     QualType DefParamBaseTy = getCoreType(DefParamTy);
4016     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4017     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4018 
4019     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4020         (DeclTyName && DeclTyName == DefTyName))
4021       Params.push_back(Idx);
4022     else  // The two parameters aren't even close
4023       return false;
4024   }
4025 
4026   return true;
4027 }
4028 
4029 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4030 /// declarator needs to be rebuilt in the current instantiation.
4031 /// Any bits of declarator which appear before the name are valid for
4032 /// consideration here.  That's specifically the type in the decl spec
4033 /// and the base type in any member-pointer chunks.
4034 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4035                                                     DeclarationName Name) {
4036   // The types we specifically need to rebuild are:
4037   //   - typenames, typeofs, and decltypes
4038   //   - types which will become injected class names
4039   // Of course, we also need to rebuild any type referencing such a
4040   // type.  It's safest to just say "dependent", but we call out a
4041   // few cases here.
4042 
4043   DeclSpec &DS = D.getMutableDeclSpec();
4044   switch (DS.getTypeSpecType()) {
4045   case DeclSpec::TST_typename:
4046   case DeclSpec::TST_typeofType:
4047   case DeclSpec::TST_underlyingType:
4048   case DeclSpec::TST_atomic: {
4049     // Grab the type from the parser.
4050     TypeSourceInfo *TSI = 0;
4051     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4052     if (T.isNull() || !T->isDependentType()) break;
4053 
4054     // Make sure there's a type source info.  This isn't really much
4055     // of a waste; most dependent types should have type source info
4056     // attached already.
4057     if (!TSI)
4058       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4059 
4060     // Rebuild the type in the current instantiation.
4061     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4062     if (!TSI) return true;
4063 
4064     // Store the new type back in the decl spec.
4065     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4066     DS.UpdateTypeRep(LocType);
4067     break;
4068   }
4069 
4070   case DeclSpec::TST_decltype:
4071   case DeclSpec::TST_typeofExpr: {
4072     Expr *E = DS.getRepAsExpr();
4073     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4074     if (Result.isInvalid()) return true;
4075     DS.UpdateExprRep(Result.get());
4076     break;
4077   }
4078 
4079   default:
4080     // Nothing to do for these decl specs.
4081     break;
4082   }
4083 
4084   // It doesn't matter what order we do this in.
4085   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4086     DeclaratorChunk &Chunk = D.getTypeObject(I);
4087 
4088     // The only type information in the declarator which can come
4089     // before the declaration name is the base type of a member
4090     // pointer.
4091     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4092       continue;
4093 
4094     // Rebuild the scope specifier in-place.
4095     CXXScopeSpec &SS = Chunk.Mem.Scope();
4096     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4097       return true;
4098   }
4099 
4100   return false;
4101 }
4102 
4103 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4104   D.setFunctionDefinitionKind(FDK_Declaration);
4105   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4106 
4107   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4108       Dcl && Dcl->getDeclContext()->isFileContext())
4109     Dcl->setTopLevelDeclInObjCContainer();
4110 
4111   return Dcl;
4112 }
4113 
4114 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4115 ///   If T is the name of a class, then each of the following shall have a
4116 ///   name different from T:
4117 ///     - every static data member of class T;
4118 ///     - every member function of class T
4119 ///     - every member of class T that is itself a type;
4120 /// \returns true if the declaration name violates these rules.
4121 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4122                                    DeclarationNameInfo NameInfo) {
4123   DeclarationName Name = NameInfo.getName();
4124 
4125   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4126     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4127       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4128       return true;
4129     }
4130 
4131   return false;
4132 }
4133 
4134 /// \brief Diagnose a declaration whose declarator-id has the given
4135 /// nested-name-specifier.
4136 ///
4137 /// \param SS The nested-name-specifier of the declarator-id.
4138 ///
4139 /// \param DC The declaration context to which the nested-name-specifier
4140 /// resolves.
4141 ///
4142 /// \param Name The name of the entity being declared.
4143 ///
4144 /// \param Loc The location of the name of the entity being declared.
4145 ///
4146 /// \returns true if we cannot safely recover from this error, false otherwise.
4147 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4148                                         DeclarationName Name,
4149                                         SourceLocation Loc) {
4150   DeclContext *Cur = CurContext;
4151   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4152     Cur = Cur->getParent();
4153 
4154   // If the user provided a superfluous scope specifier that refers back to the
4155   // class in which the entity is already declared, diagnose and ignore it.
4156   //
4157   // class X {
4158   //   void X::f();
4159   // };
4160   //
4161   // Note, it was once ill-formed to give redundant qualification in all
4162   // contexts, but that rule was removed by DR482.
4163   if (Cur->Equals(DC)) {
4164     if (Cur->isRecord()) {
4165       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4166                                       : diag::err_member_extra_qualification)
4167         << Name << FixItHint::CreateRemoval(SS.getRange());
4168       SS.clear();
4169     } else {
4170       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4171     }
4172     return false;
4173   }
4174 
4175   // Check whether the qualifying scope encloses the scope of the original
4176   // declaration.
4177   if (!Cur->Encloses(DC)) {
4178     if (Cur->isRecord())
4179       Diag(Loc, diag::err_member_qualification)
4180         << Name << SS.getRange();
4181     else if (isa<TranslationUnitDecl>(DC))
4182       Diag(Loc, diag::err_invalid_declarator_global_scope)
4183         << Name << SS.getRange();
4184     else if (isa<FunctionDecl>(Cur))
4185       Diag(Loc, diag::err_invalid_declarator_in_function)
4186         << Name << SS.getRange();
4187     else if (isa<BlockDecl>(Cur))
4188       Diag(Loc, diag::err_invalid_declarator_in_block)
4189         << Name << SS.getRange();
4190     else
4191       Diag(Loc, diag::err_invalid_declarator_scope)
4192       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4193 
4194     return true;
4195   }
4196 
4197   if (Cur->isRecord()) {
4198     // Cannot qualify members within a class.
4199     Diag(Loc, diag::err_member_qualification)
4200       << Name << SS.getRange();
4201     SS.clear();
4202 
4203     // C++ constructors and destructors with incorrect scopes can break
4204     // our AST invariants by having the wrong underlying types. If
4205     // that's the case, then drop this declaration entirely.
4206     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4207          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4208         !Context.hasSameType(Name.getCXXNameType(),
4209                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4210       return true;
4211 
4212     return false;
4213   }
4214 
4215   // C++11 [dcl.meaning]p1:
4216   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4217   //   not begin with a decltype-specifer"
4218   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4219   while (SpecLoc.getPrefix())
4220     SpecLoc = SpecLoc.getPrefix();
4221   if (dyn_cast_or_null<DecltypeType>(
4222         SpecLoc.getNestedNameSpecifier()->getAsType()))
4223     Diag(Loc, diag::err_decltype_in_declarator)
4224       << SpecLoc.getTypeLoc().getSourceRange();
4225 
4226   return false;
4227 }
4228 
4229 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4230                                   MultiTemplateParamsArg TemplateParamLists) {
4231   // TODO: consider using NameInfo for diagnostic.
4232   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4233   DeclarationName Name = NameInfo.getName();
4234 
4235   // All of these full declarators require an identifier.  If it doesn't have
4236   // one, the ParsedFreeStandingDeclSpec action should be used.
4237   if (!Name) {
4238     if (!D.isInvalidType())  // Reject this if we think it is valid.
4239       Diag(D.getDeclSpec().getLocStart(),
4240            diag::err_declarator_need_ident)
4241         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4242     return 0;
4243   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4244     return 0;
4245 
4246   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4247   // we find one that is.
4248   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4249          (S->getFlags() & Scope::TemplateParamScope) != 0)
4250     S = S->getParent();
4251 
4252   DeclContext *DC = CurContext;
4253   if (D.getCXXScopeSpec().isInvalid())
4254     D.setInvalidType();
4255   else if (D.getCXXScopeSpec().isSet()) {
4256     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4257                                         UPPC_DeclarationQualifier))
4258       return 0;
4259 
4260     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4261     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4262     if (!DC || isa<EnumDecl>(DC)) {
4263       // If we could not compute the declaration context, it's because the
4264       // declaration context is dependent but does not refer to a class,
4265       // class template, or class template partial specialization. Complain
4266       // and return early, to avoid the coming semantic disaster.
4267       Diag(D.getIdentifierLoc(),
4268            diag::err_template_qualified_declarator_no_match)
4269         << D.getCXXScopeSpec().getScopeRep()
4270         << D.getCXXScopeSpec().getRange();
4271       return 0;
4272     }
4273     bool IsDependentContext = DC->isDependentContext();
4274 
4275     if (!IsDependentContext &&
4276         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4277       return 0;
4278 
4279     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4280       Diag(D.getIdentifierLoc(),
4281            diag::err_member_def_undefined_record)
4282         << Name << DC << D.getCXXScopeSpec().getRange();
4283       D.setInvalidType();
4284     } else if (!D.getDeclSpec().isFriendSpecified()) {
4285       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4286                                       Name, D.getIdentifierLoc())) {
4287         if (DC->isRecord())
4288           return 0;
4289 
4290         D.setInvalidType();
4291       }
4292     }
4293 
4294     // Check whether we need to rebuild the type of the given
4295     // declaration in the current instantiation.
4296     if (EnteringContext && IsDependentContext &&
4297         TemplateParamLists.size() != 0) {
4298       ContextRAII SavedContext(*this, DC);
4299       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4300         D.setInvalidType();
4301     }
4302   }
4303 
4304   if (DiagnoseClassNameShadow(DC, NameInfo))
4305     // If this is a typedef, we'll end up spewing multiple diagnostics.
4306     // Just return early; it's safer.
4307     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4308       return 0;
4309 
4310   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4311   QualType R = TInfo->getType();
4312 
4313   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4314                                       UPPC_DeclarationType))
4315     D.setInvalidType();
4316 
4317   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4318                         ForRedeclaration);
4319 
4320   // See if this is a redefinition of a variable in the same scope.
4321   if (!D.getCXXScopeSpec().isSet()) {
4322     bool IsLinkageLookup = false;
4323     bool CreateBuiltins = false;
4324 
4325     // If the declaration we're planning to build will be a function
4326     // or object with linkage, then look for another declaration with
4327     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4328     //
4329     // If the declaration we're planning to build will be declared with
4330     // external linkage in the translation unit, create any builtin with
4331     // the same name.
4332     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4333       /* Do nothing*/;
4334     else if (CurContext->isFunctionOrMethod() &&
4335              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4336               R->isFunctionType())) {
4337       IsLinkageLookup = true;
4338       CreateBuiltins =
4339           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4340     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4341                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4342       CreateBuiltins = true;
4343 
4344     if (IsLinkageLookup)
4345       Previous.clear(LookupRedeclarationWithLinkage);
4346 
4347     LookupName(Previous, S, CreateBuiltins);
4348   } else { // Something like "int foo::x;"
4349     LookupQualifiedName(Previous, DC);
4350 
4351     // C++ [dcl.meaning]p1:
4352     //   When the declarator-id is qualified, the declaration shall refer to a
4353     //  previously declared member of the class or namespace to which the
4354     //  qualifier refers (or, in the case of a namespace, of an element of the
4355     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4356     //  thereof; [...]
4357     //
4358     // Note that we already checked the context above, and that we do not have
4359     // enough information to make sure that Previous contains the declaration
4360     // we want to match. For example, given:
4361     //
4362     //   class X {
4363     //     void f();
4364     //     void f(float);
4365     //   };
4366     //
4367     //   void X::f(int) { } // ill-formed
4368     //
4369     // In this case, Previous will point to the overload set
4370     // containing the two f's declared in X, but neither of them
4371     // matches.
4372 
4373     // C++ [dcl.meaning]p1:
4374     //   [...] the member shall not merely have been introduced by a
4375     //   using-declaration in the scope of the class or namespace nominated by
4376     //   the nested-name-specifier of the declarator-id.
4377     RemoveUsingDecls(Previous);
4378   }
4379 
4380   if (Previous.isSingleResult() &&
4381       Previous.getFoundDecl()->isTemplateParameter()) {
4382     // Maybe we will complain about the shadowed template parameter.
4383     if (!D.isInvalidType())
4384       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4385                                       Previous.getFoundDecl());
4386 
4387     // Just pretend that we didn't see the previous declaration.
4388     Previous.clear();
4389   }
4390 
4391   // In C++, the previous declaration we find might be a tag type
4392   // (class or enum). In this case, the new declaration will hide the
4393   // tag type. Note that this does does not apply if we're declaring a
4394   // typedef (C++ [dcl.typedef]p4).
4395   if (Previous.isSingleTagDecl() &&
4396       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4397     Previous.clear();
4398 
4399   // Check that there are no default arguments other than in the parameters
4400   // of a function declaration (C++ only).
4401   if (getLangOpts().CPlusPlus)
4402     CheckExtraCXXDefaultArguments(D);
4403 
4404   NamedDecl *New;
4405 
4406   bool AddToScope = true;
4407   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4408     if (TemplateParamLists.size()) {
4409       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4410       return 0;
4411     }
4412 
4413     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4414   } else if (R->isFunctionType()) {
4415     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4416                                   TemplateParamLists,
4417                                   AddToScope);
4418   } else {
4419     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4420                                   AddToScope);
4421   }
4422 
4423   if (New == 0)
4424     return 0;
4425 
4426   // If this has an identifier and is not an invalid redeclaration or
4427   // function template specialization, add it to the scope stack.
4428   if (New->getDeclName() && AddToScope &&
4429        !(D.isRedeclaration() && New->isInvalidDecl())) {
4430     // Only make a locally-scoped extern declaration visible if it is the first
4431     // declaration of this entity. Qualified lookup for such an entity should
4432     // only find this declaration if there is no visible declaration of it.
4433     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4434     PushOnScopeChains(New, S, AddToContext);
4435     if (!AddToContext)
4436       CurContext->addHiddenDecl(New);
4437   }
4438 
4439   return New;
4440 }
4441 
4442 /// Helper method to turn variable array types into constant array
4443 /// types in certain situations which would otherwise be errors (for
4444 /// GCC compatibility).
4445 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4446                                                     ASTContext &Context,
4447                                                     bool &SizeIsNegative,
4448                                                     llvm::APSInt &Oversized) {
4449   // This method tries to turn a variable array into a constant
4450   // array even when the size isn't an ICE.  This is necessary
4451   // for compatibility with code that depends on gcc's buggy
4452   // constant expression folding, like struct {char x[(int)(char*)2];}
4453   SizeIsNegative = false;
4454   Oversized = 0;
4455 
4456   if (T->isDependentType())
4457     return QualType();
4458 
4459   QualifierCollector Qs;
4460   const Type *Ty = Qs.strip(T);
4461 
4462   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4463     QualType Pointee = PTy->getPointeeType();
4464     QualType FixedType =
4465         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4466                                             Oversized);
4467     if (FixedType.isNull()) return FixedType;
4468     FixedType = Context.getPointerType(FixedType);
4469     return Qs.apply(Context, FixedType);
4470   }
4471   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4472     QualType Inner = PTy->getInnerType();
4473     QualType FixedType =
4474         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4475                                             Oversized);
4476     if (FixedType.isNull()) return FixedType;
4477     FixedType = Context.getParenType(FixedType);
4478     return Qs.apply(Context, FixedType);
4479   }
4480 
4481   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4482   if (!VLATy)
4483     return QualType();
4484   // FIXME: We should probably handle this case
4485   if (VLATy->getElementType()->isVariablyModifiedType())
4486     return QualType();
4487 
4488   llvm::APSInt Res;
4489   if (!VLATy->getSizeExpr() ||
4490       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4491     return QualType();
4492 
4493   // Check whether the array size is negative.
4494   if (Res.isSigned() && Res.isNegative()) {
4495     SizeIsNegative = true;
4496     return QualType();
4497   }
4498 
4499   // Check whether the array is too large to be addressed.
4500   unsigned ActiveSizeBits
4501     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4502                                               Res);
4503   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4504     Oversized = Res;
4505     return QualType();
4506   }
4507 
4508   return Context.getConstantArrayType(VLATy->getElementType(),
4509                                       Res, ArrayType::Normal, 0);
4510 }
4511 
4512 static void
4513 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4514   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4515     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4516     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4517                                       DstPTL.getPointeeLoc());
4518     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4519     return;
4520   }
4521   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4522     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4523     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4524                                       DstPTL.getInnerLoc());
4525     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4526     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4527     return;
4528   }
4529   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4530   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4531   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4532   TypeLoc DstElemTL = DstATL.getElementLoc();
4533   DstElemTL.initializeFullCopy(SrcElemTL);
4534   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4535   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4536   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4537 }
4538 
4539 /// Helper method to turn variable array types into constant array
4540 /// types in certain situations which would otherwise be errors (for
4541 /// GCC compatibility).
4542 static TypeSourceInfo*
4543 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4544                                               ASTContext &Context,
4545                                               bool &SizeIsNegative,
4546                                               llvm::APSInt &Oversized) {
4547   QualType FixedTy
4548     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4549                                           SizeIsNegative, Oversized);
4550   if (FixedTy.isNull())
4551     return 0;
4552   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4553   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4554                                     FixedTInfo->getTypeLoc());
4555   return FixedTInfo;
4556 }
4557 
4558 /// \brief Register the given locally-scoped extern "C" declaration so
4559 /// that it can be found later for redeclarations. We include any extern "C"
4560 /// declaration that is not visible in the translation unit here, not just
4561 /// function-scope declarations.
4562 void
4563 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4564   if (!getLangOpts().CPlusPlus &&
4565       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4566     // Don't need to track declarations in the TU in C.
4567     return;
4568 
4569   // Note that we have a locally-scoped external with this name.
4570   // FIXME: There can be multiple such declarations if they are functions marked
4571   // __attribute__((overloadable)) declared in function scope in C.
4572   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4573 }
4574 
4575 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4576   if (ExternalSource) {
4577     // Load locally-scoped external decls from the external source.
4578     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4579     SmallVector<NamedDecl *, 4> Decls;
4580     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4581     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4582       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4583         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4584       if (Pos == LocallyScopedExternCDecls.end())
4585         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4586     }
4587   }
4588 
4589   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4590   return D ? D->getMostRecentDecl() : 0;
4591 }
4592 
4593 /// \brief Diagnose function specifiers on a declaration of an identifier that
4594 /// does not identify a function.
4595 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4596   // FIXME: We should probably indicate the identifier in question to avoid
4597   // confusion for constructs like "inline int a(), b;"
4598   if (DS.isInlineSpecified())
4599     Diag(DS.getInlineSpecLoc(),
4600          diag::err_inline_non_function);
4601 
4602   if (DS.isVirtualSpecified())
4603     Diag(DS.getVirtualSpecLoc(),
4604          diag::err_virtual_non_function);
4605 
4606   if (DS.isExplicitSpecified())
4607     Diag(DS.getExplicitSpecLoc(),
4608          diag::err_explicit_non_function);
4609 
4610   if (DS.isNoreturnSpecified())
4611     Diag(DS.getNoreturnSpecLoc(),
4612          diag::err_noreturn_non_function);
4613 }
4614 
4615 NamedDecl*
4616 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4617                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4618   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4619   if (D.getCXXScopeSpec().isSet()) {
4620     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4621       << D.getCXXScopeSpec().getRange();
4622     D.setInvalidType();
4623     // Pretend we didn't see the scope specifier.
4624     DC = CurContext;
4625     Previous.clear();
4626   }
4627 
4628   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4629 
4630   if (D.getDeclSpec().isConstexprSpecified())
4631     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4632       << 1;
4633 
4634   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4635     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4636       << D.getName().getSourceRange();
4637     return 0;
4638   }
4639 
4640   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4641   if (!NewTD) return 0;
4642 
4643   // Handle attributes prior to checking for duplicates in MergeVarDecl
4644   ProcessDeclAttributes(S, NewTD, D);
4645 
4646   CheckTypedefForVariablyModifiedType(S, NewTD);
4647 
4648   bool Redeclaration = D.isRedeclaration();
4649   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4650   D.setRedeclaration(Redeclaration);
4651   return ND;
4652 }
4653 
4654 void
4655 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4656   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4657   // then it shall have block scope.
4658   // Note that variably modified types must be fixed before merging the decl so
4659   // that redeclarations will match.
4660   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4661   QualType T = TInfo->getType();
4662   if (T->isVariablyModifiedType()) {
4663     getCurFunction()->setHasBranchProtectedScope();
4664 
4665     if (S->getFnParent() == 0) {
4666       bool SizeIsNegative;
4667       llvm::APSInt Oversized;
4668       TypeSourceInfo *FixedTInfo =
4669         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4670                                                       SizeIsNegative,
4671                                                       Oversized);
4672       if (FixedTInfo) {
4673         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4674         NewTD->setTypeSourceInfo(FixedTInfo);
4675       } else {
4676         if (SizeIsNegative)
4677           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4678         else if (T->isVariableArrayType())
4679           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4680         else if (Oversized.getBoolValue())
4681           Diag(NewTD->getLocation(), diag::err_array_too_large)
4682             << Oversized.toString(10);
4683         else
4684           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4685         NewTD->setInvalidDecl();
4686       }
4687     }
4688   }
4689 }
4690 
4691 
4692 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4693 /// declares a typedef-name, either using the 'typedef' type specifier or via
4694 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4695 NamedDecl*
4696 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4697                            LookupResult &Previous, bool &Redeclaration) {
4698   // Merge the decl with the existing one if appropriate. If the decl is
4699   // in an outer scope, it isn't the same thing.
4700   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4701                        /*AllowInlineNamespace*/false);
4702   filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4703   if (!Previous.empty()) {
4704     Redeclaration = true;
4705     MergeTypedefNameDecl(NewTD, Previous);
4706   }
4707 
4708   // If this is the C FILE type, notify the AST context.
4709   if (IdentifierInfo *II = NewTD->getIdentifier())
4710     if (!NewTD->isInvalidDecl() &&
4711         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4712       if (II->isStr("FILE"))
4713         Context.setFILEDecl(NewTD);
4714       else if (II->isStr("jmp_buf"))
4715         Context.setjmp_bufDecl(NewTD);
4716       else if (II->isStr("sigjmp_buf"))
4717         Context.setsigjmp_bufDecl(NewTD);
4718       else if (II->isStr("ucontext_t"))
4719         Context.setucontext_tDecl(NewTD);
4720     }
4721 
4722   return NewTD;
4723 }
4724 
4725 /// \brief Determines whether the given declaration is an out-of-scope
4726 /// previous declaration.
4727 ///
4728 /// This routine should be invoked when name lookup has found a
4729 /// previous declaration (PrevDecl) that is not in the scope where a
4730 /// new declaration by the same name is being introduced. If the new
4731 /// declaration occurs in a local scope, previous declarations with
4732 /// linkage may still be considered previous declarations (C99
4733 /// 6.2.2p4-5, C++ [basic.link]p6).
4734 ///
4735 /// \param PrevDecl the previous declaration found by name
4736 /// lookup
4737 ///
4738 /// \param DC the context in which the new declaration is being
4739 /// declared.
4740 ///
4741 /// \returns true if PrevDecl is an out-of-scope previous declaration
4742 /// for a new delcaration with the same name.
4743 static bool
4744 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4745                                 ASTContext &Context) {
4746   if (!PrevDecl)
4747     return false;
4748 
4749   if (!PrevDecl->hasLinkage())
4750     return false;
4751 
4752   if (Context.getLangOpts().CPlusPlus) {
4753     // C++ [basic.link]p6:
4754     //   If there is a visible declaration of an entity with linkage
4755     //   having the same name and type, ignoring entities declared
4756     //   outside the innermost enclosing namespace scope, the block
4757     //   scope declaration declares that same entity and receives the
4758     //   linkage of the previous declaration.
4759     DeclContext *OuterContext = DC->getRedeclContext();
4760     if (!OuterContext->isFunctionOrMethod())
4761       // This rule only applies to block-scope declarations.
4762       return false;
4763 
4764     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4765     if (PrevOuterContext->isRecord())
4766       // We found a member function: ignore it.
4767       return false;
4768 
4769     // Find the innermost enclosing namespace for the new and
4770     // previous declarations.
4771     OuterContext = OuterContext->getEnclosingNamespaceContext();
4772     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4773 
4774     // The previous declaration is in a different namespace, so it
4775     // isn't the same function.
4776     if (!OuterContext->Equals(PrevOuterContext))
4777       return false;
4778   }
4779 
4780   return true;
4781 }
4782 
4783 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4784   CXXScopeSpec &SS = D.getCXXScopeSpec();
4785   if (!SS.isSet()) return;
4786   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4787 }
4788 
4789 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4790   QualType type = decl->getType();
4791   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4792   if (lifetime == Qualifiers::OCL_Autoreleasing) {
4793     // Various kinds of declaration aren't allowed to be __autoreleasing.
4794     unsigned kind = -1U;
4795     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4796       if (var->hasAttr<BlocksAttr>())
4797         kind = 0; // __block
4798       else if (!var->hasLocalStorage())
4799         kind = 1; // global
4800     } else if (isa<ObjCIvarDecl>(decl)) {
4801       kind = 3; // ivar
4802     } else if (isa<FieldDecl>(decl)) {
4803       kind = 2; // field
4804     }
4805 
4806     if (kind != -1U) {
4807       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4808         << kind;
4809     }
4810   } else if (lifetime == Qualifiers::OCL_None) {
4811     // Try to infer lifetime.
4812     if (!type->isObjCLifetimeType())
4813       return false;
4814 
4815     lifetime = type->getObjCARCImplicitLifetime();
4816     type = Context.getLifetimeQualifiedType(type, lifetime);
4817     decl->setType(type);
4818   }
4819 
4820   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4821     // Thread-local variables cannot have lifetime.
4822     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4823         var->getTLSKind()) {
4824       Diag(var->getLocation(), diag::err_arc_thread_ownership)
4825         << var->getType();
4826       return true;
4827     }
4828   }
4829 
4830   return false;
4831 }
4832 
4833 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4834   // Ensure that an auto decl is deduced otherwise the checks below might cache
4835   // the wrong linkage.
4836   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
4837 
4838   // 'weak' only applies to declarations with external linkage.
4839   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4840     if (!ND.isExternallyVisible()) {
4841       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4842       ND.dropAttr<WeakAttr>();
4843     }
4844   }
4845   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4846     if (ND.isExternallyVisible()) {
4847       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4848       ND.dropAttr<WeakRefAttr>();
4849     }
4850   }
4851 
4852   // 'selectany' only applies to externally visible varable declarations.
4853   // It does not apply to functions.
4854   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4855     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4856       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4857       ND.dropAttr<SelectAnyAttr>();
4858     }
4859   }
4860 }
4861 
4862 /// Given that we are within the definition of the given function,
4863 /// will that definition behave like C99's 'inline', where the
4864 /// definition is discarded except for optimization purposes?
4865 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4866   // Try to avoid calling GetGVALinkageForFunction.
4867 
4868   // All cases of this require the 'inline' keyword.
4869   if (!FD->isInlined()) return false;
4870 
4871   // This is only possible in C++ with the gnu_inline attribute.
4872   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4873     return false;
4874 
4875   // Okay, go ahead and call the relatively-more-expensive function.
4876 
4877 #ifndef NDEBUG
4878   // AST quite reasonably asserts that it's working on a function
4879   // definition.  We don't really have a way to tell it that we're
4880   // currently defining the function, so just lie to it in +Asserts
4881   // builds.  This is an awful hack.
4882   FD->setLazyBody(1);
4883 #endif
4884 
4885   bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4886 
4887 #ifndef NDEBUG
4888   FD->setLazyBody(0);
4889 #endif
4890 
4891   return isC99Inline;
4892 }
4893 
4894 /// Determine whether a variable is extern "C" prior to attaching
4895 /// an initializer. We can't just call isExternC() here, because that
4896 /// will also compute and cache whether the declaration is externally
4897 /// visible, which might change when we attach the initializer.
4898 ///
4899 /// This can only be used if the declaration is known to not be a
4900 /// redeclaration of an internal linkage declaration.
4901 ///
4902 /// For instance:
4903 ///
4904 ///   auto x = []{};
4905 ///
4906 /// Attaching the initializer here makes this declaration not externally
4907 /// visible, because its type has internal linkage.
4908 ///
4909 /// FIXME: This is a hack.
4910 template<typename T>
4911 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4912   if (S.getLangOpts().CPlusPlus) {
4913     // In C++, the overloadable attribute negates the effects of extern "C".
4914     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4915       return false;
4916   }
4917   return D->isExternC();
4918 }
4919 
4920 static bool shouldConsiderLinkage(const VarDecl *VD) {
4921   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4922   if (DC->isFunctionOrMethod())
4923     return VD->hasExternalStorage();
4924   if (DC->isFileContext())
4925     return true;
4926   if (DC->isRecord())
4927     return false;
4928   llvm_unreachable("Unexpected context");
4929 }
4930 
4931 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4932   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4933   if (DC->isFileContext() || DC->isFunctionOrMethod())
4934     return true;
4935   if (DC->isRecord())
4936     return false;
4937   llvm_unreachable("Unexpected context");
4938 }
4939 
4940 /// Adjust the \c DeclContext for a function or variable that might be a
4941 /// function-local external declaration.
4942 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4943   if (!DC->isFunctionOrMethod())
4944     return false;
4945 
4946   // If this is a local extern function or variable declared within a function
4947   // template, don't add it into the enclosing namespace scope until it is
4948   // instantiated; it might have a dependent type right now.
4949   if (DC->isDependentContext())
4950     return true;
4951 
4952   // C++11 [basic.link]p7:
4953   //   When a block scope declaration of an entity with linkage is not found to
4954   //   refer to some other declaration, then that entity is a member of the
4955   //   innermost enclosing namespace.
4956   //
4957   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4958   // semantically-enclosing namespace, not a lexically-enclosing one.
4959   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4960     DC = DC->getParent();
4961   return true;
4962 }
4963 
4964 NamedDecl *
4965 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4966                               TypeSourceInfo *TInfo, LookupResult &Previous,
4967                               MultiTemplateParamsArg TemplateParamLists,
4968                               bool &AddToScope) {
4969   QualType R = TInfo->getType();
4970   DeclarationName Name = GetNameForDeclarator(D).getName();
4971 
4972   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4973   VarDecl::StorageClass SC =
4974     StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
4975 
4976   DeclContext *OriginalDC = DC;
4977   bool IsLocalExternDecl = SC == SC_Extern &&
4978                            adjustContextForLocalExternDecl(DC);
4979 
4980   if (getLangOpts().OpenCL) {
4981     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
4982     QualType NR = R;
4983     while (NR->isPointerType()) {
4984       if (NR->isFunctionPointerType()) {
4985         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
4986         D.setInvalidType();
4987         break;
4988       }
4989       NR = NR->getPointeeType();
4990     }
4991 
4992     if (!getOpenCLOptions().cl_khr_fp16) {
4993       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4994       // half array type (unless the cl_khr_fp16 extension is enabled).
4995       if (Context.getBaseElementType(R)->isHalfType()) {
4996         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4997         D.setInvalidType();
4998       }
4999     }
5000   }
5001 
5002   if (SCSpec == DeclSpec::SCS_mutable) {
5003     // mutable can only appear on non-static class members, so it's always
5004     // an error here
5005     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5006     D.setInvalidType();
5007     SC = SC_None;
5008   }
5009 
5010   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5011       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5012                               D.getDeclSpec().getStorageClassSpecLoc())) {
5013     // In C++11, the 'register' storage class specifier is deprecated.
5014     // Suppress the warning in system macros, it's used in macros in some
5015     // popular C system headers, such as in glibc's htonl() macro.
5016     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5017          diag::warn_deprecated_register)
5018       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5019   }
5020 
5021   IdentifierInfo *II = Name.getAsIdentifierInfo();
5022   if (!II) {
5023     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5024       << Name;
5025     return 0;
5026   }
5027 
5028   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5029 
5030   if (!DC->isRecord() && S->getFnParent() == 0) {
5031     // C99 6.9p2: The storage-class specifiers auto and register shall not
5032     // appear in the declaration specifiers in an external declaration.
5033     if (SC == SC_Auto || SC == SC_Register) {
5034       // If this is a register variable with an asm label specified, then this
5035       // is a GNU extension.
5036       if (SC == SC_Register && D.getAsmLabel())
5037         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5038       else
5039         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5040       D.setInvalidType();
5041     }
5042   }
5043 
5044   if (getLangOpts().OpenCL) {
5045     // Set up the special work-group-local storage class for variables in the
5046     // OpenCL __local address space.
5047     if (R.getAddressSpace() == LangAS::opencl_local) {
5048       SC = SC_OpenCLWorkGroupLocal;
5049     }
5050 
5051     // OpenCL v1.2 s6.9.b p4:
5052     // The sampler type cannot be used with the __local and __global address
5053     // space qualifiers.
5054     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5055       R.getAddressSpace() == LangAS::opencl_global)) {
5056       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5057     }
5058 
5059     // OpenCL 1.2 spec, p6.9 r:
5060     // The event type cannot be used to declare a program scope variable.
5061     // The event type cannot be used with the __local, __constant and __global
5062     // address space qualifiers.
5063     if (R->isEventT()) {
5064       if (S->getParent() == 0) {
5065         Diag(D.getLocStart(), diag::err_event_t_global_var);
5066         D.setInvalidType();
5067       }
5068 
5069       if (R.getAddressSpace()) {
5070         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5071         D.setInvalidType();
5072       }
5073     }
5074   }
5075 
5076   bool IsExplicitSpecialization = false;
5077   bool IsVariableTemplateSpecialization = false;
5078   bool IsPartialSpecialization = false;
5079   bool IsVariableTemplate = false;
5080   VarDecl *NewVD = 0;
5081   VarTemplateDecl *NewTemplate = 0;
5082   TemplateParameterList *TemplateParams = 0;
5083   if (!getLangOpts().CPlusPlus) {
5084     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5085                             D.getIdentifierLoc(), II,
5086                             R, TInfo, SC);
5087 
5088     if (D.isInvalidType())
5089       NewVD->setInvalidDecl();
5090   } else {
5091     bool Invalid = false;
5092 
5093     if (DC->isRecord() && !CurContext->isRecord()) {
5094       // This is an out-of-line definition of a static data member.
5095       switch (SC) {
5096       case SC_None:
5097         break;
5098       case SC_Static:
5099         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5100              diag::err_static_out_of_line)
5101           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5102         break;
5103       case SC_Auto:
5104       case SC_Register:
5105       case SC_Extern:
5106         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5107         // to names of variables declared in a block or to function parameters.
5108         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5109         // of class members
5110 
5111         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5112              diag::err_storage_class_for_static_member)
5113           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5114         break;
5115       case SC_PrivateExtern:
5116         llvm_unreachable("C storage class in c++!");
5117       case SC_OpenCLWorkGroupLocal:
5118         llvm_unreachable("OpenCL storage class in c++!");
5119       }
5120     }
5121 
5122     if (SC == SC_Static && CurContext->isRecord()) {
5123       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5124         if (RD->isLocalClass())
5125           Diag(D.getIdentifierLoc(),
5126                diag::err_static_data_member_not_allowed_in_local_class)
5127             << Name << RD->getDeclName();
5128 
5129         // C++98 [class.union]p1: If a union contains a static data member,
5130         // the program is ill-formed. C++11 drops this restriction.
5131         if (RD->isUnion())
5132           Diag(D.getIdentifierLoc(),
5133                getLangOpts().CPlusPlus11
5134                  ? diag::warn_cxx98_compat_static_data_member_in_union
5135                  : diag::ext_static_data_member_in_union) << Name;
5136         // We conservatively disallow static data members in anonymous structs.
5137         else if (!RD->getDeclName())
5138           Diag(D.getIdentifierLoc(),
5139                diag::err_static_data_member_not_allowed_in_anon_struct)
5140             << Name << RD->isUnion();
5141       }
5142     }
5143 
5144     // Match up the template parameter lists with the scope specifier, then
5145     // determine whether we have a template or a template specialization.
5146     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5147         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5148         D.getCXXScopeSpec(), TemplateParamLists,
5149         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5150 
5151     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
5152         !TemplateParams) {
5153       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5154 
5155       // We have encountered something that the user meant to be a
5156       // specialization (because it has explicitly-specified template
5157       // arguments) but that was not introduced with a "template<>" (or had
5158       // too few of them).
5159       // FIXME: Differentiate between attempts for explicit instantiations
5160       // (starting with "template") and the rest.
5161       Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5162           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5163           << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5164                                         "template<> ");
5165       IsExplicitSpecialization = true;
5166       TemplateParams = TemplateParameterList::Create(Context, SourceLocation(),
5167                                                      SourceLocation(), 0, 0,
5168                                                      SourceLocation());
5169     }
5170 
5171     if (TemplateParams) {
5172       if (!TemplateParams->size() &&
5173           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5174         // There is an extraneous 'template<>' for this variable. Complain
5175         // about it, but allow the declaration of the variable.
5176         Diag(TemplateParams->getTemplateLoc(),
5177              diag::err_template_variable_noparams)
5178           << II
5179           << SourceRange(TemplateParams->getTemplateLoc(),
5180                          TemplateParams->getRAngleLoc());
5181         TemplateParams = 0;
5182       } else {
5183         // Only C++1y supports variable templates (N3651).
5184         Diag(D.getIdentifierLoc(),
5185              getLangOpts().CPlusPlus1y
5186                  ? diag::warn_cxx11_compat_variable_template
5187                  : diag::ext_variable_template);
5188 
5189         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5190           // This is an explicit specialization or a partial specialization.
5191           // FIXME: Check that we can declare a specialization here.
5192           IsVariableTemplateSpecialization = true;
5193           IsPartialSpecialization = TemplateParams->size() > 0;
5194         } else { // if (TemplateParams->size() > 0)
5195           // This is a template declaration.
5196           IsVariableTemplate = true;
5197 
5198           // Check that we can declare a template here.
5199           if (CheckTemplateDeclScope(S, TemplateParams))
5200             return 0;
5201         }
5202       }
5203     }
5204 
5205     if (IsVariableTemplateSpecialization) {
5206       SourceLocation TemplateKWLoc =
5207           TemplateParamLists.size() > 0
5208               ? TemplateParamLists[0]->getTemplateLoc()
5209               : SourceLocation();
5210       DeclResult Res = ActOnVarTemplateSpecialization(
5211           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5212           IsPartialSpecialization);
5213       if (Res.isInvalid())
5214         return 0;
5215       NewVD = cast<VarDecl>(Res.get());
5216       AddToScope = false;
5217     } else
5218       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5219                               D.getIdentifierLoc(), II, R, TInfo, SC);
5220 
5221     // If this is supposed to be a variable template, create it as such.
5222     if (IsVariableTemplate) {
5223       NewTemplate =
5224           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5225                                   TemplateParams, NewVD);
5226       NewVD->setDescribedVarTemplate(NewTemplate);
5227     }
5228 
5229     // If this decl has an auto type in need of deduction, make a note of the
5230     // Decl so we can diagnose uses of it in its own initializer.
5231     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5232       ParsingInitForAutoVars.insert(NewVD);
5233 
5234     if (D.isInvalidType() || Invalid) {
5235       NewVD->setInvalidDecl();
5236       if (NewTemplate)
5237         NewTemplate->setInvalidDecl();
5238     }
5239 
5240     SetNestedNameSpecifier(NewVD, D);
5241 
5242     // If we have any template parameter lists that don't directly belong to
5243     // the variable (matching the scope specifier), store them.
5244     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5245     if (TemplateParamLists.size() > VDTemplateParamLists)
5246       NewVD->setTemplateParameterListsInfo(
5247           Context, TemplateParamLists.size() - VDTemplateParamLists,
5248           TemplateParamLists.data());
5249 
5250     if (D.getDeclSpec().isConstexprSpecified())
5251       NewVD->setConstexpr(true);
5252   }
5253 
5254   // Set the lexical context. If the declarator has a C++ scope specifier, the
5255   // lexical context will be different from the semantic context.
5256   NewVD->setLexicalDeclContext(CurContext);
5257   if (NewTemplate)
5258     NewTemplate->setLexicalDeclContext(CurContext);
5259 
5260   if (IsLocalExternDecl)
5261     NewVD->setLocalExternDecl();
5262 
5263   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5264     if (NewVD->hasLocalStorage()) {
5265       // C++11 [dcl.stc]p4:
5266       //   When thread_local is applied to a variable of block scope the
5267       //   storage-class-specifier static is implied if it does not appear
5268       //   explicitly.
5269       // Core issue: 'static' is not implied if the variable is declared
5270       //   'extern'.
5271       if (SCSpec == DeclSpec::SCS_unspecified &&
5272           TSCS == DeclSpec::TSCS_thread_local &&
5273           DC->isFunctionOrMethod())
5274         NewVD->setTSCSpec(TSCS);
5275       else
5276         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5277              diag::err_thread_non_global)
5278           << DeclSpec::getSpecifierName(TSCS);
5279     } else if (!Context.getTargetInfo().isTLSSupported())
5280       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5281            diag::err_thread_unsupported);
5282     else
5283       NewVD->setTSCSpec(TSCS);
5284   }
5285 
5286   // C99 6.7.4p3
5287   //   An inline definition of a function with external linkage shall
5288   //   not contain a definition of a modifiable object with static or
5289   //   thread storage duration...
5290   // We only apply this when the function is required to be defined
5291   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5292   // that a local variable with thread storage duration still has to
5293   // be marked 'static'.  Also note that it's possible to get these
5294   // semantics in C++ using __attribute__((gnu_inline)).
5295   if (SC == SC_Static && S->getFnParent() != 0 &&
5296       !NewVD->getType().isConstQualified()) {
5297     FunctionDecl *CurFD = getCurFunctionDecl();
5298     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5299       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5300            diag::warn_static_local_in_extern_inline);
5301       MaybeSuggestAddingStaticToDecl(CurFD);
5302     }
5303   }
5304 
5305   if (D.getDeclSpec().isModulePrivateSpecified()) {
5306     if (IsVariableTemplateSpecialization)
5307       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5308           << (IsPartialSpecialization ? 1 : 0)
5309           << FixItHint::CreateRemoval(
5310                  D.getDeclSpec().getModulePrivateSpecLoc());
5311     else if (IsExplicitSpecialization)
5312       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5313         << 2
5314         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5315     else if (NewVD->hasLocalStorage())
5316       Diag(NewVD->getLocation(), diag::err_module_private_local)
5317         << 0 << NewVD->getDeclName()
5318         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5319         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5320     else {
5321       NewVD->setModulePrivate();
5322       if (NewTemplate)
5323         NewTemplate->setModulePrivate();
5324     }
5325   }
5326 
5327   // Handle attributes prior to checking for duplicates in MergeVarDecl
5328   ProcessDeclAttributes(S, NewVD, D);
5329 
5330   if (NewVD->hasAttrs())
5331     CheckAlignasUnderalignment(NewVD);
5332 
5333   if (getLangOpts().CUDA) {
5334     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5335     // storage [duration]."
5336     if (SC == SC_None && S->getFnParent() != 0 &&
5337         (NewVD->hasAttr<CUDASharedAttr>() ||
5338          NewVD->hasAttr<CUDAConstantAttr>())) {
5339       NewVD->setStorageClass(SC_Static);
5340     }
5341   }
5342 
5343   // In auto-retain/release, infer strong retension for variables of
5344   // retainable type.
5345   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5346     NewVD->setInvalidDecl();
5347 
5348   // Handle GNU asm-label extension (encoded as an attribute).
5349   if (Expr *E = (Expr*)D.getAsmLabel()) {
5350     // The parser guarantees this is a string.
5351     StringLiteral *SE = cast<StringLiteral>(E);
5352     StringRef Label = SE->getString();
5353     if (S->getFnParent() != 0) {
5354       switch (SC) {
5355       case SC_None:
5356       case SC_Auto:
5357         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5358         break;
5359       case SC_Register:
5360         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5361           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5362         break;
5363       case SC_Static:
5364       case SC_Extern:
5365       case SC_PrivateExtern:
5366       case SC_OpenCLWorkGroupLocal:
5367         break;
5368       }
5369     }
5370 
5371     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5372                                                 Context, Label, 0));
5373   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5374     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5375       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5376     if (I != ExtnameUndeclaredIdentifiers.end()) {
5377       NewVD->addAttr(I->second);
5378       ExtnameUndeclaredIdentifiers.erase(I);
5379     }
5380   }
5381 
5382   // Diagnose shadowed variables before filtering for scope.
5383   if (D.getCXXScopeSpec().isEmpty())
5384     CheckShadow(S, NewVD, Previous);
5385 
5386   // Don't consider existing declarations that are in a different
5387   // scope and are out-of-semantic-context declarations (if the new
5388   // declaration has linkage).
5389   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5390                        D.getCXXScopeSpec().isNotEmpty() ||
5391                        IsExplicitSpecialization ||
5392                        IsVariableTemplateSpecialization);
5393 
5394   // Check whether the previous declaration is in the same block scope. This
5395   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5396   if (getLangOpts().CPlusPlus &&
5397       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5398     NewVD->setPreviousDeclInSameBlockScope(
5399         Previous.isSingleResult() && !Previous.isShadowed() &&
5400         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5401 
5402   if (!getLangOpts().CPlusPlus) {
5403     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5404   } else {
5405     // If this is an explicit specialization of a static data member, check it.
5406     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5407         CheckMemberSpecialization(NewVD, Previous))
5408       NewVD->setInvalidDecl();
5409 
5410     // Merge the decl with the existing one if appropriate.
5411     if (!Previous.empty()) {
5412       if (Previous.isSingleResult() &&
5413           isa<FieldDecl>(Previous.getFoundDecl()) &&
5414           D.getCXXScopeSpec().isSet()) {
5415         // The user tried to define a non-static data member
5416         // out-of-line (C++ [dcl.meaning]p1).
5417         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5418           << D.getCXXScopeSpec().getRange();
5419         Previous.clear();
5420         NewVD->setInvalidDecl();
5421       }
5422     } else if (D.getCXXScopeSpec().isSet()) {
5423       // No previous declaration in the qualifying scope.
5424       Diag(D.getIdentifierLoc(), diag::err_no_member)
5425         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5426         << D.getCXXScopeSpec().getRange();
5427       NewVD->setInvalidDecl();
5428     }
5429 
5430     if (!IsVariableTemplateSpecialization)
5431       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5432 
5433     if (NewTemplate) {
5434       VarTemplateDecl *PrevVarTemplate =
5435           NewVD->getPreviousDecl()
5436               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5437               : 0;
5438 
5439       // Check the template parameter list of this declaration, possibly
5440       // merging in the template parameter list from the previous variable
5441       // template declaration.
5442       if (CheckTemplateParameterList(
5443               TemplateParams,
5444               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5445                               : 0,
5446               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5447                DC->isDependentContext())
5448                   ? TPC_ClassTemplateMember
5449                   : TPC_VarTemplate))
5450         NewVD->setInvalidDecl();
5451 
5452       // If we are providing an explicit specialization of a static variable
5453       // template, make a note of that.
5454       if (PrevVarTemplate &&
5455           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5456         PrevVarTemplate->setMemberSpecialization();
5457     }
5458   }
5459 
5460   ProcessPragmaWeak(S, NewVD);
5461 
5462   // If this is the first declaration of an extern C variable, update
5463   // the map of such variables.
5464   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5465       isIncompleteDeclExternC(*this, NewVD))
5466     RegisterLocallyScopedExternCDecl(NewVD, S);
5467 
5468   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5469     Decl *ManglingContextDecl;
5470     if (MangleNumberingContext *MCtx =
5471             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5472                                           ManglingContextDecl)) {
5473       Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5474     }
5475   }
5476 
5477   if (NewTemplate) {
5478     if (NewVD->isInvalidDecl())
5479       NewTemplate->setInvalidDecl();
5480     ActOnDocumentableDecl(NewTemplate);
5481     return NewTemplate;
5482   }
5483 
5484   return NewVD;
5485 }
5486 
5487 /// \brief Diagnose variable or built-in function shadowing.  Implements
5488 /// -Wshadow.
5489 ///
5490 /// This method is called whenever a VarDecl is added to a "useful"
5491 /// scope.
5492 ///
5493 /// \param S the scope in which the shadowing name is being declared
5494 /// \param R the lookup of the name
5495 ///
5496 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5497   // Return if warning is ignored.
5498   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
5499         DiagnosticsEngine::Ignored)
5500     return;
5501 
5502   // Don't diagnose declarations at file scope.
5503   if (D->hasGlobalStorage())
5504     return;
5505 
5506   DeclContext *NewDC = D->getDeclContext();
5507 
5508   // Only diagnose if we're shadowing an unambiguous field or variable.
5509   if (R.getResultKind() != LookupResult::Found)
5510     return;
5511 
5512   NamedDecl* ShadowedDecl = R.getFoundDecl();
5513   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5514     return;
5515 
5516   // Fields are not shadowed by variables in C++ static methods.
5517   if (isa<FieldDecl>(ShadowedDecl))
5518     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5519       if (MD->isStatic())
5520         return;
5521 
5522   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5523     if (shadowedVar->isExternC()) {
5524       // For shadowing external vars, make sure that we point to the global
5525       // declaration, not a locally scoped extern declaration.
5526       for (VarDecl::redecl_iterator
5527              I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5528            I != E; ++I)
5529         if (I->isFileVarDecl()) {
5530           ShadowedDecl = *I;
5531           break;
5532         }
5533     }
5534 
5535   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5536 
5537   // Only warn about certain kinds of shadowing for class members.
5538   if (NewDC && NewDC->isRecord()) {
5539     // In particular, don't warn about shadowing non-class members.
5540     if (!OldDC->isRecord())
5541       return;
5542 
5543     // TODO: should we warn about static data members shadowing
5544     // static data members from base classes?
5545 
5546     // TODO: don't diagnose for inaccessible shadowed members.
5547     // This is hard to do perfectly because we might friend the
5548     // shadowing context, but that's just a false negative.
5549   }
5550 
5551   // Determine what kind of declaration we're shadowing.
5552   unsigned Kind;
5553   if (isa<RecordDecl>(OldDC)) {
5554     if (isa<FieldDecl>(ShadowedDecl))
5555       Kind = 3; // field
5556     else
5557       Kind = 2; // static data member
5558   } else if (OldDC->isFileContext())
5559     Kind = 1; // global
5560   else
5561     Kind = 0; // local
5562 
5563   DeclarationName Name = R.getLookupName();
5564 
5565   // Emit warning and note.
5566   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5567     return;
5568   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5569   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5570 }
5571 
5572 /// \brief Check -Wshadow without the advantage of a previous lookup.
5573 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5574   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
5575         DiagnosticsEngine::Ignored)
5576     return;
5577 
5578   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5579                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5580   LookupName(R, S);
5581   CheckShadow(S, D, R);
5582 }
5583 
5584 /// Check for conflict between this global or extern "C" declaration and
5585 /// previous global or extern "C" declarations. This is only used in C++.
5586 template<typename T>
5587 static bool checkGlobalOrExternCConflict(
5588     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5589   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5590   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5591 
5592   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5593     // The common case: this global doesn't conflict with any extern "C"
5594     // declaration.
5595     return false;
5596   }
5597 
5598   if (Prev) {
5599     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5600       // Both the old and new declarations have C language linkage. This is a
5601       // redeclaration.
5602       Previous.clear();
5603       Previous.addDecl(Prev);
5604       return true;
5605     }
5606 
5607     // This is a global, non-extern "C" declaration, and there is a previous
5608     // non-global extern "C" declaration. Diagnose if this is a variable
5609     // declaration.
5610     if (!isa<VarDecl>(ND))
5611       return false;
5612   } else {
5613     // The declaration is extern "C". Check for any declaration in the
5614     // translation unit which might conflict.
5615     if (IsGlobal) {
5616       // We have already performed the lookup into the translation unit.
5617       IsGlobal = false;
5618       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5619            I != E; ++I) {
5620         if (isa<VarDecl>(*I)) {
5621           Prev = *I;
5622           break;
5623         }
5624       }
5625     } else {
5626       DeclContext::lookup_result R =
5627           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5628       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5629            I != E; ++I) {
5630         if (isa<VarDecl>(*I)) {
5631           Prev = *I;
5632           break;
5633         }
5634         // FIXME: If we have any other entity with this name in global scope,
5635         // the declaration is ill-formed, but that is a defect: it breaks the
5636         // 'stat' hack, for instance. Only variables can have mangled name
5637         // clashes with extern "C" declarations, so only they deserve a
5638         // diagnostic.
5639       }
5640     }
5641 
5642     if (!Prev)
5643       return false;
5644   }
5645 
5646   // Use the first declaration's location to ensure we point at something which
5647   // is lexically inside an extern "C" linkage-spec.
5648   assert(Prev && "should have found a previous declaration to diagnose");
5649   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5650     Prev = FD->getFirstDecl();
5651   else
5652     Prev = cast<VarDecl>(Prev)->getFirstDecl();
5653 
5654   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5655     << IsGlobal << ND;
5656   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5657     << IsGlobal;
5658   return false;
5659 }
5660 
5661 /// Apply special rules for handling extern "C" declarations. Returns \c true
5662 /// if we have found that this is a redeclaration of some prior entity.
5663 ///
5664 /// Per C++ [dcl.link]p6:
5665 ///   Two declarations [for a function or variable] with C language linkage
5666 ///   with the same name that appear in different scopes refer to the same
5667 ///   [entity]. An entity with C language linkage shall not be declared with
5668 ///   the same name as an entity in global scope.
5669 template<typename T>
5670 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5671                                                   LookupResult &Previous) {
5672   if (!S.getLangOpts().CPlusPlus) {
5673     // In C, when declaring a global variable, look for a corresponding 'extern'
5674     // variable declared in function scope. We don't need this in C++, because
5675     // we find local extern decls in the surrounding file-scope DeclContext.
5676     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5677       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5678         Previous.clear();
5679         Previous.addDecl(Prev);
5680         return true;
5681       }
5682     }
5683     return false;
5684   }
5685 
5686   // A declaration in the translation unit can conflict with an extern "C"
5687   // declaration.
5688   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5689     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5690 
5691   // An extern "C" declaration can conflict with a declaration in the
5692   // translation unit or can be a redeclaration of an extern "C" declaration
5693   // in another scope.
5694   if (isIncompleteDeclExternC(S,ND))
5695     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5696 
5697   // Neither global nor extern "C": nothing to do.
5698   return false;
5699 }
5700 
5701 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
5702   // If the decl is already known invalid, don't check it.
5703   if (NewVD->isInvalidDecl())
5704     return;
5705 
5706   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5707   QualType T = TInfo->getType();
5708 
5709   // Defer checking an 'auto' type until its initializer is attached.
5710   if (T->isUndeducedType())
5711     return;
5712 
5713   if (T->isObjCObjectType()) {
5714     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5715       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5716     T = Context.getObjCObjectPointerType(T);
5717     NewVD->setType(T);
5718   }
5719 
5720   // Emit an error if an address space was applied to decl with local storage.
5721   // This includes arrays of objects with address space qualifiers, but not
5722   // automatic variables that point to other address spaces.
5723   // ISO/IEC TR 18037 S5.1.2
5724   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5725     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5726     NewVD->setInvalidDecl();
5727     return;
5728   }
5729 
5730   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5731   // __constant address space.
5732   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5733       && T.getAddressSpace() != LangAS::opencl_constant
5734       && !T->isSamplerT()){
5735     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5736     NewVD->setInvalidDecl();
5737     return;
5738   }
5739 
5740   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5741   // scope.
5742   if ((getLangOpts().OpenCLVersion >= 120)
5743       && NewVD->isStaticLocal()) {
5744     Diag(NewVD->getLocation(), diag::err_static_function_scope);
5745     NewVD->setInvalidDecl();
5746     return;
5747   }
5748 
5749   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5750       && !NewVD->hasAttr<BlocksAttr>()) {
5751     if (getLangOpts().getGC() != LangOptions::NonGC)
5752       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5753     else {
5754       assert(!getLangOpts().ObjCAutoRefCount);
5755       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5756     }
5757   }
5758 
5759   bool isVM = T->isVariablyModifiedType();
5760   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5761       NewVD->hasAttr<BlocksAttr>())
5762     getCurFunction()->setHasBranchProtectedScope();
5763 
5764   if ((isVM && NewVD->hasLinkage()) ||
5765       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5766     bool SizeIsNegative;
5767     llvm::APSInt Oversized;
5768     TypeSourceInfo *FixedTInfo =
5769       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5770                                                     SizeIsNegative, Oversized);
5771     if (FixedTInfo == 0 && T->isVariableArrayType()) {
5772       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5773       // FIXME: This won't give the correct result for
5774       // int a[10][n];
5775       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5776 
5777       if (NewVD->isFileVarDecl())
5778         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5779         << SizeRange;
5780       else if (NewVD->isStaticLocal())
5781         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5782         << SizeRange;
5783       else
5784         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5785         << SizeRange;
5786       NewVD->setInvalidDecl();
5787       return;
5788     }
5789 
5790     if (FixedTInfo == 0) {
5791       if (NewVD->isFileVarDecl())
5792         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5793       else
5794         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5795       NewVD->setInvalidDecl();
5796       return;
5797     }
5798 
5799     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5800     NewVD->setType(FixedTInfo->getType());
5801     NewVD->setTypeSourceInfo(FixedTInfo);
5802   }
5803 
5804   if (T->isVoidType()) {
5805     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5806     //                    of objects and functions.
5807     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5808       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5809         << T;
5810       NewVD->setInvalidDecl();
5811       return;
5812     }
5813   }
5814 
5815   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5816     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5817     NewVD->setInvalidDecl();
5818     return;
5819   }
5820 
5821   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5822     Diag(NewVD->getLocation(), diag::err_block_on_vm);
5823     NewVD->setInvalidDecl();
5824     return;
5825   }
5826 
5827   if (NewVD->isConstexpr() && !T->isDependentType() &&
5828       RequireLiteralType(NewVD->getLocation(), T,
5829                          diag::err_constexpr_var_non_literal)) {
5830     // Can't perform this check until the type is deduced.
5831     NewVD->setInvalidDecl();
5832     return;
5833   }
5834 }
5835 
5836 /// \brief Perform semantic checking on a newly-created variable
5837 /// declaration.
5838 ///
5839 /// This routine performs all of the type-checking required for a
5840 /// variable declaration once it has been built. It is used both to
5841 /// check variables after they have been parsed and their declarators
5842 /// have been translated into a declaration, and to check variables
5843 /// that have been instantiated from a template.
5844 ///
5845 /// Sets NewVD->isInvalidDecl() if an error was encountered.
5846 ///
5847 /// Returns true if the variable declaration is a redeclaration.
5848 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
5849   CheckVariableDeclarationType(NewVD);
5850 
5851   // If the decl is already known invalid, don't check it.
5852   if (NewVD->isInvalidDecl())
5853     return false;
5854 
5855   // If we did not find anything by this name, look for a non-visible
5856   // extern "C" declaration with the same name.
5857   if (Previous.empty() &&
5858       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
5859     Previous.setShadowed();
5860 
5861   // Filter out any non-conflicting previous declarations.
5862   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5863 
5864   if (!Previous.empty()) {
5865     MergeVarDecl(NewVD, Previous);
5866     return true;
5867   }
5868   return false;
5869 }
5870 
5871 /// \brief Data used with FindOverriddenMethod
5872 struct FindOverriddenMethodData {
5873   Sema *S;
5874   CXXMethodDecl *Method;
5875 };
5876 
5877 /// \brief Member lookup function that determines whether a given C++
5878 /// method overrides a method in a base class, to be used with
5879 /// CXXRecordDecl::lookupInBases().
5880 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
5881                                  CXXBasePath &Path,
5882                                  void *UserData) {
5883   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5884 
5885   FindOverriddenMethodData *Data
5886     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
5887 
5888   DeclarationName Name = Data->Method->getDeclName();
5889 
5890   // FIXME: Do we care about other names here too?
5891   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5892     // We really want to find the base class destructor here.
5893     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5894     CanQualType CT = Data->S->Context.getCanonicalType(T);
5895 
5896     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
5897   }
5898 
5899   for (Path.Decls = BaseRecord->lookup(Name);
5900        !Path.Decls.empty();
5901        Path.Decls = Path.Decls.slice(1)) {
5902     NamedDecl *D = Path.Decls.front();
5903     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5904       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
5905         return true;
5906     }
5907   }
5908 
5909   return false;
5910 }
5911 
5912 namespace {
5913   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5914 }
5915 /// \brief Report an error regarding overriding, along with any relevant
5916 /// overriden methods.
5917 ///
5918 /// \param DiagID the primary error to report.
5919 /// \param MD the overriding method.
5920 /// \param OEK which overrides to include as notes.
5921 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5922                             OverrideErrorKind OEK = OEK_All) {
5923   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5924   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5925                                       E = MD->end_overridden_methods();
5926        I != E; ++I) {
5927     // This check (& the OEK parameter) could be replaced by a predicate, but
5928     // without lambdas that would be overkill. This is still nicer than writing
5929     // out the diag loop 3 times.
5930     if ((OEK == OEK_All) ||
5931         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5932         (OEK == OEK_Deleted && (*I)->isDeleted()))
5933       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5934   }
5935 }
5936 
5937 /// AddOverriddenMethods - See if a method overrides any in the base classes,
5938 /// and if so, check that it's a valid override and remember it.
5939 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5940   // Look for virtual methods in base classes that this method might override.
5941   CXXBasePaths Paths;
5942   FindOverriddenMethodData Data;
5943   Data.Method = MD;
5944   Data.S = this;
5945   bool hasDeletedOverridenMethods = false;
5946   bool hasNonDeletedOverridenMethods = false;
5947   bool AddedAny = false;
5948   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5949     for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5950          E = Paths.found_decls_end(); I != E; ++I) {
5951       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
5952         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
5953         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
5954             !CheckOverridingFunctionAttributes(MD, OldMD) &&
5955             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
5956             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
5957           hasDeletedOverridenMethods |= OldMD->isDeleted();
5958           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
5959           AddedAny = true;
5960         }
5961       }
5962     }
5963   }
5964 
5965   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5966     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5967   }
5968   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5969     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5970   }
5971 
5972   return AddedAny;
5973 }
5974 
5975 namespace {
5976   // Struct for holding all of the extra arguments needed by
5977   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5978   struct ActOnFDArgs {
5979     Scope *S;
5980     Declarator &D;
5981     MultiTemplateParamsArg TemplateParamLists;
5982     bool AddToScope;
5983   };
5984 }
5985 
5986 namespace {
5987 
5988 // Callback to only accept typo corrections that have a non-zero edit distance.
5989 // Also only accept corrections that have the same parent decl.
5990 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5991  public:
5992   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5993                             CXXRecordDecl *Parent)
5994       : Context(Context), OriginalFD(TypoFD),
5995         ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
5996 
5997   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5998     if (candidate.getEditDistance() == 0)
5999       return false;
6000 
6001     SmallVector<unsigned, 1> MismatchedParams;
6002     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6003                                           CDeclEnd = candidate.end();
6004          CDecl != CDeclEnd; ++CDecl) {
6005       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6006 
6007       if (FD && !FD->hasBody() &&
6008           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6009         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6010           CXXRecordDecl *Parent = MD->getParent();
6011           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6012             return true;
6013         } else if (!ExpectedParent) {
6014           return true;
6015         }
6016       }
6017     }
6018 
6019     return false;
6020   }
6021 
6022  private:
6023   ASTContext &Context;
6024   FunctionDecl *OriginalFD;
6025   CXXRecordDecl *ExpectedParent;
6026 };
6027 
6028 }
6029 
6030 /// \brief Generate diagnostics for an invalid function redeclaration.
6031 ///
6032 /// This routine handles generating the diagnostic messages for an invalid
6033 /// function redeclaration, including finding possible similar declarations
6034 /// or performing typo correction if there are no previous declarations with
6035 /// the same name.
6036 ///
6037 /// Returns a NamedDecl iff typo correction was performed and substituting in
6038 /// the new declaration name does not cause new errors.
6039 static NamedDecl *DiagnoseInvalidRedeclaration(
6040     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6041     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6042   DeclarationName Name = NewFD->getDeclName();
6043   DeclContext *NewDC = NewFD->getDeclContext();
6044   SmallVector<unsigned, 1> MismatchedParams;
6045   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6046   TypoCorrection Correction;
6047   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6048   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6049                                    : diag::err_member_decl_does_not_match;
6050   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6051                     IsLocalFriend ? Sema::LookupLocalFriendName
6052                                   : Sema::LookupOrdinaryName,
6053                     Sema::ForRedeclaration);
6054 
6055   NewFD->setInvalidDecl();
6056   if (IsLocalFriend)
6057     SemaRef.LookupName(Prev, S);
6058   else
6059     SemaRef.LookupQualifiedName(Prev, NewDC);
6060   assert(!Prev.isAmbiguous() &&
6061          "Cannot have an ambiguity in previous-declaration lookup");
6062   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6063   DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6064                                       MD ? MD->getParent() : 0);
6065   if (!Prev.empty()) {
6066     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6067          Func != FuncEnd; ++Func) {
6068       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6069       if (FD &&
6070           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6071         // Add 1 to the index so that 0 can mean the mismatch didn't
6072         // involve a parameter
6073         unsigned ParamNum =
6074             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6075         NearMatches.push_back(std::make_pair(FD, ParamNum));
6076       }
6077     }
6078   // If the qualified name lookup yielded nothing, try typo correction
6079   } else if ((Correction = SemaRef.CorrectTypo(
6080                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6081                  &ExtraArgs.D.getCXXScopeSpec(), Validator,
6082                  IsLocalFriend ? 0 : NewDC))) {
6083     // Set up everything for the call to ActOnFunctionDeclarator
6084     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6085                               ExtraArgs.D.getIdentifierLoc());
6086     Previous.clear();
6087     Previous.setLookupName(Correction.getCorrection());
6088     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6089                                     CDeclEnd = Correction.end();
6090          CDecl != CDeclEnd; ++CDecl) {
6091       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6092       if (FD && !FD->hasBody() &&
6093           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6094         Previous.addDecl(FD);
6095       }
6096     }
6097     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6098 
6099     NamedDecl *Result;
6100     // Retry building the function declaration with the new previous
6101     // declarations, and with errors suppressed.
6102     {
6103       // Trap errors.
6104       Sema::SFINAETrap Trap(SemaRef);
6105 
6106       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6107       // pieces need to verify the typo-corrected C++ declaration and hopefully
6108       // eliminate the need for the parameter pack ExtraArgs.
6109       Result = SemaRef.ActOnFunctionDeclarator(
6110           ExtraArgs.S, ExtraArgs.D,
6111           Correction.getCorrectionDecl()->getDeclContext(),
6112           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6113           ExtraArgs.AddToScope);
6114 
6115       if (Trap.hasErrorOccurred())
6116         Result = 0;
6117     }
6118 
6119     if (Result) {
6120       // Determine which correction we picked.
6121       Decl *Canonical = Result->getCanonicalDecl();
6122       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6123            I != E; ++I)
6124         if ((*I)->getCanonicalDecl() == Canonical)
6125           Correction.setCorrectionDecl(*I);
6126 
6127       SemaRef.diagnoseTypo(
6128           Correction,
6129           SemaRef.PDiag(IsLocalFriend
6130                           ? diag::err_no_matching_local_friend_suggest
6131                           : diag::err_member_decl_does_not_match_suggest)
6132             << Name << NewDC << IsDefinition);
6133       return Result;
6134     }
6135 
6136     // Pretend the typo correction never occurred
6137     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6138                               ExtraArgs.D.getIdentifierLoc());
6139     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6140     Previous.clear();
6141     Previous.setLookupName(Name);
6142   }
6143 
6144   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6145       << Name << NewDC << IsDefinition << NewFD->getLocation();
6146 
6147   bool NewFDisConst = false;
6148   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6149     NewFDisConst = NewMD->isConst();
6150 
6151   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6152        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6153        NearMatch != NearMatchEnd; ++NearMatch) {
6154     FunctionDecl *FD = NearMatch->first;
6155     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6156     bool FDisConst = MD && MD->isConst();
6157     bool IsMember = MD || !IsLocalFriend;
6158 
6159     // FIXME: These notes are poorly worded for the local friend case.
6160     if (unsigned Idx = NearMatch->second) {
6161       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6162       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6163       if (Loc.isInvalid()) Loc = FD->getLocation();
6164       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6165                                  : diag::note_local_decl_close_param_match)
6166         << Idx << FDParam->getType()
6167         << NewFD->getParamDecl(Idx - 1)->getType();
6168     } else if (FDisConst != NewFDisConst) {
6169       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6170           << NewFDisConst << FD->getSourceRange().getEnd();
6171     } else
6172       SemaRef.Diag(FD->getLocation(),
6173                    IsMember ? diag::note_member_def_close_match
6174                             : diag::note_local_decl_close_match);
6175   }
6176   return 0;
6177 }
6178 
6179 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6180                                                           Declarator &D) {
6181   switch (D.getDeclSpec().getStorageClassSpec()) {
6182   default: llvm_unreachable("Unknown storage class!");
6183   case DeclSpec::SCS_auto:
6184   case DeclSpec::SCS_register:
6185   case DeclSpec::SCS_mutable:
6186     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6187                  diag::err_typecheck_sclass_func);
6188     D.setInvalidType();
6189     break;
6190   case DeclSpec::SCS_unspecified: break;
6191   case DeclSpec::SCS_extern:
6192     if (D.getDeclSpec().isExternInLinkageSpec())
6193       return SC_None;
6194     return SC_Extern;
6195   case DeclSpec::SCS_static: {
6196     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6197       // C99 6.7.1p5:
6198       //   The declaration of an identifier for a function that has
6199       //   block scope shall have no explicit storage-class specifier
6200       //   other than extern
6201       // See also (C++ [dcl.stc]p4).
6202       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6203                    diag::err_static_block_func);
6204       break;
6205     } else
6206       return SC_Static;
6207   }
6208   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6209   }
6210 
6211   // No explicit storage class has already been returned
6212   return SC_None;
6213 }
6214 
6215 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6216                                            DeclContext *DC, QualType &R,
6217                                            TypeSourceInfo *TInfo,
6218                                            FunctionDecl::StorageClass SC,
6219                                            bool &IsVirtualOkay) {
6220   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6221   DeclarationName Name = NameInfo.getName();
6222 
6223   FunctionDecl *NewFD = 0;
6224   bool isInline = D.getDeclSpec().isInlineSpecified();
6225 
6226   if (!SemaRef.getLangOpts().CPlusPlus) {
6227     // Determine whether the function was written with a
6228     // prototype. This true when:
6229     //   - there is a prototype in the declarator, or
6230     //   - the type R of the function is some kind of typedef or other reference
6231     //     to a type name (which eventually refers to a function type).
6232     bool HasPrototype =
6233       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6234       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6235 
6236     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6237                                  D.getLocStart(), NameInfo, R,
6238                                  TInfo, SC, isInline,
6239                                  HasPrototype, false);
6240     if (D.isInvalidType())
6241       NewFD->setInvalidDecl();
6242 
6243     // Set the lexical context.
6244     NewFD->setLexicalDeclContext(SemaRef.CurContext);
6245 
6246     return NewFD;
6247   }
6248 
6249   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6250   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6251 
6252   // Check that the return type is not an abstract class type.
6253   // For record types, this is done by the AbstractClassUsageDiagnoser once
6254   // the class has been completely parsed.
6255   if (!DC->isRecord() &&
6256       SemaRef.RequireNonAbstractType(
6257           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
6258           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
6259     D.setInvalidType();
6260 
6261   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6262     // This is a C++ constructor declaration.
6263     assert(DC->isRecord() &&
6264            "Constructors can only be declared in a member context");
6265 
6266     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6267     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6268                                       D.getLocStart(), NameInfo,
6269                                       R, TInfo, isExplicit, isInline,
6270                                       /*isImplicitlyDeclared=*/false,
6271                                       isConstexpr);
6272 
6273   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6274     // This is a C++ destructor declaration.
6275     if (DC->isRecord()) {
6276       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6277       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6278       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6279                                         SemaRef.Context, Record,
6280                                         D.getLocStart(),
6281                                         NameInfo, R, TInfo, isInline,
6282                                         /*isImplicitlyDeclared=*/false);
6283 
6284       // If the class is complete, then we now create the implicit exception
6285       // specification. If the class is incomplete or dependent, we can't do
6286       // it yet.
6287       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6288           Record->getDefinition() && !Record->isBeingDefined() &&
6289           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6290         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6291       }
6292 
6293       IsVirtualOkay = true;
6294       return NewDD;
6295 
6296     } else {
6297       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6298       D.setInvalidType();
6299 
6300       // Create a FunctionDecl to satisfy the function definition parsing
6301       // code path.
6302       return FunctionDecl::Create(SemaRef.Context, DC,
6303                                   D.getLocStart(),
6304                                   D.getIdentifierLoc(), Name, R, TInfo,
6305                                   SC, isInline,
6306                                   /*hasPrototype=*/true, isConstexpr);
6307     }
6308 
6309   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6310     if (!DC->isRecord()) {
6311       SemaRef.Diag(D.getIdentifierLoc(),
6312            diag::err_conv_function_not_member);
6313       return 0;
6314     }
6315 
6316     SemaRef.CheckConversionDeclarator(D, R, SC);
6317     IsVirtualOkay = true;
6318     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6319                                      D.getLocStart(), NameInfo,
6320                                      R, TInfo, isInline, isExplicit,
6321                                      isConstexpr, SourceLocation());
6322 
6323   } else if (DC->isRecord()) {
6324     // If the name of the function is the same as the name of the record,
6325     // then this must be an invalid constructor that has a return type.
6326     // (The parser checks for a return type and makes the declarator a
6327     // constructor if it has no return type).
6328     if (Name.getAsIdentifierInfo() &&
6329         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6330       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6331         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6332         << SourceRange(D.getIdentifierLoc());
6333       return 0;
6334     }
6335 
6336     // This is a C++ method declaration.
6337     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6338                                                cast<CXXRecordDecl>(DC),
6339                                                D.getLocStart(), NameInfo, R,
6340                                                TInfo, SC, isInline,
6341                                                isConstexpr, SourceLocation());
6342     IsVirtualOkay = !Ret->isStatic();
6343     return Ret;
6344   } else {
6345     // Determine whether the function was written with a
6346     // prototype. This true when:
6347     //   - we're in C++ (where every function has a prototype),
6348     return FunctionDecl::Create(SemaRef.Context, DC,
6349                                 D.getLocStart(),
6350                                 NameInfo, R, TInfo, SC, isInline,
6351                                 true/*HasPrototype*/, isConstexpr);
6352   }
6353 }
6354 
6355 enum OpenCLParamType {
6356   ValidKernelParam,
6357   PtrPtrKernelParam,
6358   PtrKernelParam,
6359   InvalidKernelParam,
6360   RecordKernelParam
6361 };
6362 
6363 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6364   if (PT->isPointerType()) {
6365     QualType PointeeType = PT->getPointeeType();
6366     return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6367   }
6368 
6369   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6370   // be used as builtin types.
6371 
6372   if (PT->isImageType())
6373     return PtrKernelParam;
6374 
6375   if (PT->isBooleanType())
6376     return InvalidKernelParam;
6377 
6378   if (PT->isEventT())
6379     return InvalidKernelParam;
6380 
6381   if (PT->isHalfType())
6382     return InvalidKernelParam;
6383 
6384   if (PT->isRecordType())
6385     return RecordKernelParam;
6386 
6387   return ValidKernelParam;
6388 }
6389 
6390 static void checkIsValidOpenCLKernelParameter(
6391   Sema &S,
6392   Declarator &D,
6393   ParmVarDecl *Param,
6394   llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6395   QualType PT = Param->getType();
6396 
6397   // Cache the valid types we encounter to avoid rechecking structs that are
6398   // used again
6399   if (ValidTypes.count(PT.getTypePtr()))
6400     return;
6401 
6402   switch (getOpenCLKernelParameterType(PT)) {
6403   case PtrPtrKernelParam:
6404     // OpenCL v1.2 s6.9.a:
6405     // A kernel function argument cannot be declared as a
6406     // pointer to a pointer type.
6407     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6408     D.setInvalidType();
6409     return;
6410 
6411     // OpenCL v1.2 s6.9.k:
6412     // Arguments to kernel functions in a program cannot be declared with the
6413     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6414     // uintptr_t or a struct and/or union that contain fields declared to be
6415     // one of these built-in scalar types.
6416 
6417   case InvalidKernelParam:
6418     // OpenCL v1.2 s6.8 n:
6419     // A kernel function argument cannot be declared
6420     // of event_t type.
6421     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6422     D.setInvalidType();
6423     return;
6424 
6425   case PtrKernelParam:
6426   case ValidKernelParam:
6427     ValidTypes.insert(PT.getTypePtr());
6428     return;
6429 
6430   case RecordKernelParam:
6431     break;
6432   }
6433 
6434   // Track nested structs we will inspect
6435   SmallVector<const Decl *, 4> VisitStack;
6436 
6437   // Track where we are in the nested structs. Items will migrate from
6438   // VisitStack to HistoryStack as we do the DFS for bad field.
6439   SmallVector<const FieldDecl *, 4> HistoryStack;
6440   HistoryStack.push_back((const FieldDecl *) 0);
6441 
6442   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6443   VisitStack.push_back(PD);
6444 
6445   assert(VisitStack.back() && "First decl null?");
6446 
6447   do {
6448     const Decl *Next = VisitStack.pop_back_val();
6449     if (!Next) {
6450       assert(!HistoryStack.empty());
6451       // Found a marker, we have gone up a level
6452       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6453         ValidTypes.insert(Hist->getType().getTypePtr());
6454 
6455       continue;
6456     }
6457 
6458     // Adds everything except the original parameter declaration (which is not a
6459     // field itself) to the history stack.
6460     const RecordDecl *RD;
6461     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6462       HistoryStack.push_back(Field);
6463       RD = Field->getType()->castAs<RecordType>()->getDecl();
6464     } else {
6465       RD = cast<RecordDecl>(Next);
6466     }
6467 
6468     // Add a null marker so we know when we've gone back up a level
6469     VisitStack.push_back((const Decl *) 0);
6470 
6471     for (RecordDecl::field_iterator I = RD->field_begin(),
6472            E = RD->field_end(); I != E; ++I) {
6473       const FieldDecl *FD = *I;
6474       QualType QT = FD->getType();
6475 
6476       if (ValidTypes.count(QT.getTypePtr()))
6477         continue;
6478 
6479       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6480       if (ParamType == ValidKernelParam)
6481         continue;
6482 
6483       if (ParamType == RecordKernelParam) {
6484         VisitStack.push_back(FD);
6485         continue;
6486       }
6487 
6488       // OpenCL v1.2 s6.9.p:
6489       // Arguments to kernel functions that are declared to be a struct or union
6490       // do not allow OpenCL objects to be passed as elements of the struct or
6491       // union.
6492       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6493         S.Diag(Param->getLocation(),
6494                diag::err_record_with_pointers_kernel_param)
6495           << PT->isUnionType()
6496           << PT;
6497       } else {
6498         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6499       }
6500 
6501       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6502         << PD->getDeclName();
6503 
6504       // We have an error, now let's go back up through history and show where
6505       // the offending field came from
6506       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6507              E = HistoryStack.end(); I != E; ++I) {
6508         const FieldDecl *OuterField = *I;
6509         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6510           << OuterField->getType();
6511       }
6512 
6513       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6514         << QT->isPointerType()
6515         << QT;
6516       D.setInvalidType();
6517       return;
6518     }
6519   } while (!VisitStack.empty());
6520 }
6521 
6522 NamedDecl*
6523 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6524                               TypeSourceInfo *TInfo, LookupResult &Previous,
6525                               MultiTemplateParamsArg TemplateParamLists,
6526                               bool &AddToScope) {
6527   QualType R = TInfo->getType();
6528 
6529   assert(R.getTypePtr()->isFunctionType());
6530 
6531   // TODO: consider using NameInfo for diagnostic.
6532   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6533   DeclarationName Name = NameInfo.getName();
6534   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6535 
6536   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6537     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6538          diag::err_invalid_thread)
6539       << DeclSpec::getSpecifierName(TSCS);
6540 
6541   if (D.isFirstDeclarationOfMember())
6542     adjustMemberFunctionCC(R, D.isStaticMember());
6543 
6544   bool isFriend = false;
6545   FunctionTemplateDecl *FunctionTemplate = 0;
6546   bool isExplicitSpecialization = false;
6547   bool isFunctionTemplateSpecialization = false;
6548 
6549   bool isDependentClassScopeExplicitSpecialization = false;
6550   bool HasExplicitTemplateArgs = false;
6551   TemplateArgumentListInfo TemplateArgs;
6552 
6553   bool isVirtualOkay = false;
6554 
6555   DeclContext *OriginalDC = DC;
6556   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6557 
6558   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6559                                               isVirtualOkay);
6560   if (!NewFD) return 0;
6561 
6562   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6563     NewFD->setTopLevelDeclInObjCContainer();
6564 
6565   // Set the lexical context. If this is a function-scope declaration, or has a
6566   // C++ scope specifier, or is the object of a friend declaration, the lexical
6567   // context will be different from the semantic context.
6568   NewFD->setLexicalDeclContext(CurContext);
6569 
6570   if (IsLocalExternDecl)
6571     NewFD->setLocalExternDecl();
6572 
6573   if (getLangOpts().CPlusPlus) {
6574     bool isInline = D.getDeclSpec().isInlineSpecified();
6575     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6576     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6577     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6578     isFriend = D.getDeclSpec().isFriendSpecified();
6579     if (isFriend && !isInline && D.isFunctionDefinition()) {
6580       // C++ [class.friend]p5
6581       //   A function can be defined in a friend declaration of a
6582       //   class . . . . Such a function is implicitly inline.
6583       NewFD->setImplicitlyInline();
6584     }
6585 
6586     // If this is a method defined in an __interface, and is not a constructor
6587     // or an overloaded operator, then set the pure flag (isVirtual will already
6588     // return true).
6589     if (const CXXRecordDecl *Parent =
6590           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6591       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6592         NewFD->setPure(true);
6593     }
6594 
6595     SetNestedNameSpecifier(NewFD, D);
6596     isExplicitSpecialization = false;
6597     isFunctionTemplateSpecialization = false;
6598     if (D.isInvalidType())
6599       NewFD->setInvalidDecl();
6600 
6601     // Match up the template parameter lists with the scope specifier, then
6602     // determine whether we have a template or a template specialization.
6603     bool Invalid = false;
6604     if (TemplateParameterList *TemplateParams =
6605             MatchTemplateParametersToScopeSpecifier(
6606                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6607                 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6608                 isExplicitSpecialization, Invalid)) {
6609       if (TemplateParams->size() > 0) {
6610         // This is a function template
6611 
6612         // Check that we can declare a template here.
6613         if (CheckTemplateDeclScope(S, TemplateParams))
6614           return 0;
6615 
6616         // A destructor cannot be a template.
6617         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6618           Diag(NewFD->getLocation(), diag::err_destructor_template);
6619           return 0;
6620         }
6621 
6622         // If we're adding a template to a dependent context, we may need to
6623         // rebuilding some of the types used within the template parameter list,
6624         // now that we know what the current instantiation is.
6625         if (DC->isDependentContext()) {
6626           ContextRAII SavedContext(*this, DC);
6627           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6628             Invalid = true;
6629         }
6630 
6631 
6632         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6633                                                         NewFD->getLocation(),
6634                                                         Name, TemplateParams,
6635                                                         NewFD);
6636         FunctionTemplate->setLexicalDeclContext(CurContext);
6637         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6638 
6639         // For source fidelity, store the other template param lists.
6640         if (TemplateParamLists.size() > 1) {
6641           NewFD->setTemplateParameterListsInfo(Context,
6642                                                TemplateParamLists.size() - 1,
6643                                                TemplateParamLists.data());
6644         }
6645       } else {
6646         // This is a function template specialization.
6647         isFunctionTemplateSpecialization = true;
6648         // For source fidelity, store all the template param lists.
6649         NewFD->setTemplateParameterListsInfo(Context,
6650                                              TemplateParamLists.size(),
6651                                              TemplateParamLists.data());
6652 
6653         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6654         if (isFriend) {
6655           // We want to remove the "template<>", found here.
6656           SourceRange RemoveRange = TemplateParams->getSourceRange();
6657 
6658           // If we remove the template<> and the name is not a
6659           // template-id, we're actually silently creating a problem:
6660           // the friend declaration will refer to an untemplated decl,
6661           // and clearly the user wants a template specialization.  So
6662           // we need to insert '<>' after the name.
6663           SourceLocation InsertLoc;
6664           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6665             InsertLoc = D.getName().getSourceRange().getEnd();
6666             InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6667           }
6668 
6669           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6670             << Name << RemoveRange
6671             << FixItHint::CreateRemoval(RemoveRange)
6672             << FixItHint::CreateInsertion(InsertLoc, "<>");
6673         }
6674       }
6675     }
6676     else {
6677       // All template param lists were matched against the scope specifier:
6678       // this is NOT (an explicit specialization of) a template.
6679       if (TemplateParamLists.size() > 0)
6680         // For source fidelity, store all the template param lists.
6681         NewFD->setTemplateParameterListsInfo(Context,
6682                                              TemplateParamLists.size(),
6683                                              TemplateParamLists.data());
6684     }
6685 
6686     if (Invalid) {
6687       NewFD->setInvalidDecl();
6688       if (FunctionTemplate)
6689         FunctionTemplate->setInvalidDecl();
6690     }
6691 
6692     // C++ [dcl.fct.spec]p5:
6693     //   The virtual specifier shall only be used in declarations of
6694     //   nonstatic class member functions that appear within a
6695     //   member-specification of a class declaration; see 10.3.
6696     //
6697     if (isVirtual && !NewFD->isInvalidDecl()) {
6698       if (!isVirtualOkay) {
6699         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6700              diag::err_virtual_non_function);
6701       } else if (!CurContext->isRecord()) {
6702         // 'virtual' was specified outside of the class.
6703         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6704              diag::err_virtual_out_of_class)
6705           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6706       } else if (NewFD->getDescribedFunctionTemplate()) {
6707         // C++ [temp.mem]p3:
6708         //  A member function template shall not be virtual.
6709         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6710              diag::err_virtual_member_function_template)
6711           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6712       } else {
6713         // Okay: Add virtual to the method.
6714         NewFD->setVirtualAsWritten(true);
6715       }
6716 
6717       if (getLangOpts().CPlusPlus1y &&
6718           NewFD->getReturnType()->isUndeducedType())
6719         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
6720     }
6721 
6722     if (getLangOpts().CPlusPlus1y &&
6723         (NewFD->isDependentContext() ||
6724          (isFriend && CurContext->isDependentContext())) &&
6725         NewFD->getReturnType()->isUndeducedType()) {
6726       // If the function template is referenced directly (for instance, as a
6727       // member of the current instantiation), pretend it has a dependent type.
6728       // This is not really justified by the standard, but is the only sane
6729       // thing to do.
6730       // FIXME: For a friend function, we have not marked the function as being
6731       // a friend yet, so 'isDependentContext' on the FD doesn't work.
6732       const FunctionProtoType *FPT =
6733           NewFD->getType()->castAs<FunctionProtoType>();
6734       QualType Result =
6735           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
6736       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
6737                                              FPT->getExtProtoInfo()));
6738     }
6739 
6740     // C++ [dcl.fct.spec]p3:
6741     //  The inline specifier shall not appear on a block scope function
6742     //  declaration.
6743     if (isInline && !NewFD->isInvalidDecl()) {
6744       if (CurContext->isFunctionOrMethod()) {
6745         // 'inline' is not allowed on block scope function declaration.
6746         Diag(D.getDeclSpec().getInlineSpecLoc(),
6747              diag::err_inline_declaration_block_scope) << Name
6748           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6749       }
6750     }
6751 
6752     // C++ [dcl.fct.spec]p6:
6753     //  The explicit specifier shall be used only in the declaration of a
6754     //  constructor or conversion function within its class definition;
6755     //  see 12.3.1 and 12.3.2.
6756     if (isExplicit && !NewFD->isInvalidDecl()) {
6757       if (!CurContext->isRecord()) {
6758         // 'explicit' was specified outside of the class.
6759         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6760              diag::err_explicit_out_of_class)
6761           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6762       } else if (!isa<CXXConstructorDecl>(NewFD) &&
6763                  !isa<CXXConversionDecl>(NewFD)) {
6764         // 'explicit' was specified on a function that wasn't a constructor
6765         // or conversion function.
6766         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6767              diag::err_explicit_non_ctor_or_conv_function)
6768           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6769       }
6770     }
6771 
6772     if (isConstexpr) {
6773       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6774       // are implicitly inline.
6775       NewFD->setImplicitlyInline();
6776 
6777       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6778       // be either constructors or to return a literal type. Therefore,
6779       // destructors cannot be declared constexpr.
6780       if (isa<CXXDestructorDecl>(NewFD))
6781         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6782     }
6783 
6784     // If __module_private__ was specified, mark the function accordingly.
6785     if (D.getDeclSpec().isModulePrivateSpecified()) {
6786       if (isFunctionTemplateSpecialization) {
6787         SourceLocation ModulePrivateLoc
6788           = D.getDeclSpec().getModulePrivateSpecLoc();
6789         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6790           << 0
6791           << FixItHint::CreateRemoval(ModulePrivateLoc);
6792       } else {
6793         NewFD->setModulePrivate();
6794         if (FunctionTemplate)
6795           FunctionTemplate->setModulePrivate();
6796       }
6797     }
6798 
6799     if (isFriend) {
6800       if (FunctionTemplate) {
6801         FunctionTemplate->setObjectOfFriendDecl();
6802         FunctionTemplate->setAccess(AS_public);
6803       }
6804       NewFD->setObjectOfFriendDecl();
6805       NewFD->setAccess(AS_public);
6806     }
6807 
6808     // If a function is defined as defaulted or deleted, mark it as such now.
6809     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
6810     // definition kind to FDK_Definition.
6811     switch (D.getFunctionDefinitionKind()) {
6812       case FDK_Declaration:
6813       case FDK_Definition:
6814         break;
6815 
6816       case FDK_Defaulted:
6817         NewFD->setDefaulted();
6818         break;
6819 
6820       case FDK_Deleted:
6821         NewFD->setDeletedAsWritten();
6822         break;
6823     }
6824 
6825     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6826         D.isFunctionDefinition()) {
6827       // C++ [class.mfct]p2:
6828       //   A member function may be defined (8.4) in its class definition, in
6829       //   which case it is an inline member function (7.1.2)
6830       NewFD->setImplicitlyInline();
6831     }
6832 
6833     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6834         !CurContext->isRecord()) {
6835       // C++ [class.static]p1:
6836       //   A data or function member of a class may be declared static
6837       //   in a class definition, in which case it is a static member of
6838       //   the class.
6839 
6840       // Complain about the 'static' specifier if it's on an out-of-line
6841       // member function definition.
6842       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6843            diag::err_static_out_of_line)
6844         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6845     }
6846 
6847     // C++11 [except.spec]p15:
6848     //   A deallocation function with no exception-specification is treated
6849     //   as if it were specified with noexcept(true).
6850     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6851     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6852          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
6853         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
6854       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6855       EPI.ExceptionSpecType = EST_BasicNoexcept;
6856       NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
6857                                              FPT->getParamTypes(), EPI));
6858     }
6859   }
6860 
6861   // Filter out previous declarations that don't match the scope.
6862   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
6863                        D.getCXXScopeSpec().isNotEmpty() ||
6864                        isExplicitSpecialization ||
6865                        isFunctionTemplateSpecialization);
6866 
6867   // Handle GNU asm-label extension (encoded as an attribute).
6868   if (Expr *E = (Expr*) D.getAsmLabel()) {
6869     // The parser guarantees this is a string.
6870     StringLiteral *SE = cast<StringLiteral>(E);
6871     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6872                                                 SE->getString(), 0));
6873   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6874     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6875       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6876     if (I != ExtnameUndeclaredIdentifiers.end()) {
6877       NewFD->addAttr(I->second);
6878       ExtnameUndeclaredIdentifiers.erase(I);
6879     }
6880   }
6881 
6882   // Copy the parameter declarations from the declarator D to the function
6883   // declaration NewFD, if they are available.  First scavenge them into Params.
6884   SmallVector<ParmVarDecl*, 16> Params;
6885   if (D.isFunctionDeclarator()) {
6886     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6887 
6888     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6889     // function that takes no arguments, not a function that takes a
6890     // single void argument.
6891     // We let through "const void" here because Sema::GetTypeForDeclarator
6892     // already checks for that case.
6893     if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6894         FTI.Params[0].Param &&
6895         cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) {
6896       // Empty arg list, don't push any params.
6897     } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) {
6898       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
6899         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6900         assert(Param->getDeclContext() != NewFD && "Was set before ?");
6901         Param->setDeclContext(NewFD);
6902         Params.push_back(Param);
6903 
6904         if (Param->isInvalidDecl())
6905           NewFD->setInvalidDecl();
6906       }
6907     }
6908 
6909   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
6910     // When we're declaring a function with a typedef, typeof, etc as in the
6911     // following example, we'll need to synthesize (unnamed)
6912     // parameters for use in the declaration.
6913     //
6914     // @code
6915     // typedef void fn(int);
6916     // fn f;
6917     // @endcode
6918 
6919     // Synthesize a parameter for each argument type.
6920     for (FunctionProtoType::param_type_iterator AI = FT->param_type_begin(),
6921                                                 AE = FT->param_type_end();
6922          AI != AE; ++AI) {
6923       ParmVarDecl *Param =
6924         BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
6925       Param->setScopeInfo(0, Params.size());
6926       Params.push_back(Param);
6927     }
6928   } else {
6929     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6930            "Should not need args for typedef of non-prototype fn");
6931   }
6932 
6933   // Finally, we know we have the right number of parameters, install them.
6934   NewFD->setParams(Params);
6935 
6936   // Find all anonymous symbols defined during the declaration of this function
6937   // and add to NewFD. This lets us track decls such 'enum Y' in:
6938   //
6939   //   void f(enum Y {AA} x) {}
6940   //
6941   // which would otherwise incorrectly end up in the translation unit scope.
6942   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6943   DeclsInPrototypeScope.clear();
6944 
6945   if (D.getDeclSpec().isNoreturnSpecified())
6946     NewFD->addAttr(
6947         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6948                                        Context, 0));
6949 
6950   // Functions returning a variably modified type violate C99 6.7.5.2p2
6951   // because all functions have linkage.
6952   if (!NewFD->isInvalidDecl() &&
6953       NewFD->getReturnType()->isVariablyModifiedType()) {
6954     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6955     NewFD->setInvalidDecl();
6956   }
6957 
6958   // Handle attributes.
6959   ProcessDeclAttributes(S, NewFD, D);
6960 
6961   QualType RetType = NewFD->getReturnType();
6962   const CXXRecordDecl *Ret = RetType->isRecordType() ?
6963       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6964   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6965       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
6966     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6967     // Attach WarnUnusedResult to functions returning types with that attribute.
6968     // Don't apply the attribute to that type's own non-static member functions
6969     // (to avoid warning on things like assignment operators)
6970     if (!MD || MD->getParent() != Ret)
6971       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
6972   }
6973 
6974   if (getLangOpts().OpenCL) {
6975     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
6976     // type declaration will generate a compilation error.
6977     unsigned AddressSpace = RetType.getAddressSpace();
6978     if (AddressSpace == LangAS::opencl_local ||
6979         AddressSpace == LangAS::opencl_global ||
6980         AddressSpace == LangAS::opencl_constant) {
6981       Diag(NewFD->getLocation(),
6982            diag::err_opencl_return_value_with_address_space);
6983       NewFD->setInvalidDecl();
6984     }
6985   }
6986 
6987   if (!getLangOpts().CPlusPlus) {
6988     // Perform semantic checking on the function declaration.
6989     bool isExplicitSpecialization=false;
6990     if (!NewFD->isInvalidDecl() && NewFD->isMain())
6991       CheckMain(NewFD, D.getDeclSpec());
6992 
6993     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
6994       CheckMSVCRTEntryPoint(NewFD);
6995 
6996     if (!NewFD->isInvalidDecl())
6997       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
6998                                                   isExplicitSpecialization));
6999     else if (!Previous.empty())
7000       // Make graceful recovery from an invalid redeclaration.
7001       D.setRedeclaration(true);
7002     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7003             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7004            "previous declaration set still overloaded");
7005   } else {
7006     // C++11 [replacement.functions]p3:
7007     //  The program's definitions shall not be specified as inline.
7008     //
7009     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7010     //
7011     // Suppress the diagnostic if the function is __attribute__((used)), since
7012     // that forces an external definition to be emitted.
7013     if (D.getDeclSpec().isInlineSpecified() &&
7014         NewFD->isReplaceableGlobalAllocationFunction() &&
7015         !NewFD->hasAttr<UsedAttr>())
7016       Diag(D.getDeclSpec().getInlineSpecLoc(),
7017            diag::ext_operator_new_delete_declared_inline)
7018         << NewFD->getDeclName();
7019 
7020     // If the declarator is a template-id, translate the parser's template
7021     // argument list into our AST format.
7022     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7023       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7024       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7025       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7026       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7027                                          TemplateId->NumArgs);
7028       translateTemplateArguments(TemplateArgsPtr,
7029                                  TemplateArgs);
7030 
7031       HasExplicitTemplateArgs = true;
7032 
7033       if (NewFD->isInvalidDecl()) {
7034         HasExplicitTemplateArgs = false;
7035       } else if (FunctionTemplate) {
7036         // Function template with explicit template arguments.
7037         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7038           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7039 
7040         HasExplicitTemplateArgs = false;
7041       } else if (!isFunctionTemplateSpecialization &&
7042                  !D.getDeclSpec().isFriendSpecified()) {
7043         // We have encountered something that the user meant to be a
7044         // specialization (because it has explicitly-specified template
7045         // arguments) but that was not introduced with a "template<>" (or had
7046         // too few of them).
7047         // FIXME: Differentiate between attempts for explicit instantiations
7048         // (starting with "template") and the rest.
7049         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7050           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7051           << FixItHint::CreateInsertion(
7052                                     D.getDeclSpec().getLocStart(),
7053                                         "template<> ");
7054         isFunctionTemplateSpecialization = true;
7055       } else {
7056         // "friend void foo<>(int);" is an implicit specialization decl.
7057         isFunctionTemplateSpecialization = true;
7058       }
7059     } else if (isFriend && isFunctionTemplateSpecialization) {
7060       // This combination is only possible in a recovery case;  the user
7061       // wrote something like:
7062       //   template <> friend void foo(int);
7063       // which we're recovering from as if the user had written:
7064       //   friend void foo<>(int);
7065       // Go ahead and fake up a template id.
7066       HasExplicitTemplateArgs = true;
7067         TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7068       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7069     }
7070 
7071     // If it's a friend (and only if it's a friend), it's possible
7072     // that either the specialized function type or the specialized
7073     // template is dependent, and therefore matching will fail.  In
7074     // this case, don't check the specialization yet.
7075     bool InstantiationDependent = false;
7076     if (isFunctionTemplateSpecialization && isFriend &&
7077         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7078          TemplateSpecializationType::anyDependentTemplateArguments(
7079             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7080             InstantiationDependent))) {
7081       assert(HasExplicitTemplateArgs &&
7082              "friend function specialization without template args");
7083       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7084                                                        Previous))
7085         NewFD->setInvalidDecl();
7086     } else if (isFunctionTemplateSpecialization) {
7087       if (CurContext->isDependentContext() && CurContext->isRecord()
7088           && !isFriend) {
7089         isDependentClassScopeExplicitSpecialization = true;
7090         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7091           diag::ext_function_specialization_in_class :
7092           diag::err_function_specialization_in_class)
7093           << NewFD->getDeclName();
7094       } else if (CheckFunctionTemplateSpecialization(NewFD,
7095                                   (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7096                                                      Previous))
7097         NewFD->setInvalidDecl();
7098 
7099       // C++ [dcl.stc]p1:
7100       //   A storage-class-specifier shall not be specified in an explicit
7101       //   specialization (14.7.3)
7102       FunctionTemplateSpecializationInfo *Info =
7103           NewFD->getTemplateSpecializationInfo();
7104       if (Info && SC != SC_None) {
7105         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7106           Diag(NewFD->getLocation(),
7107                diag::err_explicit_specialization_inconsistent_storage_class)
7108             << SC
7109             << FixItHint::CreateRemoval(
7110                                       D.getDeclSpec().getStorageClassSpecLoc());
7111 
7112         else
7113           Diag(NewFD->getLocation(),
7114                diag::ext_explicit_specialization_storage_class)
7115             << FixItHint::CreateRemoval(
7116                                       D.getDeclSpec().getStorageClassSpecLoc());
7117       }
7118 
7119     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7120       if (CheckMemberSpecialization(NewFD, Previous))
7121           NewFD->setInvalidDecl();
7122     }
7123 
7124     // Perform semantic checking on the function declaration.
7125     if (!isDependentClassScopeExplicitSpecialization) {
7126       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7127         CheckMain(NewFD, D.getDeclSpec());
7128 
7129       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7130         CheckMSVCRTEntryPoint(NewFD);
7131 
7132       if (!NewFD->isInvalidDecl())
7133         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7134                                                     isExplicitSpecialization));
7135     }
7136 
7137     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7138             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7139            "previous declaration set still overloaded");
7140 
7141     NamedDecl *PrincipalDecl = (FunctionTemplate
7142                                 ? cast<NamedDecl>(FunctionTemplate)
7143                                 : NewFD);
7144 
7145     if (isFriend && D.isRedeclaration()) {
7146       AccessSpecifier Access = AS_public;
7147       if (!NewFD->isInvalidDecl())
7148         Access = NewFD->getPreviousDecl()->getAccess();
7149 
7150       NewFD->setAccess(Access);
7151       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7152     }
7153 
7154     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7155         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7156       PrincipalDecl->setNonMemberOperator();
7157 
7158     // If we have a function template, check the template parameter
7159     // list. This will check and merge default template arguments.
7160     if (FunctionTemplate) {
7161       FunctionTemplateDecl *PrevTemplate =
7162                                      FunctionTemplate->getPreviousDecl();
7163       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7164                        PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
7165                             D.getDeclSpec().isFriendSpecified()
7166                               ? (D.isFunctionDefinition()
7167                                    ? TPC_FriendFunctionTemplateDefinition
7168                                    : TPC_FriendFunctionTemplate)
7169                               : (D.getCXXScopeSpec().isSet() &&
7170                                  DC && DC->isRecord() &&
7171                                  DC->isDependentContext())
7172                                   ? TPC_ClassTemplateMember
7173                                   : TPC_FunctionTemplate);
7174     }
7175 
7176     if (NewFD->isInvalidDecl()) {
7177       // Ignore all the rest of this.
7178     } else if (!D.isRedeclaration()) {
7179       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7180                                        AddToScope };
7181       // Fake up an access specifier if it's supposed to be a class member.
7182       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7183         NewFD->setAccess(AS_public);
7184 
7185       // Qualified decls generally require a previous declaration.
7186       if (D.getCXXScopeSpec().isSet()) {
7187         // ...with the major exception of templated-scope or
7188         // dependent-scope friend declarations.
7189 
7190         // TODO: we currently also suppress this check in dependent
7191         // contexts because (1) the parameter depth will be off when
7192         // matching friend templates and (2) we might actually be
7193         // selecting a friend based on a dependent factor.  But there
7194         // are situations where these conditions don't apply and we
7195         // can actually do this check immediately.
7196         if (isFriend &&
7197             (TemplateParamLists.size() ||
7198              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7199              CurContext->isDependentContext())) {
7200           // ignore these
7201         } else {
7202           // The user tried to provide an out-of-line definition for a
7203           // function that is a member of a class or namespace, but there
7204           // was no such member function declared (C++ [class.mfct]p2,
7205           // C++ [namespace.memdef]p2). For example:
7206           //
7207           // class X {
7208           //   void f() const;
7209           // };
7210           //
7211           // void X::f() { } // ill-formed
7212           //
7213           // Complain about this problem, and attempt to suggest close
7214           // matches (e.g., those that differ only in cv-qualifiers and
7215           // whether the parameter types are references).
7216 
7217           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7218                   *this, Previous, NewFD, ExtraArgs, false, 0)) {
7219             AddToScope = ExtraArgs.AddToScope;
7220             return Result;
7221           }
7222         }
7223 
7224         // Unqualified local friend declarations are required to resolve
7225         // to something.
7226       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7227         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7228                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7229           AddToScope = ExtraArgs.AddToScope;
7230           return Result;
7231         }
7232       }
7233 
7234     } else if (!D.isFunctionDefinition() &&
7235                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7236                !isFriend && !isFunctionTemplateSpecialization &&
7237                !isExplicitSpecialization) {
7238       // An out-of-line member function declaration must also be a
7239       // definition (C++ [class.mfct]p2).
7240       // Note that this is not the case for explicit specializations of
7241       // function templates or member functions of class templates, per
7242       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7243       // extension for compatibility with old SWIG code which likes to
7244       // generate them.
7245       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7246         << D.getCXXScopeSpec().getRange();
7247     }
7248   }
7249 
7250   ProcessPragmaWeak(S, NewFD);
7251   checkAttributesAfterMerging(*this, *NewFD);
7252 
7253   AddKnownFunctionAttributes(NewFD);
7254 
7255   if (NewFD->hasAttr<OverloadableAttr>() &&
7256       !NewFD->getType()->getAs<FunctionProtoType>()) {
7257     Diag(NewFD->getLocation(),
7258          diag::err_attribute_overloadable_no_prototype)
7259       << NewFD;
7260 
7261     // Turn this into a variadic function with no parameters.
7262     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7263     FunctionProtoType::ExtProtoInfo EPI(
7264         Context.getDefaultCallingConvention(true, false));
7265     EPI.Variadic = true;
7266     EPI.ExtInfo = FT->getExtInfo();
7267 
7268     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
7269     NewFD->setType(R);
7270   }
7271 
7272   // If there's a #pragma GCC visibility in scope, and this isn't a class
7273   // member, set the visibility of this function.
7274   if (!DC->isRecord() && NewFD->isExternallyVisible())
7275     AddPushedVisibilityAttribute(NewFD);
7276 
7277   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7278   // marking the function.
7279   AddCFAuditedAttribute(NewFD);
7280 
7281   // If this is the first declaration of an extern C variable, update
7282   // the map of such variables.
7283   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7284       isIncompleteDeclExternC(*this, NewFD))
7285     RegisterLocallyScopedExternCDecl(NewFD, S);
7286 
7287   // Set this FunctionDecl's range up to the right paren.
7288   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7289 
7290   if (getLangOpts().CPlusPlus) {
7291     if (FunctionTemplate) {
7292       if (NewFD->isInvalidDecl())
7293         FunctionTemplate->setInvalidDecl();
7294       return FunctionTemplate;
7295     }
7296   }
7297 
7298   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7299     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7300     if ((getLangOpts().OpenCLVersion >= 120)
7301         && (SC == SC_Static)) {
7302       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7303       D.setInvalidType();
7304     }
7305 
7306     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7307     if (!NewFD->getReturnType()->isVoidType()) {
7308       Diag(D.getIdentifierLoc(),
7309            diag::err_expected_kernel_void_return_type);
7310       D.setInvalidType();
7311     }
7312 
7313     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7314     for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7315          PE = NewFD->param_end(); PI != PE; ++PI) {
7316       ParmVarDecl *Param = *PI;
7317       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7318     }
7319   }
7320 
7321   MarkUnusedFileScopedDecl(NewFD);
7322 
7323   if (getLangOpts().CUDA)
7324     if (IdentifierInfo *II = NewFD->getIdentifier())
7325       if (!NewFD->isInvalidDecl() &&
7326           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7327         if (II->isStr("cudaConfigureCall")) {
7328           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
7329             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7330 
7331           Context.setcudaConfigureCallDecl(NewFD);
7332         }
7333       }
7334 
7335   // Here we have an function template explicit specialization at class scope.
7336   // The actually specialization will be postponed to template instatiation
7337   // time via the ClassScopeFunctionSpecializationDecl node.
7338   if (isDependentClassScopeExplicitSpecialization) {
7339     ClassScopeFunctionSpecializationDecl *NewSpec =
7340                          ClassScopeFunctionSpecializationDecl::Create(
7341                                 Context, CurContext, SourceLocation(),
7342                                 cast<CXXMethodDecl>(NewFD),
7343                                 HasExplicitTemplateArgs, TemplateArgs);
7344     CurContext->addDecl(NewSpec);
7345     AddToScope = false;
7346   }
7347 
7348   return NewFD;
7349 }
7350 
7351 /// \brief Perform semantic checking of a new function declaration.
7352 ///
7353 /// Performs semantic analysis of the new function declaration
7354 /// NewFD. This routine performs all semantic checking that does not
7355 /// require the actual declarator involved in the declaration, and is
7356 /// used both for the declaration of functions as they are parsed
7357 /// (called via ActOnDeclarator) and for the declaration of functions
7358 /// that have been instantiated via C++ template instantiation (called
7359 /// via InstantiateDecl).
7360 ///
7361 /// \param IsExplicitSpecialization whether this new function declaration is
7362 /// an explicit specialization of the previous declaration.
7363 ///
7364 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7365 ///
7366 /// \returns true if the function declaration is a redeclaration.
7367 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7368                                     LookupResult &Previous,
7369                                     bool IsExplicitSpecialization) {
7370   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
7371          "Variably modified return types are not handled here");
7372 
7373   // Determine whether the type of this function should be merged with
7374   // a previous visible declaration. This never happens for functions in C++,
7375   // and always happens in C if the previous declaration was visible.
7376   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7377                                !Previous.isShadowed();
7378 
7379   // Filter out any non-conflicting previous declarations.
7380   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7381 
7382   bool Redeclaration = false;
7383   NamedDecl *OldDecl = 0;
7384 
7385   // Merge or overload the declaration with an existing declaration of
7386   // the same name, if appropriate.
7387   if (!Previous.empty()) {
7388     // Determine whether NewFD is an overload of PrevDecl or
7389     // a declaration that requires merging. If it's an overload,
7390     // there's no more work to do here; we'll just add the new
7391     // function to the scope.
7392     if (!AllowOverloadingOfFunction(Previous, Context)) {
7393       NamedDecl *Candidate = Previous.getFoundDecl();
7394       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7395         Redeclaration = true;
7396         OldDecl = Candidate;
7397       }
7398     } else {
7399       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7400                             /*NewIsUsingDecl*/ false)) {
7401       case Ovl_Match:
7402         Redeclaration = true;
7403         break;
7404 
7405       case Ovl_NonFunction:
7406         Redeclaration = true;
7407         break;
7408 
7409       case Ovl_Overload:
7410         Redeclaration = false;
7411         break;
7412       }
7413 
7414       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7415         // If a function name is overloadable in C, then every function
7416         // with that name must be marked "overloadable".
7417         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7418           << Redeclaration << NewFD;
7419         NamedDecl *OverloadedDecl = 0;
7420         if (Redeclaration)
7421           OverloadedDecl = OldDecl;
7422         else if (!Previous.empty())
7423           OverloadedDecl = Previous.getRepresentativeDecl();
7424         if (OverloadedDecl)
7425           Diag(OverloadedDecl->getLocation(),
7426                diag::note_attribute_overloadable_prev_overload);
7427         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7428       }
7429     }
7430   }
7431 
7432   // Check for a previous extern "C" declaration with this name.
7433   if (!Redeclaration &&
7434       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7435     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7436     if (!Previous.empty()) {
7437       // This is an extern "C" declaration with the same name as a previous
7438       // declaration, and thus redeclares that entity...
7439       Redeclaration = true;
7440       OldDecl = Previous.getFoundDecl();
7441       MergeTypeWithPrevious = false;
7442 
7443       // ... except in the presence of __attribute__((overloadable)).
7444       if (OldDecl->hasAttr<OverloadableAttr>()) {
7445         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7446           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7447             << Redeclaration << NewFD;
7448           Diag(Previous.getFoundDecl()->getLocation(),
7449                diag::note_attribute_overloadable_prev_overload);
7450           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7451         }
7452         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7453           Redeclaration = false;
7454           OldDecl = 0;
7455         }
7456       }
7457     }
7458   }
7459 
7460   // C++11 [dcl.constexpr]p8:
7461   //   A constexpr specifier for a non-static member function that is not
7462   //   a constructor declares that member function to be const.
7463   //
7464   // This needs to be delayed until we know whether this is an out-of-line
7465   // definition of a static member function.
7466   //
7467   // This rule is not present in C++1y, so we produce a backwards
7468   // compatibility warning whenever it happens in C++11.
7469   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7470   if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7471       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7472       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7473     CXXMethodDecl *OldMD = 0;
7474     if (OldDecl)
7475       OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
7476     if (!OldMD || !OldMD->isStatic()) {
7477       const FunctionProtoType *FPT =
7478         MD->getType()->castAs<FunctionProtoType>();
7479       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7480       EPI.TypeQuals |= Qualifiers::Const;
7481       MD->setType(Context.getFunctionType(FPT->getReturnType(),
7482                                           FPT->getParamTypes(), EPI));
7483 
7484       // Warn that we did this, if we're not performing template instantiation.
7485       // In that case, we'll have warned already when the template was defined.
7486       if (ActiveTemplateInstantiations.empty()) {
7487         SourceLocation AddConstLoc;
7488         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7489                 .IgnoreParens().getAs<FunctionTypeLoc>())
7490           AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7491 
7492         Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7493           << FixItHint::CreateInsertion(AddConstLoc, " const");
7494       }
7495     }
7496   }
7497 
7498   if (Redeclaration) {
7499     // NewFD and OldDecl represent declarations that need to be
7500     // merged.
7501     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7502       NewFD->setInvalidDecl();
7503       return Redeclaration;
7504     }
7505 
7506     Previous.clear();
7507     Previous.addDecl(OldDecl);
7508 
7509     if (FunctionTemplateDecl *OldTemplateDecl
7510                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7511       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7512       FunctionTemplateDecl *NewTemplateDecl
7513         = NewFD->getDescribedFunctionTemplate();
7514       assert(NewTemplateDecl && "Template/non-template mismatch");
7515       if (CXXMethodDecl *Method
7516             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7517         Method->setAccess(OldTemplateDecl->getAccess());
7518         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7519       }
7520 
7521       // If this is an explicit specialization of a member that is a function
7522       // template, mark it as a member specialization.
7523       if (IsExplicitSpecialization &&
7524           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7525         NewTemplateDecl->setMemberSpecialization();
7526         assert(OldTemplateDecl->isMemberSpecialization());
7527       }
7528 
7529     } else {
7530       // This needs to happen first so that 'inline' propagates.
7531       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7532 
7533       if (isa<CXXMethodDecl>(NewFD)) {
7534         // A valid redeclaration of a C++ method must be out-of-line,
7535         // but (unfortunately) it's not necessarily a definition
7536         // because of templates, which means that the previous
7537         // declaration is not necessarily from the class definition.
7538 
7539         // For just setting the access, that doesn't matter.
7540         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7541         NewFD->setAccess(oldMethod->getAccess());
7542 
7543         // Update the key-function state if necessary for this ABI.
7544         if (NewFD->isInlined() &&
7545             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7546           // setNonKeyFunction needs to work with the original
7547           // declaration from the class definition, and isVirtual() is
7548           // just faster in that case, so map back to that now.
7549           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7550           if (oldMethod->isVirtual()) {
7551             Context.setNonKeyFunction(oldMethod);
7552           }
7553         }
7554       }
7555     }
7556   }
7557 
7558   // Semantic checking for this function declaration (in isolation).
7559   if (getLangOpts().CPlusPlus) {
7560     // C++-specific checks.
7561     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7562       CheckConstructor(Constructor);
7563     } else if (CXXDestructorDecl *Destructor =
7564                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7565       CXXRecordDecl *Record = Destructor->getParent();
7566       QualType ClassType = Context.getTypeDeclType(Record);
7567 
7568       // FIXME: Shouldn't we be able to perform this check even when the class
7569       // type is dependent? Both gcc and edg can handle that.
7570       if (!ClassType->isDependentType()) {
7571         DeclarationName Name
7572           = Context.DeclarationNames.getCXXDestructorName(
7573                                         Context.getCanonicalType(ClassType));
7574         if (NewFD->getDeclName() != Name) {
7575           Diag(NewFD->getLocation(), diag::err_destructor_name);
7576           NewFD->setInvalidDecl();
7577           return Redeclaration;
7578         }
7579       }
7580     } else if (CXXConversionDecl *Conversion
7581                = dyn_cast<CXXConversionDecl>(NewFD)) {
7582       ActOnConversionDeclarator(Conversion);
7583     }
7584 
7585     // Find any virtual functions that this function overrides.
7586     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7587       if (!Method->isFunctionTemplateSpecialization() &&
7588           !Method->getDescribedFunctionTemplate() &&
7589           Method->isCanonicalDecl()) {
7590         if (AddOverriddenMethods(Method->getParent(), Method)) {
7591           // If the function was marked as "static", we have a problem.
7592           if (NewFD->getStorageClass() == SC_Static) {
7593             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7594           }
7595         }
7596       }
7597 
7598       if (Method->isStatic())
7599         checkThisInStaticMemberFunctionType(Method);
7600     }
7601 
7602     // Extra checking for C++ overloaded operators (C++ [over.oper]).
7603     if (NewFD->isOverloadedOperator() &&
7604         CheckOverloadedOperatorDeclaration(NewFD)) {
7605       NewFD->setInvalidDecl();
7606       return Redeclaration;
7607     }
7608 
7609     // Extra checking for C++0x literal operators (C++0x [over.literal]).
7610     if (NewFD->getLiteralIdentifier() &&
7611         CheckLiteralOperatorDeclaration(NewFD)) {
7612       NewFD->setInvalidDecl();
7613       return Redeclaration;
7614     }
7615 
7616     // In C++, check default arguments now that we have merged decls. Unless
7617     // the lexical context is the class, because in this case this is done
7618     // during delayed parsing anyway.
7619     if (!CurContext->isRecord())
7620       CheckCXXDefaultArguments(NewFD);
7621 
7622     // If this function declares a builtin function, check the type of this
7623     // declaration against the expected type for the builtin.
7624     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7625       ASTContext::GetBuiltinTypeError Error;
7626       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
7627       QualType T = Context.GetBuiltinType(BuiltinID, Error);
7628       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7629         // The type of this function differs from the type of the builtin,
7630         // so forget about the builtin entirely.
7631         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7632       }
7633     }
7634 
7635     // If this function is declared as being extern "C", then check to see if
7636     // the function returns a UDT (class, struct, or union type) that is not C
7637     // compatible, and if it does, warn the user.
7638     // But, issue any diagnostic on the first declaration only.
7639     if (NewFD->isExternC() && Previous.empty()) {
7640       QualType R = NewFD->getReturnType();
7641       if (R->isIncompleteType() && !R->isVoidType())
7642         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7643             << NewFD << R;
7644       else if (!R.isPODType(Context) && !R->isVoidType() &&
7645                !R->isObjCObjectPointerType())
7646         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
7647     }
7648   }
7649   return Redeclaration;
7650 }
7651 
7652 static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7653   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7654   if (!TSI)
7655     return SourceRange();
7656 
7657   TypeLoc TL = TSI->getTypeLoc();
7658   FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
7659   if (!FunctionTL)
7660     return SourceRange();
7661 
7662   TypeLoc ResultTL = FunctionTL.getReturnLoc();
7663   if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
7664     return ResultTL.getSourceRange();
7665 
7666   return SourceRange();
7667 }
7668 
7669 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
7670   // C++11 [basic.start.main]p3:
7671   //   A program that [...] declares main to be inline, static or
7672   //   constexpr is ill-formed.
7673   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
7674   //   appear in a declaration of main.
7675   // static main is not an error under C99, but we should warn about it.
7676   // We accept _Noreturn main as an extension.
7677   if (FD->getStorageClass() == SC_Static)
7678     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
7679          ? diag::err_static_main : diag::warn_static_main)
7680       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7681   if (FD->isInlineSpecified())
7682     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7683       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
7684   if (DS.isNoreturnSpecified()) {
7685     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7686     SourceRange NoreturnRange(NoreturnLoc,
7687                               PP.getLocForEndOfToken(NoreturnLoc));
7688     Diag(NoreturnLoc, diag::ext_noreturn_main);
7689     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7690       << FixItHint::CreateRemoval(NoreturnRange);
7691   }
7692   if (FD->isConstexpr()) {
7693     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7694       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7695     FD->setConstexpr(false);
7696   }
7697 
7698   if (getLangOpts().OpenCL) {
7699     Diag(FD->getLocation(), diag::err_opencl_no_main)
7700         << FD->hasAttr<OpenCLKernelAttr>();
7701     FD->setInvalidDecl();
7702     return;
7703   }
7704 
7705   QualType T = FD->getType();
7706   assert(T->isFunctionType() && "function decl is not of function type");
7707   const FunctionType* FT = T->castAs<FunctionType>();
7708 
7709   // All the standards say that main() should should return 'int'.
7710   if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
7711     // In C and C++, main magically returns 0 if you fall off the end;
7712     // set the flag which tells us that.
7713     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7714     FD->setHasImplicitReturnZero(true);
7715 
7716   // In C with GNU extensions we allow main() to have non-integer return
7717   // type, but we should warn about the extension, and we disable the
7718   // implicit-return-zero rule.
7719   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
7720     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7721 
7722     SourceRange ResultRange = getResultSourceRange(FD);
7723     if (ResultRange.isValid())
7724       Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7725           << FixItHint::CreateReplacement(ResultRange, "int");
7726 
7727   // Otherwise, this is just a flat-out error.
7728   } else {
7729     SourceRange ResultRange = getResultSourceRange(FD);
7730     if (ResultRange.isValid())
7731       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7732           << FixItHint::CreateReplacement(ResultRange, "int");
7733     else
7734       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7735 
7736     FD->setInvalidDecl(true);
7737   }
7738 
7739   // Treat protoless main() as nullary.
7740   if (isa<FunctionNoProtoType>(FT)) return;
7741 
7742   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7743   unsigned nparams = FTP->getNumParams();
7744   assert(FD->getNumParams() == nparams);
7745 
7746   bool HasExtraParameters = (nparams > 3);
7747 
7748   // Darwin passes an undocumented fourth argument of type char**.  If
7749   // other platforms start sprouting these, the logic below will start
7750   // getting shifty.
7751   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
7752     HasExtraParameters = false;
7753 
7754   if (HasExtraParameters) {
7755     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7756     FD->setInvalidDecl(true);
7757     nparams = 3;
7758   }
7759 
7760   // FIXME: a lot of the following diagnostics would be improved
7761   // if we had some location information about types.
7762 
7763   QualType CharPP =
7764     Context.getPointerType(Context.getPointerType(Context.CharTy));
7765   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
7766 
7767   for (unsigned i = 0; i < nparams; ++i) {
7768     QualType AT = FTP->getParamType(i);
7769 
7770     bool mismatch = true;
7771 
7772     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7773       mismatch = false;
7774     else if (Expected[i] == CharPP) {
7775       // As an extension, the following forms are okay:
7776       //   char const **
7777       //   char const * const *
7778       //   char * const *
7779 
7780       QualifierCollector qs;
7781       const PointerType* PT;
7782       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7783           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
7784           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7785                               Context.CharTy)) {
7786         qs.removeConst();
7787         mismatch = !qs.empty();
7788       }
7789     }
7790 
7791     if (mismatch) {
7792       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7793       // TODO: suggest replacing given type with expected type
7794       FD->setInvalidDecl(true);
7795     }
7796   }
7797 
7798   if (nparams == 1 && !FD->isInvalidDecl()) {
7799     Diag(FD->getLocation(), diag::warn_main_one_arg);
7800   }
7801 
7802   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7803     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
7804     FD->setInvalidDecl();
7805   }
7806 }
7807 
7808 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7809   QualType T = FD->getType();
7810   assert(T->isFunctionType() && "function decl is not of function type");
7811   const FunctionType *FT = T->castAs<FunctionType>();
7812 
7813   // Set an implicit return of 'zero' if the function can return some integral,
7814   // enumeration, pointer or nullptr type.
7815   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
7816       FT->getReturnType()->isAnyPointerType() ||
7817       FT->getReturnType()->isNullPtrType())
7818     // DllMain is exempt because a return value of zero means it failed.
7819     if (FD->getName() != "DllMain")
7820       FD->setHasImplicitReturnZero(true);
7821 
7822   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7823     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
7824     FD->setInvalidDecl();
7825   }
7826 }
7827 
7828 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
7829   // FIXME: Need strict checking.  In C89, we need to check for
7830   // any assignment, increment, decrement, function-calls, or
7831   // commas outside of a sizeof.  In C99, it's the same list,
7832   // except that the aforementioned are allowed in unevaluated
7833   // expressions.  Everything else falls under the
7834   // "may accept other forms of constant expressions" exception.
7835   // (We never end up here for C++, so the constant expression
7836   // rules there don't matter.)
7837   if (Init->isConstantInitializer(Context, false))
7838     return false;
7839   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7840     << Init->getSourceRange();
7841   return true;
7842 }
7843 
7844 namespace {
7845   // Visits an initialization expression to see if OrigDecl is evaluated in
7846   // its own initialization and throws a warning if it does.
7847   class SelfReferenceChecker
7848       : public EvaluatedExprVisitor<SelfReferenceChecker> {
7849     Sema &S;
7850     Decl *OrigDecl;
7851     bool isRecordType;
7852     bool isPODType;
7853     bool isReferenceType;
7854 
7855   public:
7856     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7857 
7858     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
7859                                                     S(S), OrigDecl(OrigDecl) {
7860       isPODType = false;
7861       isRecordType = false;
7862       isReferenceType = false;
7863       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7864         isPODType = VD->getType().isPODType(S.Context);
7865         isRecordType = VD->getType()->isRecordType();
7866         isReferenceType = VD->getType()->isReferenceType();
7867       }
7868     }
7869 
7870     // For most expressions, the cast is directly above the DeclRefExpr.
7871     // For conditional operators, the cast can be outside the conditional
7872     // operator if both expressions are DeclRefExpr's.
7873     void HandleValue(Expr *E) {
7874       if (isReferenceType)
7875         return;
7876       E = E->IgnoreParenImpCasts();
7877       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7878         HandleDeclRefExpr(DRE);
7879         return;
7880       }
7881 
7882       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7883         HandleValue(CO->getTrueExpr());
7884         HandleValue(CO->getFalseExpr());
7885         return;
7886       }
7887 
7888       if (isa<MemberExpr>(E)) {
7889         Expr *Base = E->IgnoreParenImpCasts();
7890         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7891           // Check for static member variables and don't warn on them.
7892           if (!isa<FieldDecl>(ME->getMemberDecl()))
7893             return;
7894           Base = ME->getBase()->IgnoreParenImpCasts();
7895         }
7896         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7897           HandleDeclRefExpr(DRE);
7898         return;
7899       }
7900     }
7901 
7902     // Reference types are handled here since all uses of references are
7903     // bad, not just r-value uses.
7904     void VisitDeclRefExpr(DeclRefExpr *E) {
7905       if (isReferenceType)
7906         HandleDeclRefExpr(E);
7907     }
7908 
7909     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
7910       if (E->getCastKind() == CK_LValueToRValue ||
7911           (isRecordType && E->getCastKind() == CK_NoOp))
7912         HandleValue(E->getSubExpr());
7913 
7914       Inherited::VisitImplicitCastExpr(E);
7915     }
7916 
7917     void VisitMemberExpr(MemberExpr *E) {
7918       // Don't warn on arrays since they can be treated as pointers.
7919       if (E->getType()->canDecayToPointerType()) return;
7920 
7921       // Warn when a non-static method call is followed by non-static member
7922       // field accesses, which is followed by a DeclRefExpr.
7923       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7924       bool Warn = (MD && !MD->isStatic());
7925       Expr *Base = E->getBase()->IgnoreParenImpCasts();
7926       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7927         if (!isa<FieldDecl>(ME->getMemberDecl()))
7928           Warn = false;
7929         Base = ME->getBase()->IgnoreParenImpCasts();
7930       }
7931 
7932       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7933         if (Warn)
7934           HandleDeclRefExpr(DRE);
7935         return;
7936       }
7937 
7938       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7939       // Visit that expression.
7940       Visit(Base);
7941     }
7942 
7943     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7944       if (E->getNumArgs() > 0)
7945         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7946           HandleDeclRefExpr(DRE);
7947 
7948       Inherited::VisitCXXOperatorCallExpr(E);
7949     }
7950 
7951     void VisitUnaryOperator(UnaryOperator *E) {
7952       // For POD record types, addresses of its own members are well-defined.
7953       if (E->getOpcode() == UO_AddrOf && isRecordType &&
7954           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7955         if (!isPODType)
7956           HandleValue(E->getSubExpr());
7957         return;
7958       }
7959       Inherited::VisitUnaryOperator(E);
7960     }
7961 
7962     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7963 
7964     void HandleDeclRefExpr(DeclRefExpr *DRE) {
7965       Decl* ReferenceDecl = DRE->getDecl();
7966       if (OrigDecl != ReferenceDecl) return;
7967       unsigned diag;
7968       if (isReferenceType) {
7969         diag = diag::warn_uninit_self_reference_in_reference_init;
7970       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7971         diag = diag::warn_static_self_reference_in_init;
7972       } else {
7973         diag = diag::warn_uninit_self_reference_in_init;
7974       }
7975 
7976       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
7977                             S.PDiag(diag)
7978                               << DRE->getNameInfo().getName()
7979                               << OrigDecl->getLocation()
7980                               << DRE->getSourceRange());
7981     }
7982   };
7983 
7984   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7985   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7986                                  bool DirectInit) {
7987     // Parameters arguments are occassionially constructed with itself,
7988     // for instance, in recursive functions.  Skip them.
7989     if (isa<ParmVarDecl>(OrigDecl))
7990       return;
7991 
7992     E = E->IgnoreParens();
7993 
7994     // Skip checking T a = a where T is not a record or reference type.
7995     // Doing so is a way to silence uninitialized warnings.
7996     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7997       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7998         if (ICE->getCastKind() == CK_LValueToRValue)
7999           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8000             if (DRE->getDecl() == OrigDecl)
8001               return;
8002 
8003     SelfReferenceChecker(S, OrigDecl).Visit(E);
8004   }
8005 }
8006 
8007 /// AddInitializerToDecl - Adds the initializer Init to the
8008 /// declaration dcl. If DirectInit is true, this is C++ direct
8009 /// initialization rather than copy initialization.
8010 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8011                                 bool DirectInit, bool TypeMayContainAuto) {
8012   // If there is no declaration, there was an error parsing it.  Just ignore
8013   // the initializer.
8014   if (RealDecl == 0 || RealDecl->isInvalidDecl())
8015     return;
8016 
8017   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8018     // With declarators parsed the way they are, the parser cannot
8019     // distinguish between a normal initializer and a pure-specifier.
8020     // Thus this grotesque test.
8021     IntegerLiteral *IL;
8022     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8023         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8024       CheckPureMethod(Method, Init->getSourceRange());
8025     else {
8026       Diag(Method->getLocation(), diag::err_member_function_initialization)
8027         << Method->getDeclName() << Init->getSourceRange();
8028       Method->setInvalidDecl();
8029     }
8030     return;
8031   }
8032 
8033   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8034   if (!VDecl) {
8035     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8036     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8037     RealDecl->setInvalidDecl();
8038     return;
8039   }
8040   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8041 
8042   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8043   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8044     Expr *DeduceInit = Init;
8045     // Initializer could be a C++ direct-initializer. Deduction only works if it
8046     // contains exactly one expression.
8047     if (CXXDirectInit) {
8048       if (CXXDirectInit->getNumExprs() == 0) {
8049         // It isn't possible to write this directly, but it is possible to
8050         // end up in this situation with "auto x(some_pack...);"
8051         Diag(CXXDirectInit->getLocStart(),
8052              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8053                                     : diag::err_auto_var_init_no_expression)
8054           << VDecl->getDeclName() << VDecl->getType()
8055           << VDecl->getSourceRange();
8056         RealDecl->setInvalidDecl();
8057         return;
8058       } else if (CXXDirectInit->getNumExprs() > 1) {
8059         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8060              VDecl->isInitCapture()
8061                  ? diag::err_init_capture_multiple_expressions
8062                  : diag::err_auto_var_init_multiple_expressions)
8063           << VDecl->getDeclName() << VDecl->getType()
8064           << VDecl->getSourceRange();
8065         RealDecl->setInvalidDecl();
8066         return;
8067       } else {
8068         DeduceInit = CXXDirectInit->getExpr(0);
8069       }
8070     }
8071 
8072     // Expressions default to 'id' when we're in a debugger.
8073     bool DefaultedToAuto = false;
8074     if (getLangOpts().DebuggerCastResultToId &&
8075         Init->getType() == Context.UnknownAnyTy) {
8076       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8077       if (Result.isInvalid()) {
8078         VDecl->setInvalidDecl();
8079         return;
8080       }
8081       Init = Result.take();
8082       DefaultedToAuto = true;
8083     }
8084 
8085     QualType DeducedType;
8086     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8087             DAR_Failed)
8088       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8089     if (DeducedType.isNull()) {
8090       RealDecl->setInvalidDecl();
8091       return;
8092     }
8093     VDecl->setType(DeducedType);
8094     assert(VDecl->isLinkageValid());
8095 
8096     // In ARC, infer lifetime.
8097     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8098       VDecl->setInvalidDecl();
8099 
8100     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8101     // 'id' instead of a specific object type prevents most of our usual checks.
8102     // We only want to warn outside of template instantiations, though:
8103     // inside a template, the 'id' could have come from a parameter.
8104     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8105         DeducedType->isObjCIdType()) {
8106       SourceLocation Loc =
8107           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8108       Diag(Loc, diag::warn_auto_var_is_id)
8109         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8110     }
8111 
8112     // If this is a redeclaration, check that the type we just deduced matches
8113     // the previously declared type.
8114     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8115       // We never need to merge the type, because we cannot form an incomplete
8116       // array of auto, nor deduce such a type.
8117       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8118     }
8119 
8120     // Check the deduced type is valid for a variable declaration.
8121     CheckVariableDeclarationType(VDecl);
8122     if (VDecl->isInvalidDecl())
8123       return;
8124   }
8125 
8126   // dllimport cannot be used on variable definitions.
8127   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
8128     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
8129     VDecl->setInvalidDecl();
8130     return;
8131   }
8132 
8133   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8134     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8135     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8136     VDecl->setInvalidDecl();
8137     return;
8138   }
8139 
8140   if (!VDecl->getType()->isDependentType()) {
8141     // A definition must end up with a complete type, which means it must be
8142     // complete with the restriction that an array type might be completed by
8143     // the initializer; note that later code assumes this restriction.
8144     QualType BaseDeclType = VDecl->getType();
8145     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8146       BaseDeclType = Array->getElementType();
8147     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8148                             diag::err_typecheck_decl_incomplete_type)) {
8149       RealDecl->setInvalidDecl();
8150       return;
8151     }
8152 
8153     // The variable can not have an abstract class type.
8154     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8155                                diag::err_abstract_type_in_decl,
8156                                AbstractVariableType))
8157       VDecl->setInvalidDecl();
8158   }
8159 
8160   const VarDecl *Def;
8161   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8162     Diag(VDecl->getLocation(), diag::err_redefinition)
8163       << VDecl->getDeclName();
8164     Diag(Def->getLocation(), diag::note_previous_definition);
8165     VDecl->setInvalidDecl();
8166     return;
8167   }
8168 
8169   const VarDecl* PrevInit = 0;
8170   if (getLangOpts().CPlusPlus) {
8171     // C++ [class.static.data]p4
8172     //   If a static data member is of const integral or const
8173     //   enumeration type, its declaration in the class definition can
8174     //   specify a constant-initializer which shall be an integral
8175     //   constant expression (5.19). In that case, the member can appear
8176     //   in integral constant expressions. The member shall still be
8177     //   defined in a namespace scope if it is used in the program and the
8178     //   namespace scope definition shall not contain an initializer.
8179     //
8180     // We already performed a redefinition check above, but for static
8181     // data members we also need to check whether there was an in-class
8182     // declaration with an initializer.
8183     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8184       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8185           << VDecl->getDeclName();
8186       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8187       return;
8188     }
8189 
8190     if (VDecl->hasLocalStorage())
8191       getCurFunction()->setHasBranchProtectedScope();
8192 
8193     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8194       VDecl->setInvalidDecl();
8195       return;
8196     }
8197   }
8198 
8199   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8200   // a kernel function cannot be initialized."
8201   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8202     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8203     VDecl->setInvalidDecl();
8204     return;
8205   }
8206 
8207   // Get the decls type and save a reference for later, since
8208   // CheckInitializerTypes may change it.
8209   QualType DclT = VDecl->getType(), SavT = DclT;
8210 
8211   // Expressions default to 'id' when we're in a debugger
8212   // and we are assigning it to a variable of Objective-C pointer type.
8213   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8214       Init->getType() == Context.UnknownAnyTy) {
8215     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8216     if (Result.isInvalid()) {
8217       VDecl->setInvalidDecl();
8218       return;
8219     }
8220     Init = Result.take();
8221   }
8222 
8223   // Perform the initialization.
8224   if (!VDecl->isInvalidDecl()) {
8225     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8226     InitializationKind Kind
8227       = DirectInit ?
8228           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8229                                                            Init->getLocStart(),
8230                                                            Init->getLocEnd())
8231                         : InitializationKind::CreateDirectList(
8232                                                           VDecl->getLocation())
8233                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8234                                                     Init->getLocStart());
8235 
8236     MultiExprArg Args = Init;
8237     if (CXXDirectInit)
8238       Args = MultiExprArg(CXXDirectInit->getExprs(),
8239                           CXXDirectInit->getNumExprs());
8240 
8241     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8242     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8243     if (Result.isInvalid()) {
8244       VDecl->setInvalidDecl();
8245       return;
8246     }
8247 
8248     Init = Result.takeAs<Expr>();
8249   }
8250 
8251   // Check for self-references within variable initializers.
8252   // Variables declared within a function/method body (except for references)
8253   // are handled by a dataflow analysis.
8254   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8255       VDecl->getType()->isReferenceType()) {
8256     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8257   }
8258 
8259   // If the type changed, it means we had an incomplete type that was
8260   // completed by the initializer. For example:
8261   //   int ary[] = { 1, 3, 5 };
8262   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8263   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8264     VDecl->setType(DclT);
8265 
8266   if (!VDecl->isInvalidDecl()) {
8267     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8268 
8269     if (VDecl->hasAttr<BlocksAttr>())
8270       checkRetainCycles(VDecl, Init);
8271 
8272     // It is safe to assign a weak reference into a strong variable.
8273     // Although this code can still have problems:
8274     //   id x = self.weakProp;
8275     //   id y = self.weakProp;
8276     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8277     // paths through the function. This should be revisited if
8278     // -Wrepeated-use-of-weak is made flow-sensitive.
8279     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
8280       DiagnosticsEngine::Level Level =
8281         Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8282                                  Init->getLocStart());
8283       if (Level != DiagnosticsEngine::Ignored)
8284         getCurFunction()->markSafeWeakUse(Init);
8285     }
8286   }
8287 
8288   // The initialization is usually a full-expression.
8289   //
8290   // FIXME: If this is a braced initialization of an aggregate, it is not
8291   // an expression, and each individual field initializer is a separate
8292   // full-expression. For instance, in:
8293   //
8294   //   struct Temp { ~Temp(); };
8295   //   struct S { S(Temp); };
8296   //   struct T { S a, b; } t = { Temp(), Temp() }
8297   //
8298   // we should destroy the first Temp before constructing the second.
8299   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8300                                           false,
8301                                           VDecl->isConstexpr());
8302   if (Result.isInvalid()) {
8303     VDecl->setInvalidDecl();
8304     return;
8305   }
8306   Init = Result.take();
8307 
8308   // Attach the initializer to the decl.
8309   VDecl->setInit(Init);
8310 
8311   if (VDecl->isLocalVarDecl()) {
8312     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8313     // static storage duration shall be constant expressions or string literals.
8314     // C++ does not have this restriction.
8315     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8316       if (VDecl->getStorageClass() == SC_Static)
8317         CheckForConstantInitializer(Init, DclT);
8318       // C89 is stricter than C99 for non-static aggregate types.
8319       // C89 6.5.7p3: All the expressions [...] in an initializer list
8320       // for an object that has aggregate or union type shall be
8321       // constant expressions.
8322       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8323                isa<InitListExpr>(Init) &&
8324                !Init->isConstantInitializer(Context, false))
8325         Diag(Init->getExprLoc(),
8326              diag::ext_aggregate_init_not_constant)
8327           << Init->getSourceRange();
8328     }
8329   } else if (VDecl->isStaticDataMember() &&
8330              VDecl->getLexicalDeclContext()->isRecord()) {
8331     // This is an in-class initialization for a static data member, e.g.,
8332     //
8333     // struct S {
8334     //   static const int value = 17;
8335     // };
8336 
8337     // C++ [class.mem]p4:
8338     //   A member-declarator can contain a constant-initializer only
8339     //   if it declares a static member (9.4) of const integral or
8340     //   const enumeration type, see 9.4.2.
8341     //
8342     // C++11 [class.static.data]p3:
8343     //   If a non-volatile const static data member is of integral or
8344     //   enumeration type, its declaration in the class definition can
8345     //   specify a brace-or-equal-initializer in which every initalizer-clause
8346     //   that is an assignment-expression is a constant expression. A static
8347     //   data member of literal type can be declared in the class definition
8348     //   with the constexpr specifier; if so, its declaration shall specify a
8349     //   brace-or-equal-initializer in which every initializer-clause that is
8350     //   an assignment-expression is a constant expression.
8351 
8352     // Do nothing on dependent types.
8353     if (DclT->isDependentType()) {
8354 
8355     // Allow any 'static constexpr' members, whether or not they are of literal
8356     // type. We separately check that every constexpr variable is of literal
8357     // type.
8358     } else if (VDecl->isConstexpr()) {
8359 
8360     // Require constness.
8361     } else if (!DclT.isConstQualified()) {
8362       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8363         << Init->getSourceRange();
8364       VDecl->setInvalidDecl();
8365 
8366     // We allow integer constant expressions in all cases.
8367     } else if (DclT->isIntegralOrEnumerationType()) {
8368       // Check whether the expression is a constant expression.
8369       SourceLocation Loc;
8370       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8371         // In C++11, a non-constexpr const static data member with an
8372         // in-class initializer cannot be volatile.
8373         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8374       else if (Init->isValueDependent())
8375         ; // Nothing to check.
8376       else if (Init->isIntegerConstantExpr(Context, &Loc))
8377         ; // Ok, it's an ICE!
8378       else if (Init->isEvaluatable(Context)) {
8379         // If we can constant fold the initializer through heroics, accept it,
8380         // but report this as a use of an extension for -pedantic.
8381         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8382           << Init->getSourceRange();
8383       } else {
8384         // Otherwise, this is some crazy unknown case.  Report the issue at the
8385         // location provided by the isIntegerConstantExpr failed check.
8386         Diag(Loc, diag::err_in_class_initializer_non_constant)
8387           << Init->getSourceRange();
8388         VDecl->setInvalidDecl();
8389       }
8390 
8391     // We allow foldable floating-point constants as an extension.
8392     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8393       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8394       // it anyway and provide a fixit to add the 'constexpr'.
8395       if (getLangOpts().CPlusPlus11) {
8396         Diag(VDecl->getLocation(),
8397              diag::ext_in_class_initializer_float_type_cxx11)
8398             << DclT << Init->getSourceRange();
8399         Diag(VDecl->getLocStart(),
8400              diag::note_in_class_initializer_float_type_cxx11)
8401             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8402       } else {
8403         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8404           << DclT << Init->getSourceRange();
8405 
8406         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8407           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8408             << Init->getSourceRange();
8409           VDecl->setInvalidDecl();
8410         }
8411       }
8412 
8413     // Suggest adding 'constexpr' in C++11 for literal types.
8414     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8415       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8416         << DclT << Init->getSourceRange()
8417         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8418       VDecl->setConstexpr(true);
8419 
8420     } else {
8421       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8422         << DclT << Init->getSourceRange();
8423       VDecl->setInvalidDecl();
8424     }
8425   } else if (VDecl->isFileVarDecl()) {
8426     if (VDecl->getStorageClass() == SC_Extern &&
8427         (!getLangOpts().CPlusPlus ||
8428          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8429            VDecl->isExternC())) &&
8430         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
8431       Diag(VDecl->getLocation(), diag::warn_extern_init);
8432 
8433     // C99 6.7.8p4. All file scoped initializers need to be constant.
8434     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8435       CheckForConstantInitializer(Init, DclT);
8436     else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8437              !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8438              !Init->isValueDependent() && !VDecl->isConstexpr() &&
8439              !Init->isConstantInitializer(
8440                  Context, VDecl->getType()->isReferenceType())) {
8441       // GNU C++98 edits for __thread, [basic.start.init]p4:
8442       //   An object of thread storage duration shall not require dynamic
8443       //   initialization.
8444       // FIXME: Need strict checking here.
8445       Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8446       if (getLangOpts().CPlusPlus11)
8447         Diag(VDecl->getLocation(), diag::note_use_thread_local);
8448     }
8449   }
8450 
8451   // We will represent direct-initialization similarly to copy-initialization:
8452   //    int x(1);  -as-> int x = 1;
8453   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8454   //
8455   // Clients that want to distinguish between the two forms, can check for
8456   // direct initializer using VarDecl::getInitStyle().
8457   // A major benefit is that clients that don't particularly care about which
8458   // exactly form was it (like the CodeGen) can handle both cases without
8459   // special case code.
8460 
8461   // C++ 8.5p11:
8462   // The form of initialization (using parentheses or '=') is generally
8463   // insignificant, but does matter when the entity being initialized has a
8464   // class type.
8465   if (CXXDirectInit) {
8466     assert(DirectInit && "Call-style initializer must be direct init.");
8467     VDecl->setInitStyle(VarDecl::CallInit);
8468   } else if (DirectInit) {
8469     // This must be list-initialization. No other way is direct-initialization.
8470     VDecl->setInitStyle(VarDecl::ListInit);
8471   }
8472 
8473   CheckCompleteVariableDeclaration(VDecl);
8474 }
8475 
8476 /// ActOnInitializerError - Given that there was an error parsing an
8477 /// initializer for the given declaration, try to return to some form
8478 /// of sanity.
8479 void Sema::ActOnInitializerError(Decl *D) {
8480   // Our main concern here is re-establishing invariants like "a
8481   // variable's type is either dependent or complete".
8482   if (!D || D->isInvalidDecl()) return;
8483 
8484   VarDecl *VD = dyn_cast<VarDecl>(D);
8485   if (!VD) return;
8486 
8487   // Auto types are meaningless if we can't make sense of the initializer.
8488   if (ParsingInitForAutoVars.count(D)) {
8489     D->setInvalidDecl();
8490     return;
8491   }
8492 
8493   QualType Ty = VD->getType();
8494   if (Ty->isDependentType()) return;
8495 
8496   // Require a complete type.
8497   if (RequireCompleteType(VD->getLocation(),
8498                           Context.getBaseElementType(Ty),
8499                           diag::err_typecheck_decl_incomplete_type)) {
8500     VD->setInvalidDecl();
8501     return;
8502   }
8503 
8504   // Require an abstract type.
8505   if (RequireNonAbstractType(VD->getLocation(), Ty,
8506                              diag::err_abstract_type_in_decl,
8507                              AbstractVariableType)) {
8508     VD->setInvalidDecl();
8509     return;
8510   }
8511 
8512   // Don't bother complaining about constructors or destructors,
8513   // though.
8514 }
8515 
8516 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
8517                                   bool TypeMayContainAuto) {
8518   // If there is no declaration, there was an error parsing it. Just ignore it.
8519   if (RealDecl == 0)
8520     return;
8521 
8522   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8523     QualType Type = Var->getType();
8524 
8525     // C++11 [dcl.spec.auto]p3
8526     if (TypeMayContainAuto && Type->getContainedAutoType()) {
8527       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8528         << Var->getDeclName() << Type;
8529       Var->setInvalidDecl();
8530       return;
8531     }
8532 
8533     // C++11 [class.static.data]p3: A static data member can be declared with
8534     // the constexpr specifier; if so, its declaration shall specify
8535     // a brace-or-equal-initializer.
8536     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8537     // the definition of a variable [...] or the declaration of a static data
8538     // member.
8539     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8540       if (Var->isStaticDataMember())
8541         Diag(Var->getLocation(),
8542              diag::err_constexpr_static_mem_var_requires_init)
8543           << Var->getDeclName();
8544       else
8545         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8546       Var->setInvalidDecl();
8547       return;
8548     }
8549 
8550     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8551     // be initialized.
8552     if (!Var->isInvalidDecl() &&
8553         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
8554         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
8555       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8556       Var->setInvalidDecl();
8557       return;
8558     }
8559 
8560     switch (Var->isThisDeclarationADefinition()) {
8561     case VarDecl::Definition:
8562       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8563         break;
8564 
8565       // We have an out-of-line definition of a static data member
8566       // that has an in-class initializer, so we type-check this like
8567       // a declaration.
8568       //
8569       // Fall through
8570 
8571     case VarDecl::DeclarationOnly:
8572       // It's only a declaration.
8573 
8574       // Block scope. C99 6.7p7: If an identifier for an object is
8575       // declared with no linkage (C99 6.2.2p6), the type for the
8576       // object shall be complete.
8577       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
8578           !Var->hasLinkage() && !Var->isInvalidDecl() &&
8579           RequireCompleteType(Var->getLocation(), Type,
8580                               diag::err_typecheck_decl_incomplete_type))
8581         Var->setInvalidDecl();
8582 
8583       // Make sure that the type is not abstract.
8584       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8585           RequireNonAbstractType(Var->getLocation(), Type,
8586                                  diag::err_abstract_type_in_decl,
8587                                  AbstractVariableType))
8588         Var->setInvalidDecl();
8589       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8590           Var->getStorageClass() == SC_PrivateExtern) {
8591         Diag(Var->getLocation(), diag::warn_private_extern);
8592         Diag(Var->getLocation(), diag::note_private_extern);
8593       }
8594 
8595       return;
8596 
8597     case VarDecl::TentativeDefinition:
8598       // File scope. C99 6.9.2p2: A declaration of an identifier for an
8599       // object that has file scope without an initializer, and without a
8600       // storage-class specifier or with the storage-class specifier "static",
8601       // constitutes a tentative definition. Note: A tentative definition with
8602       // external linkage is valid (C99 6.2.2p5).
8603       if (!Var->isInvalidDecl()) {
8604         if (const IncompleteArrayType *ArrayT
8605                                     = Context.getAsIncompleteArrayType(Type)) {
8606           if (RequireCompleteType(Var->getLocation(),
8607                                   ArrayT->getElementType(),
8608                                   diag::err_illegal_decl_array_incomplete_type))
8609             Var->setInvalidDecl();
8610         } else if (Var->getStorageClass() == SC_Static) {
8611           // C99 6.9.2p3: If the declaration of an identifier for an object is
8612           // a tentative definition and has internal linkage (C99 6.2.2p3), the
8613           // declared type shall not be an incomplete type.
8614           // NOTE: code such as the following
8615           //     static struct s;
8616           //     struct s { int a; };
8617           // is accepted by gcc. Hence here we issue a warning instead of
8618           // an error and we do not invalidate the static declaration.
8619           // NOTE: to avoid multiple warnings, only check the first declaration.
8620           if (Var->isFirstDecl())
8621             RequireCompleteType(Var->getLocation(), Type,
8622                                 diag::ext_typecheck_decl_incomplete_type);
8623         }
8624       }
8625 
8626       // Record the tentative definition; we're done.
8627       if (!Var->isInvalidDecl())
8628         TentativeDefinitions.push_back(Var);
8629       return;
8630     }
8631 
8632     // Provide a specific diagnostic for uninitialized variable
8633     // definitions with incomplete array type.
8634     if (Type->isIncompleteArrayType()) {
8635       Diag(Var->getLocation(),
8636            diag::err_typecheck_incomplete_array_needs_initializer);
8637       Var->setInvalidDecl();
8638       return;
8639     }
8640 
8641     // Provide a specific diagnostic for uninitialized variable
8642     // definitions with reference type.
8643     if (Type->isReferenceType()) {
8644       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8645         << Var->getDeclName()
8646         << SourceRange(Var->getLocation(), Var->getLocation());
8647       Var->setInvalidDecl();
8648       return;
8649     }
8650 
8651     // Do not attempt to type-check the default initializer for a
8652     // variable with dependent type.
8653     if (Type->isDependentType())
8654       return;
8655 
8656     if (Var->isInvalidDecl())
8657       return;
8658 
8659     if (RequireCompleteType(Var->getLocation(),
8660                             Context.getBaseElementType(Type),
8661                             diag::err_typecheck_decl_incomplete_type)) {
8662       Var->setInvalidDecl();
8663       return;
8664     }
8665 
8666     // The variable can not have an abstract class type.
8667     if (RequireNonAbstractType(Var->getLocation(), Type,
8668                                diag::err_abstract_type_in_decl,
8669                                AbstractVariableType)) {
8670       Var->setInvalidDecl();
8671       return;
8672     }
8673 
8674     // Check for jumps past the implicit initializer.  C++0x
8675     // clarifies that this applies to a "variable with automatic
8676     // storage duration", not a "local variable".
8677     // C++11 [stmt.dcl]p3
8678     //   A program that jumps from a point where a variable with automatic
8679     //   storage duration is not in scope to a point where it is in scope is
8680     //   ill-formed unless the variable has scalar type, class type with a
8681     //   trivial default constructor and a trivial destructor, a cv-qualified
8682     //   version of one of these types, or an array of one of the preceding
8683     //   types and is declared without an initializer.
8684     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
8685       if (const RecordType *Record
8686             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
8687         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
8688         // Mark the function for further checking even if the looser rules of
8689         // C++11 do not require such checks, so that we can diagnose
8690         // incompatibilities with C++98.
8691         if (!CXXRecord->isPOD())
8692           getCurFunction()->setHasBranchProtectedScope();
8693       }
8694     }
8695 
8696     // C++03 [dcl.init]p9:
8697     //   If no initializer is specified for an object, and the
8698     //   object is of (possibly cv-qualified) non-POD class type (or
8699     //   array thereof), the object shall be default-initialized; if
8700     //   the object is of const-qualified type, the underlying class
8701     //   type shall have a user-declared default
8702     //   constructor. Otherwise, if no initializer is specified for
8703     //   a non- static object, the object and its subobjects, if
8704     //   any, have an indeterminate initial value); if the object
8705     //   or any of its subobjects are of const-qualified type, the
8706     //   program is ill-formed.
8707     // C++0x [dcl.init]p11:
8708     //   If no initializer is specified for an object, the object is
8709     //   default-initialized; [...].
8710     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8711     InitializationKind Kind
8712       = InitializationKind::CreateDefault(Var->getLocation());
8713 
8714     InitializationSequence InitSeq(*this, Entity, Kind, None);
8715     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
8716     if (Init.isInvalid())
8717       Var->setInvalidDecl();
8718     else if (Init.get()) {
8719       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
8720       // This is important for template substitution.
8721       Var->setInitStyle(VarDecl::CallInit);
8722     }
8723 
8724     CheckCompleteVariableDeclaration(Var);
8725   }
8726 }
8727 
8728 void Sema::ActOnCXXForRangeDecl(Decl *D) {
8729   VarDecl *VD = dyn_cast<VarDecl>(D);
8730   if (!VD) {
8731     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8732     D->setInvalidDecl();
8733     return;
8734   }
8735 
8736   VD->setCXXForRangeDecl(true);
8737 
8738   // for-range-declaration cannot be given a storage class specifier.
8739   int Error = -1;
8740   switch (VD->getStorageClass()) {
8741   case SC_None:
8742     break;
8743   case SC_Extern:
8744     Error = 0;
8745     break;
8746   case SC_Static:
8747     Error = 1;
8748     break;
8749   case SC_PrivateExtern:
8750     Error = 2;
8751     break;
8752   case SC_Auto:
8753     Error = 3;
8754     break;
8755   case SC_Register:
8756     Error = 4;
8757     break;
8758   case SC_OpenCLWorkGroupLocal:
8759     llvm_unreachable("Unexpected storage class");
8760   }
8761   if (VD->isConstexpr())
8762     Error = 5;
8763   if (Error != -1) {
8764     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8765       << VD->getDeclName() << Error;
8766     D->setInvalidDecl();
8767   }
8768 }
8769 
8770 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8771   if (var->isInvalidDecl()) return;
8772 
8773   // In ARC, don't allow jumps past the implicit initialization of a
8774   // local retaining variable.
8775   if (getLangOpts().ObjCAutoRefCount &&
8776       var->hasLocalStorage()) {
8777     switch (var->getType().getObjCLifetime()) {
8778     case Qualifiers::OCL_None:
8779     case Qualifiers::OCL_ExplicitNone:
8780     case Qualifiers::OCL_Autoreleasing:
8781       break;
8782 
8783     case Qualifiers::OCL_Weak:
8784     case Qualifiers::OCL_Strong:
8785       getCurFunction()->setHasBranchProtectedScope();
8786       break;
8787     }
8788   }
8789 
8790   // Warn about externally-visible variables being defined without a
8791   // prior declaration.  We only want to do this for global
8792   // declarations, but we also specifically need to avoid doing it for
8793   // class members because the linkage of an anonymous class can
8794   // change if it's later given a typedef name.
8795   if (var->isThisDeclarationADefinition() &&
8796       var->getDeclContext()->getRedeclContext()->isFileContext() &&
8797       var->isExternallyVisible() && var->hasLinkage() &&
8798       getDiagnostics().getDiagnosticLevel(
8799                        diag::warn_missing_variable_declarations,
8800                        var->getLocation())) {
8801     // Find a previous declaration that's not a definition.
8802     VarDecl *prev = var->getPreviousDecl();
8803     while (prev && prev->isThisDeclarationADefinition())
8804       prev = prev->getPreviousDecl();
8805 
8806     if (!prev)
8807       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8808   }
8809 
8810   if (var->getTLSKind() == VarDecl::TLS_Static &&
8811       var->getType().isDestructedType()) {
8812     // GNU C++98 edits for __thread, [basic.start.term]p3:
8813     //   The type of an object with thread storage duration shall not
8814     //   have a non-trivial destructor.
8815     Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8816     if (getLangOpts().CPlusPlus11)
8817       Diag(var->getLocation(), diag::note_use_thread_local);
8818   }
8819 
8820   // All the following checks are C++ only.
8821   if (!getLangOpts().CPlusPlus) return;
8822 
8823   QualType type = var->getType();
8824   if (type->isDependentType()) return;
8825 
8826   // __block variables might require us to capture a copy-initializer.
8827   if (var->hasAttr<BlocksAttr>()) {
8828     // It's currently invalid to ever have a __block variable with an
8829     // array type; should we diagnose that here?
8830 
8831     // Regardless, we don't want to ignore array nesting when
8832     // constructing this copy.
8833     if (type->isStructureOrClassType()) {
8834       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
8835       SourceLocation poi = var->getLocation();
8836       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
8837       ExprResult result
8838         = PerformMoveOrCopyInitialization(
8839             InitializedEntity::InitializeBlock(poi, type, false),
8840             var, var->getType(), varRef, /*AllowNRVO=*/true);
8841       if (!result.isInvalid()) {
8842         result = MaybeCreateExprWithCleanups(result);
8843         Expr *init = result.takeAs<Expr>();
8844         Context.setBlockVarCopyInits(var, init);
8845       }
8846     }
8847   }
8848 
8849   Expr *Init = var->getInit();
8850   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
8851   QualType baseType = Context.getBaseElementType(type);
8852 
8853   if (!var->getDeclContext()->isDependentContext() &&
8854       Init && !Init->isValueDependent()) {
8855     if (IsGlobal && !var->isConstexpr() &&
8856         getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8857                                             var->getLocation())
8858           != DiagnosticsEngine::Ignored) {
8859       // Warn about globals which don't have a constant initializer.  Don't
8860       // warn about globals with a non-trivial destructor because we already
8861       // warned about them.
8862       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8863       if (!(RD && !RD->hasTrivialDestructor()) &&
8864           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8865         Diag(var->getLocation(), diag::warn_global_constructor)
8866           << Init->getSourceRange();
8867     }
8868 
8869     if (var->isConstexpr()) {
8870       SmallVector<PartialDiagnosticAt, 8> Notes;
8871       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8872         SourceLocation DiagLoc = var->getLocation();
8873         // If the note doesn't add any useful information other than a source
8874         // location, fold it into the primary diagnostic.
8875         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8876               diag::note_invalid_subexpr_in_const_expr) {
8877           DiagLoc = Notes[0].first;
8878           Notes.clear();
8879         }
8880         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8881           << var << Init->getSourceRange();
8882         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8883           Diag(Notes[I].first, Notes[I].second);
8884       }
8885     } else if (var->isUsableInConstantExpressions(Context)) {
8886       // Check whether the initializer of a const variable of integral or
8887       // enumeration type is an ICE now, since we can't tell whether it was
8888       // initialized by a constant expression if we check later.
8889       var->checkInitIsICE();
8890     }
8891   }
8892 
8893   // Require the destructor.
8894   if (const RecordType *recordType = baseType->getAs<RecordType>())
8895     FinalizeVarWithDestructor(var, recordType);
8896 }
8897 
8898 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8899 /// any semantic actions necessary after any initializer has been attached.
8900 void
8901 Sema::FinalizeDeclaration(Decl *ThisDecl) {
8902   // Note that we are no longer parsing the initializer for this declaration.
8903   ParsingInitForAutoVars.erase(ThisDecl);
8904 
8905   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
8906   if (!VD)
8907     return;
8908 
8909   checkAttributesAfterMerging(*this, *VD);
8910 
8911   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8912     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8913       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
8914       VD->dropAttr<UsedAttr>();
8915     }
8916   }
8917 
8918   if (!VD->isInvalidDecl() &&
8919       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8920     if (const VarDecl *Def = VD->getDefinition()) {
8921       if (Def->hasAttr<AliasAttr>()) {
8922         Diag(VD->getLocation(), diag::err_tentative_after_alias)
8923             << VD->getDeclName();
8924         Diag(Def->getLocation(), diag::note_previous_definition);
8925         VD->setInvalidDecl();
8926       }
8927     }
8928   }
8929 
8930   const DeclContext *DC = VD->getDeclContext();
8931   // If there's a #pragma GCC visibility in scope, and this isn't a class
8932   // member, set the visibility of this variable.
8933   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
8934     AddPushedVisibilityAttribute(VD);
8935 
8936   if (VD->isFileVarDecl())
8937     MarkUnusedFileScopedDecl(VD);
8938 
8939   // Now we have parsed the initializer and can update the table of magic
8940   // tag values.
8941   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8942       !VD->getType()->isIntegralOrEnumerationType())
8943     return;
8944 
8945   for (specific_attr_iterator<TypeTagForDatatypeAttr>
8946          I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8947          E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8948        I != E; ++I) {
8949     const Expr *MagicValueExpr = VD->getInit();
8950     if (!MagicValueExpr) {
8951       continue;
8952     }
8953     llvm::APSInt MagicValueInt;
8954     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8955       Diag(I->getRange().getBegin(),
8956            diag::err_type_tag_for_datatype_not_ice)
8957         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8958       continue;
8959     }
8960     if (MagicValueInt.getActiveBits() > 64) {
8961       Diag(I->getRange().getBegin(),
8962            diag::err_type_tag_for_datatype_too_large)
8963         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8964       continue;
8965     }
8966     uint64_t MagicValue = MagicValueInt.getZExtValue();
8967     RegisterTypeTagForDatatype(I->getArgumentKind(),
8968                                MagicValue,
8969                                I->getMatchingCType(),
8970                                I->getLayoutCompatible(),
8971                                I->getMustBeNull());
8972   }
8973 }
8974 
8975 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8976                                                    ArrayRef<Decl *> Group) {
8977   SmallVector<Decl*, 8> Decls;
8978 
8979   if (DS.isTypeSpecOwned())
8980     Decls.push_back(DS.getRepAsDecl());
8981 
8982   DeclaratorDecl *FirstDeclaratorInGroup = 0;
8983   for (unsigned i = 0, e = Group.size(); i != e; ++i)
8984     if (Decl *D = Group[i]) {
8985       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8986         if (!FirstDeclaratorInGroup)
8987           FirstDeclaratorInGroup = DD;
8988       Decls.push_back(D);
8989     }
8990 
8991   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
8992     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
8993       HandleTagNumbering(*this, Tag);
8994       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8995         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8996     }
8997   }
8998 
8999   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9000 }
9001 
9002 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9003 /// group, performing any necessary semantic checking.
9004 Sema::DeclGroupPtrTy
9005 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
9006                            bool TypeMayContainAuto) {
9007   // C++0x [dcl.spec.auto]p7:
9008   //   If the type deduced for the template parameter U is not the same in each
9009   //   deduction, the program is ill-formed.
9010   // FIXME: When initializer-list support is added, a distinction is needed
9011   // between the deduced type U and the deduced type which 'auto' stands for.
9012   //   auto a = 0, b = { 1, 2, 3 };
9013   // is legal because the deduced type U is 'int' in both cases.
9014   if (TypeMayContainAuto && Group.size() > 1) {
9015     QualType Deduced;
9016     CanQualType DeducedCanon;
9017     VarDecl *DeducedDecl = 0;
9018     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9019       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9020         AutoType *AT = D->getType()->getContainedAutoType();
9021         // Don't reissue diagnostics when instantiating a template.
9022         if (AT && D->isInvalidDecl())
9023           break;
9024         QualType U = AT ? AT->getDeducedType() : QualType();
9025         if (!U.isNull()) {
9026           CanQualType UCanon = Context.getCanonicalType(U);
9027           if (Deduced.isNull()) {
9028             Deduced = U;
9029             DeducedCanon = UCanon;
9030             DeducedDecl = D;
9031           } else if (DeducedCanon != UCanon) {
9032             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9033                  diag::err_auto_different_deductions)
9034               << (AT->isDecltypeAuto() ? 1 : 0)
9035               << Deduced << DeducedDecl->getDeclName()
9036               << U << D->getDeclName()
9037               << DeducedDecl->getInit()->getSourceRange()
9038               << D->getInit()->getSourceRange();
9039             D->setInvalidDecl();
9040             break;
9041           }
9042         }
9043       }
9044     }
9045   }
9046 
9047   ActOnDocumentableDecls(Group);
9048 
9049   return DeclGroupPtrTy::make(
9050       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9051 }
9052 
9053 void Sema::ActOnDocumentableDecl(Decl *D) {
9054   ActOnDocumentableDecls(D);
9055 }
9056 
9057 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9058   // Don't parse the comment if Doxygen diagnostics are ignored.
9059   if (Group.empty() || !Group[0])
9060    return;
9061 
9062   if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9063                                Group[0]->getLocation())
9064         == DiagnosticsEngine::Ignored)
9065     return;
9066 
9067   if (Group.size() >= 2) {
9068     // This is a decl group.  Normally it will contain only declarations
9069     // produced from declarator list.  But in case we have any definitions or
9070     // additional declaration references:
9071     //   'typedef struct S {} S;'
9072     //   'typedef struct S *S;'
9073     //   'struct S *pS;'
9074     // FinalizeDeclaratorGroup adds these as separate declarations.
9075     Decl *MaybeTagDecl = Group[0];
9076     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9077       Group = Group.slice(1);
9078     }
9079   }
9080 
9081   // See if there are any new comments that are not attached to a decl.
9082   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9083   if (!Comments.empty() &&
9084       !Comments.back()->isAttached()) {
9085     // There is at least one comment that not attached to a decl.
9086     // Maybe it should be attached to one of these decls?
9087     //
9088     // Note that this way we pick up not only comments that precede the
9089     // declaration, but also comments that *follow* the declaration -- thanks to
9090     // the lookahead in the lexer: we've consumed the semicolon and looked
9091     // ahead through comments.
9092     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9093       Context.getCommentForDecl(Group[i], &PP);
9094   }
9095 }
9096 
9097 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9098 /// to introduce parameters into function prototype scope.
9099 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9100   const DeclSpec &DS = D.getDeclSpec();
9101 
9102   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9103 
9104   // C++03 [dcl.stc]p2 also permits 'auto'.
9105   VarDecl::StorageClass StorageClass = SC_None;
9106   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9107     StorageClass = SC_Register;
9108   } else if (getLangOpts().CPlusPlus &&
9109              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9110     StorageClass = SC_Auto;
9111   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9112     Diag(DS.getStorageClassSpecLoc(),
9113          diag::err_invalid_storage_class_in_func_decl);
9114     D.getMutableDeclSpec().ClearStorageClassSpecs();
9115   }
9116 
9117   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9118     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9119       << DeclSpec::getSpecifierName(TSCS);
9120   if (DS.isConstexprSpecified())
9121     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9122       << 0;
9123 
9124   DiagnoseFunctionSpecifiers(DS);
9125 
9126   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9127   QualType parmDeclType = TInfo->getType();
9128 
9129   if (getLangOpts().CPlusPlus) {
9130     // Check that there are no default arguments inside the type of this
9131     // parameter.
9132     CheckExtraCXXDefaultArguments(D);
9133 
9134     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9135     if (D.getCXXScopeSpec().isSet()) {
9136       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9137         << D.getCXXScopeSpec().getRange();
9138       D.getCXXScopeSpec().clear();
9139     }
9140   }
9141 
9142   // Ensure we have a valid name
9143   IdentifierInfo *II = 0;
9144   if (D.hasName()) {
9145     II = D.getIdentifier();
9146     if (!II) {
9147       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9148         << GetNameForDeclarator(D).getName();
9149       D.setInvalidType(true);
9150     }
9151   }
9152 
9153   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9154   if (II) {
9155     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9156                    ForRedeclaration);
9157     LookupName(R, S);
9158     if (R.isSingleResult()) {
9159       NamedDecl *PrevDecl = R.getFoundDecl();
9160       if (PrevDecl->isTemplateParameter()) {
9161         // Maybe we will complain about the shadowed template parameter.
9162         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9163         // Just pretend that we didn't see the previous declaration.
9164         PrevDecl = 0;
9165       } else if (S->isDeclScope(PrevDecl)) {
9166         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9167         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9168 
9169         // Recover by removing the name
9170         II = 0;
9171         D.SetIdentifier(0, D.getIdentifierLoc());
9172         D.setInvalidType(true);
9173       }
9174     }
9175   }
9176 
9177   // Temporarily put parameter variables in the translation unit, not
9178   // the enclosing context.  This prevents them from accidentally
9179   // looking like class members in C++.
9180   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9181                                     D.getLocStart(),
9182                                     D.getIdentifierLoc(), II,
9183                                     parmDeclType, TInfo,
9184                                     StorageClass);
9185 
9186   if (D.isInvalidType())
9187     New->setInvalidDecl();
9188 
9189   assert(S->isFunctionPrototypeScope());
9190   assert(S->getFunctionPrototypeDepth() >= 1);
9191   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9192                     S->getNextFunctionPrototypeIndex());
9193 
9194   // Add the parameter declaration into this scope.
9195   S->AddDecl(New);
9196   if (II)
9197     IdResolver.AddDecl(New);
9198 
9199   ProcessDeclAttributes(S, New, D);
9200 
9201   if (D.getDeclSpec().isModulePrivateSpecified())
9202     Diag(New->getLocation(), diag::err_module_private_local)
9203       << 1 << New->getDeclName()
9204       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9205       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9206 
9207   if (New->hasAttr<BlocksAttr>()) {
9208     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9209   }
9210   return New;
9211 }
9212 
9213 /// \brief Synthesizes a variable for a parameter arising from a
9214 /// typedef.
9215 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9216                                               SourceLocation Loc,
9217                                               QualType T) {
9218   /* FIXME: setting StartLoc == Loc.
9219      Would it be worth to modify callers so as to provide proper source
9220      location for the unnamed parameters, embedding the parameter's type? */
9221   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
9222                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9223                                            SC_None, 0);
9224   Param->setImplicit();
9225   return Param;
9226 }
9227 
9228 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9229                                     ParmVarDecl * const *ParamEnd) {
9230   // Don't diagnose unused-parameter errors in template instantiations; we
9231   // will already have done so in the template itself.
9232   if (!ActiveTemplateInstantiations.empty())
9233     return;
9234 
9235   for (; Param != ParamEnd; ++Param) {
9236     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9237         !(*Param)->hasAttr<UnusedAttr>()) {
9238       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9239         << (*Param)->getDeclName();
9240     }
9241   }
9242 }
9243 
9244 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9245                                                   ParmVarDecl * const *ParamEnd,
9246                                                   QualType ReturnTy,
9247                                                   NamedDecl *D) {
9248   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9249     return;
9250 
9251   // Warn if the return value is pass-by-value and larger than the specified
9252   // threshold.
9253   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9254     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9255     if (Size > LangOpts.NumLargeByValueCopy)
9256       Diag(D->getLocation(), diag::warn_return_value_size)
9257           << D->getDeclName() << Size;
9258   }
9259 
9260   // Warn if any parameter is pass-by-value and larger than the specified
9261   // threshold.
9262   for (; Param != ParamEnd; ++Param) {
9263     QualType T = (*Param)->getType();
9264     if (T->isDependentType() || !T.isPODType(Context))
9265       continue;
9266     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9267     if (Size > LangOpts.NumLargeByValueCopy)
9268       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9269           << (*Param)->getDeclName() << Size;
9270   }
9271 }
9272 
9273 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9274                                   SourceLocation NameLoc, IdentifierInfo *Name,
9275                                   QualType T, TypeSourceInfo *TSInfo,
9276                                   VarDecl::StorageClass StorageClass) {
9277   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9278   if (getLangOpts().ObjCAutoRefCount &&
9279       T.getObjCLifetime() == Qualifiers::OCL_None &&
9280       T->isObjCLifetimeType()) {
9281 
9282     Qualifiers::ObjCLifetime lifetime;
9283 
9284     // Special cases for arrays:
9285     //   - if it's const, use __unsafe_unretained
9286     //   - otherwise, it's an error
9287     if (T->isArrayType()) {
9288       if (!T.isConstQualified()) {
9289         DelayedDiagnostics.add(
9290             sema::DelayedDiagnostic::makeForbiddenType(
9291             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9292       }
9293       lifetime = Qualifiers::OCL_ExplicitNone;
9294     } else {
9295       lifetime = T->getObjCARCImplicitLifetime();
9296     }
9297     T = Context.getLifetimeQualifiedType(T, lifetime);
9298   }
9299 
9300   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9301                                          Context.getAdjustedParameterType(T),
9302                                          TSInfo,
9303                                          StorageClass, 0);
9304 
9305   // Parameters can not be abstract class types.
9306   // For record types, this is done by the AbstractClassUsageDiagnoser once
9307   // the class has been completely parsed.
9308   if (!CurContext->isRecord() &&
9309       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9310                              AbstractParamType))
9311     New->setInvalidDecl();
9312 
9313   // Parameter declarators cannot be interface types. All ObjC objects are
9314   // passed by reference.
9315   if (T->isObjCObjectType()) {
9316     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9317     Diag(NameLoc,
9318          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9319       << FixItHint::CreateInsertion(TypeEndLoc, "*");
9320     T = Context.getObjCObjectPointerType(T);
9321     New->setType(T);
9322   }
9323 
9324   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9325   // duration shall not be qualified by an address-space qualifier."
9326   // Since all parameters have automatic store duration, they can not have
9327   // an address space.
9328   if (T.getAddressSpace() != 0) {
9329     Diag(NameLoc, diag::err_arg_with_address_space);
9330     New->setInvalidDecl();
9331   }
9332 
9333   return New;
9334 }
9335 
9336 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9337                                            SourceLocation LocAfterDecls) {
9338   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9339 
9340   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9341   // for a K&R function.
9342   if (!FTI.hasPrototype) {
9343     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
9344       --i;
9345       if (FTI.Params[i].Param == 0) {
9346         SmallString<256> Code;
9347         llvm::raw_svector_ostream(Code)
9348             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
9349         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
9350             << FTI.Params[i].Ident
9351             << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9352 
9353         // Implicitly declare the argument as type 'int' for lack of a better
9354         // type.
9355         AttributeFactory attrs;
9356         DeclSpec DS(attrs);
9357         const char* PrevSpec; // unused
9358         unsigned DiagID; // unused
9359         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
9360                            DiagID, Context.getPrintingPolicy());
9361         // Use the identifier location for the type source range.
9362         DS.SetRangeStart(FTI.Params[i].IdentLoc);
9363         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
9364         Declarator ParamD(DS, Declarator::KNRTypeListContext);
9365         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
9366         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
9367       }
9368     }
9369   }
9370 }
9371 
9372 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9373   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
9374   assert(D.isFunctionDeclarator() && "Not a function declarator!");
9375   Scope *ParentScope = FnBodyScope->getParent();
9376 
9377   D.setFunctionDefinitionKind(FDK_Definition);
9378   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9379   return ActOnStartOfFunctionDef(FnBodyScope, DP);
9380 }
9381 
9382 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9383                              const FunctionDecl*& PossibleZeroParamPrototype) {
9384   // Don't warn about invalid declarations.
9385   if (FD->isInvalidDecl())
9386     return false;
9387 
9388   // Or declarations that aren't global.
9389   if (!FD->isGlobal())
9390     return false;
9391 
9392   // Don't warn about C++ member functions.
9393   if (isa<CXXMethodDecl>(FD))
9394     return false;
9395 
9396   // Don't warn about 'main'.
9397   if (FD->isMain())
9398     return false;
9399 
9400   // Don't warn about inline functions.
9401   if (FD->isInlined())
9402     return false;
9403 
9404   // Don't warn about function templates.
9405   if (FD->getDescribedFunctionTemplate())
9406     return false;
9407 
9408   // Don't warn about function template specializations.
9409   if (FD->isFunctionTemplateSpecialization())
9410     return false;
9411 
9412   // Don't warn for OpenCL kernels.
9413   if (FD->hasAttr<OpenCLKernelAttr>())
9414     return false;
9415 
9416   bool MissingPrototype = true;
9417   for (const FunctionDecl *Prev = FD->getPreviousDecl();
9418        Prev; Prev = Prev->getPreviousDecl()) {
9419     // Ignore any declarations that occur in function or method
9420     // scope, because they aren't visible from the header.
9421     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9422       continue;
9423 
9424     MissingPrototype = !Prev->getType()->isFunctionProtoType();
9425     if (FD->getNumParams() == 0)
9426       PossibleZeroParamPrototype = Prev;
9427     break;
9428   }
9429 
9430   return MissingPrototype;
9431 }
9432 
9433 void
9434 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9435                                    const FunctionDecl *EffectiveDefinition) {
9436   // Don't complain if we're in GNU89 mode and the previous definition
9437   // was an extern inline function.
9438   const FunctionDecl *Definition = EffectiveDefinition;
9439   if (!Definition)
9440     if (!FD->isDefined(Definition))
9441       return;
9442 
9443   if (canRedefineFunction(Definition, getLangOpts()))
9444     return;
9445 
9446   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9447       Definition->getStorageClass() == SC_Extern)
9448     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9449         << FD->getDeclName() << getLangOpts().CPlusPlus;
9450   else
9451     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9452 
9453   Diag(Definition->getLocation(), diag::note_previous_definition);
9454   FD->setInvalidDecl();
9455 }
9456 
9457 
9458 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9459                                    Sema &S) {
9460   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9461 
9462   LambdaScopeInfo *LSI = S.PushLambdaScope();
9463   LSI->CallOperator = CallOperator;
9464   LSI->Lambda = LambdaClass;
9465   LSI->ReturnType = CallOperator->getReturnType();
9466   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9467 
9468   if (LCD == LCD_None)
9469     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9470   else if (LCD == LCD_ByCopy)
9471     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9472   else if (LCD == LCD_ByRef)
9473     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9474   DeclarationNameInfo DNI = CallOperator->getNameInfo();
9475 
9476   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9477   LSI->Mutable = !CallOperator->isConst();
9478 
9479   // Add the captures to the LSI so they can be noted as already
9480   // captured within tryCaptureVar.
9481   for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9482       CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9483     if (C->capturesVariable()) {
9484       VarDecl *VD = C->getCapturedVar();
9485       if (VD->isInitCapture())
9486         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9487       QualType CaptureType = VD->getType();
9488       const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9489       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9490           /*RefersToEnclosingLocal*/true, C->getLocation(),
9491           /*EllipsisLoc*/C->isPackExpansion()
9492                          ? C->getEllipsisLoc() : SourceLocation(),
9493           CaptureType, /*Expr*/ 0);
9494 
9495     } else if (C->capturesThis()) {
9496       LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9497                               S.getCurrentThisType(), /*Expr*/ 0);
9498     }
9499   }
9500 }
9501 
9502 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
9503   // Clear the last template instantiation error context.
9504   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9505 
9506   if (!D)
9507     return D;
9508   FunctionDecl *FD = 0;
9509 
9510   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
9511     FD = FunTmpl->getTemplatedDecl();
9512   else
9513     FD = cast<FunctionDecl>(D);
9514   // If we are instantiating a generic lambda call operator, push
9515   // a LambdaScopeInfo onto the function stack.  But use the information
9516   // that's already been calculated (ActOnLambdaExpr) to prime the current
9517   // LambdaScopeInfo.
9518   // When the template operator is being specialized, the LambdaScopeInfo,
9519   // has to be properly restored so that tryCaptureVariable doesn't try
9520   // and capture any new variables. In addition when calculating potential
9521   // captures during transformation of nested lambdas, it is necessary to
9522   // have the LSI properly restored.
9523   if (isGenericLambdaCallOperatorSpecialization(FD)) {
9524     assert(ActiveTemplateInstantiations.size() &&
9525       "There should be an active template instantiation on the stack "
9526       "when instantiating a generic lambda!");
9527     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
9528   }
9529   else
9530     // Enter a new function scope
9531     PushFunctionScope();
9532 
9533   // See if this is a redefinition.
9534   if (!FD->isLateTemplateParsed())
9535     CheckForFunctionRedefinition(FD);
9536 
9537   // Builtin functions cannot be defined.
9538   if (unsigned BuiltinID = FD->getBuiltinID()) {
9539     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9540         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
9541       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
9542       FD->setInvalidDecl();
9543     }
9544   }
9545 
9546   // The return type of a function definition must be complete
9547   // (C99 6.9.1p3, C++ [dcl.fct]p6).
9548   QualType ResultType = FD->getReturnType();
9549   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
9550       !FD->isInvalidDecl() &&
9551       RequireCompleteType(FD->getLocation(), ResultType,
9552                           diag::err_func_def_incomplete_result))
9553     FD->setInvalidDecl();
9554 
9555   // GNU warning -Wmissing-prototypes:
9556   //   Warn if a global function is defined without a previous
9557   //   prototype declaration. This warning is issued even if the
9558   //   definition itself provides a prototype. The aim is to detect
9559   //   global functions that fail to be declared in header files.
9560   const FunctionDecl *PossibleZeroParamPrototype = 0;
9561   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
9562     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
9563 
9564     if (PossibleZeroParamPrototype) {
9565       // We found a declaration that is not a prototype,
9566       // but that could be a zero-parameter prototype
9567       if (TypeSourceInfo *TI =
9568               PossibleZeroParamPrototype->getTypeSourceInfo()) {
9569         TypeLoc TL = TI->getTypeLoc();
9570         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9571           Diag(PossibleZeroParamPrototype->getLocation(),
9572                diag::note_declaration_not_a_prototype)
9573             << PossibleZeroParamPrototype
9574             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9575       }
9576     }
9577   }
9578 
9579   if (FnBodyScope)
9580     PushDeclContext(FnBodyScope, FD);
9581 
9582   // Check the validity of our function parameters
9583   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9584                            /*CheckParameterNames=*/true);
9585 
9586   // Introduce our parameters into the function scope
9587   for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9588     ParmVarDecl *Param = FD->getParamDecl(p);
9589     Param->setOwningFunction(FD);
9590 
9591     // If this has an identifier, add it to the scope stack.
9592     if (Param->getIdentifier() && FnBodyScope) {
9593       CheckShadow(FnBodyScope, Param);
9594 
9595       PushOnScopeChains(Param, FnBodyScope);
9596     }
9597   }
9598 
9599   // If we had any tags defined in the function prototype,
9600   // introduce them into the function scope.
9601   if (FnBodyScope) {
9602     for (ArrayRef<NamedDecl *>::iterator
9603              I = FD->getDeclsInPrototypeScope().begin(),
9604              E = FD->getDeclsInPrototypeScope().end();
9605          I != E; ++I) {
9606       NamedDecl *D = *I;
9607 
9608       // Some of these decls (like enums) may have been pinned to the translation unit
9609       // for lack of a real context earlier. If so, remove from the translation unit
9610       // and reattach to the current context.
9611       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9612         // Is the decl actually in the context?
9613         for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9614                DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9615           if (*DI == D) {
9616             Context.getTranslationUnitDecl()->removeDecl(D);
9617             break;
9618           }
9619         }
9620         // Either way, reassign the lexical decl context to our FunctionDecl.
9621         D->setLexicalDeclContext(CurContext);
9622       }
9623 
9624       // If the decl has a non-null name, make accessible in the current scope.
9625       if (!D->getName().empty())
9626         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9627 
9628       // Similarly, dive into enums and fish their constants out, making them
9629       // accessible in this scope.
9630       if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9631         for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9632                EE = ED->enumerator_end(); EI != EE; ++EI)
9633           PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
9634       }
9635     }
9636   }
9637 
9638   // Ensure that the function's exception specification is instantiated.
9639   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9640     ResolveExceptionSpec(D->getLocation(), FPT);
9641 
9642   // Checking attributes of current function definition
9643   // dllimport attribute.
9644   DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9645   if (DA && (!FD->hasAttr<DLLExportAttr>())) {
9646     // dllimport attribute cannot be directly applied to definition.
9647     // Microsoft accepts dllimport for functions defined within class scope.
9648     if (!DA->isInherited() &&
9649         !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
9650       Diag(FD->getLocation(),
9651            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9652         << DA;
9653       FD->setInvalidDecl();
9654       return D;
9655     }
9656 
9657     // Visual C++ appears to not think this is an issue, so only issue
9658     // a warning when Microsoft extensions are disabled.
9659     if (!LangOpts.MicrosoftExt) {
9660       // If a symbol previously declared dllimport is later defined, the
9661       // attribute is ignored in subsequent references, and a warning is
9662       // emitted.
9663       Diag(FD->getLocation(),
9664            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
9665         << FD << DA;
9666     }
9667   }
9668   // We want to attach documentation to original Decl (which might be
9669   // a function template).
9670   ActOnDocumentableDecl(D);
9671   return D;
9672 }
9673 
9674 /// \brief Given the set of return statements within a function body,
9675 /// compute the variables that are subject to the named return value
9676 /// optimization.
9677 ///
9678 /// Each of the variables that is subject to the named return value
9679 /// optimization will be marked as NRVO variables in the AST, and any
9680 /// return statement that has a marked NRVO variable as its NRVO candidate can
9681 /// use the named return value optimization.
9682 ///
9683 /// This function applies a very simplistic algorithm for NRVO: if every return
9684 /// statement in the function has the same NRVO candidate, that candidate is
9685 /// the NRVO variable.
9686 ///
9687 /// FIXME: Employ a smarter algorithm that accounts for multiple return
9688 /// statements and the lifetimes of the NRVO candidates. We should be able to
9689 /// find a maximal set of NRVO variables.
9690 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
9691   ReturnStmt **Returns = Scope->Returns.data();
9692 
9693   const VarDecl *NRVOCandidate = 0;
9694   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
9695     if (!Returns[I]->getNRVOCandidate())
9696       return;
9697 
9698     if (!NRVOCandidate)
9699       NRVOCandidate = Returns[I]->getNRVOCandidate();
9700     else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9701       return;
9702   }
9703 
9704   if (NRVOCandidate)
9705     const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9706 }
9707 
9708 bool Sema::canSkipFunctionBody(Decl *D) {
9709   // We cannot skip the body of a function (or function template) which is
9710   // constexpr, since we may need to evaluate its body in order to parse the
9711   // rest of the file.
9712   // We cannot skip the body of a function with an undeduced return type,
9713   // because any callers of that function need to know the type.
9714   if (const FunctionDecl *FD = D->getAsFunction())
9715     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
9716       return false;
9717   return Consumer.shouldSkipFunctionBody(D);
9718 }
9719 
9720 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
9721   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
9722     FD->setHasSkippedBody();
9723   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
9724     MD->setHasSkippedBody();
9725   return ActOnFinishFunctionBody(Decl, 0);
9726 }
9727 
9728 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
9729   return ActOnFinishFunctionBody(D, BodyArg, false);
9730 }
9731 
9732 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9733                                     bool IsInstantiation) {
9734   FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
9735 
9736   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
9737   sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
9738 
9739   if (FD) {
9740     FD->setBody(Body);
9741 
9742     if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9743         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
9744       // If the function has a deduced result type but contains no 'return'
9745       // statements, the result type as written must be exactly 'auto', and
9746       // the deduced result type is 'void'.
9747       if (!FD->getReturnType()->getAs<AutoType>()) {
9748         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9749             << FD->getReturnType();
9750         FD->setInvalidDecl();
9751       } else {
9752         // Substitute 'void' for the 'auto' in the type.
9753         TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9754             IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
9755         Context.adjustDeducedFunctionResultType(
9756             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
9757       }
9758     }
9759 
9760     // The only way to be included in UndefinedButUsed is if there is an
9761     // ODR use before the definition. Avoid the expensive map lookup if this
9762     // is the first declaration.
9763     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
9764       if (!FD->isExternallyVisible())
9765         UndefinedButUsed.erase(FD);
9766       else if (FD->isInlined() &&
9767                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9768                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9769         UndefinedButUsed.erase(FD);
9770     }
9771 
9772     // If the function implicitly returns zero (like 'main') or is naked,
9773     // don't complain about missing return statements.
9774     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
9775       WP.disableCheckFallThrough();
9776 
9777     // MSVC permits the use of pure specifier (=0) on function definition,
9778     // defined at class scope, warn about this non-standard construct.
9779     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
9780       Diag(FD->getLocation(), diag::warn_pure_function_definition);
9781 
9782     if (!FD->isInvalidDecl()) {
9783       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
9784       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9785                                              FD->getReturnType(), FD);
9786 
9787       // If this is a constructor, we need a vtable.
9788       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9789         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
9790 
9791       // Try to apply the named return value optimization. We have to check
9792       // if we can do this here because lambdas keep return statements around
9793       // to deduce an implicit return type.
9794       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
9795           !FD->isDependentContext())
9796         computeNRVO(Body, getCurFunction());
9797     }
9798 
9799     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9800            "Function parsing confused");
9801   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
9802     assert(MD == getCurMethodDecl() && "Method parsing confused");
9803     MD->setBody(Body);
9804     if (!MD->isInvalidDecl()) {
9805       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
9806       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9807                                              MD->getReturnType(), MD);
9808 
9809       if (Body)
9810         computeNRVO(Body, getCurFunction());
9811     }
9812     if (getCurFunction()->ObjCShouldCallSuper) {
9813       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9814         << MD->getSelector().getAsString();
9815       getCurFunction()->ObjCShouldCallSuper = false;
9816     }
9817     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9818       const ObjCMethodDecl *InitMethod = 0;
9819       bool isDesignated =
9820           MD->isDesignatedInitializerForTheInterface(&InitMethod);
9821       assert(isDesignated && InitMethod);
9822       (void)isDesignated;
9823       Diag(MD->getLocation(),
9824            diag::warn_objc_designated_init_missing_super_call);
9825       Diag(InitMethod->getLocation(),
9826            diag::note_objc_designated_init_marked_here);
9827       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9828     }
9829     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9830       Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9831       getCurFunction()->ObjCWarnForNoInitDelegation = false;
9832     }
9833   } else {
9834     return 0;
9835   }
9836 
9837   assert(!getCurFunction()->ObjCShouldCallSuper &&
9838          "This should only be set for ObjC methods, which should have been "
9839          "handled in the block above.");
9840 
9841   // Verify and clean out per-function state.
9842   if (Body) {
9843     // C++ constructors that have function-try-blocks can't have return
9844     // statements in the handlers of that block. (C++ [except.handle]p14)
9845     // Verify this.
9846     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9847       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9848 
9849     // Verify that gotos and switch cases don't jump into scopes illegally.
9850     if (getCurFunction()->NeedsScopeChecking() &&
9851         !dcl->isInvalidDecl() &&
9852         !hasAnyUnrecoverableErrorsInThisFunction() &&
9853         !PP.isCodeCompletionEnabled())
9854       DiagnoseInvalidJumps(Body);
9855 
9856     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9857       if (!Destructor->getParent()->isDependentType())
9858         CheckDestructor(Destructor);
9859 
9860       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9861                                              Destructor->getParent());
9862     }
9863 
9864     // If any errors have occurred, clear out any temporaries that may have
9865     // been leftover. This ensures that these temporaries won't be picked up for
9866     // deletion in some later function.
9867     if (PP.getDiagnostics().hasErrorOccurred() ||
9868         PP.getDiagnostics().getSuppressAllDiagnostics()) {
9869       DiscardCleanupsInEvaluationContext();
9870     }
9871     if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9872         !isa<FunctionTemplateDecl>(dcl)) {
9873       // Since the body is valid, issue any analysis-based warnings that are
9874       // enabled.
9875       ActivePolicy = &WP;
9876     }
9877 
9878     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9879         (!CheckConstexprFunctionDecl(FD) ||
9880          !CheckConstexprFunctionBody(FD, Body)))
9881       FD->setInvalidDecl();
9882 
9883     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
9884     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
9885     assert(MaybeODRUseExprs.empty() &&
9886            "Leftover expressions for odr-use checking");
9887   }
9888 
9889   if (!IsInstantiation)
9890     PopDeclContext();
9891 
9892   PopFunctionScopeInfo(ActivePolicy, dcl);
9893   // If any errors have occurred, clear out any temporaries that may have
9894   // been leftover. This ensures that these temporaries won't be picked up for
9895   // deletion in some later function.
9896   if (getDiagnostics().hasErrorOccurred()) {
9897     DiscardCleanupsInEvaluationContext();
9898   }
9899 
9900   return dcl;
9901 }
9902 
9903 
9904 /// When we finish delayed parsing of an attribute, we must attach it to the
9905 /// relevant Decl.
9906 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9907                                        ParsedAttributes &Attrs) {
9908   // Always attach attributes to the underlying decl.
9909   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9910     D = TD->getTemplatedDecl();
9911   ProcessDeclAttributeList(S, D, Attrs.getList());
9912 
9913   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9914     if (Method->isStatic())
9915       checkThisInStaticMemberFunctionAttributes(Method);
9916 }
9917 
9918 
9919 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9920 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
9921 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
9922                                           IdentifierInfo &II, Scope *S) {
9923   // Before we produce a declaration for an implicitly defined
9924   // function, see whether there was a locally-scoped declaration of
9925   // this name as a function or variable. If so, use that
9926   // (non-visible) declaration, and complain about it.
9927   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9928     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9929     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9930     return ExternCPrev;
9931   }
9932 
9933   // Extension in C99.  Legal in C90, but warn about it.
9934   unsigned diag_id;
9935   if (II.getName().startswith("__builtin_"))
9936     diag_id = diag::warn_builtin_unknown;
9937   else if (getLangOpts().C99)
9938     diag_id = diag::ext_implicit_function_decl;
9939   else
9940     diag_id = diag::warn_implicit_function_decl;
9941   Diag(Loc, diag_id) << &II;
9942 
9943   // Because typo correction is expensive, only do it if the implicit
9944   // function declaration is going to be treated as an error.
9945   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9946     TypoCorrection Corrected;
9947     DeclFilterCCC<FunctionDecl> Validator;
9948     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
9949                                       LookupOrdinaryName, S, 0, Validator)))
9950       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9951                    /*ErrorRecovery*/false);
9952   }
9953 
9954   // Set a Declarator for the implicit definition: int foo();
9955   const char *Dummy;
9956   AttributeFactory attrFactory;
9957   DeclSpec DS(attrFactory);
9958   unsigned DiagID;
9959   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
9960                                   Context.getPrintingPolicy());
9961   (void)Error; // Silence warning.
9962   assert(!Error && "Error setting up implicit decl!");
9963   SourceLocation NoLoc;
9964   Declarator D(DS, Declarator::BlockContext);
9965   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9966                                              /*IsAmbiguous=*/false,
9967                                              /*RParenLoc=*/NoLoc,
9968                                              /*ArgInfo=*/0,
9969                                              /*NumArgs=*/0,
9970                                              /*EllipsisLoc=*/NoLoc,
9971                                              /*RParenLoc=*/NoLoc,
9972                                              /*TypeQuals=*/0,
9973                                              /*RefQualifierIsLvalueRef=*/true,
9974                                              /*RefQualifierLoc=*/NoLoc,
9975                                              /*ConstQualifierLoc=*/NoLoc,
9976                                              /*VolatileQualifierLoc=*/NoLoc,
9977                                              /*MutableLoc=*/NoLoc,
9978                                              EST_None,
9979                                              /*ESpecLoc=*/NoLoc,
9980                                              /*Exceptions=*/0,
9981                                              /*ExceptionRanges=*/0,
9982                                              /*NumExceptions=*/0,
9983                                              /*NoexceptExpr=*/0,
9984                                              Loc, Loc, D),
9985                 DS.getAttributes(),
9986                 SourceLocation());
9987   D.SetIdentifier(&II, Loc);
9988 
9989   // Insert this function into translation-unit scope.
9990 
9991   DeclContext *PrevDC = CurContext;
9992   CurContext = Context.getTranslationUnitDecl();
9993 
9994   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
9995   FD->setImplicit();
9996 
9997   CurContext = PrevDC;
9998 
9999   AddKnownFunctionAttributes(FD);
10000 
10001   return FD;
10002 }
10003 
10004 /// \brief Adds any function attributes that we know a priori based on
10005 /// the declaration of this function.
10006 ///
10007 /// These attributes can apply both to implicitly-declared builtins
10008 /// (like __builtin___printf_chk) or to library-declared functions
10009 /// like NSLog or printf.
10010 ///
10011 /// We need to check for duplicate attributes both here and where user-written
10012 /// attributes are applied to declarations.
10013 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10014   if (FD->isInvalidDecl())
10015     return;
10016 
10017   // If this is a built-in function, map its builtin attributes to
10018   // actual attributes.
10019   if (unsigned BuiltinID = FD->getBuiltinID()) {
10020     // Handle printf-formatting attributes.
10021     unsigned FormatIdx;
10022     bool HasVAListArg;
10023     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10024       if (!FD->hasAttr<FormatAttr>()) {
10025         const char *fmt = "printf";
10026         unsigned int NumParams = FD->getNumParams();
10027         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10028             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10029           fmt = "NSString";
10030         FD->addAttr(FormatAttr::CreateImplicit(Context,
10031                                                &Context.Idents.get(fmt),
10032                                                FormatIdx+1,
10033                                                HasVAListArg ? 0 : FormatIdx+2,
10034                                                FD->getLocation()));
10035       }
10036     }
10037     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10038                                              HasVAListArg)) {
10039      if (!FD->hasAttr<FormatAttr>())
10040        FD->addAttr(FormatAttr::CreateImplicit(Context,
10041                                               &Context.Idents.get("scanf"),
10042                                               FormatIdx+1,
10043                                               HasVAListArg ? 0 : FormatIdx+2,
10044                                               FD->getLocation()));
10045     }
10046 
10047     // Mark const if we don't care about errno and that is the only
10048     // thing preventing the function from being const. This allows
10049     // IRgen to use LLVM intrinsics for such functions.
10050     if (!getLangOpts().MathErrno &&
10051         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10052       if (!FD->hasAttr<ConstAttr>())
10053         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10054     }
10055 
10056     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10057         !FD->hasAttr<ReturnsTwiceAttr>())
10058       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10059                                          FD->getLocation()));
10060     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10061       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10062     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10063       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10064   }
10065 
10066   IdentifierInfo *Name = FD->getIdentifier();
10067   if (!Name)
10068     return;
10069   if ((!getLangOpts().CPlusPlus &&
10070        FD->getDeclContext()->isTranslationUnit()) ||
10071       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10072        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10073        LinkageSpecDecl::lang_c)) {
10074     // Okay: this could be a libc/libm/Objective-C function we know
10075     // about.
10076   } else
10077     return;
10078 
10079   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10080     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10081     // target-specific builtins, perhaps?
10082     if (!FD->hasAttr<FormatAttr>())
10083       FD->addAttr(FormatAttr::CreateImplicit(Context,
10084                                              &Context.Idents.get("printf"), 2,
10085                                              Name->isStr("vasprintf") ? 0 : 3,
10086                                              FD->getLocation()));
10087   }
10088 
10089   if (Name->isStr("__CFStringMakeConstantString")) {
10090     // We already have a __builtin___CFStringMakeConstantString,
10091     // but builds that use -fno-constant-cfstrings don't go through that.
10092     if (!FD->hasAttr<FormatArgAttr>())
10093       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10094                                                 FD->getLocation()));
10095   }
10096 }
10097 
10098 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10099                                     TypeSourceInfo *TInfo) {
10100   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10101   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10102 
10103   if (!TInfo) {
10104     assert(D.isInvalidType() && "no declarator info for valid type");
10105     TInfo = Context.getTrivialTypeSourceInfo(T);
10106   }
10107 
10108   // Scope manipulation handled by caller.
10109   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10110                                            D.getLocStart(),
10111                                            D.getIdentifierLoc(),
10112                                            D.getIdentifier(),
10113                                            TInfo);
10114 
10115   // Bail out immediately if we have an invalid declaration.
10116   if (D.isInvalidType()) {
10117     NewTD->setInvalidDecl();
10118     return NewTD;
10119   }
10120 
10121   if (D.getDeclSpec().isModulePrivateSpecified()) {
10122     if (CurContext->isFunctionOrMethod())
10123       Diag(NewTD->getLocation(), diag::err_module_private_local)
10124         << 2 << NewTD->getDeclName()
10125         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10126         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10127     else
10128       NewTD->setModulePrivate();
10129   }
10130 
10131   // C++ [dcl.typedef]p8:
10132   //   If the typedef declaration defines an unnamed class (or
10133   //   enum), the first typedef-name declared by the declaration
10134   //   to be that class type (or enum type) is used to denote the
10135   //   class type (or enum type) for linkage purposes only.
10136   // We need to check whether the type was declared in the declaration.
10137   switch (D.getDeclSpec().getTypeSpecType()) {
10138   case TST_enum:
10139   case TST_struct:
10140   case TST_interface:
10141   case TST_union:
10142   case TST_class: {
10143     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10144 
10145     // Do nothing if the tag is not anonymous or already has an
10146     // associated typedef (from an earlier typedef in this decl group).
10147     if (tagFromDeclSpec->getIdentifier()) break;
10148     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10149 
10150     // A well-formed anonymous tag must always be a TUK_Definition.
10151     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10152 
10153     // The type must match the tag exactly;  no qualifiers allowed.
10154     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10155       break;
10156 
10157     // If we've already computed linkage for the anonymous tag, then
10158     // adding a typedef name for the anonymous decl can change that
10159     // linkage, which might be a serious problem.  Diagnose this as
10160     // unsupported and ignore the typedef name.  TODO: we should
10161     // pursue this as a language defect and establish a formal rule
10162     // for how to handle it.
10163     if (tagFromDeclSpec->hasLinkageBeenComputed()) {
10164       Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
10165 
10166       SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
10167       tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(),
10168                                           getLangOpts());
10169 
10170       llvm::SmallString<40> textToInsert;
10171       textToInsert += ' ';
10172       textToInsert += D.getIdentifier()->getName();
10173       Diag(tagLoc, diag::note_typedef_changes_linkage)
10174         << FixItHint::CreateInsertion(tagLoc, textToInsert);
10175       break;
10176     }
10177 
10178     // Otherwise, set this is the anon-decl typedef for the tag.
10179     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10180     break;
10181   }
10182 
10183   default:
10184     break;
10185   }
10186 
10187   return NewTD;
10188 }
10189 
10190 
10191 /// \brief Check that this is a valid underlying type for an enum declaration.
10192 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10193   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10194   QualType T = TI->getType();
10195 
10196   if (T->isDependentType())
10197     return false;
10198 
10199   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10200     if (BT->isInteger())
10201       return false;
10202 
10203   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10204   return true;
10205 }
10206 
10207 /// Check whether this is a valid redeclaration of a previous enumeration.
10208 /// \return true if the redeclaration was invalid.
10209 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10210                                   QualType EnumUnderlyingTy,
10211                                   const EnumDecl *Prev) {
10212   bool IsFixed = !EnumUnderlyingTy.isNull();
10213 
10214   if (IsScoped != Prev->isScoped()) {
10215     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10216       << Prev->isScoped();
10217     Diag(Prev->getLocation(), diag::note_previous_declaration);
10218     return true;
10219   }
10220 
10221   if (IsFixed && Prev->isFixed()) {
10222     if (!EnumUnderlyingTy->isDependentType() &&
10223         !Prev->getIntegerType()->isDependentType() &&
10224         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10225                                         Prev->getIntegerType())) {
10226       // TODO: Highlight the underlying type of the redeclaration.
10227       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10228         << EnumUnderlyingTy << Prev->getIntegerType();
10229       Diag(Prev->getLocation(), diag::note_previous_declaration)
10230           << Prev->getIntegerTypeRange();
10231       return true;
10232     }
10233   } else if (IsFixed != Prev->isFixed()) {
10234     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10235       << Prev->isFixed();
10236     Diag(Prev->getLocation(), diag::note_previous_declaration);
10237     return true;
10238   }
10239 
10240   return false;
10241 }
10242 
10243 /// \brief Get diagnostic %select index for tag kind for
10244 /// redeclaration diagnostic message.
10245 /// WARNING: Indexes apply to particular diagnostics only!
10246 ///
10247 /// \returns diagnostic %select index.
10248 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10249   switch (Tag) {
10250   case TTK_Struct: return 0;
10251   case TTK_Interface: return 1;
10252   case TTK_Class:  return 2;
10253   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10254   }
10255 }
10256 
10257 /// \brief Determine if tag kind is a class-key compatible with
10258 /// class for redeclaration (class, struct, or __interface).
10259 ///
10260 /// \returns true iff the tag kind is compatible.
10261 static bool isClassCompatTagKind(TagTypeKind Tag)
10262 {
10263   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10264 }
10265 
10266 /// \brief Determine whether a tag with a given kind is acceptable
10267 /// as a redeclaration of the given tag declaration.
10268 ///
10269 /// \returns true if the new tag kind is acceptable, false otherwise.
10270 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10271                                         TagTypeKind NewTag, bool isDefinition,
10272                                         SourceLocation NewTagLoc,
10273                                         const IdentifierInfo &Name) {
10274   // C++ [dcl.type.elab]p3:
10275   //   The class-key or enum keyword present in the
10276   //   elaborated-type-specifier shall agree in kind with the
10277   //   declaration to which the name in the elaborated-type-specifier
10278   //   refers. This rule also applies to the form of
10279   //   elaborated-type-specifier that declares a class-name or
10280   //   friend class since it can be construed as referring to the
10281   //   definition of the class. Thus, in any
10282   //   elaborated-type-specifier, the enum keyword shall be used to
10283   //   refer to an enumeration (7.2), the union class-key shall be
10284   //   used to refer to a union (clause 9), and either the class or
10285   //   struct class-key shall be used to refer to a class (clause 9)
10286   //   declared using the class or struct class-key.
10287   TagTypeKind OldTag = Previous->getTagKind();
10288   if (!isDefinition || !isClassCompatTagKind(NewTag))
10289     if (OldTag == NewTag)
10290       return true;
10291 
10292   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10293     // Warn about the struct/class tag mismatch.
10294     bool isTemplate = false;
10295     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10296       isTemplate = Record->getDescribedClassTemplate();
10297 
10298     if (!ActiveTemplateInstantiations.empty()) {
10299       // In a template instantiation, do not offer fix-its for tag mismatches
10300       // since they usually mess up the template instead of fixing the problem.
10301       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10302         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10303         << getRedeclDiagFromTagKind(OldTag);
10304       return true;
10305     }
10306 
10307     if (isDefinition) {
10308       // On definitions, check previous tags and issue a fix-it for each
10309       // one that doesn't match the current tag.
10310       if (Previous->getDefinition()) {
10311         // Don't suggest fix-its for redefinitions.
10312         return true;
10313       }
10314 
10315       bool previousMismatch = false;
10316       for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10317            E(Previous->redecls_end()); I != E; ++I) {
10318         if (I->getTagKind() != NewTag) {
10319           if (!previousMismatch) {
10320             previousMismatch = true;
10321             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10322               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10323               << getRedeclDiagFromTagKind(I->getTagKind());
10324           }
10325           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10326             << getRedeclDiagFromTagKind(NewTag)
10327             << FixItHint::CreateReplacement(I->getInnerLocStart(),
10328                  TypeWithKeyword::getTagTypeKindName(NewTag));
10329         }
10330       }
10331       return true;
10332     }
10333 
10334     // Check for a previous definition.  If current tag and definition
10335     // are same type, do nothing.  If no definition, but disagree with
10336     // with previous tag type, give a warning, but no fix-it.
10337     const TagDecl *Redecl = Previous->getDefinition() ?
10338                             Previous->getDefinition() : Previous;
10339     if (Redecl->getTagKind() == NewTag) {
10340       return true;
10341     }
10342 
10343     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10344       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10345       << getRedeclDiagFromTagKind(OldTag);
10346     Diag(Redecl->getLocation(), diag::note_previous_use);
10347 
10348     // If there is a previous definition, suggest a fix-it.
10349     if (Previous->getDefinition()) {
10350         Diag(NewTagLoc, diag::note_struct_class_suggestion)
10351           << getRedeclDiagFromTagKind(Redecl->getTagKind())
10352           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10353                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10354     }
10355 
10356     return true;
10357   }
10358   return false;
10359 }
10360 
10361 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10362 /// former case, Name will be non-null.  In the later case, Name will be null.
10363 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10364 /// reference/declaration/definition of a tag.
10365 ///
10366 /// IsTypeSpecifier is true if this is a type-specifier (or
10367 /// trailing-type-specifier) other than one in an alias-declaration.
10368 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10369                      SourceLocation KWLoc, CXXScopeSpec &SS,
10370                      IdentifierInfo *Name, SourceLocation NameLoc,
10371                      AttributeList *Attr, AccessSpecifier AS,
10372                      SourceLocation ModulePrivateLoc,
10373                      MultiTemplateParamsArg TemplateParameterLists,
10374                      bool &OwnedDecl, bool &IsDependent,
10375                      SourceLocation ScopedEnumKWLoc,
10376                      bool ScopedEnumUsesClassTag,
10377                      TypeResult UnderlyingType,
10378                      bool IsTypeSpecifier) {
10379   // If this is not a definition, it must have a name.
10380   IdentifierInfo *OrigName = Name;
10381   assert((Name != 0 || TUK == TUK_Definition) &&
10382          "Nameless record must be a definition!");
10383   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10384 
10385   OwnedDecl = false;
10386   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10387   bool ScopedEnum = ScopedEnumKWLoc.isValid();
10388 
10389   // FIXME: Check explicit specializations more carefully.
10390   bool isExplicitSpecialization = false;
10391   bool Invalid = false;
10392 
10393   // We only need to do this matching if we have template parameters
10394   // or a scope specifier, which also conveniently avoids this work
10395   // for non-C++ cases.
10396   if (TemplateParameterLists.size() > 0 ||
10397       (SS.isNotEmpty() && TUK != TUK_Reference)) {
10398     if (TemplateParameterList *TemplateParams =
10399             MatchTemplateParametersToScopeSpecifier(
10400                 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10401                 isExplicitSpecialization, Invalid)) {
10402       if (Kind == TTK_Enum) {
10403         Diag(KWLoc, diag::err_enum_template);
10404         return 0;
10405       }
10406 
10407       if (TemplateParams->size() > 0) {
10408         // This is a declaration or definition of a class template (which may
10409         // be a member of another template).
10410 
10411         if (Invalid)
10412           return 0;
10413 
10414         OwnedDecl = false;
10415         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
10416                                                SS, Name, NameLoc, Attr,
10417                                                TemplateParams, AS,
10418                                                ModulePrivateLoc,
10419                                                TemplateParameterLists.size()-1,
10420                                                TemplateParameterLists.data());
10421         return Result.get();
10422       } else {
10423         // The "template<>" header is extraneous.
10424         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10425           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10426         isExplicitSpecialization = true;
10427       }
10428     }
10429   }
10430 
10431   // Figure out the underlying type if this a enum declaration. We need to do
10432   // this early, because it's needed to detect if this is an incompatible
10433   // redeclaration.
10434   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10435 
10436   if (Kind == TTK_Enum) {
10437     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10438       // No underlying type explicitly specified, or we failed to parse the
10439       // type, default to int.
10440       EnumUnderlying = Context.IntTy.getTypePtr();
10441     else if (UnderlyingType.get()) {
10442       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10443       // integral type; any cv-qualification is ignored.
10444       TypeSourceInfo *TI = 0;
10445       GetTypeFromParser(UnderlyingType.get(), &TI);
10446       EnumUnderlying = TI;
10447 
10448       if (CheckEnumUnderlyingType(TI))
10449         // Recover by falling back to int.
10450         EnumUnderlying = Context.IntTy.getTypePtr();
10451 
10452       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
10453                                           UPPC_FixedUnderlyingType))
10454         EnumUnderlying = Context.IntTy.getTypePtr();
10455 
10456     } else if (getLangOpts().MSVCCompat)
10457       // Microsoft enums are always of int type.
10458       EnumUnderlying = Context.IntTy.getTypePtr();
10459   }
10460 
10461   DeclContext *SearchDC = CurContext;
10462   DeclContext *DC = CurContext;
10463   bool isStdBadAlloc = false;
10464 
10465   RedeclarationKind Redecl = ForRedeclaration;
10466   if (TUK == TUK_Friend || TUK == TUK_Reference)
10467     Redecl = NotForRedeclaration;
10468 
10469   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
10470   bool FriendSawTagOutsideEnclosingNamespace = false;
10471   if (Name && SS.isNotEmpty()) {
10472     // We have a nested-name tag ('struct foo::bar').
10473 
10474     // Check for invalid 'foo::'.
10475     if (SS.isInvalid()) {
10476       Name = 0;
10477       goto CreateNewDecl;
10478     }
10479 
10480     // If this is a friend or a reference to a class in a dependent
10481     // context, don't try to make a decl for it.
10482     if (TUK == TUK_Friend || TUK == TUK_Reference) {
10483       DC = computeDeclContext(SS, false);
10484       if (!DC) {
10485         IsDependent = true;
10486         return 0;
10487       }
10488     } else {
10489       DC = computeDeclContext(SS, true);
10490       if (!DC) {
10491         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10492           << SS.getRange();
10493         return 0;
10494       }
10495     }
10496 
10497     if (RequireCompleteDeclContext(SS, DC))
10498       return 0;
10499 
10500     SearchDC = DC;
10501     // Look-up name inside 'foo::'.
10502     LookupQualifiedName(Previous, DC);
10503 
10504     if (Previous.isAmbiguous())
10505       return 0;
10506 
10507     if (Previous.empty()) {
10508       // Name lookup did not find anything. However, if the
10509       // nested-name-specifier refers to the current instantiation,
10510       // and that current instantiation has any dependent base
10511       // classes, we might find something at instantiation time: treat
10512       // this as a dependent elaborated-type-specifier.
10513       // But this only makes any sense for reference-like lookups.
10514       if (Previous.wasNotFoundInCurrentInstantiation() &&
10515           (TUK == TUK_Reference || TUK == TUK_Friend)) {
10516         IsDependent = true;
10517         return 0;
10518       }
10519 
10520       // A tag 'foo::bar' must already exist.
10521       Diag(NameLoc, diag::err_not_tag_in_scope)
10522         << Kind << Name << DC << SS.getRange();
10523       Name = 0;
10524       Invalid = true;
10525       goto CreateNewDecl;
10526     }
10527   } else if (Name) {
10528     // If this is a named struct, check to see if there was a previous forward
10529     // declaration or definition.
10530     // FIXME: We're looking into outer scopes here, even when we
10531     // shouldn't be. Doing so can result in ambiguities that we
10532     // shouldn't be diagnosing.
10533     LookupName(Previous, S);
10534 
10535     // When declaring or defining a tag, ignore ambiguities introduced
10536     // by types using'ed into this scope.
10537     if (Previous.isAmbiguous() &&
10538         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
10539       LookupResult::Filter F = Previous.makeFilter();
10540       while (F.hasNext()) {
10541         NamedDecl *ND = F.next();
10542         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10543           F.erase();
10544       }
10545       F.done();
10546     }
10547 
10548     // C++11 [namespace.memdef]p3:
10549     //   If the name in a friend declaration is neither qualified nor
10550     //   a template-id and the declaration is a function or an
10551     //   elaborated-type-specifier, the lookup to determine whether
10552     //   the entity has been previously declared shall not consider
10553     //   any scopes outside the innermost enclosing namespace.
10554     //
10555     // Does it matter that this should be by scope instead of by
10556     // semantic context?
10557     if (!Previous.empty() && TUK == TUK_Friend) {
10558       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10559       LookupResult::Filter F = Previous.makeFilter();
10560       while (F.hasNext()) {
10561         NamedDecl *ND = F.next();
10562         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10563         if (DC->isFileContext() &&
10564             !EnclosingNS->Encloses(ND->getDeclContext())) {
10565           F.erase();
10566           FriendSawTagOutsideEnclosingNamespace = true;
10567         }
10568       }
10569       F.done();
10570     }
10571 
10572     // Note:  there used to be some attempt at recovery here.
10573     if (Previous.isAmbiguous())
10574       return 0;
10575 
10576     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
10577       // FIXME: This makes sure that we ignore the contexts associated
10578       // with C structs, unions, and enums when looking for a matching
10579       // tag declaration or definition. See the similar lookup tweak
10580       // in Sema::LookupName; is there a better way to deal with this?
10581       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10582         SearchDC = SearchDC->getParent();
10583     }
10584   } else if (S->isFunctionPrototypeScope()) {
10585     // If this is an enum declaration in function prototype scope, set its
10586     // initial context to the translation unit.
10587     // FIXME: [citation needed]
10588     SearchDC = Context.getTranslationUnitDecl();
10589   }
10590 
10591   if (Previous.isSingleResult() &&
10592       Previous.getFoundDecl()->isTemplateParameter()) {
10593     // Maybe we will complain about the shadowed template parameter.
10594     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
10595     // Just pretend that we didn't see the previous declaration.
10596     Previous.clear();
10597   }
10598 
10599   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
10600       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
10601     // This is a declaration of or a reference to "std::bad_alloc".
10602     isStdBadAlloc = true;
10603 
10604     if (Previous.empty() && StdBadAlloc) {
10605       // std::bad_alloc has been implicitly declared (but made invisible to
10606       // name lookup). Fill in this implicit declaration as the previous
10607       // declaration, so that the declarations get chained appropriately.
10608       Previous.addDecl(getStdBadAlloc());
10609     }
10610   }
10611 
10612   // If we didn't find a previous declaration, and this is a reference
10613   // (or friend reference), move to the correct scope.  In C++, we
10614   // also need to do a redeclaration lookup there, just in case
10615   // there's a shadow friend decl.
10616   if (Name && Previous.empty() &&
10617       (TUK == TUK_Reference || TUK == TUK_Friend)) {
10618     if (Invalid) goto CreateNewDecl;
10619     assert(SS.isEmpty());
10620 
10621     if (TUK == TUK_Reference) {
10622       // C++ [basic.scope.pdecl]p5:
10623       //   -- for an elaborated-type-specifier of the form
10624       //
10625       //          class-key identifier
10626       //
10627       //      if the elaborated-type-specifier is used in the
10628       //      decl-specifier-seq or parameter-declaration-clause of a
10629       //      function defined in namespace scope, the identifier is
10630       //      declared as a class-name in the namespace that contains
10631       //      the declaration; otherwise, except as a friend
10632       //      declaration, the identifier is declared in the smallest
10633       //      non-class, non-function-prototype scope that contains the
10634       //      declaration.
10635       //
10636       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10637       // C structs and unions.
10638       //
10639       // It is an error in C++ to declare (rather than define) an enum
10640       // type, including via an elaborated type specifier.  We'll
10641       // diagnose that later; for now, declare the enum in the same
10642       // scope as we would have picked for any other tag type.
10643       //
10644       // GNU C also supports this behavior as part of its incomplete
10645       // enum types extension, while GNU C++ does not.
10646       //
10647       // Find the context where we'll be declaring the tag.
10648       // FIXME: We would like to maintain the current DeclContext as the
10649       // lexical context,
10650       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
10651         SearchDC = SearchDC->getParent();
10652 
10653       // Find the scope where we'll be declaring the tag.
10654       while (S->isClassScope() ||
10655              (getLangOpts().CPlusPlus &&
10656               S->isFunctionPrototypeScope()) ||
10657              ((S->getFlags() & Scope::DeclScope) == 0) ||
10658              (S->getEntity() && S->getEntity()->isTransparentContext()))
10659         S = S->getParent();
10660     } else {
10661       assert(TUK == TUK_Friend);
10662       // C++ [namespace.memdef]p3:
10663       //   If a friend declaration in a non-local class first declares a
10664       //   class or function, the friend class or function is a member of
10665       //   the innermost enclosing namespace.
10666       SearchDC = SearchDC->getEnclosingNamespaceContext();
10667     }
10668 
10669     // In C++, we need to do a redeclaration lookup to properly
10670     // diagnose some problems.
10671     if (getLangOpts().CPlusPlus) {
10672       Previous.setRedeclarationKind(ForRedeclaration);
10673       LookupQualifiedName(Previous, SearchDC);
10674     }
10675   }
10676 
10677   if (!Previous.empty()) {
10678     NamedDecl *PrevDecl = Previous.getFoundDecl();
10679     NamedDecl *DirectPrevDecl =
10680         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
10681 
10682     // It's okay to have a tag decl in the same scope as a typedef
10683     // which hides a tag decl in the same scope.  Finding this
10684     // insanity with a redeclaration lookup can only actually happen
10685     // in C++.
10686     //
10687     // This is also okay for elaborated-type-specifiers, which is
10688     // technically forbidden by the current standard but which is
10689     // okay according to the likely resolution of an open issue;
10690     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
10691     if (getLangOpts().CPlusPlus) {
10692       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10693         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10694           TagDecl *Tag = TT->getDecl();
10695           if (Tag->getDeclName() == Name &&
10696               Tag->getDeclContext()->getRedeclContext()
10697                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
10698             PrevDecl = Tag;
10699             Previous.clear();
10700             Previous.addDecl(Tag);
10701             Previous.resolveKind();
10702           }
10703         }
10704       }
10705     }
10706 
10707     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
10708       // If this is a use of a previous tag, or if the tag is already declared
10709       // in the same scope (so that the definition/declaration completes or
10710       // rementions the tag), reuse the decl.
10711       if (TUK == TUK_Reference || TUK == TUK_Friend ||
10712           isDeclInScope(DirectPrevDecl, SearchDC, S,
10713                         SS.isNotEmpty() || isExplicitSpecialization)) {
10714         // Make sure that this wasn't declared as an enum and now used as a
10715         // struct or something similar.
10716         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10717                                           TUK == TUK_Definition, KWLoc,
10718                                           *Name)) {
10719           bool SafeToContinue
10720             = (PrevTagDecl->getTagKind() != TTK_Enum &&
10721                Kind != TTK_Enum);
10722           if (SafeToContinue)
10723             Diag(KWLoc, diag::err_use_with_wrong_tag)
10724               << Name
10725               << FixItHint::CreateReplacement(SourceRange(KWLoc),
10726                                               PrevTagDecl->getKindName());
10727           else
10728             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
10729           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
10730 
10731           if (SafeToContinue)
10732             Kind = PrevTagDecl->getTagKind();
10733           else {
10734             // Recover by making this an anonymous redefinition.
10735             Name = 0;
10736             Previous.clear();
10737             Invalid = true;
10738           }
10739         }
10740 
10741         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10742           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10743 
10744           // If this is an elaborated-type-specifier for a scoped enumeration,
10745           // the 'class' keyword is not necessary and not permitted.
10746           if (TUK == TUK_Reference || TUK == TUK_Friend) {
10747             if (ScopedEnum)
10748               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10749                 << PrevEnum->isScoped()
10750                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10751             return PrevTagDecl;
10752           }
10753 
10754           QualType EnumUnderlyingTy;
10755           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10756             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
10757           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10758             EnumUnderlyingTy = QualType(T, 0);
10759 
10760           // All conflicts with previous declarations are recovered by
10761           // returning the previous declaration, unless this is a definition,
10762           // in which case we want the caller to bail out.
10763           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10764                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
10765             return TUK == TUK_Declaration ? PrevTagDecl : 0;
10766         }
10767 
10768         // C++11 [class.mem]p1:
10769         //   A member shall not be declared twice in the member-specification,
10770         //   except that a nested class or member class template can be declared
10771         //   and then later defined.
10772         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10773             S->isDeclScope(PrevDecl)) {
10774           Diag(NameLoc, diag::ext_member_redeclared);
10775           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10776         }
10777 
10778         if (!Invalid) {
10779           // If this is a use, just return the declaration we found.
10780 
10781           // FIXME: In the future, return a variant or some other clue
10782           // for the consumer of this Decl to know it doesn't own it.
10783           // For our current ASTs this shouldn't be a problem, but will
10784           // need to be changed with DeclGroups.
10785           if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
10786                getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
10787             return PrevTagDecl;
10788 
10789           // Diagnose attempts to redefine a tag.
10790           if (TUK == TUK_Definition) {
10791             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
10792               // If we're defining a specialization and the previous definition
10793               // is from an implicit instantiation, don't emit an error
10794               // here; we'll catch this in the general case below.
10795               bool IsExplicitSpecializationAfterInstantiation = false;
10796               if (isExplicitSpecialization) {
10797                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10798                   IsExplicitSpecializationAfterInstantiation =
10799                     RD->getTemplateSpecializationKind() !=
10800                     TSK_ExplicitSpecialization;
10801                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10802                   IsExplicitSpecializationAfterInstantiation =
10803                     ED->getTemplateSpecializationKind() !=
10804                     TSK_ExplicitSpecialization;
10805               }
10806 
10807               if (!IsExplicitSpecializationAfterInstantiation) {
10808                 // A redeclaration in function prototype scope in C isn't
10809                 // visible elsewhere, so merely issue a warning.
10810                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
10811                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10812                 else
10813                   Diag(NameLoc, diag::err_redefinition) << Name;
10814                 Diag(Def->getLocation(), diag::note_previous_definition);
10815                 // If this is a redefinition, recover by making this
10816                 // struct be anonymous, which will make any later
10817                 // references get the previous definition.
10818                 Name = 0;
10819                 Previous.clear();
10820                 Invalid = true;
10821               }
10822             } else {
10823               // If the type is currently being defined, complain
10824               // about a nested redefinition.
10825               const TagType *Tag
10826                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
10827               if (Tag->isBeingDefined()) {
10828                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
10829                 Diag(PrevTagDecl->getLocation(),
10830                      diag::note_previous_definition);
10831                 Name = 0;
10832                 Previous.clear();
10833                 Invalid = true;
10834               }
10835             }
10836 
10837             // Okay, this is definition of a previously declared or referenced
10838             // tag PrevDecl. We're going to create a new Decl for it.
10839           }
10840         }
10841         // If we get here we have (another) forward declaration or we
10842         // have a definition.  Just create a new decl.
10843 
10844       } else {
10845         // If we get here, this is a definition of a new tag type in a nested
10846         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
10847         // new decl/type.  We set PrevDecl to NULL so that the entities
10848         // have distinct types.
10849         Previous.clear();
10850       }
10851       // If we get here, we're going to create a new Decl. If PrevDecl
10852       // is non-NULL, it's a definition of the tag declared by
10853       // PrevDecl. If it's NULL, we have a new definition.
10854 
10855 
10856     // Otherwise, PrevDecl is not a tag, but was found with tag
10857     // lookup.  This is only actually possible in C++, where a few
10858     // things like templates still live in the tag namespace.
10859     } else {
10860       // Use a better diagnostic if an elaborated-type-specifier
10861       // found the wrong kind of type on the first
10862       // (non-redeclaration) lookup.
10863       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10864           !Previous.isForRedeclaration()) {
10865         unsigned Kind = 0;
10866         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10867         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10868         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10869         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10870         Diag(PrevDecl->getLocation(), diag::note_declared_at);
10871         Invalid = true;
10872 
10873       // Otherwise, only diagnose if the declaration is in scope.
10874       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10875                                 SS.isNotEmpty() || isExplicitSpecialization)) {
10876         // do nothing
10877 
10878       // Diagnose implicit declarations introduced by elaborated types.
10879       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10880         unsigned Kind = 0;
10881         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10882         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10883         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10884         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10885         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10886         Invalid = true;
10887 
10888       // Otherwise it's a declaration.  Call out a particularly common
10889       // case here.
10890       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10891         unsigned Kind = 0;
10892         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
10893         Diag(NameLoc, diag::err_tag_definition_of_typedef)
10894           << Name << Kind << TND->getUnderlyingType();
10895         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10896         Invalid = true;
10897 
10898       // Otherwise, diagnose.
10899       } else {
10900         // The tag name clashes with something else in the target scope,
10901         // issue an error and recover by making this tag be anonymous.
10902         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
10903         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10904         Name = 0;
10905         Invalid = true;
10906       }
10907 
10908       // The existing declaration isn't relevant to us; we're in a
10909       // new scope, so clear out the previous declaration.
10910       Previous.clear();
10911     }
10912   }
10913 
10914 CreateNewDecl:
10915 
10916   TagDecl *PrevDecl = 0;
10917   if (Previous.isSingleResult())
10918     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10919 
10920   // If there is an identifier, use the location of the identifier as the
10921   // location of the decl, otherwise use the location of the struct/union
10922   // keyword.
10923   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
10924 
10925   // Otherwise, create a new declaration. If there is a previous
10926   // declaration of the same entity, the two will be linked via
10927   // PrevDecl.
10928   TagDecl *New;
10929 
10930   bool IsForwardReference = false;
10931   if (Kind == TTK_Enum) {
10932     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10933     // enum X { A, B, C } D;    D should chain to X.
10934     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
10935                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
10936                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
10937     // If this is an undefined enum, warn.
10938     if (TUK != TUK_Definition && !Invalid) {
10939       TagDecl *Def;
10940       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10941           cast<EnumDecl>(New)->isFixed()) {
10942         // C++0x: 7.2p2: opaque-enum-declaration.
10943         // Conflicts are diagnosed above. Do nothing.
10944       }
10945       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
10946         Diag(Loc, diag::ext_forward_ref_enum_def)
10947           << New;
10948         Diag(Def->getLocation(), diag::note_previous_definition);
10949       } else {
10950         unsigned DiagID = diag::ext_forward_ref_enum;
10951         if (getLangOpts().MSVCCompat)
10952           DiagID = diag::ext_ms_forward_ref_enum;
10953         else if (getLangOpts().CPlusPlus)
10954           DiagID = diag::err_forward_ref_enum;
10955         Diag(Loc, DiagID);
10956 
10957         // If this is a forward-declared reference to an enumeration, make a
10958         // note of it; we won't actually be introducing the declaration into
10959         // the declaration context.
10960         if (TUK == TUK_Reference)
10961           IsForwardReference = true;
10962       }
10963     }
10964 
10965     if (EnumUnderlying) {
10966       EnumDecl *ED = cast<EnumDecl>(New);
10967       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10968         ED->setIntegerTypeSourceInfo(TI);
10969       else
10970         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10971       ED->setPromotionType(ED->getIntegerType());
10972     }
10973 
10974   } else {
10975     // struct/union/class
10976 
10977     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10978     // struct X { int A; } D;    D should chain to X.
10979     if (getLangOpts().CPlusPlus) {
10980       // FIXME: Look for a way to use RecordDecl for simple structs.
10981       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10982                                   cast_or_null<CXXRecordDecl>(PrevDecl));
10983 
10984       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
10985         StdBadAlloc = cast<CXXRecordDecl>(New);
10986     } else
10987       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10988                                cast_or_null<RecordDecl>(PrevDecl));
10989   }
10990 
10991   // C++11 [dcl.type]p3:
10992   //   A type-specifier-seq shall not define a class or enumeration [...].
10993   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
10994     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
10995       << Context.getTagDeclType(New);
10996     Invalid = true;
10997   }
10998 
10999   // Maybe add qualifier info.
11000   if (SS.isNotEmpty()) {
11001     if (SS.isSet()) {
11002       // If this is either a declaration or a definition, check the
11003       // nested-name-specifier against the current context. We don't do this
11004       // for explicit specializations, because they have similar checking
11005       // (with more specific diagnostics) in the call to
11006       // CheckMemberSpecialization, below.
11007       if (!isExplicitSpecialization &&
11008           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11009           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11010         Invalid = true;
11011 
11012       New->setQualifierInfo(SS.getWithLocInContext(Context));
11013       if (TemplateParameterLists.size() > 0) {
11014         New->setTemplateParameterListsInfo(Context,
11015                                            TemplateParameterLists.size(),
11016                                            TemplateParameterLists.data());
11017       }
11018     }
11019     else
11020       Invalid = true;
11021   }
11022 
11023   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11024     // Add alignment attributes if necessary; these attributes are checked when
11025     // the ASTContext lays out the structure.
11026     //
11027     // It is important for implementing the correct semantics that this
11028     // happen here (in act on tag decl). The #pragma pack stack is
11029     // maintained as a result of parser callbacks which can occur at
11030     // many points during the parsing of a struct declaration (because
11031     // the #pragma tokens are effectively skipped over during the
11032     // parsing of the struct).
11033     if (TUK == TUK_Definition) {
11034       AddAlignmentAttributesForRecord(RD);
11035       AddMsStructLayoutForRecord(RD);
11036     }
11037   }
11038 
11039   if (ModulePrivateLoc.isValid()) {
11040     if (isExplicitSpecialization)
11041       Diag(New->getLocation(), diag::err_module_private_specialization)
11042         << 2
11043         << FixItHint::CreateRemoval(ModulePrivateLoc);
11044     // __module_private__ does not apply to local classes. However, we only
11045     // diagnose this as an error when the declaration specifiers are
11046     // freestanding. Here, we just ignore the __module_private__.
11047     else if (!SearchDC->isFunctionOrMethod())
11048       New->setModulePrivate();
11049   }
11050 
11051   // If this is a specialization of a member class (of a class template),
11052   // check the specialization.
11053   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11054     Invalid = true;
11055 
11056   if (Invalid)
11057     New->setInvalidDecl();
11058 
11059   if (Attr)
11060     ProcessDeclAttributeList(S, New, Attr);
11061 
11062   // If we're declaring or defining a tag in function prototype scope in C,
11063   // note that this type can only be used within the function and add it to
11064   // the list of decls to inject into the function definition scope.
11065   if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
11066       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
11067     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11068     DeclsInPrototypeScope.push_back(New);
11069   }
11070 
11071   // Set the lexical context. If the tag has a C++ scope specifier, the
11072   // lexical context will be different from the semantic context.
11073   New->setLexicalDeclContext(CurContext);
11074 
11075   // Mark this as a friend decl if applicable.
11076   // In Microsoft mode, a friend declaration also acts as a forward
11077   // declaration so we always pass true to setObjectOfFriendDecl to make
11078   // the tag name visible.
11079   if (TUK == TUK_Friend)
11080     New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11081                                getLangOpts().MicrosoftExt);
11082 
11083   // Set the access specifier.
11084   if (!Invalid && SearchDC->isRecord())
11085     SetMemberAccessSpecifier(New, PrevDecl, AS);
11086 
11087   if (TUK == TUK_Definition)
11088     New->startDefinition();
11089 
11090   // If this has an identifier, add it to the scope stack.
11091   if (TUK == TUK_Friend) {
11092     // We might be replacing an existing declaration in the lookup tables;
11093     // if so, borrow its access specifier.
11094     if (PrevDecl)
11095       New->setAccess(PrevDecl->getAccess());
11096 
11097     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11098     DC->makeDeclVisibleInContext(New);
11099     if (Name) // can be null along some error paths
11100       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11101         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11102   } else if (Name) {
11103     S = getNonFieldDeclScope(S);
11104     PushOnScopeChains(New, S, !IsForwardReference);
11105     if (IsForwardReference)
11106       SearchDC->makeDeclVisibleInContext(New);
11107 
11108   } else {
11109     CurContext->addDecl(New);
11110   }
11111 
11112   // If this is the C FILE type, notify the AST context.
11113   if (IdentifierInfo *II = New->getIdentifier())
11114     if (!New->isInvalidDecl() &&
11115         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11116         II->isStr("FILE"))
11117       Context.setFILEDecl(New);
11118 
11119   if (PrevDecl)
11120     mergeDeclAttributes(New, PrevDecl);
11121 
11122   // If there's a #pragma GCC visibility in scope, set the visibility of this
11123   // record.
11124   AddPushedVisibilityAttribute(New);
11125 
11126   OwnedDecl = true;
11127   // In C++, don't return an invalid declaration. We can't recover well from
11128   // the cases where we make the type anonymous.
11129   return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
11130 }
11131 
11132 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11133   AdjustDeclIfTemplate(TagD);
11134   TagDecl *Tag = cast<TagDecl>(TagD);
11135 
11136   // Enter the tag context.
11137   PushDeclContext(S, Tag);
11138 
11139   ActOnDocumentableDecl(TagD);
11140 
11141   // If there's a #pragma GCC visibility in scope, set the visibility of this
11142   // record.
11143   AddPushedVisibilityAttribute(Tag);
11144 }
11145 
11146 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11147   assert(isa<ObjCContainerDecl>(IDecl) &&
11148          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11149   DeclContext *OCD = cast<DeclContext>(IDecl);
11150   assert(getContainingDC(OCD) == CurContext &&
11151       "The next DeclContext should be lexically contained in the current one.");
11152   CurContext = OCD;
11153   return IDecl;
11154 }
11155 
11156 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11157                                            SourceLocation FinalLoc,
11158                                            bool IsFinalSpelledSealed,
11159                                            SourceLocation LBraceLoc) {
11160   AdjustDeclIfTemplate(TagD);
11161   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11162 
11163   FieldCollector->StartClass();
11164 
11165   if (!Record->getIdentifier())
11166     return;
11167 
11168   if (FinalLoc.isValid())
11169     Record->addAttr(new (Context)
11170                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11171 
11172   // C++ [class]p2:
11173   //   [...] The class-name is also inserted into the scope of the
11174   //   class itself; this is known as the injected-class-name. For
11175   //   purposes of access checking, the injected-class-name is treated
11176   //   as if it were a public member name.
11177   CXXRecordDecl *InjectedClassName
11178     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11179                             Record->getLocStart(), Record->getLocation(),
11180                             Record->getIdentifier(),
11181                             /*PrevDecl=*/0,
11182                             /*DelayTypeCreation=*/true);
11183   Context.getTypeDeclType(InjectedClassName, Record);
11184   InjectedClassName->setImplicit();
11185   InjectedClassName->setAccess(AS_public);
11186   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11187       InjectedClassName->setDescribedClassTemplate(Template);
11188   PushOnScopeChains(InjectedClassName, S);
11189   assert(InjectedClassName->isInjectedClassName() &&
11190          "Broken injected-class-name");
11191 }
11192 
11193 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11194                                     SourceLocation RBraceLoc) {
11195   AdjustDeclIfTemplate(TagD);
11196   TagDecl *Tag = cast<TagDecl>(TagD);
11197   Tag->setRBraceLoc(RBraceLoc);
11198 
11199   // Make sure we "complete" the definition even it is invalid.
11200   if (Tag->isBeingDefined()) {
11201     assert(Tag->isInvalidDecl() && "We should already have completed it");
11202     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11203       RD->completeDefinition();
11204   }
11205 
11206   if (isa<CXXRecordDecl>(Tag))
11207     FieldCollector->FinishClass();
11208 
11209   // Exit this scope of this tag's definition.
11210   PopDeclContext();
11211 
11212   if (getCurLexicalContext()->isObjCContainer() &&
11213       Tag->getDeclContext()->isFileContext())
11214     Tag->setTopLevelDeclInObjCContainer();
11215 
11216   // Notify the consumer that we've defined a tag.
11217   if (!Tag->isInvalidDecl())
11218     Consumer.HandleTagDeclDefinition(Tag);
11219 }
11220 
11221 void Sema::ActOnObjCContainerFinishDefinition() {
11222   // Exit this scope of this interface definition.
11223   PopDeclContext();
11224 }
11225 
11226 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
11227   assert(DC == CurContext && "Mismatch of container contexts");
11228   OriginalLexicalContext = DC;
11229   ActOnObjCContainerFinishDefinition();
11230 }
11231 
11232 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11233   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
11234   OriginalLexicalContext = 0;
11235 }
11236 
11237 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11238   AdjustDeclIfTemplate(TagD);
11239   TagDecl *Tag = cast<TagDecl>(TagD);
11240   Tag->setInvalidDecl();
11241 
11242   // Make sure we "complete" the definition even it is invalid.
11243   if (Tag->isBeingDefined()) {
11244     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11245       RD->completeDefinition();
11246   }
11247 
11248   // We're undoing ActOnTagStartDefinition here, not
11249   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11250   // the FieldCollector.
11251 
11252   PopDeclContext();
11253 }
11254 
11255 // Note that FieldName may be null for anonymous bitfields.
11256 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11257                                 IdentifierInfo *FieldName,
11258                                 QualType FieldTy, bool IsMsStruct,
11259                                 Expr *BitWidth, bool *ZeroWidth) {
11260   // Default to true; that shouldn't confuse checks for emptiness
11261   if (ZeroWidth)
11262     *ZeroWidth = true;
11263 
11264   // C99 6.7.2.1p4 - verify the field type.
11265   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11266   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11267     // Handle incomplete types with specific error.
11268     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11269       return ExprError();
11270     if (FieldName)
11271       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11272         << FieldName << FieldTy << BitWidth->getSourceRange();
11273     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11274       << FieldTy << BitWidth->getSourceRange();
11275   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11276                                              UPPC_BitFieldWidth))
11277     return ExprError();
11278 
11279   // If the bit-width is type- or value-dependent, don't try to check
11280   // it now.
11281   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11282     return Owned(BitWidth);
11283 
11284   llvm::APSInt Value;
11285   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11286   if (ICE.isInvalid())
11287     return ICE;
11288   BitWidth = ICE.take();
11289 
11290   if (Value != 0 && ZeroWidth)
11291     *ZeroWidth = false;
11292 
11293   // Zero-width bitfield is ok for anonymous field.
11294   if (Value == 0 && FieldName)
11295     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11296 
11297   if (Value.isSigned() && Value.isNegative()) {
11298     if (FieldName)
11299       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11300                << FieldName << Value.toString(10);
11301     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11302       << Value.toString(10);
11303   }
11304 
11305   if (!FieldTy->isDependentType()) {
11306     uint64_t TypeSize = Context.getTypeSize(FieldTy);
11307     if (Value.getZExtValue() > TypeSize) {
11308       if (!getLangOpts().CPlusPlus || IsMsStruct ||
11309           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11310         if (FieldName)
11311           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11312             << FieldName << (unsigned)Value.getZExtValue()
11313             << (unsigned)TypeSize;
11314 
11315         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11316           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11317       }
11318 
11319       if (FieldName)
11320         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11321           << FieldName << (unsigned)Value.getZExtValue()
11322           << (unsigned)TypeSize;
11323       else
11324         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11325           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11326     }
11327   }
11328 
11329   return Owned(BitWidth);
11330 }
11331 
11332 /// ActOnField - Each field of a C struct/union is passed into this in order
11333 /// to create a FieldDecl object for it.
11334 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11335                        Declarator &D, Expr *BitfieldWidth) {
11336   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11337                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11338                                /*InitStyle=*/ICIS_NoInit, AS_public);
11339   return Res;
11340 }
11341 
11342 /// HandleField - Analyze a field of a C struct or a C++ data member.
11343 ///
11344 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11345                              SourceLocation DeclStart,
11346                              Declarator &D, Expr *BitWidth,
11347                              InClassInitStyle InitStyle,
11348                              AccessSpecifier AS) {
11349   IdentifierInfo *II = D.getIdentifier();
11350   SourceLocation Loc = DeclStart;
11351   if (II) Loc = D.getIdentifierLoc();
11352 
11353   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11354   QualType T = TInfo->getType();
11355   if (getLangOpts().CPlusPlus) {
11356     CheckExtraCXXDefaultArguments(D);
11357 
11358     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11359                                         UPPC_DataMemberType)) {
11360       D.setInvalidType();
11361       T = Context.IntTy;
11362       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11363     }
11364   }
11365 
11366   // TR 18037 does not allow fields to be declared with address spaces.
11367   if (T.getQualifiers().hasAddressSpace()) {
11368     Diag(Loc, diag::err_field_with_address_space);
11369     D.setInvalidType();
11370   }
11371 
11372   // OpenCL 1.2 spec, s6.9 r:
11373   // The event type cannot be used to declare a structure or union field.
11374   if (LangOpts.OpenCL && T->isEventT()) {
11375     Diag(Loc, diag::err_event_t_struct_field);
11376     D.setInvalidType();
11377   }
11378 
11379   DiagnoseFunctionSpecifiers(D.getDeclSpec());
11380 
11381   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11382     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11383          diag::err_invalid_thread)
11384       << DeclSpec::getSpecifierName(TSCS);
11385 
11386   // Check to see if this name was declared as a member previously
11387   NamedDecl *PrevDecl = 0;
11388   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11389   LookupName(Previous, S);
11390   switch (Previous.getResultKind()) {
11391     case LookupResult::Found:
11392     case LookupResult::FoundUnresolvedValue:
11393       PrevDecl = Previous.getAsSingle<NamedDecl>();
11394       break;
11395 
11396     case LookupResult::FoundOverloaded:
11397       PrevDecl = Previous.getRepresentativeDecl();
11398       break;
11399 
11400     case LookupResult::NotFound:
11401     case LookupResult::NotFoundInCurrentInstantiation:
11402     case LookupResult::Ambiguous:
11403       break;
11404   }
11405   Previous.suppressDiagnostics();
11406 
11407   if (PrevDecl && PrevDecl->isTemplateParameter()) {
11408     // Maybe we will complain about the shadowed template parameter.
11409     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11410     // Just pretend that we didn't see the previous declaration.
11411     PrevDecl = 0;
11412   }
11413 
11414   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11415     PrevDecl = 0;
11416 
11417   bool Mutable
11418     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
11419   SourceLocation TSSL = D.getLocStart();
11420   FieldDecl *NewFD
11421     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
11422                      TSSL, AS, PrevDecl, &D);
11423 
11424   if (NewFD->isInvalidDecl())
11425     Record->setInvalidDecl();
11426 
11427   if (D.getDeclSpec().isModulePrivateSpecified())
11428     NewFD->setModulePrivate();
11429 
11430   if (NewFD->isInvalidDecl() && PrevDecl) {
11431     // Don't introduce NewFD into scope; there's already something
11432     // with the same name in the same scope.
11433   } else if (II) {
11434     PushOnScopeChains(NewFD, S);
11435   } else
11436     Record->addDecl(NewFD);
11437 
11438   return NewFD;
11439 }
11440 
11441 /// \brief Build a new FieldDecl and check its well-formedness.
11442 ///
11443 /// This routine builds a new FieldDecl given the fields name, type,
11444 /// record, etc. \p PrevDecl should refer to any previous declaration
11445 /// with the same name and in the same scope as the field to be
11446 /// created.
11447 ///
11448 /// \returns a new FieldDecl.
11449 ///
11450 /// \todo The Declarator argument is a hack. It will be removed once
11451 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
11452                                 TypeSourceInfo *TInfo,
11453                                 RecordDecl *Record, SourceLocation Loc,
11454                                 bool Mutable, Expr *BitWidth,
11455                                 InClassInitStyle InitStyle,
11456                                 SourceLocation TSSL,
11457                                 AccessSpecifier AS, NamedDecl *PrevDecl,
11458                                 Declarator *D) {
11459   IdentifierInfo *II = Name.getAsIdentifierInfo();
11460   bool InvalidDecl = false;
11461   if (D) InvalidDecl = D->isInvalidType();
11462 
11463   // If we receive a broken type, recover by assuming 'int' and
11464   // marking this declaration as invalid.
11465   if (T.isNull()) {
11466     InvalidDecl = true;
11467     T = Context.IntTy;
11468   }
11469 
11470   QualType EltTy = Context.getBaseElementType(T);
11471   if (!EltTy->isDependentType()) {
11472     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11473       // Fields of incomplete type force their record to be invalid.
11474       Record->setInvalidDecl();
11475       InvalidDecl = true;
11476     } else {
11477       NamedDecl *Def;
11478       EltTy->isIncompleteType(&Def);
11479       if (Def && Def->isInvalidDecl()) {
11480         Record->setInvalidDecl();
11481         InvalidDecl = true;
11482       }
11483     }
11484   }
11485 
11486   // OpenCL v1.2 s6.9.c: bitfields are not supported.
11487   if (BitWidth && getLangOpts().OpenCL) {
11488     Diag(Loc, diag::err_opencl_bitfields);
11489     InvalidDecl = true;
11490   }
11491 
11492   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11493   // than a variably modified type.
11494   if (!InvalidDecl && T->isVariablyModifiedType()) {
11495     bool SizeIsNegative;
11496     llvm::APSInt Oversized;
11497 
11498     TypeSourceInfo *FixedTInfo =
11499       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11500                                                     SizeIsNegative,
11501                                                     Oversized);
11502     if (FixedTInfo) {
11503       Diag(Loc, diag::warn_illegal_constant_array_size);
11504       TInfo = FixedTInfo;
11505       T = FixedTInfo->getType();
11506     } else {
11507       if (SizeIsNegative)
11508         Diag(Loc, diag::err_typecheck_negative_array_size);
11509       else if (Oversized.getBoolValue())
11510         Diag(Loc, diag::err_array_too_large)
11511           << Oversized.toString(10);
11512       else
11513         Diag(Loc, diag::err_typecheck_field_variable_size);
11514       InvalidDecl = true;
11515     }
11516   }
11517 
11518   // Fields can not have abstract class types
11519   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11520                                              diag::err_abstract_type_in_decl,
11521                                              AbstractFieldType))
11522     InvalidDecl = true;
11523 
11524   bool ZeroWidth = false;
11525   // If this is declared as a bit-field, check the bit-field.
11526   if (!InvalidDecl && BitWidth) {
11527     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11528                               &ZeroWidth).take();
11529     if (!BitWidth) {
11530       InvalidDecl = true;
11531       BitWidth = 0;
11532       ZeroWidth = false;
11533     }
11534   }
11535 
11536   // Check that 'mutable' is consistent with the type of the declaration.
11537   if (!InvalidDecl && Mutable) {
11538     unsigned DiagID = 0;
11539     if (T->isReferenceType())
11540       DiagID = diag::err_mutable_reference;
11541     else if (T.isConstQualified())
11542       DiagID = diag::err_mutable_const;
11543 
11544     if (DiagID) {
11545       SourceLocation ErrLoc = Loc;
11546       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11547         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11548       Diag(ErrLoc, DiagID);
11549       Mutable = false;
11550       InvalidDecl = true;
11551     }
11552   }
11553 
11554   // C++11 [class.union]p8 (DR1460):
11555   //   At most one variant member of a union may have a
11556   //   brace-or-equal-initializer.
11557   if (InitStyle != ICIS_NoInit)
11558     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11559 
11560   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
11561                                        BitWidth, Mutable, InitStyle);
11562   if (InvalidDecl)
11563     NewFD->setInvalidDecl();
11564 
11565   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11566     Diag(Loc, diag::err_duplicate_member) << II;
11567     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11568     NewFD->setInvalidDecl();
11569   }
11570 
11571   if (!InvalidDecl && getLangOpts().CPlusPlus) {
11572     if (Record->isUnion()) {
11573       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11574         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11575         if (RDecl->getDefinition()) {
11576           // C++ [class.union]p1: An object of a class with a non-trivial
11577           // constructor, a non-trivial copy constructor, a non-trivial
11578           // destructor, or a non-trivial copy assignment operator
11579           // cannot be a member of a union, nor can an array of such
11580           // objects.
11581           if (CheckNontrivialField(NewFD))
11582             NewFD->setInvalidDecl();
11583         }
11584       }
11585 
11586       // C++ [class.union]p1: If a union contains a member of reference type,
11587       // the program is ill-formed, except when compiling with MSVC extensions
11588       // enabled.
11589       if (EltTy->isReferenceType()) {
11590         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11591                                     diag::ext_union_member_of_reference_type :
11592                                     diag::err_union_member_of_reference_type)
11593           << NewFD->getDeclName() << EltTy;
11594         if (!getLangOpts().MicrosoftExt)
11595           NewFD->setInvalidDecl();
11596       }
11597     }
11598   }
11599 
11600   // FIXME: We need to pass in the attributes given an AST
11601   // representation, not a parser representation.
11602   if (D) {
11603     // FIXME: The current scope is almost... but not entirely... correct here.
11604     ProcessDeclAttributes(getCurScope(), NewFD, *D);
11605 
11606     if (NewFD->hasAttrs())
11607       CheckAlignasUnderalignment(NewFD);
11608   }
11609 
11610   // In auto-retain/release, infer strong retension for fields of
11611   // retainable type.
11612   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
11613     NewFD->setInvalidDecl();
11614 
11615   if (T.isObjCGCWeak())
11616     Diag(Loc, diag::warn_attribute_weak_on_field);
11617 
11618   NewFD->setAccess(AS);
11619   return NewFD;
11620 }
11621 
11622 bool Sema::CheckNontrivialField(FieldDecl *FD) {
11623   assert(FD);
11624   assert(getLangOpts().CPlusPlus && "valid check only for C++");
11625 
11626   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11627     return false;
11628 
11629   QualType EltTy = Context.getBaseElementType(FD->getType());
11630   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11631     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
11632     if (RDecl->getDefinition()) {
11633       // We check for copy constructors before constructors
11634       // because otherwise we'll never get complaints about
11635       // copy constructors.
11636 
11637       CXXSpecialMember member = CXXInvalid;
11638       // We're required to check for any non-trivial constructors. Since the
11639       // implicit default constructor is suppressed if there are any
11640       // user-declared constructors, we just need to check that there is a
11641       // trivial default constructor and a trivial copy constructor. (We don't
11642       // worry about move constructors here, since this is a C++98 check.)
11643       if (RDecl->hasNonTrivialCopyConstructor())
11644         member = CXXCopyConstructor;
11645       else if (!RDecl->hasTrivialDefaultConstructor())
11646         member = CXXDefaultConstructor;
11647       else if (RDecl->hasNonTrivialCopyAssignment())
11648         member = CXXCopyAssignment;
11649       else if (RDecl->hasNonTrivialDestructor())
11650         member = CXXDestructor;
11651 
11652       if (member != CXXInvalid) {
11653         if (!getLangOpts().CPlusPlus11 &&
11654             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
11655           // Objective-C++ ARC: it is an error to have a non-trivial field of
11656           // a union. However, system headers in Objective-C programs
11657           // occasionally have Objective-C lifetime objects within unions,
11658           // and rather than cause the program to fail, we make those
11659           // members unavailable.
11660           SourceLocation Loc = FD->getLocation();
11661           if (getSourceManager().isInSystemHeader(Loc)) {
11662             if (!FD->hasAttr<UnavailableAttr>())
11663               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11664                                   "this system field has retaining ownership",
11665                                   Loc));
11666             return false;
11667           }
11668         }
11669 
11670         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
11671                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11672                diag::err_illegal_union_or_anon_struct_member)
11673           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
11674         DiagnoseNontrivial(RDecl, member);
11675         return !getLangOpts().CPlusPlus11;
11676       }
11677     }
11678   }
11679 
11680   return false;
11681 }
11682 
11683 /// TranslateIvarVisibility - Translate visibility from a token ID to an
11684 ///  AST enum value.
11685 static ObjCIvarDecl::AccessControl
11686 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
11687   switch (ivarVisibility) {
11688   default: llvm_unreachable("Unknown visitibility kind");
11689   case tok::objc_private: return ObjCIvarDecl::Private;
11690   case tok::objc_public: return ObjCIvarDecl::Public;
11691   case tok::objc_protected: return ObjCIvarDecl::Protected;
11692   case tok::objc_package: return ObjCIvarDecl::Package;
11693   }
11694 }
11695 
11696 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
11697 /// in order to create an IvarDecl object for it.
11698 Decl *Sema::ActOnIvar(Scope *S,
11699                                 SourceLocation DeclStart,
11700                                 Declarator &D, Expr *BitfieldWidth,
11701                                 tok::ObjCKeywordKind Visibility) {
11702 
11703   IdentifierInfo *II = D.getIdentifier();
11704   Expr *BitWidth = (Expr*)BitfieldWidth;
11705   SourceLocation Loc = DeclStart;
11706   if (II) Loc = D.getIdentifierLoc();
11707 
11708   // FIXME: Unnamed fields can be handled in various different ways, for
11709   // example, unnamed unions inject all members into the struct namespace!
11710 
11711   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11712   QualType T = TInfo->getType();
11713 
11714   if (BitWidth) {
11715     // 6.7.2.1p3, 6.7.2.1p4
11716     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
11717     if (!BitWidth)
11718       D.setInvalidType();
11719   } else {
11720     // Not a bitfield.
11721 
11722     // validate II.
11723 
11724   }
11725   if (T->isReferenceType()) {
11726     Diag(Loc, diag::err_ivar_reference_type);
11727     D.setInvalidType();
11728   }
11729   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11730   // than a variably modified type.
11731   else if (T->isVariablyModifiedType()) {
11732     Diag(Loc, diag::err_typecheck_ivar_variable_size);
11733     D.setInvalidType();
11734   }
11735 
11736   // Get the visibility (access control) for this ivar.
11737   ObjCIvarDecl::AccessControl ac =
11738     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11739                                         : ObjCIvarDecl::None;
11740   // Must set ivar's DeclContext to its enclosing interface.
11741   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
11742   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11743     return 0;
11744   ObjCContainerDecl *EnclosingContext;
11745   if (ObjCImplementationDecl *IMPDecl =
11746       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11747     if (LangOpts.ObjCRuntime.isFragile()) {
11748     // Case of ivar declared in an implementation. Context is that of its class.
11749       EnclosingContext = IMPDecl->getClassInterface();
11750       assert(EnclosingContext && "Implementation has no class interface!");
11751     }
11752     else
11753       EnclosingContext = EnclosingDecl;
11754   } else {
11755     if (ObjCCategoryDecl *CDecl =
11756         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11757       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
11758         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
11759         return 0;
11760       }
11761     }
11762     EnclosingContext = EnclosingDecl;
11763   }
11764 
11765   // Construct the decl.
11766   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11767                                              DeclStart, Loc, II, T,
11768                                              TInfo, ac, (Expr *)BitfieldWidth);
11769 
11770   if (II) {
11771     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
11772                                            ForRedeclaration);
11773     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
11774         && !isa<TagDecl>(PrevDecl)) {
11775       Diag(Loc, diag::err_duplicate_member) << II;
11776       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11777       NewID->setInvalidDecl();
11778     }
11779   }
11780 
11781   // Process attributes attached to the ivar.
11782   ProcessDeclAttributes(S, NewID, D);
11783 
11784   if (D.isInvalidType())
11785     NewID->setInvalidDecl();
11786 
11787   // In ARC, infer 'retaining' for ivars of retainable type.
11788   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
11789     NewID->setInvalidDecl();
11790 
11791   if (D.getDeclSpec().isModulePrivateSpecified())
11792     NewID->setModulePrivate();
11793 
11794   if (II) {
11795     // FIXME: When interfaces are DeclContexts, we'll need to add
11796     // these to the interface.
11797     S->AddDecl(NewID);
11798     IdResolver.AddDecl(NewID);
11799   }
11800 
11801   if (LangOpts.ObjCRuntime.isNonFragile() &&
11802       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
11803     Diag(Loc, diag::warn_ivars_in_interface);
11804 
11805   return NewID;
11806 }
11807 
11808 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
11809 /// class and class extensions. For every class \@interface and class
11810 /// extension \@interface, if the last ivar is a bitfield of any type,
11811 /// then add an implicit `char :0` ivar to the end of that interface.
11812 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
11813                              SmallVectorImpl<Decl *> &AllIvarDecls) {
11814   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
11815     return;
11816 
11817   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11818   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11819 
11820   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
11821     return;
11822   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
11823   if (!ID) {
11824     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
11825       if (!CD->IsClassExtension())
11826         return;
11827     }
11828     // No need to add this to end of @implementation.
11829     else
11830       return;
11831   }
11832   // All conditions are met. Add a new bitfield to the tail end of ivars.
11833   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11834   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
11835 
11836   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
11837                               DeclLoc, DeclLoc, 0,
11838                               Context.CharTy,
11839                               Context.getTrivialTypeSourceInfo(Context.CharTy,
11840                                                                DeclLoc),
11841                               ObjCIvarDecl::Private, BW,
11842                               true);
11843   AllIvarDecls.push_back(Ivar);
11844 }
11845 
11846 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11847                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
11848                        SourceLocation RBrac, AttributeList *Attr) {
11849   assert(EnclosingDecl && "missing record or interface decl");
11850 
11851   // If this is an Objective-C @implementation or category and we have
11852   // new fields here we should reset the layout of the interface since
11853   // it will now change.
11854   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11855     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11856     switch (DC->getKind()) {
11857     default: break;
11858     case Decl::ObjCCategory:
11859       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11860       break;
11861     case Decl::ObjCImplementation:
11862       Context.
11863         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11864       break;
11865     }
11866   }
11867 
11868   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11869 
11870   // Start counting up the number of named members; make sure to include
11871   // members of anonymous structs and unions in the total.
11872   unsigned NumNamedMembers = 0;
11873   if (Record) {
11874     for (RecordDecl::decl_iterator i = Record->decls_begin(),
11875                                    e = Record->decls_end(); i != e; i++) {
11876       if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11877         if (IFD->getDeclName())
11878           ++NumNamedMembers;
11879     }
11880   }
11881 
11882   // Verify that all the fields are okay.
11883   SmallVector<FieldDecl*, 32> RecFields;
11884 
11885   bool ARCErrReported = false;
11886   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
11887        i != end; ++i) {
11888     FieldDecl *FD = cast<FieldDecl>(*i);
11889 
11890     // Get the type for the field.
11891     const Type *FDTy = FD->getType().getTypePtr();
11892 
11893     if (!FD->isAnonymousStructOrUnion()) {
11894       // Remember all fields written by the user.
11895       RecFields.push_back(FD);
11896     }
11897 
11898     // If the field is already invalid for some reason, don't emit more
11899     // diagnostics about it.
11900     if (FD->isInvalidDecl()) {
11901       EnclosingDecl->setInvalidDecl();
11902       continue;
11903     }
11904 
11905     // C99 6.7.2.1p2:
11906     //   A structure or union shall not contain a member with
11907     //   incomplete or function type (hence, a structure shall not
11908     //   contain an instance of itself, but may contain a pointer to
11909     //   an instance of itself), except that the last member of a
11910     //   structure with more than one named member may have incomplete
11911     //   array type; such a structure (and any union containing,
11912     //   possibly recursively, a member that is such a structure)
11913     //   shall not be a member of a structure or an element of an
11914     //   array.
11915     if (FDTy->isFunctionType()) {
11916       // Field declared as a function.
11917       Diag(FD->getLocation(), diag::err_field_declared_as_function)
11918         << FD->getDeclName();
11919       FD->setInvalidDecl();
11920       EnclosingDecl->setInvalidDecl();
11921       continue;
11922     } else if (FDTy->isIncompleteArrayType() && Record &&
11923                ((i + 1 == Fields.end() && !Record->isUnion()) ||
11924                 ((getLangOpts().MicrosoftExt ||
11925                   getLangOpts().CPlusPlus) &&
11926                  (i + 1 == Fields.end() || Record->isUnion())))) {
11927       // Flexible array member.
11928       // Microsoft and g++ is more permissive regarding flexible array.
11929       // It will accept flexible array in union and also
11930       // as the sole element of a struct/class.
11931       unsigned DiagID = 0;
11932       if (Record->isUnion())
11933         DiagID = getLangOpts().MicrosoftExt
11934                      ? diag::ext_flexible_array_union_ms
11935                      : getLangOpts().CPlusPlus
11936                            ? diag::ext_flexible_array_union_gnu
11937                            : diag::err_flexible_array_union;
11938       else if (Fields.size() == 1)
11939         DiagID = getLangOpts().MicrosoftExt
11940                      ? diag::ext_flexible_array_empty_aggregate_ms
11941                      : getLangOpts().CPlusPlus
11942                            ? diag::ext_flexible_array_empty_aggregate_gnu
11943                            : NumNamedMembers < 1
11944                                  ? diag::err_flexible_array_empty_aggregate
11945                                  : 0;
11946 
11947       if (DiagID)
11948         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11949                                         << Record->getTagKind();
11950       // While the layout of types that contain virtual bases is not specified
11951       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11952       // virtual bases after the derived members.  This would make a flexible
11953       // array member declared at the end of an object not adjacent to the end
11954       // of the type.
11955       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11956         if (RD->getNumVBases() != 0)
11957           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11958             << FD->getDeclName() << Record->getTagKind();
11959       if (!getLangOpts().C99)
11960         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11961           << FD->getDeclName() << Record->getTagKind();
11962 
11963       // If the element type has a non-trivial destructor, we would not
11964       // implicitly destroy the elements, so disallow it for now.
11965       //
11966       // FIXME: GCC allows this. We should probably either implicitly delete
11967       // the destructor of the containing class, or just allow this.
11968       QualType BaseElem = Context.getBaseElementType(FD->getType());
11969       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
11970         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
11971           << FD->getDeclName() << FD->getType();
11972         FD->setInvalidDecl();
11973         EnclosingDecl->setInvalidDecl();
11974         continue;
11975       }
11976       // Okay, we have a legal flexible array member at the end of the struct.
11977       if (Record)
11978         Record->setHasFlexibleArrayMember(true);
11979     } else if (!FDTy->isDependentType() &&
11980                RequireCompleteType(FD->getLocation(), FD->getType(),
11981                                    diag::err_field_incomplete)) {
11982       // Incomplete type
11983       FD->setInvalidDecl();
11984       EnclosingDecl->setInvalidDecl();
11985       continue;
11986     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
11987       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11988         // If this is a member of a union, then entire union becomes "flexible".
11989         if (Record && Record->isUnion()) {
11990           Record->setHasFlexibleArrayMember(true);
11991         } else {
11992           // If this is a struct/class and this is not the last element, reject
11993           // it.  Note that GCC supports variable sized arrays in the middle of
11994           // structures.
11995           if (i + 1 != Fields.end())
11996             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
11997               << FD->getDeclName() << FD->getType();
11998           else {
11999             // We support flexible arrays at the end of structs in
12000             // other structs as an extension.
12001             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12002               << FD->getDeclName();
12003             if (Record)
12004               Record->setHasFlexibleArrayMember(true);
12005           }
12006         }
12007       }
12008       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12009           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12010                                  diag::err_abstract_type_in_decl,
12011                                  AbstractIvarType)) {
12012         // Ivars can not have abstract class types
12013         FD->setInvalidDecl();
12014       }
12015       if (Record && FDTTy->getDecl()->hasObjectMember())
12016         Record->setHasObjectMember(true);
12017       if (Record && FDTTy->getDecl()->hasVolatileMember())
12018         Record->setHasVolatileMember(true);
12019     } else if (FDTy->isObjCObjectType()) {
12020       /// A field cannot be an Objective-c object
12021       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12022         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12023       QualType T = Context.getObjCObjectPointerType(FD->getType());
12024       FD->setType(T);
12025     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12026                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12027       // It's an error in ARC if a field has lifetime.
12028       // We don't want to report this in a system header, though,
12029       // so we just make the field unavailable.
12030       // FIXME: that's really not sufficient; we need to make the type
12031       // itself invalid to, say, initialize or copy.
12032       QualType T = FD->getType();
12033       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12034       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12035         SourceLocation loc = FD->getLocation();
12036         if (getSourceManager().isInSystemHeader(loc)) {
12037           if (!FD->hasAttr<UnavailableAttr>()) {
12038             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12039                               "this system field has retaining ownership",
12040                               loc));
12041           }
12042         } else {
12043           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12044             << T->isBlockPointerType() << Record->getTagKind();
12045         }
12046         ARCErrReported = true;
12047       }
12048     } else if (getLangOpts().ObjC1 &&
12049                getLangOpts().getGC() != LangOptions::NonGC &&
12050                Record && !Record->hasObjectMember()) {
12051       if (FD->getType()->isObjCObjectPointerType() ||
12052           FD->getType().isObjCGCStrong())
12053         Record->setHasObjectMember(true);
12054       else if (Context.getAsArrayType(FD->getType())) {
12055         QualType BaseType = Context.getBaseElementType(FD->getType());
12056         if (BaseType->isRecordType() &&
12057             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12058           Record->setHasObjectMember(true);
12059         else if (BaseType->isObjCObjectPointerType() ||
12060                  BaseType.isObjCGCStrong())
12061                Record->setHasObjectMember(true);
12062       }
12063     }
12064     if (Record && FD->getType().isVolatileQualified())
12065       Record->setHasVolatileMember(true);
12066     // Keep track of the number of named members.
12067     if (FD->getIdentifier())
12068       ++NumNamedMembers;
12069   }
12070 
12071   // Okay, we successfully defined 'Record'.
12072   if (Record) {
12073     bool Completed = false;
12074     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12075       if (!CXXRecord->isInvalidDecl()) {
12076         // Set access bits correctly on the directly-declared conversions.
12077         for (CXXRecordDecl::conversion_iterator
12078                I = CXXRecord->conversion_begin(),
12079                E = CXXRecord->conversion_end(); I != E; ++I)
12080           I.setAccess((*I)->getAccess());
12081 
12082         if (!CXXRecord->isDependentType()) {
12083           if (CXXRecord->hasUserDeclaredDestructor()) {
12084             // Adjust user-defined destructor exception spec.
12085             if (getLangOpts().CPlusPlus11)
12086               AdjustDestructorExceptionSpec(CXXRecord,
12087                                             CXXRecord->getDestructor());
12088           }
12089 
12090           // Add any implicitly-declared members to this class.
12091           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12092 
12093           // If we have virtual base classes, we may end up finding multiple
12094           // final overriders for a given virtual function. Check for this
12095           // problem now.
12096           if (CXXRecord->getNumVBases()) {
12097             CXXFinalOverriderMap FinalOverriders;
12098             CXXRecord->getFinalOverriders(FinalOverriders);
12099 
12100             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12101                                              MEnd = FinalOverriders.end();
12102                  M != MEnd; ++M) {
12103               for (OverridingMethods::iterator SO = M->second.begin(),
12104                                             SOEnd = M->second.end();
12105                    SO != SOEnd; ++SO) {
12106                 assert(SO->second.size() > 0 &&
12107                        "Virtual function without overridding functions?");
12108                 if (SO->second.size() == 1)
12109                   continue;
12110 
12111                 // C++ [class.virtual]p2:
12112                 //   In a derived class, if a virtual member function of a base
12113                 //   class subobject has more than one final overrider the
12114                 //   program is ill-formed.
12115                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12116                   << (const NamedDecl *)M->first << Record;
12117                 Diag(M->first->getLocation(),
12118                      diag::note_overridden_virtual_function);
12119                 for (OverridingMethods::overriding_iterator
12120                           OM = SO->second.begin(),
12121                        OMEnd = SO->second.end();
12122                      OM != OMEnd; ++OM)
12123                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12124                     << (const NamedDecl *)M->first << OM->Method->getParent();
12125 
12126                 Record->setInvalidDecl();
12127               }
12128             }
12129             CXXRecord->completeDefinition(&FinalOverriders);
12130             Completed = true;
12131           }
12132         }
12133       }
12134     }
12135 
12136     if (!Completed)
12137       Record->completeDefinition();
12138 
12139     if (Record->hasAttrs()) {
12140       CheckAlignasUnderalignment(Record);
12141 
12142       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
12143         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
12144                                            IA->getRange(), IA->getBestCase(),
12145                                            IA->getSemanticSpelling());
12146     }
12147 
12148     // Check if the structure/union declaration is a type that can have zero
12149     // size in C. For C this is a language extension, for C++ it may cause
12150     // compatibility problems.
12151     bool CheckForZeroSize;
12152     if (!getLangOpts().CPlusPlus) {
12153       CheckForZeroSize = true;
12154     } else {
12155       // For C++ filter out types that cannot be referenced in C code.
12156       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12157       CheckForZeroSize =
12158           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12159           !CXXRecord->isDependentType() &&
12160           CXXRecord->isCLike();
12161     }
12162     if (CheckForZeroSize) {
12163       bool ZeroSize = true;
12164       bool IsEmpty = true;
12165       unsigned NonBitFields = 0;
12166       for (RecordDecl::field_iterator I = Record->field_begin(),
12167                                       E = Record->field_end();
12168            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12169         IsEmpty = false;
12170         if (I->isUnnamedBitfield()) {
12171           if (I->getBitWidthValue(Context) > 0)
12172             ZeroSize = false;
12173         } else {
12174           ++NonBitFields;
12175           QualType FieldType = I->getType();
12176           if (FieldType->isIncompleteType() ||
12177               !Context.getTypeSizeInChars(FieldType).isZero())
12178             ZeroSize = false;
12179         }
12180       }
12181 
12182       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12183       // allowed in C++, but warn if its declaration is inside
12184       // extern "C" block.
12185       if (ZeroSize) {
12186         Diag(RecLoc, getLangOpts().CPlusPlus ?
12187                          diag::warn_zero_size_struct_union_in_extern_c :
12188                          diag::warn_zero_size_struct_union_compat)
12189           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12190       }
12191 
12192       // Structs without named members are extension in C (C99 6.7.2.1p7),
12193       // but are accepted by GCC.
12194       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12195         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12196                                diag::ext_no_named_members_in_struct_union)
12197           << Record->isUnion();
12198       }
12199     }
12200   } else {
12201     ObjCIvarDecl **ClsFields =
12202       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12203     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12204       ID->setEndOfDefinitionLoc(RBrac);
12205       // Add ivar's to class's DeclContext.
12206       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12207         ClsFields[i]->setLexicalDeclContext(ID);
12208         ID->addDecl(ClsFields[i]);
12209       }
12210       // Must enforce the rule that ivars in the base classes may not be
12211       // duplicates.
12212       if (ID->getSuperClass())
12213         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12214     } else if (ObjCImplementationDecl *IMPDecl =
12215                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12216       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12217       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12218         // Ivar declared in @implementation never belongs to the implementation.
12219         // Only it is in implementation's lexical context.
12220         ClsFields[I]->setLexicalDeclContext(IMPDecl);
12221       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12222       IMPDecl->setIvarLBraceLoc(LBrac);
12223       IMPDecl->setIvarRBraceLoc(RBrac);
12224     } else if (ObjCCategoryDecl *CDecl =
12225                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12226       // case of ivars in class extension; all other cases have been
12227       // reported as errors elsewhere.
12228       // FIXME. Class extension does not have a LocEnd field.
12229       // CDecl->setLocEnd(RBrac);
12230       // Add ivar's to class extension's DeclContext.
12231       // Diagnose redeclaration of private ivars.
12232       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
12233       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12234         if (IDecl) {
12235           if (const ObjCIvarDecl *ClsIvar =
12236               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12237             Diag(ClsFields[i]->getLocation(),
12238                  diag::err_duplicate_ivar_declaration);
12239             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12240             continue;
12241           }
12242           for (ObjCInterfaceDecl::known_extensions_iterator
12243                  Ext = IDecl->known_extensions_begin(),
12244                  ExtEnd = IDecl->known_extensions_end();
12245                Ext != ExtEnd; ++Ext) {
12246             if (const ObjCIvarDecl *ClsExtIvar
12247                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
12248               Diag(ClsFields[i]->getLocation(),
12249                    diag::err_duplicate_ivar_declaration);
12250               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12251               continue;
12252             }
12253           }
12254         }
12255         ClsFields[i]->setLexicalDeclContext(CDecl);
12256         CDecl->addDecl(ClsFields[i]);
12257       }
12258       CDecl->setIvarLBraceLoc(LBrac);
12259       CDecl->setIvarRBraceLoc(RBrac);
12260     }
12261   }
12262 
12263   if (Attr)
12264     ProcessDeclAttributeList(S, Record, Attr);
12265 }
12266 
12267 /// \brief Determine whether the given integral value is representable within
12268 /// the given type T.
12269 static bool isRepresentableIntegerValue(ASTContext &Context,
12270                                         llvm::APSInt &Value,
12271                                         QualType T) {
12272   assert(T->isIntegralType(Context) && "Integral type required!");
12273   unsigned BitWidth = Context.getIntWidth(T);
12274 
12275   if (Value.isUnsigned() || Value.isNonNegative()) {
12276     if (T->isSignedIntegerOrEnumerationType())
12277       --BitWidth;
12278     return Value.getActiveBits() <= BitWidth;
12279   }
12280   return Value.getMinSignedBits() <= BitWidth;
12281 }
12282 
12283 // \brief Given an integral type, return the next larger integral type
12284 // (or a NULL type of no such type exists).
12285 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12286   // FIXME: Int128/UInt128 support, which also needs to be introduced into
12287   // enum checking below.
12288   assert(T->isIntegralType(Context) && "Integral type required!");
12289   const unsigned NumTypes = 4;
12290   QualType SignedIntegralTypes[NumTypes] = {
12291     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12292   };
12293   QualType UnsignedIntegralTypes[NumTypes] = {
12294     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12295     Context.UnsignedLongLongTy
12296   };
12297 
12298   unsigned BitWidth = Context.getTypeSize(T);
12299   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12300                                                         : UnsignedIntegralTypes;
12301   for (unsigned I = 0; I != NumTypes; ++I)
12302     if (Context.getTypeSize(Types[I]) > BitWidth)
12303       return Types[I];
12304 
12305   return QualType();
12306 }
12307 
12308 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12309                                           EnumConstantDecl *LastEnumConst,
12310                                           SourceLocation IdLoc,
12311                                           IdentifierInfo *Id,
12312                                           Expr *Val) {
12313   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12314   llvm::APSInt EnumVal(IntWidth);
12315   QualType EltTy;
12316 
12317   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12318     Val = 0;
12319 
12320   if (Val)
12321     Val = DefaultLvalueConversion(Val).take();
12322 
12323   if (Val) {
12324     if (Enum->isDependentType() || Val->isTypeDependent())
12325       EltTy = Context.DependentTy;
12326     else {
12327       SourceLocation ExpLoc;
12328       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12329           !getLangOpts().MSVCCompat) {
12330         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12331         // constant-expression in the enumerator-definition shall be a converted
12332         // constant expression of the underlying type.
12333         EltTy = Enum->getIntegerType();
12334         ExprResult Converted =
12335           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12336                                            CCEK_Enumerator);
12337         if (Converted.isInvalid())
12338           Val = 0;
12339         else
12340           Val = Converted.take();
12341       } else if (!Val->isValueDependent() &&
12342                  !(Val = VerifyIntegerConstantExpression(Val,
12343                                                          &EnumVal).take())) {
12344         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12345       } else {
12346         if (Enum->isFixed()) {
12347           EltTy = Enum->getIntegerType();
12348 
12349           // In Obj-C and Microsoft mode, require the enumeration value to be
12350           // representable in the underlying type of the enumeration. In C++11,
12351           // we perform a non-narrowing conversion as part of converted constant
12352           // expression checking.
12353           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12354             if (getLangOpts().MSVCCompat) {
12355               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12356               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12357             } else
12358               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12359           } else
12360             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12361         } else if (getLangOpts().CPlusPlus) {
12362           // C++11 [dcl.enum]p5:
12363           //   If the underlying type is not fixed, the type of each enumerator
12364           //   is the type of its initializing value:
12365           //     - If an initializer is specified for an enumerator, the
12366           //       initializing value has the same type as the expression.
12367           EltTy = Val->getType();
12368         } else {
12369           // C99 6.7.2.2p2:
12370           //   The expression that defines the value of an enumeration constant
12371           //   shall be an integer constant expression that has a value
12372           //   representable as an int.
12373 
12374           // Complain if the value is not representable in an int.
12375           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12376             Diag(IdLoc, diag::ext_enum_value_not_int)
12377               << EnumVal.toString(10) << Val->getSourceRange()
12378               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12379           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12380             // Force the type of the expression to 'int'.
12381             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12382           }
12383           EltTy = Val->getType();
12384         }
12385       }
12386     }
12387   }
12388 
12389   if (!Val) {
12390     if (Enum->isDependentType())
12391       EltTy = Context.DependentTy;
12392     else if (!LastEnumConst) {
12393       // C++0x [dcl.enum]p5:
12394       //   If the underlying type is not fixed, the type of each enumerator
12395       //   is the type of its initializing value:
12396       //     - If no initializer is specified for the first enumerator, the
12397       //       initializing value has an unspecified integral type.
12398       //
12399       // GCC uses 'int' for its unspecified integral type, as does
12400       // C99 6.7.2.2p3.
12401       if (Enum->isFixed()) {
12402         EltTy = Enum->getIntegerType();
12403       }
12404       else {
12405         EltTy = Context.IntTy;
12406       }
12407     } else {
12408       // Assign the last value + 1.
12409       EnumVal = LastEnumConst->getInitVal();
12410       ++EnumVal;
12411       EltTy = LastEnumConst->getType();
12412 
12413       // Check for overflow on increment.
12414       if (EnumVal < LastEnumConst->getInitVal()) {
12415         // C++0x [dcl.enum]p5:
12416         //   If the underlying type is not fixed, the type of each enumerator
12417         //   is the type of its initializing value:
12418         //
12419         //     - Otherwise the type of the initializing value is the same as
12420         //       the type of the initializing value of the preceding enumerator
12421         //       unless the incremented value is not representable in that type,
12422         //       in which case the type is an unspecified integral type
12423         //       sufficient to contain the incremented value. If no such type
12424         //       exists, the program is ill-formed.
12425         QualType T = getNextLargerIntegralType(Context, EltTy);
12426         if (T.isNull() || Enum->isFixed()) {
12427           // There is no integral type larger enough to represent this
12428           // value. Complain, then allow the value to wrap around.
12429           EnumVal = LastEnumConst->getInitVal();
12430           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
12431           ++EnumVal;
12432           if (Enum->isFixed())
12433             // When the underlying type is fixed, this is ill-formed.
12434             Diag(IdLoc, diag::err_enumerator_wrapped)
12435               << EnumVal.toString(10)
12436               << EltTy;
12437           else
12438             Diag(IdLoc, diag::warn_enumerator_too_large)
12439               << EnumVal.toString(10);
12440         } else {
12441           EltTy = T;
12442         }
12443 
12444         // Retrieve the last enumerator's value, extent that type to the
12445         // type that is supposed to be large enough to represent the incremented
12446         // value, then increment.
12447         EnumVal = LastEnumConst->getInitVal();
12448         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12449         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
12450         ++EnumVal;
12451 
12452         // If we're not in C++, diagnose the overflow of enumerator values,
12453         // which in C99 means that the enumerator value is not representable in
12454         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12455         // permits enumerator values that are representable in some larger
12456         // integral type.
12457         if (!getLangOpts().CPlusPlus && !T.isNull())
12458           Diag(IdLoc, diag::warn_enum_value_overflow);
12459       } else if (!getLangOpts().CPlusPlus &&
12460                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12461         // Enforce C99 6.7.2.2p2 even when we compute the next value.
12462         Diag(IdLoc, diag::ext_enum_value_not_int)
12463           << EnumVal.toString(10) << 1;
12464       }
12465     }
12466   }
12467 
12468   if (!EltTy->isDependentType()) {
12469     // Make the enumerator value match the signedness and size of the
12470     // enumerator's type.
12471     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
12472     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12473   }
12474 
12475   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
12476                                   Val, EnumVal);
12477 }
12478 
12479 
12480 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12481                               SourceLocation IdLoc, IdentifierInfo *Id,
12482                               AttributeList *Attr,
12483                               SourceLocation EqualLoc, Expr *Val) {
12484   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
12485   EnumConstantDecl *LastEnumConst =
12486     cast_or_null<EnumConstantDecl>(lastEnumConst);
12487 
12488   // The scope passed in may not be a decl scope.  Zip up the scope tree until
12489   // we find one that is.
12490   S = getNonFieldDeclScope(S);
12491 
12492   // Verify that there isn't already something declared with this name in this
12493   // scope.
12494   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
12495                                          ForRedeclaration);
12496   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12497     // Maybe we will complain about the shadowed template parameter.
12498     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12499     // Just pretend that we didn't see the previous declaration.
12500     PrevDecl = 0;
12501   }
12502 
12503   if (PrevDecl) {
12504     // When in C++, we may get a TagDecl with the same name; in this case the
12505     // enum constant will 'hide' the tag.
12506     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
12507            "Received TagDecl when not in C++!");
12508     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
12509       if (isa<EnumConstantDecl>(PrevDecl))
12510         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
12511       else
12512         Diag(IdLoc, diag::err_redefinition) << Id;
12513       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12514       return 0;
12515     }
12516   }
12517 
12518   // C++ [class.mem]p15:
12519   // If T is the name of a class, then each of the following shall have a name
12520   // different from T:
12521   // - every enumerator of every member of class T that is an unscoped
12522   // enumerated type
12523   if (CXXRecordDecl *Record
12524                       = dyn_cast<CXXRecordDecl>(
12525                              TheEnumDecl->getDeclContext()->getRedeclContext()))
12526     if (!TheEnumDecl->isScoped() &&
12527         Record->getIdentifier() && Record->getIdentifier() == Id)
12528       Diag(IdLoc, diag::err_member_name_of_class) << Id;
12529 
12530   EnumConstantDecl *New =
12531     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
12532 
12533   if (New) {
12534     // Process attributes.
12535     if (Attr) ProcessDeclAttributeList(S, New, Attr);
12536 
12537     // Register this decl in the current scope stack.
12538     New->setAccess(TheEnumDecl->getAccess());
12539     PushOnScopeChains(New, S);
12540   }
12541 
12542   ActOnDocumentableDecl(New);
12543 
12544   return New;
12545 }
12546 
12547 // Returns true when the enum initial expression does not trigger the
12548 // duplicate enum warning.  A few common cases are exempted as follows:
12549 // Element2 = Element1
12550 // Element2 = Element1 + 1
12551 // Element2 = Element1 - 1
12552 // Where Element2 and Element1 are from the same enum.
12553 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12554   Expr *InitExpr = ECD->getInitExpr();
12555   if (!InitExpr)
12556     return true;
12557   InitExpr = InitExpr->IgnoreImpCasts();
12558 
12559   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12560     if (!BO->isAdditiveOp())
12561       return true;
12562     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12563     if (!IL)
12564       return true;
12565     if (IL->getValue() != 1)
12566       return true;
12567 
12568     InitExpr = BO->getLHS();
12569   }
12570 
12571   // This checks if the elements are from the same enum.
12572   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12573   if (!DRE)
12574     return true;
12575 
12576   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12577   if (!EnumConstant)
12578     return true;
12579 
12580   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12581       Enum)
12582     return true;
12583 
12584   return false;
12585 }
12586 
12587 struct DupKey {
12588   int64_t val;
12589   bool isTombstoneOrEmptyKey;
12590   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12591     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12592 };
12593 
12594 static DupKey GetDupKey(const llvm::APSInt& Val) {
12595   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12596                 false);
12597 }
12598 
12599 struct DenseMapInfoDupKey {
12600   static DupKey getEmptyKey() { return DupKey(0, true); }
12601   static DupKey getTombstoneKey() { return DupKey(1, true); }
12602   static unsigned getHashValue(const DupKey Key) {
12603     return (unsigned)(Key.val * 37);
12604   }
12605   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12606     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12607            LHS.val == RHS.val;
12608   }
12609 };
12610 
12611 // Emits a warning when an element is implicitly set a value that
12612 // a previous element has already been set to.
12613 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12614                                         EnumDecl *Enum,
12615                                         QualType EnumType) {
12616   if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12617                                  Enum->getLocation()) ==
12618       DiagnosticsEngine::Ignored)
12619     return;
12620   // Avoid anonymous enums
12621   if (!Enum->getIdentifier())
12622     return;
12623 
12624   // Only check for small enums.
12625   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12626     return;
12627 
12628   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12629   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
12630 
12631   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12632   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12633           ValueToVectorMap;
12634 
12635   DuplicatesVector DupVector;
12636   ValueToVectorMap EnumMap;
12637 
12638   // Populate the EnumMap with all values represented by enum constants without
12639   // an initialier.
12640   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12641     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12642 
12643     // Null EnumConstantDecl means a previous diagnostic has been emitted for
12644     // this constant.  Skip this enum since it may be ill-formed.
12645     if (!ECD) {
12646       return;
12647     }
12648 
12649     if (ECD->getInitExpr())
12650       continue;
12651 
12652     DupKey Key = GetDupKey(ECD->getInitVal());
12653     DeclOrVector &Entry = EnumMap[Key];
12654 
12655     // First time encountering this value.
12656     if (Entry.isNull())
12657       Entry = ECD;
12658   }
12659 
12660   // Create vectors for any values that has duplicates.
12661   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12662     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12663     if (!ValidDuplicateEnum(ECD, Enum))
12664       continue;
12665 
12666     DupKey Key = GetDupKey(ECD->getInitVal());
12667 
12668     DeclOrVector& Entry = EnumMap[Key];
12669     if (Entry.isNull())
12670       continue;
12671 
12672     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12673       // Ensure constants are different.
12674       if (D == ECD)
12675         continue;
12676 
12677       // Create new vector and push values onto it.
12678       ECDVector *Vec = new ECDVector();
12679       Vec->push_back(D);
12680       Vec->push_back(ECD);
12681 
12682       // Update entry to point to the duplicates vector.
12683       Entry = Vec;
12684 
12685       // Store the vector somewhere we can consult later for quick emission of
12686       // diagnostics.
12687       DupVector.push_back(Vec);
12688       continue;
12689     }
12690 
12691     ECDVector *Vec = Entry.get<ECDVector*>();
12692     // Make sure constants are not added more than once.
12693     if (*Vec->begin() == ECD)
12694       continue;
12695 
12696     Vec->push_back(ECD);
12697   }
12698 
12699   // Emit diagnostics.
12700   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12701                                   DupVectorEnd = DupVector.end();
12702        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12703     ECDVector *Vec = *DupVectorIter;
12704     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12705 
12706     // Emit warning for one enum constant.
12707     ECDVector::iterator I = Vec->begin();
12708     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12709       << (*I)->getName() << (*I)->getInitVal().toString(10)
12710       << (*I)->getSourceRange();
12711     ++I;
12712 
12713     // Emit one note for each of the remaining enum constants with
12714     // the same value.
12715     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12716       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12717         << (*I)->getName() << (*I)->getInitVal().toString(10)
12718         << (*I)->getSourceRange();
12719     delete Vec;
12720   }
12721 }
12722 
12723 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
12724                          SourceLocation RBraceLoc, Decl *EnumDeclX,
12725                          ArrayRef<Decl *> Elements,
12726                          Scope *S, AttributeList *Attr) {
12727   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
12728   QualType EnumType = Context.getTypeDeclType(Enum);
12729 
12730   if (Attr)
12731     ProcessDeclAttributeList(S, Enum, Attr);
12732 
12733   if (Enum->isDependentType()) {
12734     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12735       EnumConstantDecl *ECD =
12736         cast_or_null<EnumConstantDecl>(Elements[i]);
12737       if (!ECD) continue;
12738 
12739       ECD->setType(EnumType);
12740     }
12741 
12742     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
12743     return;
12744   }
12745 
12746   // TODO: If the result value doesn't fit in an int, it must be a long or long
12747   // long value.  ISO C does not support this, but GCC does as an extension,
12748   // emit a warning.
12749   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12750   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12751   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
12752 
12753   // Verify that all the values are okay, compute the size of the values, and
12754   // reverse the list.
12755   unsigned NumNegativeBits = 0;
12756   unsigned NumPositiveBits = 0;
12757 
12758   // Keep track of whether all elements have type int.
12759   bool AllElementsInt = true;
12760 
12761   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12762     EnumConstantDecl *ECD =
12763       cast_or_null<EnumConstantDecl>(Elements[i]);
12764     if (!ECD) continue;  // Already issued a diagnostic.
12765 
12766     const llvm::APSInt &InitVal = ECD->getInitVal();
12767 
12768     // Keep track of the size of positive and negative values.
12769     if (InitVal.isUnsigned() || InitVal.isNonNegative())
12770       NumPositiveBits = std::max(NumPositiveBits,
12771                                  (unsigned)InitVal.getActiveBits());
12772     else
12773       NumNegativeBits = std::max(NumNegativeBits,
12774                                  (unsigned)InitVal.getMinSignedBits());
12775 
12776     // Keep track of whether every enum element has type int (very commmon).
12777     if (AllElementsInt)
12778       AllElementsInt = ECD->getType() == Context.IntTy;
12779   }
12780 
12781   // Figure out the type that should be used for this enum.
12782   QualType BestType;
12783   unsigned BestWidth;
12784 
12785   // C++0x N3000 [conv.prom]p3:
12786   //   An rvalue of an unscoped enumeration type whose underlying
12787   //   type is not fixed can be converted to an rvalue of the first
12788   //   of the following types that can represent all the values of
12789   //   the enumeration: int, unsigned int, long int, unsigned long
12790   //   int, long long int, or unsigned long long int.
12791   // C99 6.4.4.3p2:
12792   //   An identifier declared as an enumeration constant has type int.
12793   // The C99 rule is modified by a gcc extension
12794   QualType BestPromotionType;
12795 
12796   bool Packed = Enum->hasAttr<PackedAttr>();
12797   // -fshort-enums is the equivalent to specifying the packed attribute on all
12798   // enum definitions.
12799   if (LangOpts.ShortEnums)
12800     Packed = true;
12801 
12802   if (Enum->isFixed()) {
12803     BestType = Enum->getIntegerType();
12804     if (BestType->isPromotableIntegerType())
12805       BestPromotionType = Context.getPromotedIntegerType(BestType);
12806     else
12807       BestPromotionType = BestType;
12808     // We don't need to set BestWidth, because BestType is going to be the type
12809     // of the enumerators, but we do anyway because otherwise some compilers
12810     // warn that it might be used uninitialized.
12811     BestWidth = CharWidth;
12812   }
12813   else if (NumNegativeBits) {
12814     // If there is a negative value, figure out the smallest integer type (of
12815     // int/long/longlong) that fits.
12816     // If it's packed, check also if it fits a char or a short.
12817     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
12818       BestType = Context.SignedCharTy;
12819       BestWidth = CharWidth;
12820     } else if (Packed && NumNegativeBits <= ShortWidth &&
12821                NumPositiveBits < ShortWidth) {
12822       BestType = Context.ShortTy;
12823       BestWidth = ShortWidth;
12824     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
12825       BestType = Context.IntTy;
12826       BestWidth = IntWidth;
12827     } else {
12828       BestWidth = Context.getTargetInfo().getLongWidth();
12829 
12830       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
12831         BestType = Context.LongTy;
12832       } else {
12833         BestWidth = Context.getTargetInfo().getLongLongWidth();
12834 
12835         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
12836           Diag(Enum->getLocation(), diag::warn_enum_too_large);
12837         BestType = Context.LongLongTy;
12838       }
12839     }
12840     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
12841   } else {
12842     // If there is no negative value, figure out the smallest type that fits
12843     // all of the enumerator values.
12844     // If it's packed, check also if it fits a char or a short.
12845     if (Packed && NumPositiveBits <= CharWidth) {
12846       BestType = Context.UnsignedCharTy;
12847       BestPromotionType = Context.IntTy;
12848       BestWidth = CharWidth;
12849     } else if (Packed && NumPositiveBits <= ShortWidth) {
12850       BestType = Context.UnsignedShortTy;
12851       BestPromotionType = Context.IntTy;
12852       BestWidth = ShortWidth;
12853     } else if (NumPositiveBits <= IntWidth) {
12854       BestType = Context.UnsignedIntTy;
12855       BestWidth = IntWidth;
12856       BestPromotionType
12857         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12858                            ? Context.UnsignedIntTy : Context.IntTy;
12859     } else if (NumPositiveBits <=
12860                (BestWidth = Context.getTargetInfo().getLongWidth())) {
12861       BestType = Context.UnsignedLongTy;
12862       BestPromotionType
12863         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12864                            ? Context.UnsignedLongTy : Context.LongTy;
12865     } else {
12866       BestWidth = Context.getTargetInfo().getLongLongWidth();
12867       assert(NumPositiveBits <= BestWidth &&
12868              "How could an initializer get larger than ULL?");
12869       BestType = Context.UnsignedLongLongTy;
12870       BestPromotionType
12871         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12872                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
12873     }
12874   }
12875 
12876   // Loop over all of the enumerator constants, changing their types to match
12877   // the type of the enum if needed.
12878   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12879     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12880     if (!ECD) continue;  // Already issued a diagnostic.
12881 
12882     // Standard C says the enumerators have int type, but we allow, as an
12883     // extension, the enumerators to be larger than int size.  If each
12884     // enumerator value fits in an int, type it as an int, otherwise type it the
12885     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
12886     // that X has type 'int', not 'unsigned'.
12887 
12888     // Determine whether the value fits into an int.
12889     llvm::APSInt InitVal = ECD->getInitVal();
12890 
12891     // If it fits into an integer type, force it.  Otherwise force it to match
12892     // the enum decl type.
12893     QualType NewTy;
12894     unsigned NewWidth;
12895     bool NewSign;
12896     if (!getLangOpts().CPlusPlus &&
12897         !Enum->isFixed() &&
12898         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
12899       NewTy = Context.IntTy;
12900       NewWidth = IntWidth;
12901       NewSign = true;
12902     } else if (ECD->getType() == BestType) {
12903       // Already the right type!
12904       if (getLangOpts().CPlusPlus)
12905         // C++ [dcl.enum]p4: Following the closing brace of an
12906         // enum-specifier, each enumerator has the type of its
12907         // enumeration.
12908         ECD->setType(EnumType);
12909       continue;
12910     } else {
12911       NewTy = BestType;
12912       NewWidth = BestWidth;
12913       NewSign = BestType->isSignedIntegerOrEnumerationType();
12914     }
12915 
12916     // Adjust the APSInt value.
12917     InitVal = InitVal.extOrTrunc(NewWidth);
12918     InitVal.setIsSigned(NewSign);
12919     ECD->setInitVal(InitVal);
12920 
12921     // Adjust the Expr initializer and type.
12922     if (ECD->getInitExpr() &&
12923         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
12924       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
12925                                                 CK_IntegralCast,
12926                                                 ECD->getInitExpr(),
12927                                                 /*base paths*/ 0,
12928                                                 VK_RValue));
12929     if (getLangOpts().CPlusPlus)
12930       // C++ [dcl.enum]p4: Following the closing brace of an
12931       // enum-specifier, each enumerator has the type of its
12932       // enumeration.
12933       ECD->setType(EnumType);
12934     else
12935       ECD->setType(NewTy);
12936   }
12937 
12938   Enum->completeDefinition(BestType, BestPromotionType,
12939                            NumPositiveBits, NumNegativeBits);
12940 
12941   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
12942 
12943   // Now that the enum type is defined, ensure it's not been underaligned.
12944   if (Enum->hasAttrs())
12945     CheckAlignasUnderalignment(Enum);
12946 }
12947 
12948 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12949                                   SourceLocation StartLoc,
12950                                   SourceLocation EndLoc) {
12951   StringLiteral *AsmString = cast<StringLiteral>(expr);
12952 
12953   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
12954                                                    AsmString, StartLoc,
12955                                                    EndLoc);
12956   CurContext->addDecl(New);
12957   return New;
12958 }
12959 
12960 static void checkModuleImportContext(Sema &S, Module *M,
12961                                      SourceLocation ImportLoc,
12962                                      DeclContext *DC) {
12963   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
12964     switch (LSD->getLanguage()) {
12965     case LinkageSpecDecl::lang_c:
12966       if (!M->IsExternC) {
12967         S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
12968           << M->getFullModuleName();
12969         S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
12970         return;
12971       }
12972       break;
12973     case LinkageSpecDecl::lang_cxx:
12974       break;
12975     }
12976     DC = LSD->getParent();
12977   }
12978 
12979   while (isa<LinkageSpecDecl>(DC))
12980     DC = DC->getParent();
12981   if (!isa<TranslationUnitDecl>(DC)) {
12982     S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
12983       << M->getFullModuleName() << DC;
12984     S.Diag(cast<Decl>(DC)->getLocStart(),
12985            diag::note_module_import_not_at_top_level)
12986       << DC;
12987   }
12988 }
12989 
12990 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12991                                    SourceLocation ImportLoc,
12992                                    ModuleIdPath Path) {
12993   Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
12994                                                 Module::AllVisible,
12995                                                 /*IsIncludeDirective=*/false);
12996   if (!Mod)
12997     return true;
12998 
12999   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
13000 
13001   SmallVector<SourceLocation, 2> IdentifierLocs;
13002   Module *ModCheck = Mod;
13003   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
13004     // If we've run out of module parents, just drop the remaining identifiers.
13005     // We need the length to be consistent.
13006     if (!ModCheck)
13007       break;
13008     ModCheck = ModCheck->Parent;
13009 
13010     IdentifierLocs.push_back(Path[I].second);
13011   }
13012 
13013   ImportDecl *Import = ImportDecl::Create(Context,
13014                                           Context.getTranslationUnitDecl(),
13015                                           AtLoc.isValid()? AtLoc : ImportLoc,
13016                                           Mod, IdentifierLocs);
13017   Context.getTranslationUnitDecl()->addDecl(Import);
13018   return Import;
13019 }
13020 
13021 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
13022   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
13023 
13024   // FIXME: Should we synthesize an ImportDecl here?
13025   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
13026                                          /*Complain=*/true);
13027 }
13028 
13029 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
13030   // Create the implicit import declaration.
13031   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13032   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13033                                                    Loc, Mod, Loc);
13034   TU->addDecl(ImportD);
13035   Consumer.HandleImplicitImportDecl(ImportD);
13036 
13037   // Make the module visible.
13038   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13039                                          /*Complain=*/false);
13040 }
13041 
13042 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13043                                       IdentifierInfo* AliasName,
13044                                       SourceLocation PragmaLoc,
13045                                       SourceLocation NameLoc,
13046                                       SourceLocation AliasNameLoc) {
13047   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13048                                     LookupOrdinaryName);
13049   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13050                                                     AliasName->getName(), 0);
13051 
13052   if (PrevDecl)
13053     PrevDecl->addAttr(Attr);
13054   else
13055     (void)ExtnameUndeclaredIdentifiers.insert(
13056       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13057 }
13058 
13059 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13060                              SourceLocation PragmaLoc,
13061                              SourceLocation NameLoc) {
13062   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13063 
13064   if (PrevDecl) {
13065     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13066   } else {
13067     (void)WeakUndeclaredIdentifiers.insert(
13068       std::pair<IdentifierInfo*,WeakInfo>
13069         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
13070   }
13071 }
13072 
13073 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13074                                 IdentifierInfo* AliasName,
13075                                 SourceLocation PragmaLoc,
13076                                 SourceLocation NameLoc,
13077                                 SourceLocation AliasNameLoc) {
13078   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13079                                     LookupOrdinaryName);
13080   WeakInfo W = WeakInfo(Name, NameLoc);
13081 
13082   if (PrevDecl) {
13083     if (!PrevDecl->hasAttr<AliasAttr>())
13084       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13085         DeclApplyPragmaWeak(TUScope, ND, W);
13086   } else {
13087     (void)WeakUndeclaredIdentifiers.insert(
13088       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13089   }
13090 }
13091 
13092 Decl *Sema::getObjCDeclContext() const {
13093   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13094 }
13095 
13096 AvailabilityResult Sema::getCurContextAvailability() const {
13097   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13098   // If we are within an Objective-C method, we should consult
13099   // both the availability of the method as well as the
13100   // enclosing class.  If the class is (say) deprecated,
13101   // the entire method is considered deprecated from the
13102   // purpose of checking if the current context is deprecated.
13103   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13104     AvailabilityResult R = MD->getAvailability();
13105     if (R != AR_Available)
13106       return R;
13107     D = MD->getClassInterface();
13108   }
13109   // If we are within an Objective-c @implementation, it
13110   // gets the same availability context as the @interface.
13111   else if (const ObjCImplementationDecl *ID =
13112             dyn_cast<ObjCImplementationDecl>(D)) {
13113     D = ID->getClassInterface();
13114   }
13115   return D->getAvailability();
13116 }
13117