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