SemaDecl.cpp revision b4609806e9232593ece09ce08b630836e825865c
10b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
20b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//
30b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//                     The LLVM Compiler Infrastructure
40b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//
50b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach// This file is distributed under the University of Illinois Open Source
60b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach// License. See LICENSE.TXT for details.
70b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//
80b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//===----------------------------------------------------------------------===//
90b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//
100b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//  This file implements semantic analysis for declarations.
110b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//
120b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach//===----------------------------------------------------------------------===//
130b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach
140b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach#include "Sema.h"
157c788888872233748da10a8177a9a1eb176c1bc8Peter Collingbourne#include "clang/AST/APValue.h"
160b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach#include "clang/AST/ASTConsumer.h"
170b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach#include "clang/AST/ASTContext.h"
180b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach#include "clang/AST/DeclObjC.h"
190b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach#include "clang/AST/ExprCXX.h"
200b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach#include "clang/Parse/DeclSpec.h"
210b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach#include "clang/Basic/Diagnostic.h"
220b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach#include "clang/Basic/TargetInfo.h"
2397c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach#include "clang/Basic/SourceManager.h"
2497c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
2597c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach#include "clang/Lex/Preprocessor.h"
2697c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach#include "clang/Lex/HeaderSearch.h"
2797c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach#include "llvm/ADT/SmallSet.h"
2897c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach#include "llvm/ADT/StringExtras.h"
2997c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbachusing namespace clang;
3097c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach
3197c02bf2409bccdb43c3822c438e3ff977d8514eJim GrosbachSema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S,
3228b810e9e4b11074a241aad87e1e09ec7859a691Jim Grosbach                               const CXXScopeSpec *SS) {
3397c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach  DeclContext *DC = 0;
3497c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach  if (SS) {
3597c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach    if (SS->isInvalid())
3697c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach      return 0;
3797c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach    DC = static_cast<DeclContext*>(SS->getScopeRep());
3897c02bf2409bccdb43c3822c438e3ff977d8514eJim Grosbach  }
390b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach  Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
403f2d5f60b31fd057c10f77b2e607b23a8c94f6d3Chris Lattner
410b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach  if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
420b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach                 isa<ObjCInterfaceDecl>(IIDecl) ||
430b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach                 isa<TagDecl>(IIDecl)))
443f2d5f60b31fd057c10f77b2e607b23a8c94f6d3Chris Lattner    return IIDecl;
450b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach  return 0;
460b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach}
470b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach
480b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim GrosbachDeclContext *Sema::getContainingDC(DeclContext *DC) {
490b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
500b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach    // A C++ out-of-line method will return to the file declaration context.
510b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach    if (MD->isOutOfLineDefinition())
520b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach      return MD->getLexicalDeclContext();
530b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach
540b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach    // A C++ inline method is parsed *after* the topmost class it was declared in
550b6a44afb92fed0365b6709c1f46b0c5e49e1a72Jim Grosbach    // is fully parsed (it's "complete").
56    // The parsing of a C++ inline method happens at the declaration context of
57    // the topmost (non-nested) class it is declared in.
58    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
59    DC = MD->getParent();
60    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
61      DC = RD;
62
63    // Return the declaration context of the topmost class the inline method is
64    // declared in.
65    return DC;
66  }
67
68  if (isa<ObjCMethodDecl>(DC))
69    return Context.getTranslationUnitDecl();
70
71  if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
72    return SD->getLexicalDeclContext();
73
74  return DC->getParent();
75}
76
77void Sema::PushDeclContext(DeclContext *DC) {
78  assert(getContainingDC(DC) == CurContext &&
79       "The next DeclContext should be lexically contained in the current one.");
80  CurContext = DC;
81}
82
83void Sema::PopDeclContext() {
84  assert(CurContext && "DeclContext imbalance!");
85  CurContext = getContainingDC(CurContext);
86}
87
88/// Add this decl to the scope shadowed decl chains.
89void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
90  S->AddDecl(D);
91
92  // C++ [basic.scope]p4:
93  //   -- exactly one declaration shall declare a class name or
94  //   enumeration name that is not a typedef name and the other
95  //   declarations shall all refer to the same object or
96  //   enumerator, or all refer to functions and function templates;
97  //   in this case the class name or enumeration name is hidden.
98  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
99    // We are pushing the name of a tag (enum or class).
100    IdentifierResolver::iterator
101        I = IdResolver.begin(TD->getIdentifier(),
102                             TD->getDeclContext(), false/*LookInParentCtx*/);
103    if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
104      // There is already a declaration with the same name in the same
105      // scope. It must be found before we find the new declaration,
106      // so swap the order on the shadowed declaration chain.
107
108      IdResolver.AddShadowedDecl(TD, *I);
109      return;
110    }
111  } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
112    FunctionDecl *FD = cast<FunctionDecl>(D);
113    // We are pushing the name of a function, which might be an
114    // overloaded name.
115    IdentifierResolver::iterator
116        I = IdResolver.begin(FD->getIdentifier(),
117                             FD->getDeclContext(), false/*LookInParentCtx*/);
118    if (I != IdResolver.end() &&
119        IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
120        (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
121      // There is already a declaration with the same name in the same
122      // scope. It must be a function or an overloaded function.
123      OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
124      if (!Ovl) {
125        // We haven't yet overloaded this function. Take the existing
126        // FunctionDecl and put it into an OverloadedFunctionDecl.
127        Ovl = OverloadedFunctionDecl::Create(Context,
128                                             FD->getDeclContext(),
129                                             FD->getIdentifier());
130        Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
131
132        // Remove the name binding to the existing FunctionDecl...
133        IdResolver.RemoveDecl(*I);
134
135        // ... and put the OverloadedFunctionDecl in its place.
136        IdResolver.AddDecl(Ovl);
137      }
138
139      // We have an OverloadedFunctionDecl. Add the new FunctionDecl
140      // to its list of overloads.
141      Ovl->addOverload(FD);
142
143      return;
144    }
145  }
146
147  IdResolver.AddDecl(D);
148}
149
150void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
151  if (S->decl_empty()) return;
152  assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
153
154  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
155       I != E; ++I) {
156    Decl *TmpD = static_cast<Decl*>(*I);
157    assert(TmpD && "This decl didn't get pushed??");
158
159    if (isa<CXXFieldDecl>(TmpD)) continue;
160
161    assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
162    ScopedDecl *D = cast<ScopedDecl>(TmpD);
163
164    IdentifierInfo *II = D->getIdentifier();
165    if (!II) continue;
166
167    // We only want to remove the decls from the identifier decl chains for
168    // local scopes, when inside a function/method.
169    if (S->getFnParent() != 0)
170      IdResolver.RemoveDecl(D);
171
172    // Chain this decl to the containing DeclContext.
173    D->setNext(CurContext->getDeclChain());
174    CurContext->setDeclChain(D);
175  }
176}
177
178/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
179/// return 0 if one not found.
180ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
181  // The third "scope" argument is 0 since we aren't enabling lazy built-in
182  // creation from this context.
183  Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
184
185  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
186}
187
188/// LookupDecl - Look up the inner-most declaration in the specified
189/// namespace.
190Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI, Scope *S,
191                       const DeclContext *LookupCtx,
192                       bool enableLazyBuiltinCreation) {
193  if (II == 0) return 0;
194  unsigned NS = NSI;
195  if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
196    NS |= Decl::IDNS_Tag;
197
198  IdentifierResolver::iterator
199    I = LookupCtx ? IdResolver.begin(II, LookupCtx, false/*LookInParentCtx*/) :
200                    IdResolver.begin(II, CurContext, true/*LookInParentCtx*/);
201  // Scan up the scope chain looking for a decl that matches this identifier
202  // that is in the appropriate namespace.  This search should not take long, as
203  // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
204  for (; I != IdResolver.end(); ++I)
205    if ((*I)->getIdentifierNamespace() & NS)
206      return *I;
207
208  // If we didn't find a use of this identifier, and if the identifier
209  // corresponds to a compiler builtin, create the decl object for the builtin
210  // now, injecting it into translation unit scope, and return it.
211  if (NS & Decl::IDNS_Ordinary) {
212    if (enableLazyBuiltinCreation &&
213        (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
214      // If this is a builtin on this (or all) targets, create the decl.
215      if (unsigned BuiltinID = II->getBuiltinID())
216        return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
217    }
218    if (getLangOptions().ObjC1) {
219      // @interface and @compatibility_alias introduce typedef-like names.
220      // Unlike typedef's, they can only be introduced at file-scope (and are
221      // therefore not scoped decls). They can, however, be shadowed by
222      // other names in IDNS_Ordinary.
223      ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
224      if (IDI != ObjCInterfaceDecls.end())
225        return IDI->second;
226      ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
227      if (I != ObjCAliasDecls.end())
228        return I->second->getClassInterface();
229    }
230  }
231  return 0;
232}
233
234void Sema::InitBuiltinVaListType() {
235  if (!Context.getBuiltinVaListType().isNull())
236    return;
237
238  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
239  Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
240  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
241  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
242}
243
244/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
245/// lazily create a decl for it.
246ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
247                                      Scope *S) {
248  Builtin::ID BID = (Builtin::ID)bid;
249
250  if (Context.BuiltinInfo.hasVAListUse(BID))
251    InitBuiltinVaListType();
252
253  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
254  FunctionDecl *New = FunctionDecl::Create(Context,
255                                           Context.getTranslationUnitDecl(),
256                                           SourceLocation(), II, R,
257                                           FunctionDecl::Extern, false, 0);
258
259  // Create Decl objects for each parameter, adding them to the
260  // FunctionDecl.
261  if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
262    llvm::SmallVector<ParmVarDecl*, 16> Params;
263    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
264      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
265                                           FT->getArgType(i), VarDecl::None, 0,
266                                           0));
267    New->setParams(&Params[0], Params.size());
268  }
269
270
271
272  // TUScope is the translation-unit scope to insert this function into.
273  PushOnScopeChains(New, TUScope);
274  return New;
275}
276
277/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
278/// everything from the standard library is defined.
279NamespaceDecl *Sema::GetStdNamespace() {
280  if (!StdNamespace) {
281    DeclContext *Global = Context.getTranslationUnitDecl();
282    Decl *Std = LookupDecl(Ident_StdNs, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
283                           0, Global, /*enableLazyBuiltinCreation=*/false);
284    StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
285  }
286  return StdNamespace;
287}
288
289/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
290/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
291/// situation, merging decls or emitting diagnostics as appropriate.
292///
293TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
294  // Allow multiple definitions for ObjC built-in typedefs.
295  // FIXME: Verify the underlying types are equivalent!
296  if (getLangOptions().ObjC1) {
297    const IdentifierInfo *typeIdent = New->getIdentifier();
298    if (typeIdent == Ident_id) {
299      Context.setObjCIdType(New);
300      return New;
301    } else if (typeIdent == Ident_Class) {
302      Context.setObjCClassType(New);
303      return New;
304    } else if (typeIdent == Ident_SEL) {
305      Context.setObjCSelType(New);
306      return New;
307    } else if (typeIdent == Ident_Protocol) {
308      Context.setObjCProtoType(New->getUnderlyingType());
309      return New;
310    }
311    // Fall through - the typedef name was not a builtin type.
312  }
313  // Verify the old decl was also a typedef.
314  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
315  if (!Old) {
316    Diag(New->getLocation(), diag::err_redefinition_different_kind,
317         New->getName());
318    Diag(OldD->getLocation(), diag::err_previous_definition);
319    return New;
320  }
321
322  // If the typedef types are not identical, reject them in all languages and
323  // with any extensions enabled.
324  if (Old->getUnderlyingType() != New->getUnderlyingType() &&
325      Context.getCanonicalType(Old->getUnderlyingType()) !=
326      Context.getCanonicalType(New->getUnderlyingType())) {
327    Diag(New->getLocation(), diag::err_redefinition_different_typedef,
328         New->getUnderlyingType().getAsString(),
329         Old->getUnderlyingType().getAsString());
330    Diag(Old->getLocation(), diag::err_previous_definition);
331    return Old;
332  }
333
334  if (getLangOptions().Microsoft) return New;
335
336  // Redeclaration of a type is a constraint violation (6.7.2.3p1).
337  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
338  // *either* declaration is in a system header. The code below implements
339  // this adhoc compatibility rule. FIXME: The following code will not
340  // work properly when compiling ".i" files (containing preprocessed output).
341  if (PP.getDiagnostics().getSuppressSystemWarnings()) {
342    SourceManager &SrcMgr = Context.getSourceManager();
343    if (SrcMgr.isInSystemHeader(Old->getLocation()))
344      return New;
345    if (SrcMgr.isInSystemHeader(New->getLocation()))
346      return New;
347  }
348
349  Diag(New->getLocation(), diag::err_redefinition, New->getName());
350  Diag(Old->getLocation(), diag::err_previous_definition);
351  return New;
352}
353
354/// DeclhasAttr - returns true if decl Declaration already has the target
355/// attribute.
356static bool DeclHasAttr(const Decl *decl, const Attr *target) {
357  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
358    if (attr->getKind() == target->getKind())
359      return true;
360
361  return false;
362}
363
364/// MergeAttributes - append attributes from the Old decl to the New one.
365static void MergeAttributes(Decl *New, Decl *Old) {
366  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
367
368  while (attr) {
369     tmp = attr;
370     attr = attr->getNext();
371
372    if (!DeclHasAttr(New, tmp)) {
373       New->addAttr(tmp);
374    } else {
375       tmp->setNext(0);
376       delete(tmp);
377    }
378  }
379
380  Old->invalidateAttrs();
381}
382
383/// MergeFunctionDecl - We just parsed a function 'New' from
384/// declarator D which has the same name and scope as a previous
385/// declaration 'Old'.  Figure out how to resolve this situation,
386/// merging decls or emitting diagnostics as appropriate.
387/// Redeclaration will be set true if this New is a redeclaration OldD.
388///
389/// In C++, New and Old must be declarations that are not
390/// overloaded. Use IsOverload to determine whether New and Old are
391/// overloaded, and to select the Old declaration that New should be
392/// merged with.
393FunctionDecl *
394Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
395  assert(!isa<OverloadedFunctionDecl>(OldD) &&
396         "Cannot merge with an overloaded function declaration");
397
398  Redeclaration = false;
399  // Verify the old decl was also a function.
400  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
401  if (!Old) {
402    Diag(New->getLocation(), diag::err_redefinition_different_kind,
403         New->getName());
404    Diag(OldD->getLocation(), diag::err_previous_definition);
405    return New;
406  }
407
408  // Determine whether the previous declaration was a definition,
409  // implicit declaration, or a declaration.
410  diag::kind PrevDiag;
411  if (Old->isThisDeclarationADefinition())
412    PrevDiag = diag::err_previous_definition;
413  else if (Old->isImplicit())
414    PrevDiag = diag::err_previous_implicit_declaration;
415  else
416    PrevDiag = diag::err_previous_declaration;
417
418  QualType OldQType = Context.getCanonicalType(Old->getType());
419  QualType NewQType = Context.getCanonicalType(New->getType());
420
421  if (getLangOptions().CPlusPlus) {
422    // (C++98 13.1p2):
423    //   Certain function declarations cannot be overloaded:
424    //     -- Function declarations that differ only in the return type
425    //        cannot be overloaded.
426    QualType OldReturnType
427      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
428    QualType NewReturnType
429      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
430    if (OldReturnType != NewReturnType) {
431      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
432      Diag(Old->getLocation(), PrevDiag);
433      return New;
434    }
435
436    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
437    const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
438    if (OldMethod && NewMethod) {
439      //    -- Member function declarations with the same name and the
440      //       same parameter types cannot be overloaded if any of them
441      //       is a static member function declaration.
442      if (OldMethod->isStatic() || NewMethod->isStatic()) {
443        Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
444        Diag(Old->getLocation(), PrevDiag);
445        return New;
446      }
447    }
448
449    // (C++98 8.3.5p3):
450    //   All declarations for a function shall agree exactly in both the
451    //   return type and the parameter-type-list.
452    if (OldQType == NewQType) {
453      // We have a redeclaration.
454      MergeAttributes(New, Old);
455      Redeclaration = true;
456      return MergeCXXFunctionDecl(New, Old);
457    }
458
459    // Fall through for conflicting redeclarations and redefinitions.
460  }
461
462  // C: Function types need to be compatible, not identical. This handles
463  // duplicate function decls like "void f(int); void f(enum X);" properly.
464  if (!getLangOptions().CPlusPlus &&
465      Context.typesAreCompatible(OldQType, NewQType)) {
466    MergeAttributes(New, Old);
467    Redeclaration = true;
468    return New;
469  }
470
471  // A function that has already been declared has been redeclared or defined
472  // with a different type- show appropriate diagnostic
473
474  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
475  // TODO: This is totally simplistic.  It should handle merging functions
476  // together etc, merging extern int X; int X; ...
477  Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
478  Diag(Old->getLocation(), PrevDiag);
479  return New;
480}
481
482/// Predicate for C "tentative" external object definitions (C99 6.9.2).
483static bool isTentativeDefinition(VarDecl *VD) {
484  if (VD->isFileVarDecl())
485    return (!VD->getInit() &&
486            (VD->getStorageClass() == VarDecl::None ||
487             VD->getStorageClass() == VarDecl::Static));
488  return false;
489}
490
491/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
492/// when dealing with C "tentative" external object definitions (C99 6.9.2).
493void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
494  bool VDIsTentative = isTentativeDefinition(VD);
495  bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
496
497  for (IdentifierResolver::iterator
498       I = IdResolver.begin(VD->getIdentifier(),
499                            VD->getDeclContext(), false/*LookInParentCtx*/),
500       E = IdResolver.end(); I != E; ++I) {
501    if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
502      VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
503
504      // Handle the following case:
505      //   int a[10];
506      //   int a[];   - the code below makes sure we set the correct type.
507      //   int a[11]; - this is an error, size isn't 10.
508      if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
509          OldDecl->getType()->isConstantArrayType())
510        VD->setType(OldDecl->getType());
511
512      // Check for "tentative" definitions. We can't accomplish this in
513      // MergeVarDecl since the initializer hasn't been attached.
514      if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
515        continue;
516
517      // Handle __private_extern__ just like extern.
518      if (OldDecl->getStorageClass() != VarDecl::Extern &&
519          OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
520          VD->getStorageClass() != VarDecl::Extern &&
521          VD->getStorageClass() != VarDecl::PrivateExtern) {
522        Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
523        Diag(OldDecl->getLocation(), diag::err_previous_definition);
524      }
525    }
526  }
527}
528
529/// MergeVarDecl - We just parsed a variable 'New' which has the same name
530/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
531/// situation, merging decls or emitting diagnostics as appropriate.
532///
533/// Tentative definition rules (C99 6.9.2p2) are checked by
534/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
535/// definitions here, since the initializer hasn't been attached.
536///
537VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
538  // Verify the old decl was also a variable.
539  VarDecl *Old = dyn_cast<VarDecl>(OldD);
540  if (!Old) {
541    Diag(New->getLocation(), diag::err_redefinition_different_kind,
542         New->getName());
543    Diag(OldD->getLocation(), diag::err_previous_definition);
544    return New;
545  }
546
547  MergeAttributes(New, Old);
548
549  // Verify the types match.
550  QualType OldCType = Context.getCanonicalType(Old->getType());
551  QualType NewCType = Context.getCanonicalType(New->getType());
552  if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
553    Diag(New->getLocation(), diag::err_redefinition, New->getName());
554    Diag(Old->getLocation(), diag::err_previous_definition);
555    return New;
556  }
557  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
558  if (New->getStorageClass() == VarDecl::Static &&
559      (Old->getStorageClass() == VarDecl::None ||
560       Old->getStorageClass() == VarDecl::Extern)) {
561    Diag(New->getLocation(), diag::err_static_non_static, New->getName());
562    Diag(Old->getLocation(), diag::err_previous_definition);
563    return New;
564  }
565  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
566  if (New->getStorageClass() != VarDecl::Static &&
567      Old->getStorageClass() == VarDecl::Static) {
568    Diag(New->getLocation(), diag::err_non_static_static, New->getName());
569    Diag(Old->getLocation(), diag::err_previous_definition);
570    return New;
571  }
572  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
573  if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
574    Diag(New->getLocation(), diag::err_redefinition, New->getName());
575    Diag(Old->getLocation(), diag::err_previous_definition);
576  }
577  return New;
578}
579
580/// CheckParmsForFunctionDef - Check that the parameters of the given
581/// function are appropriate for the definition of a function. This
582/// takes care of any checks that cannot be performed on the
583/// declaration itself, e.g., that the types of each of the function
584/// parameters are complete.
585bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
586  bool HasInvalidParm = false;
587  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
588    ParmVarDecl *Param = FD->getParamDecl(p);
589
590    // C99 6.7.5.3p4: the parameters in a parameter type list in a
591    // function declarator that is part of a function definition of
592    // that function shall not have incomplete type.
593    if (Param->getType()->isIncompleteType() &&
594        !Param->isInvalidDecl()) {
595      Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
596           Param->getType().getAsString());
597      Param->setInvalidDecl();
598      HasInvalidParm = true;
599    }
600  }
601
602  return HasInvalidParm;
603}
604
605/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
606/// no declarator (e.g. "struct foo;") is parsed.
607Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
608  // TODO: emit error on 'int;' or 'const enum foo;'.
609  // TODO: emit error on 'typedef int;'
610  // if (!DS.isMissingDeclaratorOk()) Diag(...);
611
612  return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
613}
614
615bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
616  // Get the type before calling CheckSingleAssignmentConstraints(), since
617  // it can promote the expression.
618  QualType InitType = Init->getType();
619
620  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
621  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
622                                  InitType, Init, "initializing");
623}
624
625bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
626  const ArrayType *AT = Context.getAsArrayType(DeclT);
627
628  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
629    // C99 6.7.8p14. We have an array of character type with unknown size
630    // being initialized to a string literal.
631    llvm::APSInt ConstVal(32);
632    ConstVal = strLiteral->getByteLength() + 1;
633    // Return a new array type (C99 6.7.8p22).
634    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
635                                         ArrayType::Normal, 0);
636  } else {
637    const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
638    // C99 6.7.8p14. We have an array of character type with known size.
639    // FIXME: Avoid truncation for 64-bit length strings.
640    if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
641      Diag(strLiteral->getSourceRange().getBegin(),
642           diag::warn_initializer_string_for_char_array_too_long,
643           strLiteral->getSourceRange());
644  }
645  // Set type from "char *" to "constant array of char".
646  strLiteral->setType(DeclT);
647  // For now, we always return false (meaning success).
648  return false;
649}
650
651StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
652  const ArrayType *AT = Context.getAsArrayType(DeclType);
653  if (AT && AT->getElementType()->isCharType()) {
654    return dyn_cast<StringLiteral>(Init);
655  }
656  return 0;
657}
658
659bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
660                                 SourceLocation InitLoc,
661                                 std::string InitEntity) {
662  // C++ [dcl.init.ref]p1:
663  //   A variable declared to be a T&, that is “reference to type T”
664  //   (8.3.2), shall be initialized by an object, or function, of
665  //   type T or by an object that can be converted into a T.
666  if (DeclType->isReferenceType())
667    return CheckReferenceInit(Init, DeclType);
668
669  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
670  // of unknown size ("[]") or an object type that is not a variable array type.
671  if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
672    return Diag(InitLoc,
673                diag::err_variable_object_no_init,
674                VAT->getSizeExpr()->getSourceRange());
675
676  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
677  if (!InitList) {
678    // FIXME: Handle wide strings
679    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
680      return CheckStringLiteralInit(strLiteral, DeclType);
681
682    // C++ [dcl.init]p14:
683    //   -- If the destination type is a (possibly cv-qualified) class
684    //      type:
685    if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
686      QualType DeclTypeC = Context.getCanonicalType(DeclType);
687      QualType InitTypeC = Context.getCanonicalType(Init->getType());
688
689      //   -- If the initialization is direct-initialization, or if it is
690      //      copy-initialization where the cv-unqualified version of the
691      //      source type is the same class as, or a derived class of, the
692      //      class of the destination, constructors are considered.
693      if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
694          IsDerivedFrom(InitTypeC, DeclTypeC)) {
695        CXXConstructorDecl *Constructor
696          = PerformInitializationByConstructor(DeclType, &Init, 1,
697                                               InitLoc, Init->getSourceRange(),
698                                               InitEntity, IK_Copy);
699        return Constructor == 0;
700      }
701
702      //   -- Otherwise (i.e., for the remaining copy-initialization
703      //      cases), user-defined conversion sequences that can
704      //      convert from the source type to the destination type or
705      //      (when a conversion function is used) to a derived class
706      //      thereof are enumerated as described in 13.3.1.4, and the
707      //      best one is chosen through overload resolution
708      //      (13.3). If the conversion cannot be done or is
709      //      ambiguous, the initialization is ill-formed. The
710      //      function selected is called with the initializer
711      //      expression as its argument; if the function is a
712      //      constructor, the call initializes a temporary of the
713      //      destination type.
714      // FIXME: We're pretending to do copy elision here; return to
715      // this when we have ASTs for such things.
716      if (PerformImplicitConversion(Init, DeclType))
717        return Diag(InitLoc,
718                    diag::err_typecheck_convert_incompatible,
719                    DeclType.getAsString(), InitEntity,
720                    "initializing",
721                    Init->getSourceRange());
722      else
723        return false;
724    }
725
726    // C99 6.7.8p16.
727    if (DeclType->isArrayType())
728      return Diag(Init->getLocStart(),
729                  diag::err_array_init_list_required,
730                  Init->getSourceRange());
731
732    return CheckSingleInitializer(Init, DeclType);
733  } else if (getLangOptions().CPlusPlus) {
734    // C++ [dcl.init]p14:
735    //   [...] If the class is an aggregate (8.5.1), and the initializer
736    //   is a brace-enclosed list, see 8.5.1.
737    //
738    // Note: 8.5.1 is handled below; here, we diagnose the case where
739    // we have an initializer list and a destination type that is not
740    // an aggregate.
741    // FIXME: In C++0x, this is yet another form of initialization.
742    if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
743      const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
744      if (!ClassDecl->isAggregate())
745        return Diag(InitLoc,
746                    diag::err_init_non_aggr_init_list,
747                    DeclType.getAsString(),
748                    Init->getSourceRange());
749    }
750  }
751
752  InitListChecker CheckInitList(this, InitList, DeclType);
753  return CheckInitList.HadError();
754}
755
756Sema::DeclTy *
757Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
758  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
759  IdentifierInfo *II = D.getIdentifier();
760
761  // All of these full declarators require an identifier.  If it doesn't have
762  // one, the ParsedFreeStandingDeclSpec action should be used.
763  if (II == 0) {
764    if (!D.getInvalidType())  // Reject this if we think it is valid.
765      Diag(D.getDeclSpec().getSourceRange().getBegin(),
766           diag::err_declarator_need_ident,
767           D.getDeclSpec().getSourceRange(), D.getSourceRange());
768    return 0;
769  }
770
771  // The scope passed in may not be a decl scope.  Zip up the scope tree until
772  // we find one that is.
773  while ((S->getFlags() & Scope::DeclScope) == 0)
774    S = S->getParent();
775
776  DeclContext *DC;
777  Decl *PrevDecl;
778  ScopedDecl *New;
779  bool InvalidDecl = false;
780
781  // See if this is a redefinition of a variable in the same scope.
782  if (!D.getCXXScopeSpec().isSet()) {
783    DC = CurContext;
784    PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
785  } else { // Something like "int foo::x;"
786    DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
787    PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S, DC);
788
789    // C++ 7.3.1.2p2:
790    // Members (including explicit specializations of templates) of a named
791    // namespace can also be defined outside that namespace by explicit
792    // qualification of the name being defined, provided that the entity being
793    // defined was already declared in the namespace and the definition appears
794    // after the point of declaration in a namespace that encloses the
795    // declarations namespace.
796    //
797    if (PrevDecl == 0) {
798      // No previous declaration in the qualifying scope.
799      Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member,
800           II->getName(), D.getCXXScopeSpec().getRange());
801    } else if (!CurContext->Encloses(DC)) {
802      // The qualifying scope doesn't enclose the original declaration.
803      // Emit diagnostic based on current scope.
804      SourceLocation L = D.getIdentifierLoc();
805      SourceRange R = D.getCXXScopeSpec().getRange();
806      if (isa<FunctionDecl>(CurContext)) {
807        Diag(L, diag::err_invalid_declarator_in_function, II->getName(), R);
808      } else {
809      Diag(L, diag::err_invalid_declarator_scope, II->getName(),
810           cast<NamedDecl>(DC)->getName(), R);
811      }
812    }
813  }
814
815  // In C++, the previous declaration we find might be a tag type
816  // (class or enum). In this case, the new declaration will hide the
817  // tag type.
818  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
819    PrevDecl = 0;
820
821  QualType R = GetTypeForDeclarator(D, S);
822  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
823
824  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
825    // Check that there are no default arguments (C++ only).
826    if (getLangOptions().CPlusPlus)
827      CheckExtraCXXDefaultArguments(D);
828
829    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
830    if (!NewTD) return 0;
831
832    // Handle attributes prior to checking for duplicates in MergeVarDecl
833    ProcessDeclAttributes(NewTD, D);
834    // Merge the decl with the existing one if appropriate. If the decl is
835    // in an outer scope, it isn't the same thing.
836    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
837      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
838      if (NewTD == 0) return 0;
839    }
840    New = NewTD;
841    if (S->getFnParent() == 0) {
842      // C99 6.7.7p2: If a typedef name specifies a variably modified type
843      // then it shall have block scope.
844      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
845        // FIXME: Diagnostic needs to be fixed.
846        Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
847        InvalidDecl = true;
848      }
849    }
850  } else if (R.getTypePtr()->isFunctionType()) {
851    FunctionDecl::StorageClass SC = FunctionDecl::None;
852    switch (D.getDeclSpec().getStorageClassSpec()) {
853      default: assert(0 && "Unknown storage class!");
854      case DeclSpec::SCS_auto:
855      case DeclSpec::SCS_register:
856        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
857             R.getAsString());
858        InvalidDecl = true;
859        break;
860      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
861      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
862      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
863      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
864    }
865
866    bool isInline = D.getDeclSpec().isInlineSpecified();
867    // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
868    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
869
870    FunctionDecl *NewFD;
871    if (D.getKind() == Declarator::DK_Constructor) {
872      // This is a C++ constructor declaration.
873      assert(DC->isCXXRecord() &&
874             "Constructors can only be declared in a member context");
875
876      bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
877
878      // Create the new declaration
879      NewFD = CXXConstructorDecl::Create(Context,
880                                         cast<CXXRecordDecl>(DC),
881                                         D.getIdentifierLoc(), II, R,
882                                         isExplicit, isInline,
883                                         /*isImplicitlyDeclared=*/false);
884
885      if (isInvalidDecl)
886        NewFD->setInvalidDecl();
887    } else if (D.getKind() == Declarator::DK_Destructor) {
888      // This is a C++ destructor declaration.
889      if (DC->isCXXRecord()) {
890        bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
891
892        NewFD = CXXDestructorDecl::Create(Context,
893                                          cast<CXXRecordDecl>(DC),
894                                          D.getIdentifierLoc(), II, R,
895                                          isInline,
896                                          /*isImplicitlyDeclared=*/false);
897
898        if (isInvalidDecl)
899          NewFD->setInvalidDecl();
900      } else {
901        Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
902        // Create a FunctionDecl to satisfy the function definition parsing
903        // code path.
904        NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
905                                     II, R, SC, isInline, LastDeclarator,
906                                     // FIXME: Move to DeclGroup...
907                                   D.getDeclSpec().getSourceRange().getBegin());
908        NewFD->setInvalidDecl();
909      }
910    } else if (D.getKind() == Declarator::DK_Conversion) {
911      if (!DC->isCXXRecord()) {
912        Diag(D.getIdentifierLoc(),
913             diag::err_conv_function_not_member);
914        return 0;
915      } else {
916        bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
917
918        NewFD = CXXConversionDecl::Create(Context,
919                                          cast<CXXRecordDecl>(DC),
920                                          D.getIdentifierLoc(), II, R,
921                                          isInline, isExplicit);
922
923        if (isInvalidDecl)
924          NewFD->setInvalidDecl();
925      }
926    } else if (DC->isCXXRecord()) {
927      // This is a C++ method declaration.
928      NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
929                                    D.getIdentifierLoc(), II, R,
930                                    (SC == FunctionDecl::Static), isInline,
931                                    LastDeclarator);
932    } else {
933      NewFD = FunctionDecl::Create(Context, DC,
934                                   D.getIdentifierLoc(),
935                                   II, R, SC, isInline, LastDeclarator,
936                                   // FIXME: Move to DeclGroup...
937                                   D.getDeclSpec().getSourceRange().getBegin());
938    }
939    // Handle attributes.
940    ProcessDeclAttributes(NewFD, D);
941
942    // Handle GNU asm-label extension (encoded as an attribute).
943    if (Expr *E = (Expr*) D.getAsmLabel()) {
944      // The parser guarantees this is a string.
945      StringLiteral *SE = cast<StringLiteral>(E);
946      NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
947                                                  SE->getByteLength())));
948    }
949
950    // Copy the parameter declarations from the declarator D to
951    // the function declaration NewFD, if they are available.
952    if (D.getNumTypeObjects() > 0) {
953      DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
954
955      // Create Decl objects for each parameter, adding them to the
956      // FunctionDecl.
957      llvm::SmallVector<ParmVarDecl*, 16> Params;
958
959      // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
960      // function that takes no arguments, not a function that takes a
961      // single void argument.
962      // We let through "const void" here because Sema::GetTypeForDeclarator
963      // already checks for that case.
964      if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
965          FTI.ArgInfo[0].Param &&
966          ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
967        // empty arg list, don't push any params.
968        ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
969
970        // In C++, the empty parameter-type-list must be spelled "void"; a
971        // typedef of void is not permitted.
972        if (getLangOptions().CPlusPlus &&
973            Param->getType().getUnqualifiedType() != Context.VoidTy) {
974          Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
975        }
976      } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
977        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
978          Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
979      }
980
981      NewFD->setParams(&Params[0], Params.size());
982    } else if (R->getAsTypedefType()) {
983      // When we're declaring a function with a typedef, as in the
984      // following example, we'll need to synthesize (unnamed)
985      // parameters for use in the declaration.
986      //
987      // @code
988      // typedef void fn(int);
989      // fn f;
990      // @endcode
991      const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
992      if (!FT) {
993        // This is a typedef of a function with no prototype, so we
994        // don't need to do anything.
995      } else if ((FT->getNumArgs() == 0) ||
996          (FT->getNumArgs() == 1 && !FT->isVariadic() &&
997           FT->getArgType(0)->isVoidType())) {
998        // This is a zero-argument function. We don't need to do anything.
999      } else {
1000        // Synthesize a parameter for each argument type.
1001        llvm::SmallVector<ParmVarDecl*, 16> Params;
1002        for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1003             ArgType != FT->arg_type_end(); ++ArgType) {
1004          Params.push_back(ParmVarDecl::Create(Context, DC,
1005                                               SourceLocation(), 0,
1006                                               *ArgType, VarDecl::None,
1007                                               0, 0));
1008        }
1009
1010        NewFD->setParams(&Params[0], Params.size());
1011      }
1012    }
1013
1014    // C++ constructors and destructors are handled by separate
1015    // routines, since they don't require any declaration merging (C++
1016    // [class.mfct]p2) and they aren't ever pushed into scope, because
1017    // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1018    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1019      return ActOnConstructorDeclarator(Constructor);
1020    else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1021      return ActOnDestructorDeclarator(Destructor);
1022    else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1023      return ActOnConversionDeclarator(Conversion);
1024
1025    // Extra checking for C++ overloaded operators (C++ [over.oper]).
1026    if (NewFD->isOverloadedOperator() &&
1027        CheckOverloadedOperatorDeclaration(NewFD))
1028      NewFD->setInvalidDecl();
1029
1030    // Merge the decl with the existing one if appropriate. Since C functions
1031    // are in a flat namespace, make sure we consider decls in outer scopes.
1032    if (PrevDecl &&
1033        (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1034      bool Redeclaration = false;
1035
1036      // If C++, determine whether NewFD is an overload of PrevDecl or
1037      // a declaration that requires merging. If it's an overload,
1038      // there's no more work to do here; we'll just add the new
1039      // function to the scope.
1040      OverloadedFunctionDecl::function_iterator MatchedDecl;
1041      if (!getLangOptions().CPlusPlus ||
1042          !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1043        Decl *OldDecl = PrevDecl;
1044
1045        // If PrevDecl was an overloaded function, extract the
1046        // FunctionDecl that matched.
1047        if (isa<OverloadedFunctionDecl>(PrevDecl))
1048          OldDecl = *MatchedDecl;
1049
1050        // NewFD and PrevDecl represent declarations that need to be
1051        // merged.
1052        NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1053
1054        if (NewFD == 0) return 0;
1055        if (Redeclaration) {
1056          NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1057
1058          if (OldDecl == PrevDecl) {
1059            // Remove the name binding for the previous
1060            // declaration. We'll add the binding back later, but then
1061            // it will refer to the new declaration (which will
1062            // contain more information).
1063            IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1064          } else {
1065            // We need to update the OverloadedFunctionDecl with the
1066            // latest declaration of this function, so that name
1067            // lookup will always refer to the latest declaration of
1068            // this function.
1069            *MatchedDecl = NewFD;
1070
1071            // Add the redeclaration to the current scope, since we'll
1072            // be skipping PushOnScopeChains.
1073            S->AddDecl(NewFD);
1074
1075            return NewFD;
1076          }
1077        }
1078      }
1079    }
1080    New = NewFD;
1081
1082    // In C++, check default arguments now that we have merged decls.
1083    if (getLangOptions().CPlusPlus)
1084      CheckCXXDefaultArguments(NewFD);
1085  } else {
1086    // Check that there are no default arguments (C++ only).
1087    if (getLangOptions().CPlusPlus)
1088      CheckExtraCXXDefaultArguments(D);
1089
1090    if (R.getTypePtr()->isObjCInterfaceType()) {
1091      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1092           D.getIdentifier()->getName());
1093      InvalidDecl = true;
1094    }
1095
1096    VarDecl *NewVD;
1097    VarDecl::StorageClass SC;
1098    switch (D.getDeclSpec().getStorageClassSpec()) {
1099    default: assert(0 && "Unknown storage class!");
1100    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
1101    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
1102    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
1103    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
1104    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
1105    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1106    }
1107    if (DC->isCXXRecord()) {
1108      assert(SC == VarDecl::Static && "Invalid storage class for member!");
1109      // This is a static data member for a C++ class.
1110      NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1111                                      D.getIdentifierLoc(), II,
1112                                      R, LastDeclarator);
1113    } else {
1114      bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1115      if (S->getFnParent() == 0) {
1116        // C99 6.9p2: The storage-class specifiers auto and register shall not
1117        // appear in the declaration specifiers in an external declaration.
1118        if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1119          Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1120               R.getAsString());
1121          InvalidDecl = true;
1122        }
1123      }
1124        NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1125                                II, R, SC, LastDeclarator,
1126                                // FIXME: Move to DeclGroup...
1127                                D.getDeclSpec().getSourceRange().getBegin());
1128        NewVD->setThreadSpecified(ThreadSpecified);
1129    }
1130    // Handle attributes prior to checking for duplicates in MergeVarDecl
1131    ProcessDeclAttributes(NewVD, D);
1132
1133    // Handle GNU asm-label extension (encoded as an attribute).
1134    if (Expr *E = (Expr*) D.getAsmLabel()) {
1135      // The parser guarantees this is a string.
1136      StringLiteral *SE = cast<StringLiteral>(E);
1137      NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1138                                                  SE->getByteLength())));
1139    }
1140
1141    // Emit an error if an address space was applied to decl with local storage.
1142    // This includes arrays of objects with address space qualifiers, but not
1143    // automatic variables that point to other address spaces.
1144    // ISO/IEC TR 18037 S5.1.2
1145    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1146      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1147      InvalidDecl = true;
1148    }
1149    // Merge the decl with the existing one if appropriate. If the decl is
1150    // in an outer scope, it isn't the same thing.
1151    if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1152      NewVD = MergeVarDecl(NewVD, PrevDecl);
1153      if (NewVD == 0) return 0;
1154    }
1155    New = NewVD;
1156  }
1157
1158  // Set the lexical context. If the declarator has a C++ scope specifier, the
1159  // lexical context will be different from the semantic context.
1160  New->setLexicalDeclContext(CurContext);
1161
1162  // If this has an identifier, add it to the scope stack.
1163  if (II)
1164    PushOnScopeChains(New, S);
1165  // If any semantic error occurred, mark the decl as invalid.
1166  if (D.getInvalidType() || InvalidDecl)
1167    New->setInvalidDecl();
1168
1169  return New;
1170}
1171
1172void Sema::InitializerElementNotConstant(const Expr *Init) {
1173  Diag(Init->getExprLoc(),
1174       diag::err_init_element_not_constant, Init->getSourceRange());
1175}
1176
1177bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1178  switch (Init->getStmtClass()) {
1179  default:
1180    InitializerElementNotConstant(Init);
1181    return true;
1182  case Expr::ParenExprClass: {
1183    const ParenExpr* PE = cast<ParenExpr>(Init);
1184    return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1185  }
1186  case Expr::CompoundLiteralExprClass:
1187    return cast<CompoundLiteralExpr>(Init)->isFileScope();
1188  case Expr::DeclRefExprClass: {
1189    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1190    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1191      if (VD->hasGlobalStorage())
1192        return false;
1193      InitializerElementNotConstant(Init);
1194      return true;
1195    }
1196    if (isa<FunctionDecl>(D))
1197      return false;
1198    InitializerElementNotConstant(Init);
1199    return true;
1200  }
1201  case Expr::MemberExprClass: {
1202    const MemberExpr *M = cast<MemberExpr>(Init);
1203    if (M->isArrow())
1204      return CheckAddressConstantExpression(M->getBase());
1205    return CheckAddressConstantExpressionLValue(M->getBase());
1206  }
1207  case Expr::ArraySubscriptExprClass: {
1208    // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1209    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1210    return CheckAddressConstantExpression(ASE->getBase()) ||
1211           CheckArithmeticConstantExpression(ASE->getIdx());
1212  }
1213  case Expr::StringLiteralClass:
1214  case Expr::PredefinedExprClass:
1215    return false;
1216  case Expr::UnaryOperatorClass: {
1217    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1218
1219    // C99 6.6p9
1220    if (Exp->getOpcode() == UnaryOperator::Deref)
1221      return CheckAddressConstantExpression(Exp->getSubExpr());
1222
1223    InitializerElementNotConstant(Init);
1224    return true;
1225  }
1226  }
1227}
1228
1229bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1230  switch (Init->getStmtClass()) {
1231  default:
1232    InitializerElementNotConstant(Init);
1233    return true;
1234  case Expr::ParenExprClass:
1235    return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
1236  case Expr::StringLiteralClass:
1237  case Expr::ObjCStringLiteralClass:
1238    return false;
1239  case Expr::CallExprClass:
1240  case Expr::CXXOperatorCallExprClass:
1241    // __builtin___CFStringMakeConstantString is a valid constant l-value.
1242    if (cast<CallExpr>(Init)->isBuiltinCall() ==
1243           Builtin::BI__builtin___CFStringMakeConstantString)
1244      return false;
1245
1246    InitializerElementNotConstant(Init);
1247    return true;
1248
1249  case Expr::UnaryOperatorClass: {
1250    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1251
1252    // C99 6.6p9
1253    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1254      return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1255
1256    if (Exp->getOpcode() == UnaryOperator::Extension)
1257      return CheckAddressConstantExpression(Exp->getSubExpr());
1258
1259    InitializerElementNotConstant(Init);
1260    return true;
1261  }
1262  case Expr::BinaryOperatorClass: {
1263    // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1264    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1265
1266    Expr *PExp = Exp->getLHS();
1267    Expr *IExp = Exp->getRHS();
1268    if (IExp->getType()->isPointerType())
1269      std::swap(PExp, IExp);
1270
1271    // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1272    return CheckAddressConstantExpression(PExp) ||
1273           CheckArithmeticConstantExpression(IExp);
1274  }
1275  case Expr::ImplicitCastExprClass:
1276  case Expr::CStyleCastExprClass: {
1277    const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
1278    if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1279      // Check for implicit promotion
1280      if (SubExpr->getType()->isFunctionType() ||
1281          SubExpr->getType()->isArrayType())
1282        return CheckAddressConstantExpressionLValue(SubExpr);
1283    }
1284
1285    // Check for pointer->pointer cast
1286    if (SubExpr->getType()->isPointerType())
1287      return CheckAddressConstantExpression(SubExpr);
1288
1289    if (SubExpr->getType()->isIntegralType()) {
1290      // Check for the special-case of a pointer->int->pointer cast;
1291      // this isn't standard, but some code requires it. See
1292      // PR2720 for an example.
1293      if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1294        if (SubCast->getSubExpr()->getType()->isPointerType()) {
1295          unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1296          unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1297          if (IntWidth >= PointerWidth) {
1298            return CheckAddressConstantExpression(SubCast->getSubExpr());
1299          }
1300        }
1301      }
1302    }
1303    if (SubExpr->getType()->isArithmeticType()) {
1304      return CheckArithmeticConstantExpression(SubExpr);
1305    }
1306
1307    InitializerElementNotConstant(Init);
1308    return true;
1309  }
1310  case Expr::ConditionalOperatorClass: {
1311    // FIXME: Should we pedwarn here?
1312    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1313    if (!Exp->getCond()->getType()->isArithmeticType()) {
1314      InitializerElementNotConstant(Init);
1315      return true;
1316    }
1317    if (CheckArithmeticConstantExpression(Exp->getCond()))
1318      return true;
1319    if (Exp->getLHS() &&
1320        CheckAddressConstantExpression(Exp->getLHS()))
1321      return true;
1322    return CheckAddressConstantExpression(Exp->getRHS());
1323  }
1324  case Expr::AddrLabelExprClass:
1325    return false;
1326  }
1327}
1328
1329static const Expr* FindExpressionBaseAddress(const Expr* E);
1330
1331static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1332  switch (E->getStmtClass()) {
1333  default:
1334    return E;
1335  case Expr::ParenExprClass: {
1336    const ParenExpr* PE = cast<ParenExpr>(E);
1337    return FindExpressionBaseAddressLValue(PE->getSubExpr());
1338  }
1339  case Expr::MemberExprClass: {
1340    const MemberExpr *M = cast<MemberExpr>(E);
1341    if (M->isArrow())
1342      return FindExpressionBaseAddress(M->getBase());
1343    return FindExpressionBaseAddressLValue(M->getBase());
1344  }
1345  case Expr::ArraySubscriptExprClass: {
1346    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1347    return FindExpressionBaseAddress(ASE->getBase());
1348  }
1349  case Expr::UnaryOperatorClass: {
1350    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1351
1352    if (Exp->getOpcode() == UnaryOperator::Deref)
1353      return FindExpressionBaseAddress(Exp->getSubExpr());
1354
1355    return E;
1356  }
1357  }
1358}
1359
1360static const Expr* FindExpressionBaseAddress(const Expr* E) {
1361  switch (E->getStmtClass()) {
1362  default:
1363    return E;
1364  case Expr::ParenExprClass: {
1365    const ParenExpr* PE = cast<ParenExpr>(E);
1366    return FindExpressionBaseAddress(PE->getSubExpr());
1367  }
1368  case Expr::UnaryOperatorClass: {
1369    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1370
1371    // C99 6.6p9
1372    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1373      return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1374
1375    if (Exp->getOpcode() == UnaryOperator::Extension)
1376      return FindExpressionBaseAddress(Exp->getSubExpr());
1377
1378    return E;
1379  }
1380  case Expr::BinaryOperatorClass: {
1381    const BinaryOperator *Exp = cast<BinaryOperator>(E);
1382
1383    Expr *PExp = Exp->getLHS();
1384    Expr *IExp = Exp->getRHS();
1385    if (IExp->getType()->isPointerType())
1386      std::swap(PExp, IExp);
1387
1388    return FindExpressionBaseAddress(PExp);
1389  }
1390  case Expr::ImplicitCastExprClass: {
1391    const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1392
1393    // Check for implicit promotion
1394    if (SubExpr->getType()->isFunctionType() ||
1395        SubExpr->getType()->isArrayType())
1396      return FindExpressionBaseAddressLValue(SubExpr);
1397
1398    // Check for pointer->pointer cast
1399    if (SubExpr->getType()->isPointerType())
1400      return FindExpressionBaseAddress(SubExpr);
1401
1402    // We assume that we have an arithmetic expression here;
1403    // if we don't, we'll figure it out later
1404    return 0;
1405  }
1406  case Expr::CStyleCastExprClass: {
1407    const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1408
1409    // Check for pointer->pointer cast
1410    if (SubExpr->getType()->isPointerType())
1411      return FindExpressionBaseAddress(SubExpr);
1412
1413    // We assume that we have an arithmetic expression here;
1414    // if we don't, we'll figure it out later
1415    return 0;
1416  }
1417  }
1418}
1419
1420bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1421  switch (Init->getStmtClass()) {
1422  default:
1423    InitializerElementNotConstant(Init);
1424    return true;
1425  case Expr::ParenExprClass: {
1426    const ParenExpr* PE = cast<ParenExpr>(Init);
1427    return CheckArithmeticConstantExpression(PE->getSubExpr());
1428  }
1429  case Expr::FloatingLiteralClass:
1430  case Expr::IntegerLiteralClass:
1431  case Expr::CharacterLiteralClass:
1432  case Expr::ImaginaryLiteralClass:
1433  case Expr::TypesCompatibleExprClass:
1434  case Expr::CXXBoolLiteralExprClass:
1435    return false;
1436  case Expr::CallExprClass:
1437  case Expr::CXXOperatorCallExprClass: {
1438    const CallExpr *CE = cast<CallExpr>(Init);
1439
1440    // Allow any constant foldable calls to builtins.
1441    if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
1442      return false;
1443
1444    InitializerElementNotConstant(Init);
1445    return true;
1446  }
1447  case Expr::DeclRefExprClass: {
1448    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1449    if (isa<EnumConstantDecl>(D))
1450      return false;
1451    InitializerElementNotConstant(Init);
1452    return true;
1453  }
1454  case Expr::CompoundLiteralExprClass:
1455    // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1456    // but vectors are allowed to be magic.
1457    if (Init->getType()->isVectorType())
1458      return false;
1459    InitializerElementNotConstant(Init);
1460    return true;
1461  case Expr::UnaryOperatorClass: {
1462    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1463
1464    switch (Exp->getOpcode()) {
1465    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1466    // See C99 6.6p3.
1467    default:
1468      InitializerElementNotConstant(Init);
1469      return true;
1470    case UnaryOperator::OffsetOf:
1471      if (Exp->getSubExpr()->getType()->isConstantSizeType())
1472        return false;
1473      InitializerElementNotConstant(Init);
1474      return true;
1475    case UnaryOperator::Extension:
1476    case UnaryOperator::LNot:
1477    case UnaryOperator::Plus:
1478    case UnaryOperator::Minus:
1479    case UnaryOperator::Not:
1480      return CheckArithmeticConstantExpression(Exp->getSubExpr());
1481    }
1482  }
1483  case Expr::SizeOfAlignOfExprClass: {
1484    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
1485    // Special check for void types, which are allowed as an extension
1486    if (Exp->getTypeOfArgument()->isVoidType())
1487      return false;
1488    // alignof always evaluates to a constant.
1489    // FIXME: is sizeof(int[3.0]) a constant expression?
1490    if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
1491      InitializerElementNotConstant(Init);
1492      return true;
1493    }
1494    return false;
1495  }
1496  case Expr::BinaryOperatorClass: {
1497    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1498
1499    if (Exp->getLHS()->getType()->isArithmeticType() &&
1500        Exp->getRHS()->getType()->isArithmeticType()) {
1501      return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1502             CheckArithmeticConstantExpression(Exp->getRHS());
1503    }
1504
1505    if (Exp->getLHS()->getType()->isPointerType() &&
1506        Exp->getRHS()->getType()->isPointerType()) {
1507      const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1508      const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1509
1510      // Only allow a null (constant integer) base; we could
1511      // allow some additional cases if necessary, but this
1512      // is sufficient to cover offsetof-like constructs.
1513      if (!LHSBase && !RHSBase) {
1514        return CheckAddressConstantExpression(Exp->getLHS()) ||
1515               CheckAddressConstantExpression(Exp->getRHS());
1516      }
1517    }
1518
1519    InitializerElementNotConstant(Init);
1520    return true;
1521  }
1522  case Expr::ImplicitCastExprClass:
1523  case Expr::CStyleCastExprClass: {
1524    const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
1525    if (SubExpr->getType()->isArithmeticType())
1526      return CheckArithmeticConstantExpression(SubExpr);
1527
1528    if (SubExpr->getType()->isPointerType()) {
1529      const Expr* Base = FindExpressionBaseAddress(SubExpr);
1530      // If the pointer has a null base, this is an offsetof-like construct
1531      if (!Base)
1532        return CheckAddressConstantExpression(SubExpr);
1533    }
1534
1535    InitializerElementNotConstant(Init);
1536    return true;
1537  }
1538  case Expr::ConditionalOperatorClass: {
1539    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1540
1541    // If GNU extensions are disabled, we require all operands to be arithmetic
1542    // constant expressions.
1543    if (getLangOptions().NoExtensions) {
1544      return CheckArithmeticConstantExpression(Exp->getCond()) ||
1545          (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1546             CheckArithmeticConstantExpression(Exp->getRHS());
1547    }
1548
1549    // Otherwise, we have to emulate some of the behavior of fold here.
1550    // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1551    // because it can constant fold things away.  To retain compatibility with
1552    // GCC code, we see if we can fold the condition to a constant (which we
1553    // should always be able to do in theory).  If so, we only require the
1554    // specified arm of the conditional to be a constant.  This is a horrible
1555    // hack, but is require by real world code that uses __builtin_constant_p.
1556    APValue Val;
1557    if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1558      // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1559      // won't be able to either.  Use it to emit the diagnostic though.
1560      bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1561      assert(Res && "tryEvaluate couldn't evaluate this constant?");
1562      return Res;
1563    }
1564
1565    // Verify that the side following the condition is also a constant.
1566    const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1567    if (Val.getInt() == 0)
1568      std::swap(TrueSide, FalseSide);
1569
1570    if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
1571      return true;
1572
1573    // Okay, the evaluated side evaluates to a constant, so we accept this.
1574    // Check to see if the other side is obviously not a constant.  If so,
1575    // emit a warning that this is a GNU extension.
1576    if (FalseSide && !FalseSide->isEvaluatable(Context))
1577      Diag(Init->getExprLoc(),
1578           diag::ext_typecheck_expression_not_constant_but_accepted,
1579           FalseSide->getSourceRange());
1580    return false;
1581  }
1582  }
1583}
1584
1585bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1586  Init = Init->IgnoreParens();
1587
1588  // Look through CXXDefaultArgExprs; they have no meaning in this context.
1589  if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1590    return CheckForConstantInitializer(DAE->getExpr(), DclT);
1591
1592  if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1593    return CheckForConstantInitializer(e->getInitializer(), DclT);
1594
1595  if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1596    unsigned numInits = Exp->getNumInits();
1597    for (unsigned i = 0; i < numInits; i++) {
1598      // FIXME: Need to get the type of the declaration for C++,
1599      // because it could be a reference?
1600      if (CheckForConstantInitializer(Exp->getInit(i),
1601                                      Exp->getInit(i)->getType()))
1602        return true;
1603    }
1604    return false;
1605  }
1606
1607  if (Init->isNullPointerConstant(Context))
1608    return false;
1609  if (Init->getType()->isArithmeticType()) {
1610    QualType InitTy = Context.getCanonicalType(Init->getType())
1611                             .getUnqualifiedType();
1612    if (InitTy == Context.BoolTy) {
1613      // Special handling for pointers implicitly cast to bool;
1614      // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1615      if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1616        Expr* SubE = ICE->getSubExpr();
1617        if (SubE->getType()->isPointerType() ||
1618            SubE->getType()->isArrayType() ||
1619            SubE->getType()->isFunctionType()) {
1620          return CheckAddressConstantExpression(Init);
1621        }
1622      }
1623    } else if (InitTy->isIntegralType()) {
1624      Expr* SubE = 0;
1625      if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1626        SubE = CE->getSubExpr();
1627      // Special check for pointer cast to int; we allow as an extension
1628      // an address constant cast to an integer if the integer
1629      // is of an appropriate width (this sort of code is apparently used
1630      // in some places).
1631      // FIXME: Add pedwarn?
1632      // FIXME: Don't allow bitfields here!  Need the FieldDecl for that.
1633      if (SubE && (SubE->getType()->isPointerType() ||
1634                   SubE->getType()->isArrayType() ||
1635                   SubE->getType()->isFunctionType())) {
1636        unsigned IntWidth = Context.getTypeSize(Init->getType());
1637        unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1638        if (IntWidth >= PointerWidth)
1639          return CheckAddressConstantExpression(Init);
1640      }
1641    }
1642
1643    return CheckArithmeticConstantExpression(Init);
1644  }
1645
1646  if (Init->getType()->isPointerType())
1647    return CheckAddressConstantExpression(Init);
1648
1649  // An array type at the top level that isn't an init-list must
1650  // be a string literal
1651  if (Init->getType()->isArrayType())
1652    return false;
1653
1654  if (Init->getType()->isFunctionType())
1655    return false;
1656
1657  // Allow block exprs at top level.
1658  if (Init->getType()->isBlockPointerType())
1659    return false;
1660
1661  InitializerElementNotConstant(Init);
1662  return true;
1663}
1664
1665void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
1666  Decl *RealDecl = static_cast<Decl *>(dcl);
1667  Expr *Init = static_cast<Expr *>(init);
1668  assert(Init && "missing initializer");
1669
1670  // If there is no declaration, there was an error parsing it.  Just ignore
1671  // the initializer.
1672  if (RealDecl == 0) {
1673    delete Init;
1674    return;
1675  }
1676
1677  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1678  if (!VDecl) {
1679    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1680         diag::err_illegal_initializer);
1681    RealDecl->setInvalidDecl();
1682    return;
1683  }
1684  // Get the decls type and save a reference for later, since
1685  // CheckInitializerTypes may change it.
1686  QualType DclT = VDecl->getType(), SavT = DclT;
1687  if (VDecl->isBlockVarDecl()) {
1688    VarDecl::StorageClass SC = VDecl->getStorageClass();
1689    if (SC == VarDecl::Extern) { // C99 6.7.8p5
1690      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
1691      VDecl->setInvalidDecl();
1692    } else if (!VDecl->isInvalidDecl()) {
1693      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1694                                VDecl->getName()))
1695        VDecl->setInvalidDecl();
1696
1697      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1698      if (!getLangOptions().CPlusPlus) {
1699        if (SC == VarDecl::Static) // C99 6.7.8p4.
1700          CheckForConstantInitializer(Init, DclT);
1701      }
1702    }
1703  } else if (VDecl->isFileVarDecl()) {
1704    if (VDecl->getStorageClass() == VarDecl::Extern)
1705      Diag(VDecl->getLocation(), diag::warn_extern_init);
1706    if (!VDecl->isInvalidDecl())
1707      if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1708                                VDecl->getName()))
1709        VDecl->setInvalidDecl();
1710
1711    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1712    if (!getLangOptions().CPlusPlus) {
1713      // C99 6.7.8p4. All file scoped initializers need to be constant.
1714      CheckForConstantInitializer(Init, DclT);
1715    }
1716  }
1717  // If the type changed, it means we had an incomplete type that was
1718  // completed by the initializer. For example:
1719  //   int ary[] = { 1, 3, 5 };
1720  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
1721  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
1722    VDecl->setType(DclT);
1723    Init->setType(DclT);
1724  }
1725
1726  // Attach the initializer to the decl.
1727  VDecl->setInit(Init);
1728  return;
1729}
1730
1731void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1732  Decl *RealDecl = static_cast<Decl *>(dcl);
1733
1734  // If there is no declaration, there was an error parsing it. Just ignore it.
1735  if (RealDecl == 0)
1736    return;
1737
1738  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1739    QualType Type = Var->getType();
1740    // C++ [dcl.init.ref]p3:
1741    //   The initializer can be omitted for a reference only in a
1742    //   parameter declaration (8.3.5), in the declaration of a
1743    //   function return type, in the declaration of a class member
1744    //   within its class declaration (9.2), and where the extern
1745    //   specifier is explicitly used.
1746    if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
1747      Diag(Var->getLocation(),
1748           diag::err_reference_var_requires_init,
1749           Var->getName(),
1750           SourceRange(Var->getLocation(), Var->getLocation()));
1751      Var->setInvalidDecl();
1752      return;
1753    }
1754
1755    // C++ [dcl.init]p9:
1756    //
1757    //   If no initializer is specified for an object, and the object
1758    //   is of (possibly cv-qualified) non-POD class type (or array
1759    //   thereof), the object shall be default-initialized; if the
1760    //   object is of const-qualified type, the underlying class type
1761    //   shall have a user-declared default constructor.
1762    if (getLangOptions().CPlusPlus) {
1763      QualType InitType = Type;
1764      if (const ArrayType *Array = Context.getAsArrayType(Type))
1765        InitType = Array->getElementType();
1766      if (InitType->isRecordType()) {
1767        const CXXConstructorDecl *Constructor
1768          = PerformInitializationByConstructor(InitType, 0, 0,
1769                                               Var->getLocation(),
1770                                               SourceRange(Var->getLocation(),
1771                                                           Var->getLocation()),
1772                                               Var->getName(),
1773                                               IK_Default);
1774        if (!Constructor)
1775          Var->setInvalidDecl();
1776      }
1777    }
1778
1779#if 0
1780    // FIXME: Temporarily disabled because we are not properly parsing
1781    // linkage specifications on declarations, e.g.,
1782    //
1783    //   extern "C" const CGPoint CGPointerZero;
1784    //
1785    // C++ [dcl.init]p9:
1786    //
1787    //     If no initializer is specified for an object, and the
1788    //     object is of (possibly cv-qualified) non-POD class type (or
1789    //     array thereof), the object shall be default-initialized; if
1790    //     the object is of const-qualified type, the underlying class
1791    //     type shall have a user-declared default
1792    //     constructor. Otherwise, if no initializer is specified for
1793    //     an object, the object and its subobjects, if any, have an
1794    //     indeterminate initial value; if the object or any of its
1795    //     subobjects are of const-qualified type, the program is
1796    //     ill-formed.
1797    //
1798    // This isn't technically an error in C, so we don't diagnose it.
1799    //
1800    // FIXME: Actually perform the POD/user-defined default
1801    // constructor check.
1802    if (getLangOptions().CPlusPlus &&
1803        Context.getCanonicalType(Type).isConstQualified() &&
1804        Var->getStorageClass() != VarDecl::Extern)
1805      Diag(Var->getLocation(),
1806           diag::err_const_var_requires_init,
1807           Var->getName(),
1808           SourceRange(Var->getLocation(), Var->getLocation()));
1809#endif
1810  }
1811}
1812
1813/// The declarators are chained together backwards, reverse the list.
1814Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1815  // Often we have single declarators, handle them quickly.
1816  Decl *GroupDecl = static_cast<Decl*>(group);
1817  if (GroupDecl == 0)
1818    return 0;
1819
1820  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1821  ScopedDecl *NewGroup = 0;
1822  if (Group->getNextDeclarator() == 0)
1823    NewGroup = Group;
1824  else { // reverse the list.
1825    while (Group) {
1826      ScopedDecl *Next = Group->getNextDeclarator();
1827      Group->setNextDeclarator(NewGroup);
1828      NewGroup = Group;
1829      Group = Next;
1830    }
1831  }
1832  // Perform semantic analysis that depends on having fully processed both
1833  // the declarator and initializer.
1834  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
1835    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1836    if (!IDecl)
1837      continue;
1838    QualType T = IDecl->getType();
1839
1840    // C99 6.7.5.2p2: If an identifier is declared to be an object with
1841    // static storage duration, it shall not have a variable length array.
1842    if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1843        IDecl->getStorageClass() == VarDecl::Static) {
1844      if (T->isVariableArrayType()) {
1845        Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1846        IDecl->setInvalidDecl();
1847      }
1848    }
1849    // Block scope. C99 6.7p7: If an identifier for an object is declared with
1850    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
1851    if (IDecl->isBlockVarDecl() &&
1852        IDecl->getStorageClass() != VarDecl::Extern) {
1853      if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1854        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1855             T.getAsString());
1856        IDecl->setInvalidDecl();
1857      }
1858    }
1859    // File scope. C99 6.9.2p2: A declaration of an identifier for and
1860    // object that has file scope without an initializer, and without a
1861    // storage-class specifier or with the storage-class specifier "static",
1862    // constitutes a tentative definition. Note: A tentative definition with
1863    // external linkage is valid (C99 6.2.2p5).
1864    if (isTentativeDefinition(IDecl)) {
1865      if (T->isIncompleteArrayType()) {
1866        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1867        // array to be completed. Don't issue a diagnostic.
1868      } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1869        // C99 6.9.2p3: If the declaration of an identifier for an object is
1870        // a tentative definition and has internal linkage (C99 6.2.2p3), the
1871        // declared type shall not be an incomplete type.
1872        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1873             T.getAsString());
1874        IDecl->setInvalidDecl();
1875      }
1876    }
1877    if (IDecl->isFileVarDecl())
1878      CheckForFileScopedRedefinitions(S, IDecl);
1879  }
1880  return NewGroup;
1881}
1882
1883/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1884/// to introduce parameters into function prototype scope.
1885Sema::DeclTy *
1886Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1887  // FIXME: disallow CXXScopeSpec for param declarators.
1888  const DeclSpec &DS = D.getDeclSpec();
1889
1890  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1891  VarDecl::StorageClass StorageClass = VarDecl::None;
1892  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1893    StorageClass = VarDecl::Register;
1894  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
1895    Diag(DS.getStorageClassSpecLoc(),
1896         diag::err_invalid_storage_class_in_func_decl);
1897    D.getMutableDeclSpec().ClearStorageClassSpecs();
1898  }
1899  if (DS.isThreadSpecified()) {
1900    Diag(DS.getThreadSpecLoc(),
1901         diag::err_invalid_storage_class_in_func_decl);
1902    D.getMutableDeclSpec().ClearStorageClassSpecs();
1903  }
1904
1905  // Check that there are no default arguments inside the type of this
1906  // parameter (C++ only).
1907  if (getLangOptions().CPlusPlus)
1908    CheckExtraCXXDefaultArguments(D);
1909
1910  // In this context, we *do not* check D.getInvalidType(). If the declarator
1911  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1912  // though it will not reflect the user specified type.
1913  QualType parmDeclType = GetTypeForDeclarator(D, S);
1914
1915  assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1916
1917  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1918  // Can this happen for params?  We already checked that they don't conflict
1919  // among each other.  Here they can only shadow globals, which is ok.
1920  IdentifierInfo *II = D.getIdentifier();
1921  if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1922    if (S->isDeclScope(PrevDecl)) {
1923      Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1924           dyn_cast<NamedDecl>(PrevDecl)->getName());
1925
1926      // Recover by removing the name
1927      II = 0;
1928      D.SetIdentifier(0, D.getIdentifierLoc());
1929    }
1930  }
1931
1932  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1933  // Doing the promotion here has a win and a loss. The win is the type for
1934  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1935  // code generator). The loss is the orginal type isn't preserved. For example:
1936  //
1937  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1938  //    int blockvardecl[5];
1939  //    sizeof(parmvardecl);  // size == 4
1940  //    sizeof(blockvardecl); // size == 20
1941  // }
1942  //
1943  // For expressions, all implicit conversions are captured using the
1944  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1945  //
1946  // FIXME: If a source translation tool needs to see the original type, then
1947  // we need to consider storing both types (in ParmVarDecl)...
1948  //
1949  if (parmDeclType->isArrayType()) {
1950    // int x[restrict 4] ->  int *restrict
1951    parmDeclType = Context.getArrayDecayedType(parmDeclType);
1952  } else if (parmDeclType->isFunctionType())
1953    parmDeclType = Context.getPointerType(parmDeclType);
1954
1955  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1956                                         D.getIdentifierLoc(), II,
1957                                         parmDeclType, StorageClass,
1958                                         0, 0);
1959
1960  if (D.getInvalidType())
1961    New->setInvalidDecl();
1962
1963  if (II)
1964    PushOnScopeChains(New, S);
1965
1966  ProcessDeclAttributes(New, D);
1967  return New;
1968
1969}
1970
1971Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
1972  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
1973  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1974         "Not a function declarator!");
1975  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1976
1977  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1978  // for a K&R function.
1979  if (!FTI.hasPrototype) {
1980    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1981      if (FTI.ArgInfo[i].Param == 0) {
1982        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1983             FTI.ArgInfo[i].Ident->getName());
1984        // Implicitly declare the argument as type 'int' for lack of a better
1985        // type.
1986        DeclSpec DS;
1987        const char* PrevSpec; // unused
1988        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1989                           PrevSpec);
1990        Declarator ParamD(DS, Declarator::KNRTypeListContext);
1991        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1992        FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
1993      }
1994    }
1995  } else {
1996    // FIXME: Diagnose arguments without names in C.
1997  }
1998
1999  Scope *GlobalScope = FnBodyScope->getParent();
2000
2001  return ActOnStartOfFunctionDef(FnBodyScope,
2002                                 ActOnDeclarator(GlobalScope, D, 0));
2003}
2004
2005Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2006  Decl *decl = static_cast<Decl*>(D);
2007  FunctionDecl *FD = cast<FunctionDecl>(decl);
2008
2009  // See if this is a redefinition.
2010  const FunctionDecl *Definition;
2011  if (FD->getBody(Definition)) {
2012    Diag(FD->getLocation(), diag::err_redefinition,
2013         FD->getName());
2014    Diag(Definition->getLocation(), diag::err_previous_definition);
2015  }
2016
2017  PushDeclContext(FD);
2018
2019  // Check the validity of our function parameters
2020  CheckParmsForFunctionDef(FD);
2021
2022  // Introduce our parameters into the function scope
2023  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2024    ParmVarDecl *Param = FD->getParamDecl(p);
2025    // If this has an identifier, add it to the scope stack.
2026    if (Param->getIdentifier())
2027      PushOnScopeChains(Param, FnBodyScope);
2028  }
2029
2030  return FD;
2031}
2032
2033Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2034  Decl *dcl = static_cast<Decl *>(D);
2035  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
2036    FD->setBody((Stmt*)Body);
2037    assert(FD == getCurFunctionDecl() && "Function parsing confused");
2038  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
2039    MD->setBody((Stmt*)Body);
2040  } else
2041    return 0;
2042  PopDeclContext();
2043  // Verify and clean out per-function state.
2044
2045  // Check goto/label use.
2046  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2047       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2048    // Verify that we have no forward references left.  If so, there was a goto
2049    // or address of a label taken, but no definition of it.  Label fwd
2050    // definitions are indicated with a null substmt.
2051    if (I->second->getSubStmt() == 0) {
2052      LabelStmt *L = I->second;
2053      // Emit error.
2054      Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2055
2056      // At this point, we have gotos that use the bogus label.  Stitch it into
2057      // the function body so that they aren't leaked and that the AST is well
2058      // formed.
2059      if (Body) {
2060        L->setSubStmt(new NullStmt(L->getIdentLoc()));
2061        cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2062      } else {
2063        // The whole function wasn't parsed correctly, just delete this.
2064        delete L;
2065      }
2066    }
2067  }
2068  LabelMap.clear();
2069
2070  return D;
2071}
2072
2073/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2074/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
2075ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2076                                           IdentifierInfo &II, Scope *S) {
2077  // Extension in C99.  Legal in C90, but warn about it.
2078  if (getLangOptions().C99)
2079    Diag(Loc, diag::ext_implicit_function_decl, II.getName());
2080  else
2081    Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2082
2083  // FIXME: handle stuff like:
2084  // void foo() { extern float X(); }
2085  // void bar() { X(); }  <-- implicit decl for X in another scope.
2086
2087  // Set a Declarator for the implicit definition: int foo();
2088  const char *Dummy;
2089  DeclSpec DS;
2090  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2091  Error = Error; // Silence warning.
2092  assert(!Error && "Error setting up implicit decl!");
2093  Declarator D(DS, Declarator::BlockContext);
2094  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
2095  D.SetIdentifier(&II, Loc);
2096
2097  // Insert this function into translation-unit scope.
2098
2099  DeclContext *PrevDC = CurContext;
2100  CurContext = Context.getTranslationUnitDecl();
2101
2102  FunctionDecl *FD =
2103    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
2104  FD->setImplicit();
2105
2106  CurContext = PrevDC;
2107
2108  return FD;
2109}
2110
2111
2112TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2113                                    ScopedDecl *LastDeclarator) {
2114  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
2115  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2116
2117  // Scope manipulation handled by caller.
2118  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2119                                           D.getIdentifierLoc(),
2120                                           D.getIdentifier(),
2121                                           T, LastDeclarator);
2122  if (D.getInvalidType())
2123    NewTD->setInvalidDecl();
2124  return NewTD;
2125}
2126
2127/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
2128/// former case, Name will be non-null.  In the later case, Name will be null.
2129/// TagType indicates what kind of tag this is. TK indicates whether this is a
2130/// reference/declaration/definition of a tag.
2131Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
2132                             SourceLocation KWLoc, const CXXScopeSpec &SS,
2133                             IdentifierInfo *Name, SourceLocation NameLoc,
2134                             AttributeList *Attr) {
2135  // If this is a use of an existing tag, it must have a name.
2136  assert((Name != 0 || TK == TK_Definition) &&
2137         "Nameless record must be a definition!");
2138
2139  TagDecl::TagKind Kind;
2140  switch (TagType) {
2141  default: assert(0 && "Unknown tag type!");
2142  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2143  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
2144  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
2145  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
2146  }
2147
2148  // Two code paths: a new one for structs/unions/classes where we create
2149  //   separate decls for forward declarations, and an old (eventually to
2150  //   be removed) code path for enums.
2151  if (Kind != TagDecl::TK_enum)
2152    return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
2153
2154  DeclContext *DC = CurContext;
2155  ScopedDecl *PrevDecl = 0;
2156
2157  if (Name && SS.isNotEmpty()) {
2158    // We have a nested-name tag ('struct foo::bar').
2159
2160    // Check for invalid 'foo::'.
2161    if (SS.isInvalid()) {
2162      Name = 0;
2163      goto CreateNewDecl;
2164    }
2165
2166    DC = static_cast<DeclContext*>(SS.getScopeRep());
2167    // Look-up name inside 'foo::'.
2168    PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2169
2170    // A tag 'foo::bar' must already exist.
2171    if (PrevDecl == 0) {
2172      Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2173           SS.getRange());
2174      Name = 0;
2175      goto CreateNewDecl;
2176    }
2177  } else {
2178    // If this is a named struct, check to see if there was a previous forward
2179    // declaration or definition.
2180    // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2181    PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2182  }
2183
2184  if (PrevDecl) {
2185    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2186            "unexpected Decl type");
2187    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2188      // If this is a use of a previous tag, or if the tag is already declared
2189      // in the same scope (so that the definition/declaration completes or
2190      // rementions the tag), reuse the decl.
2191      if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
2192        // Make sure that this wasn't declared as an enum and now used as a
2193        // struct or something similar.
2194        if (PrevTagDecl->getTagKind() != Kind) {
2195          Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2196          Diag(PrevDecl->getLocation(), diag::err_previous_use);
2197          // Recover by making this an anonymous redefinition.
2198          Name = 0;
2199          PrevDecl = 0;
2200        } else {
2201          // If this is a use or a forward declaration, we're good.
2202          if (TK != TK_Definition)
2203            return PrevDecl;
2204
2205          // Diagnose attempts to redefine a tag.
2206          if (PrevTagDecl->isDefinition()) {
2207            Diag(NameLoc, diag::err_redefinition, Name->getName());
2208            Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2209            // If this is a redefinition, recover by making this struct be
2210            // anonymous, which will make any later references get the previous
2211            // definition.
2212            Name = 0;
2213          } else {
2214            // Okay, this is definition of a previously declared or referenced
2215            // tag. Move the location of the decl to be the definition site.
2216            PrevDecl->setLocation(NameLoc);
2217            return PrevDecl;
2218          }
2219        }
2220      }
2221      // If we get here, this is a definition of a new struct type in a nested
2222      // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2223      // type.
2224    } else {
2225      // PrevDecl is a namespace.
2226      if (isDeclInScope(PrevDecl, DC, S)) {
2227        // The tag name clashes with a namespace name, issue an error and
2228        // recover by making this tag be anonymous.
2229        Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2230        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2231        Name = 0;
2232      }
2233    }
2234  }
2235
2236  CreateNewDecl:
2237
2238  // If there is an identifier, use the location of the identifier as the
2239  // location of the decl, otherwise use the location of the struct/union
2240  // keyword.
2241  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2242
2243  // Otherwise, if this is the first time we've seen this tag, create the decl.
2244  TagDecl *New;
2245  if (Kind == TagDecl::TK_enum) {
2246    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2247    // enum X { A, B, C } D;    D should chain to X.
2248    New = EnumDecl::Create(Context, DC, Loc, Name, 0);
2249    // If this is an undefined enum, warn.
2250    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
2251  } else {
2252    // struct/union/class
2253
2254    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2255    // struct X { int A; } D;    D should chain to X.
2256    if (getLangOptions().CPlusPlus)
2257      // FIXME: Look for a way to use RecordDecl for simple structs.
2258      New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
2259    else
2260      New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
2261  }
2262
2263  // If this has an identifier, add it to the scope stack.
2264  if (Name) {
2265    // The scope passed in may not be a decl scope.  Zip up the scope tree until
2266    // we find one that is.
2267    while ((S->getFlags() & Scope::DeclScope) == 0)
2268      S = S->getParent();
2269
2270    // Add it to the decl chain.
2271    PushOnScopeChains(New, S);
2272  }
2273
2274  if (Attr)
2275    ProcessDeclAttributeList(New, Attr);
2276
2277  // Set the lexical context. If the tag has a C++ scope specifier, the
2278  // lexical context will be different from the semantic context.
2279  New->setLexicalDeclContext(CurContext);
2280
2281  return New;
2282}
2283
2284/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes.  Unlike
2285///  the logic for enums, we create separate decls for forward declarations.
2286///  This is called by ActOnTag, but eventually will replace its logic.
2287Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
2288                             SourceLocation KWLoc, const CXXScopeSpec &SS,
2289                             IdentifierInfo *Name, SourceLocation NameLoc,
2290                             AttributeList *Attr) {
2291  DeclContext *DC = CurContext;
2292  ScopedDecl *PrevDecl = 0;
2293
2294  if (Name && SS.isNotEmpty()) {
2295    // We have a nested-name tag ('struct foo::bar').
2296
2297    // Check for invalid 'foo::'.
2298    if (SS.isInvalid()) {
2299      Name = 0;
2300      goto CreateNewDecl;
2301    }
2302
2303    DC = static_cast<DeclContext*>(SS.getScopeRep());
2304    // Look-up name inside 'foo::'.
2305    PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2306
2307    // A tag 'foo::bar' must already exist.
2308    if (PrevDecl == 0) {
2309      Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2310           SS.getRange());
2311      Name = 0;
2312      goto CreateNewDecl;
2313    }
2314  } else {
2315    // If this is a named struct, check to see if there was a previous forward
2316    // declaration or definition.
2317    // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2318    PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2319  }
2320
2321  if (PrevDecl) {
2322    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2323           "unexpected Decl type");
2324
2325    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2326      // If this is a use of a previous tag, or if the tag is already declared
2327      // in the same scope (so that the definition/declaration completes or
2328      // rementions the tag), reuse the decl.
2329      if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
2330        // Make sure that this wasn't declared as an enum and now used as a
2331        // struct or something similar.
2332        if (PrevTagDecl->getTagKind() != Kind) {
2333          Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2334          Diag(PrevDecl->getLocation(), diag::err_previous_use);
2335          // Recover by making this an anonymous redefinition.
2336          Name = 0;
2337          PrevDecl = 0;
2338        } else {
2339          // If this is a use, return the original decl.
2340
2341          // FIXME: In the future, return a variant or some other clue
2342          //  for the consumer of this Decl to know it doesn't own it.
2343          //  For our current ASTs this shouldn't be a problem, but will
2344          //  need to be changed with DeclGroups.
2345          if (TK == TK_Reference)
2346            return PrevDecl;
2347
2348          // The new decl is a definition?
2349          if (TK == TK_Definition) {
2350            // Diagnose attempts to redefine a tag.
2351            if (RecordDecl* DefRecord =
2352                cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2353              Diag(NameLoc, diag::err_redefinition, Name->getName());
2354              Diag(DefRecord->getLocation(), diag::err_previous_definition);
2355              // If this is a redefinition, recover by making this struct be
2356              // anonymous, which will make any later references get the previous
2357              // definition.
2358              Name = 0;
2359              PrevDecl = 0;
2360            }
2361            // Okay, this is definition of a previously declared or referenced
2362            // tag.  We're going to create a new Decl.
2363          }
2364        }
2365        // If we get here we have (another) forward declaration.  Just create
2366        // a new decl.
2367      }
2368      else {
2369        // If we get here, this is a definition of a new struct type in a nested
2370        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2371        // new decl/type.  We set PrevDecl to NULL so that the Records
2372        // have distinct types.
2373        PrevDecl = 0;
2374      }
2375    } else {
2376      // PrevDecl is a namespace.
2377      if (isDeclInScope(PrevDecl, DC, S)) {
2378        // The tag name clashes with a namespace name, issue an error and
2379        // recover by making this tag be anonymous.
2380        Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2381        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2382        Name = 0;
2383      }
2384    }
2385  }
2386
2387  CreateNewDecl:
2388
2389  // If there is an identifier, use the location of the identifier as the
2390  // location of the decl, otherwise use the location of the struct/union
2391  // keyword.
2392  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2393
2394  // Otherwise, if this is the first time we've seen this tag, create the decl.
2395  TagDecl *New;
2396
2397  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2398  // struct X { int A; } D;    D should chain to X.
2399  if (getLangOptions().CPlusPlus)
2400    // FIXME: Look for a way to use RecordDecl for simple structs.
2401    New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2402                                dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2403  else
2404    New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2405                             dyn_cast_or_null<RecordDecl>(PrevDecl));
2406
2407  // If this has an identifier, add it to the scope stack.
2408  if ((TK == TK_Definition || !PrevDecl) && Name) {
2409    // The scope passed in may not be a decl scope.  Zip up the scope tree until
2410    // we find one that is.
2411    while ((S->getFlags() & Scope::DeclScope) == 0)
2412      S = S->getParent();
2413
2414    // Add it to the decl chain.
2415    PushOnScopeChains(New, S);
2416  }
2417
2418  // Handle #pragma pack: if the #pragma pack stack has non-default
2419  // alignment, make up a packed attribute for this decl. These
2420  // attributes are checked when the ASTContext lays out the
2421  // structure.
2422  //
2423  // It is important for implementing the correct semantics that this
2424  // happen here (in act on tag decl). The #pragma pack stack is
2425  // maintained as a result of parser callbacks which can occur at
2426  // many points during the parsing of a struct declaration (because
2427  // the #pragma tokens are effectively skipped over during the
2428  // parsing of the struct).
2429  if (unsigned Alignment = PackContext.getAlignment())
2430    New->addAttr(new PackedAttr(Alignment * 8));
2431
2432  if (Attr)
2433    ProcessDeclAttributeList(New, Attr);
2434
2435  // Set the lexical context. If the tag has a C++ scope specifier, the
2436  // lexical context will be different from the semantic context.
2437  New->setLexicalDeclContext(CurContext);
2438
2439  return New;
2440}
2441
2442
2443/// Collect the instance variables declared in an Objective-C object.  Used in
2444/// the creation of structures from objects using the @defs directive.
2445static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
2446                         llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
2447  if (Class->getSuperClass())
2448    CollectIvars(Class->getSuperClass(), Ctx, ivars);
2449
2450  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
2451  for (ObjCInterfaceDecl::ivar_iterator
2452        I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2453
2454    ObjCIvarDecl* ID = *I;
2455    ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2456                                                ID->getIdentifier(),
2457                                                ID->getType(),
2458                                                ID->getBitWidth()));
2459  }
2460}
2461
2462/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
2463/// instance variables of ClassName into Decls.
2464void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2465                     IdentifierInfo *ClassName,
2466                     llvm::SmallVectorImpl<DeclTy*> &Decls) {
2467  // Check that ClassName is a valid class
2468  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2469  if (!Class) {
2470    Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2471    return;
2472  }
2473  // Collect the instance variables
2474  CollectIvars(Class, Context, Decls);
2475}
2476
2477/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2478/// types into constant array types in certain situations which would otherwise
2479/// be errors (for GCC compatibility).
2480static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2481                                                    ASTContext &Context) {
2482  // This method tries to turn a variable array into a constant
2483  // array even when the size isn't an ICE.  This is necessary
2484  // for compatibility with code that depends on gcc's buggy
2485  // constant expression folding, like struct {char x[(int)(char*)2];}
2486  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2487  if (!VLATy) return QualType();
2488
2489  APValue Result;
2490  if (!VLATy->getSizeExpr() ||
2491      !VLATy->getSizeExpr()->tryEvaluate(Result, Context))
2492    return QualType();
2493
2494  assert(Result.isInt() && "Size expressions must be integers!");
2495  llvm::APSInt &Res = Result.getInt();
2496  if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2497    return Context.getConstantArrayType(VLATy->getElementType(),
2498                                        Res, ArrayType::Normal, 0);
2499  return QualType();
2500}
2501
2502/// ActOnField - Each field of a struct/union/class is passed into this in order
2503/// to create a FieldDecl object for it.
2504Sema::DeclTy *Sema::ActOnField(Scope *S,
2505                               SourceLocation DeclStart,
2506                               Declarator &D, ExprTy *BitfieldWidth) {
2507  IdentifierInfo *II = D.getIdentifier();
2508  Expr *BitWidth = (Expr*)BitfieldWidth;
2509  SourceLocation Loc = DeclStart;
2510  if (II) Loc = D.getIdentifierLoc();
2511
2512  // FIXME: Unnamed fields can be handled in various different ways, for
2513  // example, unnamed unions inject all members into the struct namespace!
2514
2515  if (BitWidth) {
2516    // TODO: Validate.
2517    //printf("WARNING: BITFIELDS IGNORED!\n");
2518
2519    // 6.7.2.1p3
2520    // 6.7.2.1p4
2521
2522  } else {
2523    // Not a bitfield.
2524
2525    // validate II.
2526
2527  }
2528
2529  QualType T = GetTypeForDeclarator(D, S);
2530  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2531  bool InvalidDecl = false;
2532
2533  // C99 6.7.2.1p8: A member of a structure or union may have any type other
2534  // than a variably modified type.
2535  if (T->isVariablyModifiedType()) {
2536    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
2537    if (!FixedTy.isNull()) {
2538      Diag(Loc, diag::warn_illegal_constant_array_size);
2539      T = FixedTy;
2540    } else {
2541      Diag(Loc, diag::err_typecheck_field_variable_size);
2542      T = Context.IntTy;
2543      InvalidDecl = true;
2544    }
2545  }
2546  // FIXME: Chain fielddecls together.
2547  FieldDecl *NewFD;
2548
2549  if (getLangOptions().CPlusPlus) {
2550    // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2551    NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2552                                 Loc, II, T, BitWidth);
2553    if (II)
2554      PushOnScopeChains(NewFD, S);
2555  }
2556  else
2557    NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
2558
2559  ProcessDeclAttributes(NewFD, D);
2560
2561  if (D.getInvalidType() || InvalidDecl)
2562    NewFD->setInvalidDecl();
2563  return NewFD;
2564}
2565
2566/// TranslateIvarVisibility - Translate visibility from a token ID to an
2567///  AST enum value.
2568static ObjCIvarDecl::AccessControl
2569TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
2570  switch (ivarVisibility) {
2571  default: assert(0 && "Unknown visitibility kind");
2572  case tok::objc_private: return ObjCIvarDecl::Private;
2573  case tok::objc_public: return ObjCIvarDecl::Public;
2574  case tok::objc_protected: return ObjCIvarDecl::Protected;
2575  case tok::objc_package: return ObjCIvarDecl::Package;
2576  }
2577}
2578
2579/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2580/// in order to create an IvarDecl object for it.
2581Sema::DeclTy *Sema::ActOnIvar(Scope *S,
2582                              SourceLocation DeclStart,
2583                              Declarator &D, ExprTy *BitfieldWidth,
2584                              tok::ObjCKeywordKind Visibility) {
2585  IdentifierInfo *II = D.getIdentifier();
2586  Expr *BitWidth = (Expr*)BitfieldWidth;
2587  SourceLocation Loc = DeclStart;
2588  if (II) Loc = D.getIdentifierLoc();
2589
2590  // FIXME: Unnamed fields can be handled in various different ways, for
2591  // example, unnamed unions inject all members into the struct namespace!
2592
2593
2594  if (BitWidth) {
2595    // TODO: Validate.
2596    //printf("WARNING: BITFIELDS IGNORED!\n");
2597
2598    // 6.7.2.1p3
2599    // 6.7.2.1p4
2600
2601  } else {
2602    // Not a bitfield.
2603
2604    // validate II.
2605
2606  }
2607
2608  QualType T = GetTypeForDeclarator(D, S);
2609  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2610  bool InvalidDecl = false;
2611
2612  // C99 6.7.2.1p8: A member of a structure or union may have any type other
2613  // than a variably modified type.
2614  if (T->isVariablyModifiedType()) {
2615    // FIXME: This diagnostic needs work
2616    Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2617    InvalidDecl = true;
2618  }
2619
2620  // Get the visibility (access control) for this ivar.
2621  ObjCIvarDecl::AccessControl ac =
2622    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2623                                        : ObjCIvarDecl::None;
2624
2625  // Construct the decl.
2626  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
2627                                             (Expr *)BitfieldWidth);
2628
2629  // Process attributes attached to the ivar.
2630  ProcessDeclAttributes(NewID, D);
2631
2632  if (D.getInvalidType() || InvalidDecl)
2633    NewID->setInvalidDecl();
2634
2635  return NewID;
2636}
2637
2638void Sema::ActOnFields(Scope* S,
2639                       SourceLocation RecLoc, DeclTy *RecDecl,
2640                       DeclTy **Fields, unsigned NumFields,
2641                       SourceLocation LBrac, SourceLocation RBrac,
2642                       AttributeList *Attr) {
2643  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2644  assert(EnclosingDecl && "missing record or interface decl");
2645  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2646
2647  if (Record)
2648    if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2649      // Diagnose code like:
2650      //     struct S { struct S {} X; };
2651      // We discover this when we complete the outer S.  Reject and ignore the
2652      // outer S.
2653      Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2654           DefRecord->getKindName());
2655      Diag(RecLoc, diag::err_previous_definition);
2656      Record->setInvalidDecl();
2657      return;
2658    }
2659
2660  // Verify that all the fields are okay.
2661  unsigned NumNamedMembers = 0;
2662  llvm::SmallVector<FieldDecl*, 32> RecFields;
2663  llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
2664
2665  for (unsigned i = 0; i != NumFields; ++i) {
2666
2667    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2668    assert(FD && "missing field decl");
2669
2670    // Remember all fields.
2671    RecFields.push_back(FD);
2672
2673    // Get the type for the field.
2674    Type *FDTy = FD->getType().getTypePtr();
2675
2676    // C99 6.7.2.1p2 - A field may not be a function type.
2677    if (FDTy->isFunctionType()) {
2678      Diag(FD->getLocation(), diag::err_field_declared_as_function,
2679           FD->getName());
2680      FD->setInvalidDecl();
2681      EnclosingDecl->setInvalidDecl();
2682      continue;
2683    }
2684    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2685    if (FDTy->isIncompleteType()) {
2686      if (!Record) {  // Incomplete ivar type is always an error.
2687        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
2688        FD->setInvalidDecl();
2689        EnclosingDecl->setInvalidDecl();
2690        continue;
2691      }
2692      if (i != NumFields-1 ||                   // ... that the last member ...
2693          !Record->isStruct() ||  // ... of a structure ...
2694          !FDTy->isArrayType()) {         //... may have incomplete array type.
2695        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
2696        FD->setInvalidDecl();
2697        EnclosingDecl->setInvalidDecl();
2698        continue;
2699      }
2700      if (NumNamedMembers < 1) {  //... must have more than named member ...
2701        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2702             FD->getName());
2703        FD->setInvalidDecl();
2704        EnclosingDecl->setInvalidDecl();
2705        continue;
2706      }
2707      // Okay, we have a legal flexible array member at the end of the struct.
2708      if (Record)
2709        Record->setHasFlexibleArrayMember(true);
2710    }
2711    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2712    /// field of another structure or the element of an array.
2713    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
2714      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2715        // If this is a member of a union, then entire union becomes "flexible".
2716        if (Record && Record->isUnion()) {
2717          Record->setHasFlexibleArrayMember(true);
2718        } else {
2719          // If this is a struct/class and this is not the last element, reject
2720          // it.  Note that GCC supports variable sized arrays in the middle of
2721          // structures.
2722          if (i != NumFields-1) {
2723            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2724                 FD->getName());
2725            FD->setInvalidDecl();
2726            EnclosingDecl->setInvalidDecl();
2727            continue;
2728          }
2729          // We support flexible arrays at the end of structs in other structs
2730          // as an extension.
2731          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2732               FD->getName());
2733          if (Record)
2734            Record->setHasFlexibleArrayMember(true);
2735        }
2736      }
2737    }
2738    /// A field cannot be an Objective-c object
2739    if (FDTy->isObjCInterfaceType()) {
2740      Diag(FD->getLocation(), diag::err_statically_allocated_object,
2741           FD->getName());
2742      FD->setInvalidDecl();
2743      EnclosingDecl->setInvalidDecl();
2744      continue;
2745    }
2746    // Keep track of the number of named members.
2747    if (IdentifierInfo *II = FD->getIdentifier()) {
2748      // Detect duplicate member names.
2749      if (!FieldIDs.insert(II)) {
2750        Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2751        // Find the previous decl.
2752        SourceLocation PrevLoc;
2753        for (unsigned i = 0; ; ++i) {
2754          assert(i != RecFields.size() && "Didn't find previous def!");
2755          if (RecFields[i]->getIdentifier() == II) {
2756            PrevLoc = RecFields[i]->getLocation();
2757            break;
2758          }
2759        }
2760        Diag(PrevLoc, diag::err_previous_definition);
2761        FD->setInvalidDecl();
2762        EnclosingDecl->setInvalidDecl();
2763        continue;
2764      }
2765      ++NumNamedMembers;
2766    }
2767  }
2768
2769  // Okay, we successfully defined 'Record'.
2770  if (Record) {
2771    Record->defineBody(Context, &RecFields[0], RecFields.size());
2772    // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2773    // Sema::ActOnFinishCXXClassDef.
2774    if (!isa<CXXRecordDecl>(Record))
2775      Consumer.HandleTagDeclDefinition(Record);
2776  } else {
2777    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2778    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2779      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2780    else if (ObjCImplementationDecl *IMPDecl =
2781               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
2782      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2783      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
2784      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
2785    }
2786  }
2787
2788  if (Attr)
2789    ProcessDeclAttributeList(Record, Attr);
2790}
2791
2792Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
2793                                      DeclTy *lastEnumConst,
2794                                      SourceLocation IdLoc, IdentifierInfo *Id,
2795                                      SourceLocation EqualLoc, ExprTy *val) {
2796  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
2797  EnumConstantDecl *LastEnumConst =
2798    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2799  Expr *Val = static_cast<Expr*>(val);
2800
2801  // The scope passed in may not be a decl scope.  Zip up the scope tree until
2802  // we find one that is.
2803  while ((S->getFlags() & Scope::DeclScope) == 0)
2804    S = S->getParent();
2805
2806  // Verify that there isn't already something declared with this name in this
2807  // scope.
2808  if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
2809    // When in C++, we may get a TagDecl with the same name; in this case the
2810    // enum constant will 'hide' the tag.
2811    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2812           "Received TagDecl when not in C++!");
2813    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
2814      if (isa<EnumConstantDecl>(PrevDecl))
2815        Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2816      else
2817        Diag(IdLoc, diag::err_redefinition, Id->getName());
2818      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2819      delete Val;
2820      return 0;
2821    }
2822  }
2823
2824  llvm::APSInt EnumVal(32);
2825  QualType EltTy;
2826  if (Val) {
2827    // Make sure to promote the operand type to int.
2828    UsualUnaryConversions(Val);
2829
2830    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2831    SourceLocation ExpLoc;
2832    if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2833      Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2834           Id->getName());
2835      delete Val;
2836      Val = 0;  // Just forget about it.
2837    } else {
2838      EltTy = Val->getType();
2839    }
2840  }
2841
2842  if (!Val) {
2843    if (LastEnumConst) {
2844      // Assign the last value + 1.
2845      EnumVal = LastEnumConst->getInitVal();
2846      ++EnumVal;
2847
2848      // Check for overflow on increment.
2849      if (EnumVal < LastEnumConst->getInitVal())
2850        Diag(IdLoc, diag::warn_enum_value_overflow);
2851
2852      EltTy = LastEnumConst->getType();
2853    } else {
2854      // First value, set to zero.
2855      EltTy = Context.IntTy;
2856      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
2857    }
2858  }
2859
2860  EnumConstantDecl *New =
2861    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2862                             Val, EnumVal,
2863                             LastEnumConst);
2864
2865  // Register this decl in the current scope stack.
2866  PushOnScopeChains(New, S);
2867  return New;
2868}
2869
2870// FIXME: For consistency with ActOnFields(), we should have the parser
2871// pass in the source location for the left/right braces.
2872void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
2873                         DeclTy **Elements, unsigned NumElements) {
2874  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2875
2876  if (Enum && Enum->isDefinition()) {
2877    // Diagnose code like:
2878    //   enum e0 {
2879    //     E0 = sizeof(enum e0 { E1 })
2880    //   };
2881    Diag(Enum->getLocation(), diag::err_nested_redefinition,
2882         Enum->getName());
2883    Diag(EnumLoc, diag::err_previous_definition);
2884    Enum->setInvalidDecl();
2885    return;
2886  }
2887  // TODO: If the result value doesn't fit in an int, it must be a long or long
2888  // long value.  ISO C does not support this, but GCC does as an extension,
2889  // emit a warning.
2890  unsigned IntWidth = Context.Target.getIntWidth();
2891
2892  // Verify that all the values are okay, compute the size of the values, and
2893  // reverse the list.
2894  unsigned NumNegativeBits = 0;
2895  unsigned NumPositiveBits = 0;
2896
2897  // Keep track of whether all elements have type int.
2898  bool AllElementsInt = true;
2899
2900  EnumConstantDecl *EltList = 0;
2901  for (unsigned i = 0; i != NumElements; ++i) {
2902    EnumConstantDecl *ECD =
2903      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2904    if (!ECD) continue;  // Already issued a diagnostic.
2905
2906    // If the enum value doesn't fit in an int, emit an extension warning.
2907    const llvm::APSInt &InitVal = ECD->getInitVal();
2908    assert(InitVal.getBitWidth() >= IntWidth &&
2909           "Should have promoted value to int");
2910    if (InitVal.getBitWidth() > IntWidth) {
2911      llvm::APSInt V(InitVal);
2912      V.trunc(IntWidth);
2913      V.extend(InitVal.getBitWidth());
2914      if (V != InitVal)
2915        Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2916             InitVal.toString(10));
2917    }
2918
2919    // Keep track of the size of positive and negative values.
2920    if (InitVal.isUnsigned() || InitVal.isNonNegative())
2921      NumPositiveBits = std::max(NumPositiveBits,
2922                                 (unsigned)InitVal.getActiveBits());
2923    else
2924      NumNegativeBits = std::max(NumNegativeBits,
2925                                 (unsigned)InitVal.getMinSignedBits());
2926
2927    // Keep track of whether every enum element has type int (very commmon).
2928    if (AllElementsInt)
2929      AllElementsInt = ECD->getType() == Context.IntTy;
2930
2931    ECD->setNextDeclarator(EltList);
2932    EltList = ECD;
2933  }
2934
2935  // Figure out the type that should be used for this enum.
2936  // FIXME: Support attribute(packed) on enums and -fshort-enums.
2937  QualType BestType;
2938  unsigned BestWidth;
2939
2940  if (NumNegativeBits) {
2941    // If there is a negative value, figure out the smallest integer type (of
2942    // int/long/longlong) that fits.
2943    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
2944      BestType = Context.IntTy;
2945      BestWidth = IntWidth;
2946    } else {
2947      BestWidth = Context.Target.getLongWidth();
2948
2949      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
2950        BestType = Context.LongTy;
2951      else {
2952        BestWidth = Context.Target.getLongLongWidth();
2953
2954        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
2955          Diag(Enum->getLocation(), diag::warn_enum_too_large);
2956        BestType = Context.LongLongTy;
2957      }
2958    }
2959  } else {
2960    // If there is no negative value, figure out which of uint, ulong, ulonglong
2961    // fits.
2962    if (NumPositiveBits <= IntWidth) {
2963      BestType = Context.UnsignedIntTy;
2964      BestWidth = IntWidth;
2965    } else if (NumPositiveBits <=
2966               (BestWidth = Context.Target.getLongWidth())) {
2967      BestType = Context.UnsignedLongTy;
2968    } else {
2969      BestWidth = Context.Target.getLongLongWidth();
2970      assert(NumPositiveBits <= BestWidth &&
2971             "How could an initializer get larger than ULL?");
2972      BestType = Context.UnsignedLongLongTy;
2973    }
2974  }
2975
2976  // Loop over all of the enumerator constants, changing their types to match
2977  // the type of the enum if needed.
2978  for (unsigned i = 0; i != NumElements; ++i) {
2979    EnumConstantDecl *ECD =
2980      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2981    if (!ECD) continue;  // Already issued a diagnostic.
2982
2983    // Standard C says the enumerators have int type, but we allow, as an
2984    // extension, the enumerators to be larger than int size.  If each
2985    // enumerator value fits in an int, type it as an int, otherwise type it the
2986    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
2987    // that X has type 'int', not 'unsigned'.
2988    if (ECD->getType() == Context.IntTy) {
2989      // Make sure the init value is signed.
2990      llvm::APSInt IV = ECD->getInitVal();
2991      IV.setIsSigned(true);
2992      ECD->setInitVal(IV);
2993      continue;  // Already int type.
2994    }
2995
2996    // Determine whether the value fits into an int.
2997    llvm::APSInt InitVal = ECD->getInitVal();
2998    bool FitsInInt;
2999    if (InitVal.isUnsigned() || !InitVal.isNegative())
3000      FitsInInt = InitVal.getActiveBits() < IntWidth;
3001    else
3002      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3003
3004    // If it fits into an integer type, force it.  Otherwise force it to match
3005    // the enum decl type.
3006    QualType NewTy;
3007    unsigned NewWidth;
3008    bool NewSign;
3009    if (FitsInInt) {
3010      NewTy = Context.IntTy;
3011      NewWidth = IntWidth;
3012      NewSign = true;
3013    } else if (ECD->getType() == BestType) {
3014      // Already the right type!
3015      continue;
3016    } else {
3017      NewTy = BestType;
3018      NewWidth = BestWidth;
3019      NewSign = BestType->isSignedIntegerType();
3020    }
3021
3022    // Adjust the APSInt value.
3023    InitVal.extOrTrunc(NewWidth);
3024    InitVal.setIsSigned(NewSign);
3025    ECD->setInitVal(InitVal);
3026
3027    // Adjust the Expr initializer and type.
3028    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3029                                          /*isLvalue=*/false));
3030    ECD->setType(NewTy);
3031  }
3032
3033  Enum->defineElements(EltList, BestType);
3034  Consumer.HandleTagDeclDefinition(Enum);
3035}
3036
3037Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3038                                          ExprTy *expr) {
3039  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3040
3041  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
3042}
3043
3044Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
3045                                     SourceLocation LBrace,
3046                                     SourceLocation RBrace,
3047                                     const char *Lang,
3048                                     unsigned StrSize,
3049                                     DeclTy *D) {
3050  LinkageSpecDecl::LanguageIDs Language;
3051  Decl *dcl = static_cast<Decl *>(D);
3052  if (strncmp(Lang, "\"C\"", StrSize) == 0)
3053    Language = LinkageSpecDecl::lang_c;
3054  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3055    Language = LinkageSpecDecl::lang_cxx;
3056  else {
3057    Diag(Loc, diag::err_bad_language);
3058    return 0;
3059  }
3060
3061  // FIXME: Add all the various semantics of linkage specifications
3062  return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
3063}
3064
3065void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3066                           ExprTy *alignment, SourceLocation PragmaLoc,
3067                           SourceLocation LParenLoc, SourceLocation RParenLoc) {
3068  Expr *Alignment = static_cast<Expr *>(alignment);
3069
3070  // If specified then alignment must be a "small" power of two.
3071  unsigned AlignmentVal = 0;
3072  if (Alignment) {
3073    llvm::APSInt Val;
3074    if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3075        !Val.isPowerOf2() ||
3076        Val.getZExtValue() > 16) {
3077      Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3078      delete Alignment;
3079      return; // Ignore
3080    }
3081
3082    AlignmentVal = (unsigned) Val.getZExtValue();
3083  }
3084
3085  switch (Kind) {
3086  case Action::PPK_Default: // pack([n])
3087    PackContext.setAlignment(AlignmentVal);
3088    break;
3089
3090  case Action::PPK_Show: // pack(show)
3091    // Show the current alignment, making sure to show the right value
3092    // for the default.
3093    AlignmentVal = PackContext.getAlignment();
3094    // FIXME: This should come from the target.
3095    if (AlignmentVal == 0)
3096      AlignmentVal = 8;
3097    Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
3098    break;
3099
3100  case Action::PPK_Push: // pack(push [, id] [, [n])
3101    PackContext.push(Name);
3102    // Set the new alignment if specified.
3103    if (Alignment)
3104      PackContext.setAlignment(AlignmentVal);
3105    break;
3106
3107  case Action::PPK_Pop: // pack(pop [, id] [,  n])
3108    // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3109    // "#pragma pack(pop, identifier, n) is undefined"
3110    if (Alignment && Name)
3111      Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3112
3113    // Do the pop.
3114    if (!PackContext.pop(Name)) {
3115      // If a name was specified then failure indicates the name
3116      // wasn't found. Otherwise failure indicates the stack was
3117      // empty.
3118      Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3119           Name ? "no record matching name" : "stack empty");
3120
3121      // FIXME: Warn about popping named records as MSVC does.
3122    } else {
3123      // Pop succeeded, set the new alignment if specified.
3124      if (Alignment)
3125        PackContext.setAlignment(AlignmentVal);
3126    }
3127    break;
3128
3129  default:
3130    assert(0 && "Invalid #pragma pack kind.");
3131  }
3132}
3133
3134bool PragmaPackStack::pop(IdentifierInfo *Name) {
3135  if (Stack.empty())
3136    return false;
3137
3138  // If name is empty just pop top.
3139  if (!Name) {
3140    Alignment = Stack.back().first;
3141    Stack.pop_back();
3142    return true;
3143  }
3144
3145  // Otherwise, find the named record.
3146  for (unsigned i = Stack.size(); i != 0; ) {
3147    --i;
3148    if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3149      // Found it, pop up to and including this record.
3150      Alignment = Stack[i].first;
3151      Stack.erase(Stack.begin() + i, Stack.end());
3152      return true;
3153    }
3154  }
3155
3156  return false;
3157}
3158