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