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