SemaDecl.cpp revision c5eb7311445bb14b6a26eb2ad667fe7a1ca20887
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(const IdentifierInfo &II, Scope *S) {
31  Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
32
33  if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
34                 isa<ObjCInterfaceDecl>(IIDecl) ||
35                 isa<TagDecl>(IIDecl)))
36    return IIDecl;
37  return 0;
38}
39
40DeclContext *Sema::getDCParent(DeclContext *DC) {
41  // If CurContext is a ObjC method, getParent() will return NULL.
42  if (isa<ObjCMethodDecl>(DC))
43    return Context.getTranslationUnitDecl();
44
45  // A C++ inline method is parsed *after* the topmost class it was declared in
46  // is fully parsed (it's "complete").
47  // The parsing of a C++ inline method happens at the declaration context of
48  // the topmost (non-nested) class it is declared in.
49  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
50    assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
51    DC = MD->getParent();
52    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
53      DC = RD;
54
55    // Return the declaration context of the topmost class the inline method is
56    // declared in.
57    return DC;
58  }
59
60  return DC->getParent();
61}
62
63void Sema::PushDeclContext(DeclContext *DC) {
64  assert(getDCParent(DC) == CurContext &&
65       "The next DeclContext should be directly contained in the current one.");
66  CurContext = DC;
67}
68
69void Sema::PopDeclContext() {
70  assert(CurContext && "DeclContext imbalance!");
71  CurContext = getDCParent(CurContext);
72}
73
74/// Add this decl to the scope shadowed decl chains.
75void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
76  S->AddDecl(D);
77
78  // C++ [basic.scope]p4:
79  //   -- exactly one declaration shall declare a class name or
80  //   enumeration name that is not a typedef name and the other
81  //   declarations shall all refer to the same object or
82  //   enumerator, or all refer to functions and function templates;
83  //   in this case the class name or enumeration name is hidden.
84  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
85    // We are pushing the name of a tag (enum or class).
86    IdentifierResolver::iterator
87        I = IdResolver.begin(TD->getIdentifier(),
88                             TD->getDeclContext(), false/*LookInParentCtx*/);
89    if (I != IdResolver.end() &&
90        IdResolver.isDeclInScope(*I, TD->getDeclContext(), S)) {
91      // There is already a declaration with the same name in the same
92      // scope. It must be found before we find the new declaration,
93      // so swap the order on the shadowed declaration chain.
94
95      IdResolver.AddShadowedDecl(TD, *I);
96      return;
97    }
98  }
99  IdResolver.AddDecl(D);
100}
101
102void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
103  if (S->decl_empty()) return;
104  assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
105
106  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
107       I != E; ++I) {
108    Decl *TmpD = static_cast<Decl*>(*I);
109    assert(TmpD && "This decl didn't get pushed??");
110
111    if (isa<CXXFieldDecl>(TmpD)) continue;
112
113    assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
114    ScopedDecl *D = cast<ScopedDecl>(TmpD);
115
116    IdentifierInfo *II = D->getIdentifier();
117    if (!II) continue;
118
119    // We only want to remove the decls from the identifier decl chains for local
120    // scopes, when inside a function/method.
121    if (S->getFnParent() != 0)
122      IdResolver.RemoveDecl(D);
123
124    // Chain this decl to the containing DeclContext.
125    D->setNext(CurContext->getDeclChain());
126    CurContext->setDeclChain(D);
127  }
128}
129
130/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
131/// return 0 if one not found.
132ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
133  // The third "scope" argument is 0 since we aren't enabling lazy built-in
134  // creation from this context.
135  Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
136
137  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
138}
139
140/// LookupDecl - Look up the inner-most declaration in the specified
141/// namespace.
142Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
143                       Scope *S, bool enableLazyBuiltinCreation) {
144  if (II == 0) return 0;
145  unsigned NS = NSI;
146  if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
147    NS |= Decl::IDNS_Tag;
148
149  // Scan up the scope chain looking for a decl that matches this identifier
150  // that is in the appropriate namespace.  This search should not take long, as
151  // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
152  for (IdentifierResolver::iterator
153       I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
154    if ((*I)->getIdentifierNamespace() & NS)
155      return *I;
156
157  // If we didn't find a use of this identifier, and if the identifier
158  // corresponds to a compiler builtin, create the decl object for the builtin
159  // now, injecting it into translation unit scope, and return it.
160  if (NS & Decl::IDNS_Ordinary) {
161    if (enableLazyBuiltinCreation) {
162      // If this is a builtin on this (or all) targets, create the decl.
163      if (unsigned BuiltinID = II->getBuiltinID())
164        return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
165    }
166    if (getLangOptions().ObjC1) {
167      // @interface and @compatibility_alias introduce typedef-like names.
168      // Unlike typedef's, they can only be introduced at file-scope (and are
169      // therefore not scoped decls). They can, however, be shadowed by
170      // other names in IDNS_Ordinary.
171      ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
172      if (IDI != ObjCInterfaceDecls.end())
173        return IDI->second;
174      ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
175      if (I != ObjCAliasDecls.end())
176        return I->second->getClassInterface();
177    }
178  }
179  return 0;
180}
181
182void Sema::InitBuiltinVaListType() {
183  if (!Context.getBuiltinVaListType().isNull())
184    return;
185
186  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
187  Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
188  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
189  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
190}
191
192/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
193/// lazily create a decl for it.
194ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
195                                      Scope *S) {
196  Builtin::ID BID = (Builtin::ID)bid;
197
198  if (BID == Builtin::BI__builtin_va_start ||
199      BID == Builtin::BI__builtin_va_copy ||
200      BID == Builtin::BI__builtin_va_end ||
201      BID == Builtin::BI__builtin_stdarg_start)
202    InitBuiltinVaListType();
203
204  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
205  FunctionDecl *New = FunctionDecl::Create(Context,
206                                           Context.getTranslationUnitDecl(),
207                                           SourceLocation(), II, R,
208                                           FunctionDecl::Extern, false, 0);
209
210  // Create Decl objects for each parameter, adding them to the
211  // FunctionDecl.
212  if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
213    llvm::SmallVector<ParmVarDecl*, 16> Params;
214    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
215      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
216                                           FT->getArgType(i), VarDecl::None, 0,
217                                           0));
218    New->setParams(&Params[0], Params.size());
219  }
220
221
222
223  // TUScope is the translation-unit scope to insert this function into.
224  PushOnScopeChains(New, TUScope);
225  return New;
226}
227
228/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
229/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
230/// situation, merging decls or emitting diagnostics as appropriate.
231///
232TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
233  // Verify the old decl was also a typedef.
234  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
235  if (!Old) {
236    Diag(New->getLocation(), diag::err_redefinition_different_kind,
237         New->getName());
238    Diag(OldD->getLocation(), diag::err_previous_definition);
239    return New;
240  }
241
242  // If the typedef types are not identical, reject them in all languages and
243  // with any extensions enabled.
244  if (Old->getUnderlyingType() != New->getUnderlyingType() &&
245      Context.getCanonicalType(Old->getUnderlyingType()) !=
246      Context.getCanonicalType(New->getUnderlyingType())) {
247    Diag(New->getLocation(), diag::err_redefinition_different_typedef,
248         New->getUnderlyingType().getAsString(),
249         Old->getUnderlyingType().getAsString());
250    Diag(Old->getLocation(), diag::err_previous_definition);
251    return Old;
252  }
253
254  // Allow multiple definitions for ObjC built-in typedefs.
255  // FIXME: Verify the underlying types are equivalent!
256  if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
257    return Old;
258
259  if (getLangOptions().Microsoft) return New;
260
261  // Redeclaration of a type is a constraint violation (6.7.2.3p1).
262  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
263  // *either* declaration is in a system header. The code below implements
264  // this adhoc compatibility rule. FIXME: The following code will not
265  // work properly when compiling ".i" files (containing preprocessed output).
266  SourceManager &SrcMgr = Context.getSourceManager();
267  HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
268  const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
269  if (OldDeclFile) {
270    DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
271    // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
272    if (OldDirType != DirectoryLookup::NormalHeaderDir)
273      return New;
274  }
275  const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
276  if (NewDeclFile) {
277    DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
278    // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
279    if (NewDirType != DirectoryLookup::NormalHeaderDir)
280      return New;
281  }
282
283  Diag(New->getLocation(), diag::err_redefinition, New->getName());
284  Diag(Old->getLocation(), diag::err_previous_definition);
285  return New;
286}
287
288/// DeclhasAttr - returns true if decl Declaration already has the target
289/// attribute.
290static bool DeclHasAttr(const Decl *decl, const Attr *target) {
291  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
292    if (attr->getKind() == target->getKind())
293      return true;
294
295  return false;
296}
297
298/// MergeAttributes - append attributes from the Old decl to the New one.
299static void MergeAttributes(Decl *New, Decl *Old) {
300  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
301
302  while (attr) {
303     tmp = attr;
304     attr = attr->getNext();
305
306    if (!DeclHasAttr(New, tmp)) {
307       New->addAttr(tmp);
308    } else {
309       tmp->setNext(0);
310       delete(tmp);
311    }
312  }
313
314  Old->invalidateAttrs();
315}
316
317/// MergeFunctionDecl - We just parsed a function 'New' from
318/// declarator D which has the same name and scope as a previous
319/// declaration 'Old'.  Figure out how to resolve this situation,
320/// merging decls or emitting diagnostics as appropriate.
321/// Redeclaration will be set true if thisNew is a redeclaration OldD.
322FunctionDecl *
323Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
324  Redeclaration = false;
325  // Verify the old decl was also a function.
326  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
327  if (!Old) {
328    Diag(New->getLocation(), diag::err_redefinition_different_kind,
329         New->getName());
330    Diag(OldD->getLocation(), diag::err_previous_definition);
331    return New;
332  }
333
334  QualType OldQType = Context.getCanonicalType(Old->getType());
335  QualType NewQType = Context.getCanonicalType(New->getType());
336
337  // C++ [dcl.fct]p3:
338  //   All declarations for a function shall agree exactly in both the
339  //   return type and the parameter-type-list.
340  if (getLangOptions().CPlusPlus && OldQType == NewQType) {
341    MergeAttributes(New, Old);
342    Redeclaration = true;
343    return MergeCXXFunctionDecl(New, Old);
344  }
345
346  // C: Function types need to be compatible, not identical. This handles
347  // duplicate function decls like "void f(int); void f(enum X);" properly.
348  if (!getLangOptions().CPlusPlus &&
349      Context.typesAreCompatible(OldQType, NewQType)) {
350    MergeAttributes(New, Old);
351    Redeclaration = true;
352    return New;
353  }
354
355  // A function that has already been declared has been redeclared or defined
356  // with a different type- show appropriate diagnostic
357  diag::kind PrevDiag;
358  if (Old->isThisDeclarationADefinition())
359    PrevDiag = diag::err_previous_definition;
360  else if (Old->isImplicit())
361    PrevDiag = diag::err_previous_implicit_declaration;
362  else
363    PrevDiag = diag::err_previous_declaration;
364
365  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
366  // TODO: This is totally simplistic.  It should handle merging functions
367  // together etc, merging extern int X; int X; ...
368  Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
369  Diag(Old->getLocation(), PrevDiag);
370  return New;
371}
372
373/// Predicate for C "tentative" external object definitions (C99 6.9.2).
374static bool isTentativeDefinition(VarDecl *VD) {
375  if (VD->isFileVarDecl())
376    return (!VD->getInit() &&
377            (VD->getStorageClass() == VarDecl::None ||
378             VD->getStorageClass() == VarDecl::Static));
379  return false;
380}
381
382/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
383/// when dealing with C "tentative" external object definitions (C99 6.9.2).
384void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
385  bool VDIsTentative = isTentativeDefinition(VD);
386  bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
387
388  for (IdentifierResolver::iterator
389       I = IdResolver.begin(VD->getIdentifier(),
390                            VD->getDeclContext(), false/*LookInParentCtx*/),
391       E = IdResolver.end(); I != E; ++I) {
392    if (*I != VD && IdResolver.isDeclInScope(*I, VD->getDeclContext(), S)) {
393      VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
394
395      // Handle the following case:
396      //   int a[10];
397      //   int a[];   - the code below makes sure we set the correct type.
398      //   int a[11]; - this is an error, size isn't 10.
399      if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
400          OldDecl->getType()->isConstantArrayType())
401        VD->setType(OldDecl->getType());
402
403      // Check for "tentative" definitions. We can't accomplish this in
404      // MergeVarDecl since the initializer hasn't been attached.
405      if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
406        continue;
407
408      // Handle __private_extern__ just like extern.
409      if (OldDecl->getStorageClass() != VarDecl::Extern &&
410          OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
411          VD->getStorageClass() != VarDecl::Extern &&
412          VD->getStorageClass() != VarDecl::PrivateExtern) {
413        Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
414        Diag(OldDecl->getLocation(), diag::err_previous_definition);
415      }
416    }
417  }
418}
419
420/// MergeVarDecl - We just parsed a variable 'New' which has the same name
421/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
422/// situation, merging decls or emitting diagnostics as appropriate.
423///
424/// Tentative definition rules (C99 6.9.2p2) are checked by
425/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
426/// definitions here, since the initializer hasn't been attached.
427///
428VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
429  // Verify the old decl was also a variable.
430  VarDecl *Old = dyn_cast<VarDecl>(OldD);
431  if (!Old) {
432    Diag(New->getLocation(), diag::err_redefinition_different_kind,
433         New->getName());
434    Diag(OldD->getLocation(), diag::err_previous_definition);
435    return New;
436  }
437
438  MergeAttributes(New, Old);
439
440  // Verify the types match.
441  QualType OldCType = Context.getCanonicalType(Old->getType());
442  QualType NewCType = Context.getCanonicalType(New->getType());
443  if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
444    Diag(New->getLocation(), diag::err_redefinition, New->getName());
445    Diag(Old->getLocation(), diag::err_previous_definition);
446    return New;
447  }
448  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
449  if (New->getStorageClass() == VarDecl::Static &&
450      (Old->getStorageClass() == VarDecl::None ||
451       Old->getStorageClass() == VarDecl::Extern)) {
452    Diag(New->getLocation(), diag::err_static_non_static, New->getName());
453    Diag(Old->getLocation(), diag::err_previous_definition);
454    return New;
455  }
456  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
457  if (New->getStorageClass() != VarDecl::Static &&
458      Old->getStorageClass() == VarDecl::Static) {
459    Diag(New->getLocation(), diag::err_non_static_static, New->getName());
460    Diag(Old->getLocation(), diag::err_previous_definition);
461    return New;
462  }
463  // File scoped variables are analyzed in FinalizeDeclaratorGroup.
464  if (!New->isFileVarDecl()) {
465    Diag(New->getLocation(), diag::err_redefinition, New->getName());
466    Diag(Old->getLocation(), diag::err_previous_definition);
467  }
468  return New;
469}
470
471/// CheckParmsForFunctionDef - Check that the parameters of the given
472/// function are appropriate for the definition of a function. This
473/// takes care of any checks that cannot be performed on the
474/// declaration itself, e.g., that the types of each of the function
475/// parameters are complete.
476bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
477  bool HasInvalidParm = false;
478  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
479    ParmVarDecl *Param = FD->getParamDecl(p);
480
481    // C99 6.7.5.3p4: the parameters in a parameter type list in a
482    // function declarator that is part of a function definition of
483    // that function shall not have incomplete type.
484    if (Param->getType()->isIncompleteType() &&
485        !Param->isInvalidDecl()) {
486      Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
487           Param->getType().getAsString());
488      Param->setInvalidDecl();
489      HasInvalidParm = true;
490    }
491  }
492
493  return HasInvalidParm;
494}
495
496/// CreateImplicitParameter - Creates an implicit function parameter
497/// in the scope S and with the given type. This routine is used, for
498/// example, to create the implicit "self" parameter in an Objective-C
499/// method.
500ImplicitParamDecl *
501Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
502                              SourceLocation IdLoc, QualType Type) {
503  ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
504      IdLoc, Id, Type, 0);
505  if (Id)
506    PushOnScopeChains(New, S);
507
508  return New;
509}
510
511/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
512/// no declarator (e.g. "struct foo;") is parsed.
513Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
514  // TODO: emit error on 'int;' or 'const enum foo;'.
515  // TODO: emit error on 'typedef int;'
516  // if (!DS.isMissingDeclaratorOk()) Diag(...);
517
518  return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
519}
520
521bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
522  // Get the type before calling CheckSingleAssignmentConstraints(), since
523  // it can promote the expression.
524  QualType InitType = Init->getType();
525
526  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
527  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
528                                  InitType, Init, "initializing");
529}
530
531bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
532  const ArrayType *AT = Context.getAsArrayType(DeclT);
533
534  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
535    // C99 6.7.8p14. We have an array of character type with unknown size
536    // being initialized to a string literal.
537    llvm::APSInt ConstVal(32);
538    ConstVal = strLiteral->getByteLength() + 1;
539    // Return a new array type (C99 6.7.8p22).
540    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
541                                         ArrayType::Normal, 0);
542  } else {
543    const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
544    // C99 6.7.8p14. We have an array of character type with known size.
545    // FIXME: Avoid truncation for 64-bit length strings.
546    if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
547      Diag(strLiteral->getSourceRange().getBegin(),
548           diag::warn_initializer_string_for_char_array_too_long,
549           strLiteral->getSourceRange());
550  }
551  // Set type from "char *" to "constant array of char".
552  strLiteral->setType(DeclT);
553  // For now, we always return false (meaning success).
554  return false;
555}
556
557StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
558  const ArrayType *AT = Context.getAsArrayType(DeclType);
559  if (AT && AT->getElementType()->isCharType()) {
560    return dyn_cast<StringLiteral>(Init);
561  }
562  return 0;
563}
564
565bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
566  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
567  // of unknown size ("[]") or an object type that is not a variable array type.
568  if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
569    return Diag(VAT->getSizeExpr()->getLocStart(),
570                diag::err_variable_object_no_init,
571                VAT->getSizeExpr()->getSourceRange());
572
573  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
574  if (!InitList) {
575    // FIXME: Handle wide strings
576    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
577      return CheckStringLiteralInit(strLiteral, DeclType);
578
579    if (DeclType->isArrayType())
580      return Diag(Init->getLocStart(),
581                  diag::err_array_init_list_required,
582                  Init->getSourceRange());
583
584    return CheckSingleInitializer(Init, DeclType);
585  }
586
587  InitListChecker CheckInitList(this, InitList, DeclType);
588  return CheckInitList.HadError();
589}
590
591Sema::DeclTy *
592Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
593  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
594  IdentifierInfo *II = D.getIdentifier();
595
596  // All of these full declarators require an identifier.  If it doesn't have
597  // one, the ParsedFreeStandingDeclSpec action should be used.
598  if (II == 0) {
599    Diag(D.getDeclSpec().getSourceRange().getBegin(),
600         diag::err_declarator_need_ident,
601         D.getDeclSpec().getSourceRange(), D.getSourceRange());
602    return 0;
603  }
604
605  // The scope passed in may not be a decl scope.  Zip up the scope tree until
606  // we find one that is.
607  while ((S->getFlags() & Scope::DeclScope) == 0)
608    S = S->getParent();
609
610  // See if this is a redefinition of a variable in the same scope.
611  Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
612  ScopedDecl *New;
613  bool InvalidDecl = false;
614
615  // In C++, the previous declaration we find might be a tag type
616  // (class or enum). In this case, the new declaration will hide the
617  // tag type.
618  if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
619    PrevDecl = 0;
620
621  QualType R = GetTypeForDeclarator(D, S);
622  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
623
624  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
625    // Check that there are no default arguments (C++ only).
626    if (getLangOptions().CPlusPlus)
627      CheckExtraCXXDefaultArguments(D);
628
629    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
630    if (!NewTD) return 0;
631
632    // Handle attributes prior to checking for duplicates in MergeVarDecl
633    ProcessDeclAttributes(NewTD, D);
634    // Merge the decl with the existing one if appropriate. If the decl is
635    // in an outer scope, it isn't the same thing.
636    if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
637      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
638      if (NewTD == 0) return 0;
639    }
640    New = NewTD;
641    if (S->getFnParent() == 0) {
642      // C99 6.7.7p2: If a typedef name specifies a variably modified type
643      // then it shall have block scope.
644      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
645        // FIXME: Diagnostic needs to be fixed.
646        Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
647        InvalidDecl = true;
648      }
649    }
650  } else if (R.getTypePtr()->isFunctionType()) {
651    FunctionDecl::StorageClass SC = FunctionDecl::None;
652    switch (D.getDeclSpec().getStorageClassSpec()) {
653      default: assert(0 && "Unknown storage class!");
654      case DeclSpec::SCS_auto:
655      case DeclSpec::SCS_register:
656        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
657             R.getAsString());
658        InvalidDecl = true;
659        break;
660      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
661      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
662      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
663      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
664    }
665
666    bool isInline = D.getDeclSpec().isInlineSpecified();
667    FunctionDecl *NewFD;
668    if (D.getContext() == Declarator::MemberContext) {
669      // This is a C++ method declaration.
670      NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
671                                    D.getIdentifierLoc(), II, R,
672                                    (SC == FunctionDecl::Static), isInline,
673                                    LastDeclarator);
674    } else {
675      NewFD = FunctionDecl::Create(Context, CurContext,
676                                   D.getIdentifierLoc(),
677                                   II, R, SC, isInline,
678                                   LastDeclarator);
679    }
680    // Handle attributes.
681    ProcessDeclAttributes(NewFD, D);
682
683    // Handle GNU asm-label extension (encoded as an attribute).
684    if (Expr *E = (Expr*) D.getAsmLabel()) {
685      // The parser guarantees this is a string.
686      StringLiteral *SE = cast<StringLiteral>(E);
687      NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
688                                                  SE->getByteLength())));
689    }
690
691    // Copy the parameter declarations from the declarator D to
692    // the function declaration NewFD, if they are available.
693    if (D.getNumTypeObjects() > 0 &&
694        D.getTypeObject(0).Fun.hasPrototype) {
695      DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
696
697      // Create Decl objects for each parameter, adding them to the
698      // FunctionDecl.
699      llvm::SmallVector<ParmVarDecl*, 16> Params;
700
701      // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
702      // function that takes no arguments, not a function that takes a
703      // single void argument.
704      // We let through "const void" here because Sema::GetTypeForDeclarator
705      // already checks for that case.
706      if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
707          FTI.ArgInfo[0].Param &&
708          ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
709        // empty arg list, don't push any params.
710        ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
711
712        // In C++, the empty parameter-type-list must be spelled "void"; a
713        // typedef of void is not permitted.
714        if (getLangOptions().CPlusPlus &&
715            Param->getType().getUnqualifiedType() != Context.VoidTy) {
716          Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
717        }
718
719      } else {
720        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
721          Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
722      }
723
724      NewFD->setParams(&Params[0], Params.size());
725    }
726
727    // Merge the decl with the existing one if appropriate. Since C functions
728    // are in a flat namespace, make sure we consider decls in outer scopes.
729    if (PrevDecl &&
730        (!getLangOptions().CPlusPlus ||
731         IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
732      bool Redeclaration = false;
733      NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
734      if (NewFD == 0) return 0;
735      if (Redeclaration) {
736        NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
737      }
738    }
739    New = NewFD;
740
741    // In C++, check default arguments now that we have merged decls.
742    if (getLangOptions().CPlusPlus)
743      CheckCXXDefaultArguments(NewFD);
744  } else {
745    // Check that there are no default arguments (C++ only).
746    if (getLangOptions().CPlusPlus)
747      CheckExtraCXXDefaultArguments(D);
748
749    if (R.getTypePtr()->isObjCInterfaceType()) {
750      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
751           D.getIdentifier()->getName());
752      InvalidDecl = true;
753    }
754
755    VarDecl *NewVD;
756    VarDecl::StorageClass SC;
757    switch (D.getDeclSpec().getStorageClassSpec()) {
758    default: assert(0 && "Unknown storage class!");
759    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
760    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
761    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
762    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
763    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
764    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
765    }
766    if (D.getContext() == Declarator::MemberContext) {
767      assert(SC == VarDecl::Static && "Invalid storage class for member!");
768      // This is a static data member for a C++ class.
769      NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
770                                      D.getIdentifierLoc(), II,
771                                      R, LastDeclarator);
772    } else {
773      if (S->getFnParent() == 0) {
774        // C99 6.9p2: The storage-class specifiers auto and register shall not
775        // appear in the declaration specifiers in an external declaration.
776        if (SC == VarDecl::Auto || SC == VarDecl::Register) {
777          Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
778               R.getAsString());
779          InvalidDecl = true;
780        }
781        NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
782                                II, R, SC, LastDeclarator);
783      } else {
784        NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
785                                II, R, SC, LastDeclarator);
786      }
787    }
788    // Handle attributes prior to checking for duplicates in MergeVarDecl
789    ProcessDeclAttributes(NewVD, D);
790
791    // Handle GNU asm-label extension (encoded as an attribute).
792    if (Expr *E = (Expr*) D.getAsmLabel()) {
793      // The parser guarantees this is a string.
794      StringLiteral *SE = cast<StringLiteral>(E);
795      NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
796                                                  SE->getByteLength())));
797    }
798
799    // Emit an error if an address space was applied to decl with local storage.
800    // This includes arrays of objects with address space qualifiers, but not
801    // automatic variables that point to other address spaces.
802    // ISO/IEC TR 18037 S5.1.2
803    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
804      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
805      InvalidDecl = true;
806    }
807    // Merge the decl with the existing one if appropriate. If the decl is
808    // in an outer scope, it isn't the same thing.
809    if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
810      NewVD = MergeVarDecl(NewVD, PrevDecl);
811      if (NewVD == 0) return 0;
812    }
813    New = NewVD;
814  }
815
816  // If this has an identifier, add it to the scope stack.
817  if (II)
818    PushOnScopeChains(New, S);
819  // If any semantic error occurred, mark the decl as invalid.
820  if (D.getInvalidType() || InvalidDecl)
821    New->setInvalidDecl();
822
823  return New;
824}
825
826bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
827  switch (Init->getStmtClass()) {
828  default:
829    Diag(Init->getExprLoc(),
830         diag::err_init_element_not_constant, Init->getSourceRange());
831    return true;
832  case Expr::ParenExprClass: {
833    const ParenExpr* PE = cast<ParenExpr>(Init);
834    return CheckAddressConstantExpressionLValue(PE->getSubExpr());
835  }
836  case Expr::CompoundLiteralExprClass:
837    return cast<CompoundLiteralExpr>(Init)->isFileScope();
838  case Expr::DeclRefExprClass: {
839    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
840    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
841      if (VD->hasGlobalStorage())
842        return false;
843      Diag(Init->getExprLoc(),
844           diag::err_init_element_not_constant, Init->getSourceRange());
845      return true;
846    }
847    if (isa<FunctionDecl>(D))
848      return false;
849    Diag(Init->getExprLoc(),
850         diag::err_init_element_not_constant, Init->getSourceRange());
851    return true;
852  }
853  case Expr::MemberExprClass: {
854    const MemberExpr *M = cast<MemberExpr>(Init);
855    if (M->isArrow())
856      return CheckAddressConstantExpression(M->getBase());
857    return CheckAddressConstantExpressionLValue(M->getBase());
858  }
859  case Expr::ArraySubscriptExprClass: {
860    // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
861    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
862    return CheckAddressConstantExpression(ASE->getBase()) ||
863           CheckArithmeticConstantExpression(ASE->getIdx());
864  }
865  case Expr::StringLiteralClass:
866  case Expr::PredefinedExprClass:
867    return false;
868  case Expr::UnaryOperatorClass: {
869    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
870
871    // C99 6.6p9
872    if (Exp->getOpcode() == UnaryOperator::Deref)
873      return CheckAddressConstantExpression(Exp->getSubExpr());
874
875    Diag(Init->getExprLoc(),
876         diag::err_init_element_not_constant, Init->getSourceRange());
877    return true;
878  }
879  }
880}
881
882bool Sema::CheckAddressConstantExpression(const Expr* Init) {
883  switch (Init->getStmtClass()) {
884  default:
885    Diag(Init->getExprLoc(),
886         diag::err_init_element_not_constant, Init->getSourceRange());
887    return true;
888  case Expr::ParenExprClass: {
889    const ParenExpr* PE = cast<ParenExpr>(Init);
890    return CheckAddressConstantExpression(PE->getSubExpr());
891  }
892  case Expr::StringLiteralClass:
893  case Expr::ObjCStringLiteralClass:
894    return false;
895  case Expr::CallExprClass: {
896    const CallExpr *CE = cast<CallExpr>(Init);
897    if (CE->isBuiltinConstantExpr())
898      return false;
899    Diag(Init->getExprLoc(),
900         diag::err_init_element_not_constant, Init->getSourceRange());
901    return true;
902  }
903  case Expr::UnaryOperatorClass: {
904    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
905
906    // C99 6.6p9
907    if (Exp->getOpcode() == UnaryOperator::AddrOf)
908      return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
909
910    if (Exp->getOpcode() == UnaryOperator::Extension)
911      return CheckAddressConstantExpression(Exp->getSubExpr());
912
913    Diag(Init->getExprLoc(),
914         diag::err_init_element_not_constant, Init->getSourceRange());
915    return true;
916  }
917  case Expr::BinaryOperatorClass: {
918    // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
919    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
920
921    Expr *PExp = Exp->getLHS();
922    Expr *IExp = Exp->getRHS();
923    if (IExp->getType()->isPointerType())
924      std::swap(PExp, IExp);
925
926    // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
927    return CheckAddressConstantExpression(PExp) ||
928           CheckArithmeticConstantExpression(IExp);
929  }
930  case Expr::ImplicitCastExprClass: {
931    const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
932
933    // Check for implicit promotion
934    if (SubExpr->getType()->isFunctionType() ||
935        SubExpr->getType()->isArrayType())
936      return CheckAddressConstantExpressionLValue(SubExpr);
937
938    // Check for pointer->pointer cast
939    if (SubExpr->getType()->isPointerType())
940      return CheckAddressConstantExpression(SubExpr);
941
942    if (SubExpr->getType()->isArithmeticType())
943      return CheckArithmeticConstantExpression(SubExpr);
944
945    Diag(Init->getExprLoc(),
946         diag::err_init_element_not_constant, Init->getSourceRange());
947    return true;
948  }
949  case Expr::ExplicitCastExprClass: {
950    const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
951
952    // Check for pointer->pointer cast
953    if (SubExpr->getType()->isPointerType())
954      return CheckAddressConstantExpression(SubExpr);
955
956    // FIXME: Should we pedwarn for (int*)(0+0)?
957    if (SubExpr->getType()->isArithmeticType())
958      return CheckArithmeticConstantExpression(SubExpr);
959
960    Diag(Init->getExprLoc(),
961         diag::err_init_element_not_constant, Init->getSourceRange());
962    return true;
963  }
964  case Expr::ConditionalOperatorClass: {
965    // FIXME: Should we pedwarn here?
966    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
967    if (!Exp->getCond()->getType()->isArithmeticType()) {
968      Diag(Init->getExprLoc(),
969           diag::err_init_element_not_constant, Init->getSourceRange());
970      return true;
971    }
972    if (CheckArithmeticConstantExpression(Exp->getCond()))
973      return true;
974    if (Exp->getLHS() &&
975        CheckAddressConstantExpression(Exp->getLHS()))
976      return true;
977    return CheckAddressConstantExpression(Exp->getRHS());
978  }
979  case Expr::AddrLabelExprClass:
980    return false;
981  }
982}
983
984static const Expr* FindExpressionBaseAddress(const Expr* E);
985
986static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
987  switch (E->getStmtClass()) {
988  default:
989    return E;
990  case Expr::ParenExprClass: {
991    const ParenExpr* PE = cast<ParenExpr>(E);
992    return FindExpressionBaseAddressLValue(PE->getSubExpr());
993  }
994  case Expr::MemberExprClass: {
995    const MemberExpr *M = cast<MemberExpr>(E);
996    if (M->isArrow())
997      return FindExpressionBaseAddress(M->getBase());
998    return FindExpressionBaseAddressLValue(M->getBase());
999  }
1000  case Expr::ArraySubscriptExprClass: {
1001    const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1002    return FindExpressionBaseAddress(ASE->getBase());
1003  }
1004  case Expr::UnaryOperatorClass: {
1005    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1006
1007    if (Exp->getOpcode() == UnaryOperator::Deref)
1008      return FindExpressionBaseAddress(Exp->getSubExpr());
1009
1010    return E;
1011  }
1012  }
1013}
1014
1015static const Expr* FindExpressionBaseAddress(const Expr* E) {
1016  switch (E->getStmtClass()) {
1017  default:
1018    return E;
1019  case Expr::ParenExprClass: {
1020    const ParenExpr* PE = cast<ParenExpr>(E);
1021    return FindExpressionBaseAddress(PE->getSubExpr());
1022  }
1023  case Expr::UnaryOperatorClass: {
1024    const UnaryOperator *Exp = cast<UnaryOperator>(E);
1025
1026    // C99 6.6p9
1027    if (Exp->getOpcode() == UnaryOperator::AddrOf)
1028      return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1029
1030    if (Exp->getOpcode() == UnaryOperator::Extension)
1031      return FindExpressionBaseAddress(Exp->getSubExpr());
1032
1033    return E;
1034  }
1035  case Expr::BinaryOperatorClass: {
1036    const BinaryOperator *Exp = cast<BinaryOperator>(E);
1037
1038    Expr *PExp = Exp->getLHS();
1039    Expr *IExp = Exp->getRHS();
1040    if (IExp->getType()->isPointerType())
1041      std::swap(PExp, IExp);
1042
1043    return FindExpressionBaseAddress(PExp);
1044  }
1045  case Expr::ImplicitCastExprClass: {
1046    const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1047
1048    // Check for implicit promotion
1049    if (SubExpr->getType()->isFunctionType() ||
1050        SubExpr->getType()->isArrayType())
1051      return FindExpressionBaseAddressLValue(SubExpr);
1052
1053    // Check for pointer->pointer cast
1054    if (SubExpr->getType()->isPointerType())
1055      return FindExpressionBaseAddress(SubExpr);
1056
1057    // We assume that we have an arithmetic expression here;
1058    // if we don't, we'll figure it out later
1059    return 0;
1060  }
1061  case Expr::ExplicitCastExprClass: {
1062    const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1063
1064    // Check for pointer->pointer cast
1065    if (SubExpr->getType()->isPointerType())
1066      return FindExpressionBaseAddress(SubExpr);
1067
1068    // We assume that we have an arithmetic expression here;
1069    // if we don't, we'll figure it out later
1070    return 0;
1071  }
1072  }
1073}
1074
1075bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1076  switch (Init->getStmtClass()) {
1077  default:
1078    Diag(Init->getExprLoc(),
1079         diag::err_init_element_not_constant, Init->getSourceRange());
1080    return true;
1081  case Expr::ParenExprClass: {
1082    const ParenExpr* PE = cast<ParenExpr>(Init);
1083    return CheckArithmeticConstantExpression(PE->getSubExpr());
1084  }
1085  case Expr::FloatingLiteralClass:
1086  case Expr::IntegerLiteralClass:
1087  case Expr::CharacterLiteralClass:
1088  case Expr::ImaginaryLiteralClass:
1089  case Expr::TypesCompatibleExprClass:
1090  case Expr::CXXBoolLiteralExprClass:
1091    return false;
1092  case Expr::CallExprClass: {
1093    const CallExpr *CE = cast<CallExpr>(Init);
1094    if (CE->isBuiltinConstantExpr())
1095      return false;
1096    Diag(Init->getExprLoc(),
1097         diag::err_init_element_not_constant, Init->getSourceRange());
1098    return true;
1099  }
1100  case Expr::DeclRefExprClass: {
1101    const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1102    if (isa<EnumConstantDecl>(D))
1103      return false;
1104    Diag(Init->getExprLoc(),
1105         diag::err_init_element_not_constant, Init->getSourceRange());
1106    return true;
1107  }
1108  case Expr::CompoundLiteralExprClass:
1109    // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1110    // but vectors are allowed to be magic.
1111    if (Init->getType()->isVectorType())
1112      return false;
1113    Diag(Init->getExprLoc(),
1114         diag::err_init_element_not_constant, Init->getSourceRange());
1115    return true;
1116  case Expr::UnaryOperatorClass: {
1117    const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1118
1119    switch (Exp->getOpcode()) {
1120    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1121    // See C99 6.6p3.
1122    default:
1123      Diag(Init->getExprLoc(),
1124           diag::err_init_element_not_constant, Init->getSourceRange());
1125      return true;
1126    case UnaryOperator::SizeOf:
1127    case UnaryOperator::AlignOf:
1128    case UnaryOperator::OffsetOf:
1129      // sizeof(E) is a constantexpr if and only if E is not evaluted.
1130      // See C99 6.5.3.4p2 and 6.6p3.
1131      if (Exp->getSubExpr()->getType()->isConstantSizeType())
1132        return false;
1133      Diag(Init->getExprLoc(),
1134           diag::err_init_element_not_constant, Init->getSourceRange());
1135      return true;
1136    case UnaryOperator::Extension:
1137    case UnaryOperator::LNot:
1138    case UnaryOperator::Plus:
1139    case UnaryOperator::Minus:
1140    case UnaryOperator::Not:
1141      return CheckArithmeticConstantExpression(Exp->getSubExpr());
1142    }
1143  }
1144  case Expr::SizeOfAlignOfTypeExprClass: {
1145    const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1146    // Special check for void types, which are allowed as an extension
1147    if (Exp->getArgumentType()->isVoidType())
1148      return false;
1149    // alignof always evaluates to a constant.
1150    // FIXME: is sizeof(int[3.0]) a constant expression?
1151    if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1152      Diag(Init->getExprLoc(),
1153           diag::err_init_element_not_constant, Init->getSourceRange());
1154      return true;
1155    }
1156    return false;
1157  }
1158  case Expr::BinaryOperatorClass: {
1159    const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1160
1161    if (Exp->getLHS()->getType()->isArithmeticType() &&
1162        Exp->getRHS()->getType()->isArithmeticType()) {
1163      return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1164             CheckArithmeticConstantExpression(Exp->getRHS());
1165    }
1166
1167    if (Exp->getLHS()->getType()->isPointerType() &&
1168        Exp->getRHS()->getType()->isPointerType()) {
1169      const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1170      const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1171
1172      // Only allow a null (constant integer) base; we could
1173      // allow some additional cases if necessary, but this
1174      // is sufficient to cover offsetof-like constructs.
1175      if (!LHSBase && !RHSBase) {
1176        return CheckAddressConstantExpression(Exp->getLHS()) ||
1177               CheckAddressConstantExpression(Exp->getRHS());
1178      }
1179    }
1180
1181    Diag(Init->getExprLoc(),
1182         diag::err_init_element_not_constant, Init->getSourceRange());
1183    return true;
1184  }
1185  case Expr::ImplicitCastExprClass:
1186  case Expr::ExplicitCastExprClass: {
1187    const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
1188    if (SubExpr->getType()->isArithmeticType())
1189      return CheckArithmeticConstantExpression(SubExpr);
1190
1191    Diag(Init->getExprLoc(),
1192         diag::err_init_element_not_constant, Init->getSourceRange());
1193    return true;
1194  }
1195  case Expr::ConditionalOperatorClass: {
1196    const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1197    if (CheckArithmeticConstantExpression(Exp->getCond()))
1198      return true;
1199    if (Exp->getLHS() &&
1200        CheckArithmeticConstantExpression(Exp->getLHS()))
1201      return true;
1202    return CheckArithmeticConstantExpression(Exp->getRHS());
1203  }
1204  }
1205}
1206
1207bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
1208  Init = Init->IgnoreParens();
1209
1210  // Look through CXXDefaultArgExprs; they have no meaning in this context.
1211  if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1212    return CheckForConstantInitializer(DAE->getExpr(), DclT);
1213
1214  if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1215    return CheckForConstantInitializer(e->getInitializer(), DclT);
1216
1217  if (Init->getType()->isReferenceType()) {
1218    // FIXME: Work out how the heck reference types work
1219    return false;
1220#if 0
1221    // A reference is constant if the address of the expression
1222    // is constant
1223    // We look through initlists here to simplify
1224    // CheckAddressConstantExpressionLValue.
1225    if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1226      assert(Exp->getNumInits() > 0 &&
1227             "Refernce initializer cannot be empty");
1228      Init = Exp->getInit(0);
1229    }
1230    return CheckAddressConstantExpressionLValue(Init);
1231#endif
1232  }
1233
1234  if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1235    unsigned numInits = Exp->getNumInits();
1236    for (unsigned i = 0; i < numInits; i++) {
1237      // FIXME: Need to get the type of the declaration for C++,
1238      // because it could be a reference?
1239      if (CheckForConstantInitializer(Exp->getInit(i),
1240                                      Exp->getInit(i)->getType()))
1241        return true;
1242    }
1243    return false;
1244  }
1245
1246  if (Init->isNullPointerConstant(Context))
1247    return false;
1248  if (Init->getType()->isArithmeticType()) {
1249    QualType InitTy = Context.getCanonicalType(Init->getType())
1250                             .getUnqualifiedType();
1251    if (InitTy == Context.BoolTy) {
1252      // Special handling for pointers implicitly cast to bool;
1253      // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1254      if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1255        Expr* SubE = ICE->getSubExpr();
1256        if (SubE->getType()->isPointerType() ||
1257            SubE->getType()->isArrayType() ||
1258            SubE->getType()->isFunctionType()) {
1259          return CheckAddressConstantExpression(Init);
1260        }
1261      }
1262    } else if (InitTy->isIntegralType()) {
1263      Expr* SubE = 0;
1264      if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1265        SubE = CE->getSubExpr();
1266      // Special check for pointer cast to int; we allow as an extension
1267      // an address constant cast to an integer if the integer
1268      // is of an appropriate width (this sort of code is apparently used
1269      // in some places).
1270      // FIXME: Add pedwarn?
1271      // FIXME: Don't allow bitfields here!  Need the FieldDecl for that.
1272      if (SubE && (SubE->getType()->isPointerType() ||
1273                   SubE->getType()->isArrayType() ||
1274                   SubE->getType()->isFunctionType())) {
1275        unsigned IntWidth = Context.getTypeSize(Init->getType());
1276        unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1277        if (IntWidth >= PointerWidth)
1278          return CheckAddressConstantExpression(Init);
1279      }
1280    }
1281
1282    return CheckArithmeticConstantExpression(Init);
1283  }
1284
1285  if (Init->getType()->isPointerType())
1286    return CheckAddressConstantExpression(Init);
1287
1288  // An array type at the top level that isn't an init-list must
1289  // be a string literal
1290  if (Init->getType()->isArrayType())
1291    return false;
1292
1293  Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1294       Init->getSourceRange());
1295  return true;
1296}
1297
1298void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
1299  Decl *RealDecl = static_cast<Decl *>(dcl);
1300  Expr *Init = static_cast<Expr *>(init);
1301  assert(Init && "missing initializer");
1302
1303  // If there is no declaration, there was an error parsing it.  Just ignore
1304  // the initializer.
1305  if (RealDecl == 0) {
1306    delete Init;
1307    return;
1308  }
1309
1310  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1311  if (!VDecl) {
1312    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1313         diag::err_illegal_initializer);
1314    RealDecl->setInvalidDecl();
1315    return;
1316  }
1317  // Get the decls type and save a reference for later, since
1318  // CheckInitializerTypes may change it.
1319  QualType DclT = VDecl->getType(), SavT = DclT;
1320  if (VDecl->isBlockVarDecl()) {
1321    VarDecl::StorageClass SC = VDecl->getStorageClass();
1322    if (SC == VarDecl::Extern) { // C99 6.7.8p5
1323      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
1324      VDecl->setInvalidDecl();
1325    } else if (!VDecl->isInvalidDecl()) {
1326      if (CheckInitializerTypes(Init, DclT))
1327        VDecl->setInvalidDecl();
1328
1329      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1330      if (!getLangOptions().CPlusPlus) {
1331        if (SC == VarDecl::Static) // C99 6.7.8p4.
1332          CheckForConstantInitializer(Init, DclT);
1333      }
1334    }
1335  } else if (VDecl->isFileVarDecl()) {
1336    if (VDecl->getStorageClass() == VarDecl::Extern)
1337      Diag(VDecl->getLocation(), diag::warn_extern_init);
1338    if (!VDecl->isInvalidDecl())
1339      if (CheckInitializerTypes(Init, DclT))
1340        VDecl->setInvalidDecl();
1341
1342    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1343    if (!getLangOptions().CPlusPlus) {
1344      // C99 6.7.8p4. All file scoped initializers need to be constant.
1345      CheckForConstantInitializer(Init, DclT);
1346    }
1347  }
1348  // If the type changed, it means we had an incomplete type that was
1349  // completed by the initializer. For example:
1350  //   int ary[] = { 1, 3, 5 };
1351  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
1352  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
1353    VDecl->setType(DclT);
1354    Init->setType(DclT);
1355  }
1356
1357  // Attach the initializer to the decl.
1358  VDecl->setInit(Init);
1359  return;
1360}
1361
1362/// The declarators are chained together backwards, reverse the list.
1363Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1364  // Often we have single declarators, handle them quickly.
1365  Decl *GroupDecl = static_cast<Decl*>(group);
1366  if (GroupDecl == 0)
1367    return 0;
1368
1369  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1370  ScopedDecl *NewGroup = 0;
1371  if (Group->getNextDeclarator() == 0)
1372    NewGroup = Group;
1373  else { // reverse the list.
1374    while (Group) {
1375      ScopedDecl *Next = Group->getNextDeclarator();
1376      Group->setNextDeclarator(NewGroup);
1377      NewGroup = Group;
1378      Group = Next;
1379    }
1380  }
1381  // Perform semantic analysis that depends on having fully processed both
1382  // the declarator and initializer.
1383  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
1384    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1385    if (!IDecl)
1386      continue;
1387    QualType T = IDecl->getType();
1388
1389    // C99 6.7.5.2p2: If an identifier is declared to be an object with
1390    // static storage duration, it shall not have a variable length array.
1391    if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1392        IDecl->getStorageClass() == VarDecl::Static) {
1393      if (T->isVariableArrayType()) {
1394        Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1395        IDecl->setInvalidDecl();
1396      }
1397    }
1398    // Block scope. C99 6.7p7: If an identifier for an object is declared with
1399    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
1400    if (IDecl->isBlockVarDecl() &&
1401        IDecl->getStorageClass() != VarDecl::Extern) {
1402      if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1403        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1404             T.getAsString());
1405        IDecl->setInvalidDecl();
1406      }
1407    }
1408    // File scope. C99 6.9.2p2: A declaration of an identifier for and
1409    // object that has file scope without an initializer, and without a
1410    // storage-class specifier or with the storage-class specifier "static",
1411    // constitutes a tentative definition. Note: A tentative definition with
1412    // external linkage is valid (C99 6.2.2p5).
1413    if (isTentativeDefinition(IDecl)) {
1414      if (T->isIncompleteArrayType()) {
1415        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1416        // array to be completed. Don't issue a diagnostic.
1417      } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
1418        // C99 6.9.2p3: If the declaration of an identifier for an object is
1419        // a tentative definition and has internal linkage (C99 6.2.2p3), the
1420        // declared type shall not be an incomplete type.
1421        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1422             T.getAsString());
1423        IDecl->setInvalidDecl();
1424      }
1425    }
1426    if (IDecl->isFileVarDecl())
1427      CheckForFileScopedRedefinitions(S, IDecl);
1428  }
1429  return NewGroup;
1430}
1431
1432/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1433/// to introduce parameters into function prototype scope.
1434Sema::DeclTy *
1435Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1436  const DeclSpec &DS = D.getDeclSpec();
1437
1438  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1439  if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1440      DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1441    Diag(DS.getStorageClassSpecLoc(),
1442         diag::err_invalid_storage_class_in_func_decl);
1443    D.getMutableDeclSpec().ClearStorageClassSpecs();
1444  }
1445  if (DS.isThreadSpecified()) {
1446    Diag(DS.getThreadSpecLoc(),
1447         diag::err_invalid_storage_class_in_func_decl);
1448    D.getMutableDeclSpec().ClearStorageClassSpecs();
1449  }
1450
1451  // Check that there are no default arguments inside the type of this
1452  // parameter (C++ only).
1453  if (getLangOptions().CPlusPlus)
1454    CheckExtraCXXDefaultArguments(D);
1455
1456  // In this context, we *do not* check D.getInvalidType(). If the declarator
1457  // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1458  // though it will not reflect the user specified type.
1459  QualType parmDeclType = GetTypeForDeclarator(D, S);
1460
1461  assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1462
1463  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1464  // Can this happen for params?  We already checked that they don't conflict
1465  // among each other.  Here they can only shadow globals, which is ok.
1466  IdentifierInfo *II = D.getIdentifier();
1467  if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1468    if (S->isDeclScope(PrevDecl)) {
1469      Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1470           dyn_cast<NamedDecl>(PrevDecl)->getName());
1471
1472      // Recover by removing the name
1473      II = 0;
1474      D.SetIdentifier(0, D.getIdentifierLoc());
1475    }
1476  }
1477
1478  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1479  // Doing the promotion here has a win and a loss. The win is the type for
1480  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1481  // code generator). The loss is the orginal type isn't preserved. For example:
1482  //
1483  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1484  //    int blockvardecl[5];
1485  //    sizeof(parmvardecl);  // size == 4
1486  //    sizeof(blockvardecl); // size == 20
1487  // }
1488  //
1489  // For expressions, all implicit conversions are captured using the
1490  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1491  //
1492  // FIXME: If a source translation tool needs to see the original type, then
1493  // we need to consider storing both types (in ParmVarDecl)...
1494  //
1495  if (parmDeclType->isArrayType()) {
1496    // int x[restrict 4] ->  int *restrict
1497    parmDeclType = Context.getArrayDecayedType(parmDeclType);
1498  } else if (parmDeclType->isFunctionType())
1499    parmDeclType = Context.getPointerType(parmDeclType);
1500
1501  ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1502                                         D.getIdentifierLoc(), II,
1503                                         parmDeclType, VarDecl::None,
1504                                         0, 0);
1505
1506  if (D.getInvalidType())
1507    New->setInvalidDecl();
1508
1509  if (II)
1510    PushOnScopeChains(New, S);
1511
1512  ProcessDeclAttributes(New, D);
1513  return New;
1514
1515}
1516
1517Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
1518  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
1519  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1520         "Not a function declarator!");
1521  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1522
1523  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1524  // for a K&R function.
1525  if (!FTI.hasPrototype) {
1526    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1527      if (FTI.ArgInfo[i].Param == 0) {
1528        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1529             FTI.ArgInfo[i].Ident->getName());
1530        // Implicitly declare the argument as type 'int' for lack of a better
1531        // type.
1532        DeclSpec DS;
1533        const char* PrevSpec; // unused
1534        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1535                           PrevSpec);
1536        Declarator ParamD(DS, Declarator::KNRTypeListContext);
1537        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1538        FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
1539      }
1540    }
1541
1542    // Since this is a function definition, act as though we have information
1543    // about the arguments.
1544    if (FTI.NumArgs)
1545      FTI.hasPrototype = true;
1546  } else {
1547    // FIXME: Diagnose arguments without names in C.
1548  }
1549
1550  Scope *GlobalScope = FnBodyScope->getParent();
1551
1552  // See if this is a redefinition.
1553  Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1554                             GlobalScope);
1555  if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1556    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1557      const FunctionDecl *Definition;
1558      if (FD->getBody(Definition)) {
1559        Diag(D.getIdentifierLoc(), diag::err_redefinition,
1560             D.getIdentifier()->getName());
1561        Diag(Definition->getLocation(), diag::err_previous_definition);
1562      }
1563    }
1564  }
1565
1566  return ActOnStartOfFunctionDef(FnBodyScope,
1567                                 ActOnDeclarator(GlobalScope, D, 0));
1568}
1569
1570Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1571  Decl *decl = static_cast<Decl*>(D);
1572  FunctionDecl *FD = cast<FunctionDecl>(decl);
1573  PushDeclContext(FD);
1574
1575  // Check the validity of our function parameters
1576  CheckParmsForFunctionDef(FD);
1577
1578  // Introduce our parameters into the function scope
1579  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1580    ParmVarDecl *Param = FD->getParamDecl(p);
1581    // If this has an identifier, add it to the scope stack.
1582    if (Param->getIdentifier())
1583      PushOnScopeChains(Param, FnBodyScope);
1584  }
1585
1586  return FD;
1587}
1588
1589Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1590  Decl *dcl = static_cast<Decl *>(D);
1591  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
1592    FD->setBody((Stmt*)Body);
1593    assert(FD == getCurFunctionDecl() && "Function parsing confused");
1594  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
1595    MD->setBody((Stmt*)Body);
1596  } else
1597    return 0;
1598  PopDeclContext();
1599  // Verify and clean out per-function state.
1600
1601  // Check goto/label use.
1602  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1603       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1604    // Verify that we have no forward references left.  If so, there was a goto
1605    // or address of a label taken, but no definition of it.  Label fwd
1606    // definitions are indicated with a null substmt.
1607    if (I->second->getSubStmt() == 0) {
1608      LabelStmt *L = I->second;
1609      // Emit error.
1610      Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1611
1612      // At this point, we have gotos that use the bogus label.  Stitch it into
1613      // the function body so that they aren't leaked and that the AST is well
1614      // formed.
1615      if (Body) {
1616        L->setSubStmt(new NullStmt(L->getIdentLoc()));
1617        cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1618      } else {
1619        // The whole function wasn't parsed correctly, just delete this.
1620        delete L;
1621      }
1622    }
1623  }
1624  LabelMap.clear();
1625
1626  return D;
1627}
1628
1629/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1630/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
1631ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1632                                           IdentifierInfo &II, Scope *S) {
1633  // Extension in C99.  Legal in C90, but warn about it.
1634  if (getLangOptions().C99)
1635    Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1636  else
1637    Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1638
1639  // FIXME: handle stuff like:
1640  // void foo() { extern float X(); }
1641  // void bar() { X(); }  <-- implicit decl for X in another scope.
1642
1643  // Set a Declarator for the implicit definition: int foo();
1644  const char *Dummy;
1645  DeclSpec DS;
1646  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1647  Error = Error; // Silence warning.
1648  assert(!Error && "Error setting up implicit decl!");
1649  Declarator D(DS, Declarator::BlockContext);
1650  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1651  D.SetIdentifier(&II, Loc);
1652
1653  // Insert this function into translation-unit scope.
1654
1655  DeclContext *PrevDC = CurContext;
1656  CurContext = Context.getTranslationUnitDecl();
1657
1658  FunctionDecl *FD =
1659    dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
1660  FD->setImplicit();
1661
1662  CurContext = PrevDC;
1663
1664  return FD;
1665}
1666
1667
1668TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1669                                    ScopedDecl *LastDeclarator) {
1670  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
1671  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1672
1673  // Scope manipulation handled by caller.
1674  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1675                                           D.getIdentifierLoc(),
1676                                           D.getIdentifier(),
1677                                           T, LastDeclarator);
1678  if (D.getInvalidType())
1679    NewTD->setInvalidDecl();
1680  return NewTD;
1681}
1682
1683/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
1684/// former case, Name will be non-null.  In the later case, Name will be null.
1685/// TagType indicates what kind of tag this is. TK indicates whether this is a
1686/// reference/declaration/definition of a tag.
1687Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
1688                             SourceLocation KWLoc, IdentifierInfo *Name,
1689                             SourceLocation NameLoc, AttributeList *Attr) {
1690  // If this is a use of an existing tag, it must have a name.
1691  assert((Name != 0 || TK == TK_Definition) &&
1692         "Nameless record must be a definition!");
1693
1694  TagDecl::TagKind Kind;
1695  switch (TagType) {
1696  default: assert(0 && "Unknown tag type!");
1697  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1698  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
1699  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
1700  case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
1701  }
1702
1703  // If this is a named struct, check to see if there was a previous forward
1704  // declaration or definition.
1705  // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1706  if (ScopedDecl *PrevDecl =
1707          dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
1708
1709    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1710            "unexpected Decl type");
1711    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1712      // If this is a use of a previous tag, or if the tag is already declared
1713      // in the same scope (so that the definition/declaration completes or
1714      // rementions the tag), reuse the decl.
1715      if (TK == TK_Reference ||
1716          IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1717        // Make sure that this wasn't declared as an enum and now used as a
1718        // struct or something similar.
1719        if (PrevTagDecl->getTagKind() != Kind) {
1720          Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1721          Diag(PrevDecl->getLocation(), diag::err_previous_use);
1722          // Recover by making this an anonymous redefinition.
1723          Name = 0;
1724          PrevDecl = 0;
1725        } else {
1726          // If this is a use or a forward declaration, we're good.
1727          if (TK != TK_Definition)
1728            return PrevDecl;
1729
1730          // Diagnose attempts to redefine a tag.
1731          if (PrevTagDecl->isDefinition()) {
1732            Diag(NameLoc, diag::err_redefinition, Name->getName());
1733            Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1734            // If this is a redefinition, recover by making this struct be
1735            // anonymous, which will make any later references get the previous
1736            // definition.
1737            Name = 0;
1738          } else {
1739            // Okay, this is definition of a previously declared or referenced
1740            // tag. Move the location of the decl to be the definition site.
1741            PrevDecl->setLocation(NameLoc);
1742            return PrevDecl;
1743          }
1744        }
1745      }
1746      // If we get here, this is a definition of a new struct type in a nested
1747      // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1748      // type.
1749    } else {
1750      // PrevDecl is a namespace.
1751      if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1752        // The tag name clashes with a namespace name, issue an error and recover
1753        // by making this tag be anonymous.
1754        Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1755        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1756        Name = 0;
1757      }
1758    }
1759  }
1760
1761  // If there is an identifier, use the location of the identifier as the
1762  // location of the decl, otherwise use the location of the struct/union
1763  // keyword.
1764  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1765
1766  // Otherwise, if this is the first time we've seen this tag, create the decl.
1767  TagDecl *New;
1768  if (Kind == TagDecl::TK_enum) {
1769    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1770    // enum X { A, B, C } D;    D should chain to X.
1771    New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
1772    // If this is an undefined enum, warn.
1773    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1774  } else {
1775    // struct/union/class
1776
1777    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1778    // struct X { int A; } D;    D should chain to X.
1779    if (getLangOptions().CPlusPlus)
1780      // FIXME: Look for a way to use RecordDecl for simple structs.
1781      New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1782    else
1783      New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1784  }
1785
1786  // If this has an identifier, add it to the scope stack.
1787  if (Name) {
1788    // The scope passed in may not be a decl scope.  Zip up the scope tree until
1789    // we find one that is.
1790    while ((S->getFlags() & Scope::DeclScope) == 0)
1791      S = S->getParent();
1792
1793    // Add it to the decl chain.
1794    PushOnScopeChains(New, S);
1795  }
1796
1797  if (Attr)
1798    ProcessDeclAttributeList(New, Attr);
1799  return New;
1800}
1801
1802/// Collect the instance variables declared in an Objective-C object.  Used in
1803/// the creation of structures from objects using the @defs directive.
1804static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
1805                         llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
1806  if (Class->getSuperClass())
1807    CollectIvars(Class->getSuperClass(), Ctx, ivars);
1808
1809  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1810  for (ObjCInterfaceDecl::ivar_iterator I=Class->ivar_begin(), E=Class->ivar_end();
1811       I!=E; ++I) {
1812
1813    ObjCIvarDecl* ID = *I;
1814    ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1815                                                ID->getIdentifier(),
1816                                                ID->getType(),
1817                                                ID->getBitWidth()));
1818  }
1819}
1820
1821/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1822/// instance variables of ClassName into Decls.
1823void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1824                     IdentifierInfo *ClassName,
1825                     llvm::SmallVectorImpl<DeclTy*> &Decls) {
1826  // Check that ClassName is a valid class
1827  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1828  if (!Class) {
1829    Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1830    return;
1831  }
1832  // Collect the instance variables
1833  CollectIvars(Class, Context, Decls);
1834}
1835
1836QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1837  // This method tries to turn a variable array into a constant
1838  // array even when the size isn't an ICE.  This is necessary
1839  // for compatibility with code that depends on gcc's buggy
1840  // constant expression folding, like struct {char x[(int)(char*)2];}
1841  if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
1842    APValue Result;
1843    if (VLATy->getSizeExpr() &&
1844        VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1845      llvm::APSInt &Res = Result.getInt();
1846      if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1847        return Context.getConstantArrayType(VLATy->getElementType(),
1848                                            Res, ArrayType::Normal, 0);
1849    }
1850  }
1851  return QualType();
1852}
1853
1854/// ActOnField - Each field of a struct/union/class is passed into this in order
1855/// to create a FieldDecl object for it.
1856Sema::DeclTy *Sema::ActOnField(Scope *S,
1857                               SourceLocation DeclStart,
1858                               Declarator &D, ExprTy *BitfieldWidth) {
1859  IdentifierInfo *II = D.getIdentifier();
1860  Expr *BitWidth = (Expr*)BitfieldWidth;
1861  SourceLocation Loc = DeclStart;
1862  if (II) Loc = D.getIdentifierLoc();
1863
1864  // FIXME: Unnamed fields can be handled in various different ways, for
1865  // example, unnamed unions inject all members into the struct namespace!
1866
1867
1868  if (BitWidth) {
1869    // TODO: Validate.
1870    //printf("WARNING: BITFIELDS IGNORED!\n");
1871
1872    // 6.7.2.1p3
1873    // 6.7.2.1p4
1874
1875  } else {
1876    // Not a bitfield.
1877
1878    // validate II.
1879
1880  }
1881
1882  QualType T = GetTypeForDeclarator(D, S);
1883  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1884  bool InvalidDecl = false;
1885
1886  // C99 6.7.2.1p8: A member of a structure or union may have any type other
1887  // than a variably modified type.
1888  if (T->isVariablyModifiedType()) {
1889    QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1890    if (!FixedTy.isNull()) {
1891      Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1892      T = FixedTy;
1893    } else {
1894      // FIXME: This diagnostic needs work
1895      Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1896      InvalidDecl = true;
1897    }
1898  }
1899  // FIXME: Chain fielddecls together.
1900  FieldDecl *NewFD;
1901
1902  if (getLangOptions().CPlusPlus) {
1903    // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
1904    NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1905                                 Loc, II, T, BitWidth);
1906    if (II)
1907      PushOnScopeChains(NewFD, S);
1908  }
1909  else
1910    NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
1911
1912  ProcessDeclAttributes(NewFD, D);
1913
1914  if (D.getInvalidType() || InvalidDecl)
1915    NewFD->setInvalidDecl();
1916  return NewFD;
1917}
1918
1919/// TranslateIvarVisibility - Translate visibility from a token ID to an
1920///  AST enum value.
1921static ObjCIvarDecl::AccessControl
1922TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
1923  switch (ivarVisibility) {
1924    case tok::objc_private: return ObjCIvarDecl::Private;
1925    case tok::objc_public: return ObjCIvarDecl::Public;
1926    case tok::objc_protected: return ObjCIvarDecl::Protected;
1927    case tok::objc_package: return ObjCIvarDecl::Package;
1928    default: assert(false && "Unknown visitibility kind");
1929  }
1930}
1931
1932/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1933/// in order to create an IvarDecl object for it.
1934Sema::DeclTy *Sema::ActOnIvar(Scope *S,
1935                              SourceLocation DeclStart,
1936                              Declarator &D, ExprTy *BitfieldWidth,
1937                              tok::ObjCKeywordKind Visibility) {
1938  IdentifierInfo *II = D.getIdentifier();
1939  Expr *BitWidth = (Expr*)BitfieldWidth;
1940  SourceLocation Loc = DeclStart;
1941  if (II) Loc = D.getIdentifierLoc();
1942
1943  // FIXME: Unnamed fields can be handled in various different ways, for
1944  // example, unnamed unions inject all members into the struct namespace!
1945
1946
1947  if (BitWidth) {
1948    // TODO: Validate.
1949    //printf("WARNING: BITFIELDS IGNORED!\n");
1950
1951    // 6.7.2.1p3
1952    // 6.7.2.1p4
1953
1954  } else {
1955    // Not a bitfield.
1956
1957    // validate II.
1958
1959  }
1960
1961  QualType T = GetTypeForDeclarator(D, S);
1962  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1963  bool InvalidDecl = false;
1964
1965  // C99 6.7.2.1p8: A member of a structure or union may have any type other
1966  // than a variably modified type.
1967  if (T->isVariablyModifiedType()) {
1968    // FIXME: This diagnostic needs work
1969    Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1970    InvalidDecl = true;
1971  }
1972
1973  // Get the visibility (access control) for this ivar.
1974  ObjCIvarDecl::AccessControl ac =
1975    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
1976                                        : ObjCIvarDecl::None;
1977
1978  // Construct the decl.
1979  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
1980                                             (Expr *)BitfieldWidth);
1981
1982  // Process attributes attached to the ivar.
1983  ProcessDeclAttributes(NewID, D);
1984
1985  if (D.getInvalidType() || InvalidDecl)
1986    NewID->setInvalidDecl();
1987
1988  return NewID;
1989}
1990
1991void Sema::ActOnFields(Scope* S,
1992                       SourceLocation RecLoc, DeclTy *RecDecl,
1993                       DeclTy **Fields, unsigned NumFields,
1994                       SourceLocation LBrac, SourceLocation RBrac) {
1995  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1996  assert(EnclosingDecl && "missing record or interface decl");
1997  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1998
1999  if (Record && Record->isDefinition()) {
2000    // Diagnose code like:
2001    //     struct S { struct S {} X; };
2002    // We discover this when we complete the outer S.  Reject and ignore the
2003    // outer S.
2004    Diag(Record->getLocation(), diag::err_nested_redefinition,
2005         Record->getKindName());
2006    Diag(RecLoc, diag::err_previous_definition);
2007    Record->setInvalidDecl();
2008    return;
2009  }
2010  // Verify that all the fields are okay.
2011  unsigned NumNamedMembers = 0;
2012  llvm::SmallVector<FieldDecl*, 32> RecFields;
2013  llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
2014
2015  for (unsigned i = 0; i != NumFields; ++i) {
2016
2017    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2018    assert(FD && "missing field decl");
2019
2020    // Remember all fields.
2021    RecFields.push_back(FD);
2022
2023    // Get the type for the field.
2024    Type *FDTy = FD->getType().getTypePtr();
2025
2026    // C99 6.7.2.1p2 - A field may not be a function type.
2027    if (FDTy->isFunctionType()) {
2028      Diag(FD->getLocation(), diag::err_field_declared_as_function,
2029           FD->getName());
2030      FD->setInvalidDecl();
2031      EnclosingDecl->setInvalidDecl();
2032      continue;
2033    }
2034    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2035    if (FDTy->isIncompleteType()) {
2036      if (!Record) {  // Incomplete ivar type is always an error.
2037        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
2038        FD->setInvalidDecl();
2039        EnclosingDecl->setInvalidDecl();
2040        continue;
2041      }
2042      if (i != NumFields-1 ||                   // ... that the last member ...
2043          !Record->isStruct() ||  // ... of a structure ...
2044          !FDTy->isArrayType()) {         //... may have incomplete array type.
2045        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
2046        FD->setInvalidDecl();
2047        EnclosingDecl->setInvalidDecl();
2048        continue;
2049      }
2050      if (NumNamedMembers < 1) {  //... must have more than named member ...
2051        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2052             FD->getName());
2053        FD->setInvalidDecl();
2054        EnclosingDecl->setInvalidDecl();
2055        continue;
2056      }
2057      // Okay, we have a legal flexible array member at the end of the struct.
2058      if (Record)
2059        Record->setHasFlexibleArrayMember(true);
2060    }
2061    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2062    /// field of another structure or the element of an array.
2063    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
2064      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2065        // If this is a member of a union, then entire union becomes "flexible".
2066        if (Record && Record->isUnion()) {
2067          Record->setHasFlexibleArrayMember(true);
2068        } else {
2069          // If this is a struct/class and this is not the last element, reject
2070          // it.  Note that GCC supports variable sized arrays in the middle of
2071          // structures.
2072          if (i != NumFields-1) {
2073            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2074                 FD->getName());
2075            FD->setInvalidDecl();
2076            EnclosingDecl->setInvalidDecl();
2077            continue;
2078          }
2079          // We support flexible arrays at the end of structs in other structs
2080          // as an extension.
2081          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2082               FD->getName());
2083          if (Record)
2084            Record->setHasFlexibleArrayMember(true);
2085        }
2086      }
2087    }
2088    /// A field cannot be an Objective-c object
2089    if (FDTy->isObjCInterfaceType()) {
2090      Diag(FD->getLocation(), diag::err_statically_allocated_object,
2091           FD->getName());
2092      FD->setInvalidDecl();
2093      EnclosingDecl->setInvalidDecl();
2094      continue;
2095    }
2096    // Keep track of the number of named members.
2097    if (IdentifierInfo *II = FD->getIdentifier()) {
2098      // Detect duplicate member names.
2099      if (!FieldIDs.insert(II)) {
2100        Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2101        // Find the previous decl.
2102        SourceLocation PrevLoc;
2103        for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2104          assert(i != e && "Didn't find previous def!");
2105          if (RecFields[i]->getIdentifier() == II) {
2106            PrevLoc = RecFields[i]->getLocation();
2107            break;
2108          }
2109        }
2110        Diag(PrevLoc, diag::err_previous_definition);
2111        FD->setInvalidDecl();
2112        EnclosingDecl->setInvalidDecl();
2113        continue;
2114      }
2115      ++NumNamedMembers;
2116    }
2117  }
2118
2119  // Okay, we successfully defined 'Record'.
2120  if (Record) {
2121    Record->defineBody(&RecFields[0], RecFields.size());
2122    // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2123    // Sema::ActOnFinishCXXClassDef.
2124    if (!isa<CXXRecordDecl>(Record))
2125      Consumer.HandleTagDeclDefinition(Record);
2126  } else {
2127    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2128    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2129      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2130    else if (ObjCImplementationDecl *IMPDecl =
2131               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
2132      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2133      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
2134      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
2135    }
2136  }
2137}
2138
2139Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
2140                                      DeclTy *lastEnumConst,
2141                                      SourceLocation IdLoc, IdentifierInfo *Id,
2142                                      SourceLocation EqualLoc, ExprTy *val) {
2143  EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
2144  EnumConstantDecl *LastEnumConst =
2145    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2146  Expr *Val = static_cast<Expr*>(val);
2147
2148  // The scope passed in may not be a decl scope.  Zip up the scope tree until
2149  // we find one that is.
2150  while ((S->getFlags() & Scope::DeclScope) == 0)
2151    S = S->getParent();
2152
2153  // Verify that there isn't already something declared with this name in this
2154  // scope.
2155  if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
2156    // When in C++, we may get a TagDecl with the same name; in this case the
2157    // enum constant will 'hide' the tag.
2158    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2159           "Received TagDecl when not in C++!");
2160    if (!isa<TagDecl>(PrevDecl) &&
2161        IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
2162      if (isa<EnumConstantDecl>(PrevDecl))
2163        Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2164      else
2165        Diag(IdLoc, diag::err_redefinition, Id->getName());
2166      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2167      delete Val;
2168      return 0;
2169    }
2170  }
2171
2172  llvm::APSInt EnumVal(32);
2173  QualType EltTy;
2174  if (Val) {
2175    // Make sure to promote the operand type to int.
2176    UsualUnaryConversions(Val);
2177
2178    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2179    SourceLocation ExpLoc;
2180    if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2181      Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2182           Id->getName());
2183      delete Val;
2184      Val = 0;  // Just forget about it.
2185    } else {
2186      EltTy = Val->getType();
2187    }
2188  }
2189
2190  if (!Val) {
2191    if (LastEnumConst) {
2192      // Assign the last value + 1.
2193      EnumVal = LastEnumConst->getInitVal();
2194      ++EnumVal;
2195
2196      // Check for overflow on increment.
2197      if (EnumVal < LastEnumConst->getInitVal())
2198        Diag(IdLoc, diag::warn_enum_value_overflow);
2199
2200      EltTy = LastEnumConst->getType();
2201    } else {
2202      // First value, set to zero.
2203      EltTy = Context.IntTy;
2204      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
2205    }
2206  }
2207
2208  EnumConstantDecl *New =
2209    EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2210                             Val, EnumVal,
2211                             LastEnumConst);
2212
2213  // Register this decl in the current scope stack.
2214  PushOnScopeChains(New, S);
2215  return New;
2216}
2217
2218// FIXME: For consistency with ActOnFields(), we should have the parser
2219// pass in the source location for the left/right braces.
2220void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
2221                         DeclTy **Elements, unsigned NumElements) {
2222  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2223
2224  if (Enum && Enum->isDefinition()) {
2225    // Diagnose code like:
2226    //   enum e0 {
2227    //     E0 = sizeof(enum e0 { E1 })
2228    //   };
2229    Diag(Enum->getLocation(), diag::err_nested_redefinition,
2230         Enum->getName());
2231    Diag(EnumLoc, diag::err_previous_definition);
2232    Enum->setInvalidDecl();
2233    return;
2234  }
2235  // TODO: If the result value doesn't fit in an int, it must be a long or long
2236  // long value.  ISO C does not support this, but GCC does as an extension,
2237  // emit a warning.
2238  unsigned IntWidth = Context.Target.getIntWidth();
2239
2240  // Verify that all the values are okay, compute the size of the values, and
2241  // reverse the list.
2242  unsigned NumNegativeBits = 0;
2243  unsigned NumPositiveBits = 0;
2244
2245  // Keep track of whether all elements have type int.
2246  bool AllElementsInt = true;
2247
2248  EnumConstantDecl *EltList = 0;
2249  for (unsigned i = 0; i != NumElements; ++i) {
2250    EnumConstantDecl *ECD =
2251      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2252    if (!ECD) continue;  // Already issued a diagnostic.
2253
2254    // If the enum value doesn't fit in an int, emit an extension warning.
2255    const llvm::APSInt &InitVal = ECD->getInitVal();
2256    assert(InitVal.getBitWidth() >= IntWidth &&
2257           "Should have promoted value to int");
2258    if (InitVal.getBitWidth() > IntWidth) {
2259      llvm::APSInt V(InitVal);
2260      V.trunc(IntWidth);
2261      V.extend(InitVal.getBitWidth());
2262      if (V != InitVal)
2263        Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2264             InitVal.toString(10));
2265    }
2266
2267    // Keep track of the size of positive and negative values.
2268    if (InitVal.isUnsigned() || InitVal.isNonNegative())
2269      NumPositiveBits = std::max(NumPositiveBits,
2270                                 (unsigned)InitVal.getActiveBits());
2271    else
2272      NumNegativeBits = std::max(NumNegativeBits,
2273                                 (unsigned)InitVal.getMinSignedBits());
2274
2275    // Keep track of whether every enum element has type int (very commmon).
2276    if (AllElementsInt)
2277      AllElementsInt = ECD->getType() == Context.IntTy;
2278
2279    ECD->setNextDeclarator(EltList);
2280    EltList = ECD;
2281  }
2282
2283  // Figure out the type that should be used for this enum.
2284  // FIXME: Support attribute(packed) on enums and -fshort-enums.
2285  QualType BestType;
2286  unsigned BestWidth;
2287
2288  if (NumNegativeBits) {
2289    // If there is a negative value, figure out the smallest integer type (of
2290    // int/long/longlong) that fits.
2291    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
2292      BestType = Context.IntTy;
2293      BestWidth = IntWidth;
2294    } else {
2295      BestWidth = Context.Target.getLongWidth();
2296
2297      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
2298        BestType = Context.LongTy;
2299      else {
2300        BestWidth = Context.Target.getLongLongWidth();
2301
2302        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
2303          Diag(Enum->getLocation(), diag::warn_enum_too_large);
2304        BestType = Context.LongLongTy;
2305      }
2306    }
2307  } else {
2308    // If there is no negative value, figure out which of uint, ulong, ulonglong
2309    // fits.
2310    if (NumPositiveBits <= IntWidth) {
2311      BestType = Context.UnsignedIntTy;
2312      BestWidth = IntWidth;
2313    } else if (NumPositiveBits <=
2314               (BestWidth = Context.Target.getLongWidth())) {
2315      BestType = Context.UnsignedLongTy;
2316    } else {
2317      BestWidth = Context.Target.getLongLongWidth();
2318      assert(NumPositiveBits <= BestWidth &&
2319             "How could an initializer get larger than ULL?");
2320      BestType = Context.UnsignedLongLongTy;
2321    }
2322  }
2323
2324  // Loop over all of the enumerator constants, changing their types to match
2325  // the type of the enum if needed.
2326  for (unsigned i = 0; i != NumElements; ++i) {
2327    EnumConstantDecl *ECD =
2328      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2329    if (!ECD) continue;  // Already issued a diagnostic.
2330
2331    // Standard C says the enumerators have int type, but we allow, as an
2332    // extension, the enumerators to be larger than int size.  If each
2333    // enumerator value fits in an int, type it as an int, otherwise type it the
2334    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
2335    // that X has type 'int', not 'unsigned'.
2336    if (ECD->getType() == Context.IntTy) {
2337      // Make sure the init value is signed.
2338      llvm::APSInt IV = ECD->getInitVal();
2339      IV.setIsSigned(true);
2340      ECD->setInitVal(IV);
2341      continue;  // Already int type.
2342    }
2343
2344    // Determine whether the value fits into an int.
2345    llvm::APSInt InitVal = ECD->getInitVal();
2346    bool FitsInInt;
2347    if (InitVal.isUnsigned() || !InitVal.isNegative())
2348      FitsInInt = InitVal.getActiveBits() < IntWidth;
2349    else
2350      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2351
2352    // If it fits into an integer type, force it.  Otherwise force it to match
2353    // the enum decl type.
2354    QualType NewTy;
2355    unsigned NewWidth;
2356    bool NewSign;
2357    if (FitsInInt) {
2358      NewTy = Context.IntTy;
2359      NewWidth = IntWidth;
2360      NewSign = true;
2361    } else if (ECD->getType() == BestType) {
2362      // Already the right type!
2363      continue;
2364    } else {
2365      NewTy = BestType;
2366      NewWidth = BestWidth;
2367      NewSign = BestType->isSignedIntegerType();
2368    }
2369
2370    // Adjust the APSInt value.
2371    InitVal.extOrTrunc(NewWidth);
2372    InitVal.setIsSigned(NewSign);
2373    ECD->setInitVal(InitVal);
2374
2375    // Adjust the Expr initializer and type.
2376    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2377    ECD->setType(NewTy);
2378  }
2379
2380  Enum->defineElements(EltList, BestType);
2381  Consumer.HandleTagDeclDefinition(Enum);
2382}
2383
2384Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2385                                          ExprTy *expr) {
2386  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2387
2388  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
2389}
2390
2391Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
2392                                     SourceLocation LBrace,
2393                                     SourceLocation RBrace,
2394                                     const char *Lang,
2395                                     unsigned StrSize,
2396                                     DeclTy *D) {
2397  LinkageSpecDecl::LanguageIDs Language;
2398  Decl *dcl = static_cast<Decl *>(D);
2399  if (strncmp(Lang, "\"C\"", StrSize) == 0)
2400    Language = LinkageSpecDecl::lang_c;
2401  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2402    Language = LinkageSpecDecl::lang_cxx;
2403  else {
2404    Diag(Loc, diag::err_bad_language);
2405    return 0;
2406  }
2407
2408  // FIXME: Add all the various semantics of linkage specifications
2409  return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
2410}
2411