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