SemaDecl.cpp revision 02564e5ad0db7f1d553ba4b620c95eeb111e7e4d
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/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/DenseSet.h"
33using namespace clang;
34
35Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
36  Decl *IIDecl = II.getFETokenInfo<Decl>();
37  // Find first occurance of none-tagged declaration
38  while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
39    IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
40  if (!IIDecl)
41    return 0;
42  if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
43    return IIDecl;
44  if (ObjCCompatibleAliasDecl *ADecl =
45      dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
46    return ADecl->getClassInterface();
47  return 0;
48}
49
50void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
51  if (S->decl_empty()) return;
52  assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
53
54  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
55       I != E; ++I) {
56    Decl *TmpD = static_cast<Decl*>(*I);
57    assert(TmpD && "This decl didn't get pushed??");
58    ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
59    assert(D && "This decl isn't a ScopedDecl?");
60
61    IdentifierInfo *II = D->getIdentifier();
62    if (!II) continue;
63
64    // Unlink this decl from the identifier.  Because the scope contains decls
65    // in an unordered collection, and because we have multiple identifier
66    // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
67    if (II->getFETokenInfo<Decl>() == D) {
68      // Normal case, no multiple decls in different namespaces.
69      II->setFETokenInfo(D->getNext());
70    } else {
71      // Scan ahead.  There are only three namespaces in C, so this loop can
72      // never execute more than 3 times.
73      ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
74      while (SomeDecl->getNext() != D) {
75        SomeDecl = SomeDecl->getNext();
76        assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
77      }
78      SomeDecl->setNext(D->getNext());
79    }
80
81    // This will have to be revisited for C++: there we want to nest stuff in
82    // namespace decls etc.  Even for C, we might want a top-level translation
83    // unit decl or something.
84    if (!CurFunctionDecl)
85      continue;
86
87    // Chain this decl to the containing function, it now owns the memory for
88    // the decl.
89    D->setNext(CurFunctionDecl->getDeclChain());
90    CurFunctionDecl->setDeclChain(D);
91  }
92}
93
94/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
95/// Return the first declaration found (which may or may not be a class
96/// declaration. Caller is responsible for handling the none-class case.
97/// Bypassing the alias of a class by returning the aliased class.
98ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
99  ScopedDecl *IDecl;
100  // Scan up the scope chain looking for a decl that matches this identifier
101  // that is in the appropriate namespace.
102  for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
103       IDecl = IDecl->getNext())
104    if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
105      break;
106
107  if (ObjCCompatibleAliasDecl *ADecl =
108      dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
109    return ADecl->getClassInterface();
110  return IDecl;
111}
112
113/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
114/// return 0 if one not found.
115ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
116  ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
117  return cast_or_null<ObjCInterfaceDecl>(IdDecl);
118}
119
120/// LookupScopedDecl - Look up the inner-most declaration in the specified
121/// namespace.
122ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
123                                   SourceLocation IdLoc, Scope *S) {
124  if (II == 0) return 0;
125  Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
126
127  // Scan up the scope chain looking for a decl that matches this identifier
128  // that is in the appropriate namespace.  This search should not take long, as
129  // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
130  for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
131    if (D->getIdentifierNamespace() == NS)
132      return D;
133
134  // If we didn't find a use of this identifier, and if the identifier
135  // corresponds to a compiler builtin, create the decl object for the builtin
136  // now, injecting it into translation unit scope, and return it.
137  if (NS == Decl::IDNS_Ordinary) {
138    // If this is a builtin on this (or all) targets, create the decl.
139    if (unsigned BuiltinID = II->getBuiltinID())
140      return LazilyCreateBuiltin(II, BuiltinID, S);
141  }
142  return 0;
143}
144
145void Sema::InitBuiltinVaListType()
146{
147  if (!Context.getBuiltinVaListType().isNull())
148    return;
149
150  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
151  ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
152                                          SourceLocation(), TUScope);
153  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
154  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
155}
156
157/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
158/// lazily create a decl for it.
159ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
160                                      Scope *S) {
161  Builtin::ID BID = (Builtin::ID)bid;
162
163  if (BID == Builtin::BI__builtin_va_start ||
164       BID == Builtin::BI__builtin_va_copy ||
165       BID == Builtin::BI__builtin_va_end)
166    InitBuiltinVaListType();
167
168  QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
169  FunctionDecl *New = FunctionDecl::Create(Context, SourceLocation(), II, R,
170                                           FunctionDecl::Extern, false, 0);
171
172  // Find translation-unit scope to insert this function into.
173  if (Scope *FnS = S->getFnParent())
174    S = FnS->getParent();   // Skip all scopes in a function at once.
175  while (S->getParent())
176    S = S->getParent();
177  S->AddDecl(New);
178
179  // Add this decl to the end of the identifier info.
180  if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
181    // Scan until we find the last (outermost) decl in the id chain.
182    while (LastDecl->getNext())
183      LastDecl = LastDecl->getNext();
184    // Insert before (outside) it.
185    LastDecl->setNext(New);
186  } else {
187    II->setFETokenInfo(New);
188  }
189  return New;
190}
191
192/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
193/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
194/// situation, merging decls or emitting diagnostics as appropriate.
195///
196TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
197  // Verify the old decl was also a typedef.
198  TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
199  if (!Old) {
200    Diag(New->getLocation(), diag::err_redefinition_different_kind,
201         New->getName());
202    Diag(OldD->getLocation(), diag::err_previous_definition);
203    return New;
204  }
205
206  // Allow multiple definitions for ObjC built-in typedefs.
207  // FIXME: Verify the underlying types are equivalent!
208  if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
209    return Old;
210
211  // Redeclaration of a type is a constraint violation (6.7.2.3p1).
212  // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
213  // *either* declaration is in a system header. The code below implements
214  // this adhoc compatibility rule. FIXME: The following code will not
215  // work properly when compiling ".i" files (containing preprocessed output).
216  SourceManager &SrcMgr = Context.getSourceManager();
217  const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
218  const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
219  HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
220  DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
221  DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
222
223  if ((OldDirType == DirectoryLookup::ExternCSystemHeaderDir ||
224       NewDirType == DirectoryLookup::ExternCSystemHeaderDir) ||
225      getLangOptions().Microsoft)
226    return New;
227
228  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
229  // TODO: This is totally simplistic.  It should handle merging functions
230  // together etc, merging extern int X; int X; ...
231  Diag(New->getLocation(), diag::err_redefinition, New->getName());
232  Diag(Old->getLocation(), diag::err_previous_definition);
233  return New;
234}
235
236/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
237static bool DeclHasAttr(const Decl *decl, const Attr *target) {
238  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
239    if (attr->getKind() == target->getKind())
240      return true;
241
242  return false;
243}
244
245/// MergeAttributes - append attributes from the Old decl to the New one.
246static void MergeAttributes(Decl *New, Decl *Old) {
247  Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
248
249// FIXME: fix this code to cleanup the Old attrs correctly
250  while (attr) {
251     tmp = attr;
252     attr = attr->getNext();
253
254    if (!DeclHasAttr(New, tmp)) {
255       New->addAttr(tmp);
256    } else {
257       tmp->setNext(0);
258       delete(tmp);
259    }
260  }
261}
262
263/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
264/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
265/// situation, merging decls or emitting diagnostics as appropriate.
266///
267FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
268  // Verify the old decl was also a function.
269  FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
270  if (!Old) {
271    Diag(New->getLocation(), diag::err_redefinition_different_kind,
272         New->getName());
273    Diag(OldD->getLocation(), diag::err_previous_definition);
274    return New;
275  }
276
277  MergeAttributes(New, Old);
278
279
280  QualType OldQType = Old->getCanonicalType();
281  QualType NewQType = New->getCanonicalType();
282
283  // Function types need to be compatible, not identical. This handles
284  // duplicate function decls like "void f(int); void f(enum X);" properly.
285  if (Context.functionTypesAreCompatible(OldQType, NewQType))
286    return New;
287
288  // A function that has already been declared has been redeclared or defined
289  // with a different type- show appropriate diagnostic
290  diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
291                                         diag::err_previous_declaration;
292
293  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
294  // TODO: This is totally simplistic.  It should handle merging functions
295  // together etc, merging extern int X; int X; ...
296  Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
297  Diag(Old->getLocation(), PrevDiag);
298  return New;
299}
300
301/// equivalentArrayTypes - Used to determine whether two array types are
302/// equivalent.
303/// We need to check this explicitly as an incomplete array definition is
304/// considered a VariableArrayType, so will not match a complete array
305/// definition that would be otherwise equivalent.
306static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
307  const ArrayType *NewAT = NewQType->getAsArrayType();
308  const ArrayType *OldAT = OldQType->getAsArrayType();
309
310  if (!NewAT || !OldAT)
311    return false;
312
313  // If either (or both) array types in incomplete we need to strip off the
314  // outer VariableArrayType.  Once the outer VAT is removed the remaining
315  // types must be identical if the array types are to be considered
316  // equivalent.
317  // eg. int[][1] and int[1][1] become
318  //     VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
319  // removing the outermost VAT gives
320  //     CAT(1, int) and CAT(1, int)
321  // which are equal, therefore the array types are equivalent.
322  if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
323    if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
324      return false;
325    NewQType = NewAT->getElementType().getCanonicalType();
326    OldQType = OldAT->getElementType().getCanonicalType();
327  }
328
329  return NewQType == OldQType;
330}
331
332/// MergeVarDecl - We just parsed a variable 'New' which has the same name
333/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
334/// situation, merging decls or emitting diagnostics as appropriate.
335///
336/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
337/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
338///
339VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
340  // Verify the old decl was also a variable.
341  VarDecl *Old = dyn_cast<VarDecl>(OldD);
342  if (!Old) {
343    Diag(New->getLocation(), diag::err_redefinition_different_kind,
344         New->getName());
345    Diag(OldD->getLocation(), diag::err_previous_definition);
346    return New;
347  }
348
349  MergeAttributes(New, Old);
350
351  // Verify the types match.
352  if (Old->getCanonicalType() != New->getCanonicalType() &&
353      !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
354    Diag(New->getLocation(), diag::err_redefinition, New->getName());
355    Diag(Old->getLocation(), diag::err_previous_definition);
356    return New;
357  }
358  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
359  if (New->getStorageClass() == VarDecl::Static &&
360      (Old->getStorageClass() == VarDecl::None ||
361       Old->getStorageClass() == VarDecl::Extern)) {
362    Diag(New->getLocation(), diag::err_static_non_static, New->getName());
363    Diag(Old->getLocation(), diag::err_previous_definition);
364    return New;
365  }
366  // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
367  if (New->getStorageClass() != VarDecl::Static &&
368      Old->getStorageClass() == VarDecl::Static) {
369    Diag(New->getLocation(), diag::err_non_static_static, New->getName());
370    Diag(Old->getLocation(), diag::err_previous_definition);
371    return New;
372  }
373  // We've verified the types match, now handle "tentative" definitions.
374  FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
375  FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
376
377  if (OldFSDecl && NewFSDecl) {
378    // Handle C "tentative" external object definitions (C99 6.9.2).
379    bool OldIsTentative = false;
380    bool NewIsTentative = false;
381
382    if (!OldFSDecl->getInit() &&
383        (OldFSDecl->getStorageClass() == VarDecl::None ||
384         OldFSDecl->getStorageClass() == VarDecl::Static))
385      OldIsTentative = true;
386
387    // FIXME: this check doesn't work (since the initializer hasn't been
388    // attached yet). This check should be moved to FinalizeDeclaratorGroup.
389    // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
390    // thrown out the old decl.
391    if (!NewFSDecl->getInit() &&
392        (NewFSDecl->getStorageClass() == VarDecl::None ||
393         NewFSDecl->getStorageClass() == VarDecl::Static))
394      ; // change to NewIsTentative = true; once the code is moved.
395
396    if (NewIsTentative || OldIsTentative)
397      return New;
398  }
399  if (Old->getStorageClass() != VarDecl::Extern &&
400      New->getStorageClass() != VarDecl::Extern) {
401    Diag(New->getLocation(), diag::err_redefinition, New->getName());
402    Diag(Old->getLocation(), diag::err_previous_definition);
403  }
404  return New;
405}
406
407/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
408/// no declarator (e.g. "struct foo;") is parsed.
409Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
410  // TODO: emit error on 'int;' or 'const enum foo;'.
411  // TODO: emit error on 'typedef int;'
412  // if (!DS.isMissingDeclaratorOk()) Diag(...);
413
414  return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
415}
416
417bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
418  // Get the type before calling CheckSingleAssignmentConstraints(), since
419  // it can promote the expression.
420  QualType InitType = Init->getType();
421
422  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
423  return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
424                                  InitType, Init, "initializing");
425}
426
427bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
428                         QualType ElementType) {
429  Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
430  if (CheckSingleInitializer(expr, ElementType))
431    return true; // types weren't compatible.
432
433  if (savExpr != expr) // The type was promoted, update initializer list.
434    IList->setInit(slot, expr);
435  return false;
436}
437
438bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
439  if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
440    // C99 6.7.8p14. We have an array of character type with unknown size
441    // being initialized to a string literal.
442    llvm::APSInt ConstVal(32);
443    ConstVal = strLiteral->getByteLength() + 1;
444    // Return a new array type (C99 6.7.8p22).
445    DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
446                                         ArrayType::Normal, 0);
447  } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
448    // C99 6.7.8p14. We have an array of character type with known size.
449    if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
450      Diag(strLiteral->getSourceRange().getBegin(),
451           diag::warn_initializer_string_for_char_array_too_long,
452           strLiteral->getSourceRange());
453  } else {
454    assert(0 && "HandleStringLiteralInit(): Invalid array type");
455  }
456  // Set type from "char *" to "constant array of char".
457  strLiteral->setType(DeclT);
458  // For now, we always return false (meaning success).
459  return false;
460}
461
462StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
463  const ArrayType *AT = DeclType->getAsArrayType();
464  if (AT && AT->getElementType()->isCharType()) {
465    return dyn_cast<StringLiteral>(Init);
466  }
467  return 0;
468}
469
470// CheckInitializerListTypes - Checks the types of elements of an initializer
471// list. This function is recursive: it calls itself to initialize subelements
472// of aggregate types.  Note that the topLevel parameter essentially refers to
473// whether this expression "owns" the initializer list passed in, or if this
474// initialization is taking elements out of a parent initializer.  Each
475// call to this function adds zero or more to startIndex, reports any errors,
476// and returns true if it found any inconsistent types.
477bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
478                                     bool topLevel, unsigned& startIndex) {
479  bool hadError = false;
480
481  if (DeclType->isScalarType()) {
482    // The simplest case: initializing a single scalar
483    if (topLevel) {
484      Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
485           IList->getSourceRange());
486    }
487    if (startIndex < IList->getNumInits()) {
488      Expr* expr = IList->getInit(startIndex);
489      if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
490        // FIXME: Should an error be reported here instead?
491        unsigned newIndex = 0;
492        CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
493      } else {
494        hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
495      }
496      ++startIndex;
497    }
498    // FIXME: Should an error be reported for empty initializer list + scalar?
499  } else if (DeclType->isVectorType()) {
500    if (startIndex < IList->getNumInits()) {
501      const VectorType *VT = DeclType->getAsVectorType();
502      int maxElements = VT->getNumElements();
503      QualType elementType = VT->getElementType();
504
505      for (int i = 0; i < maxElements; ++i) {
506        // Don't attempt to go past the end of the init list
507        if (startIndex >= IList->getNumInits())
508          break;
509        Expr* expr = IList->getInit(startIndex);
510        if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
511          unsigned newIndex = 0;
512          hadError |= CheckInitializerListTypes(SubInitList, elementType,
513                                                true, newIndex);
514          ++startIndex;
515        } else {
516          hadError |= CheckInitializerListTypes(IList, elementType,
517                                                false, startIndex);
518        }
519      }
520    }
521  } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
522    if (DeclType->isStructureType() || DeclType->isUnionType()) {
523      if (startIndex < IList->getNumInits() && !topLevel &&
524          Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
525                                     DeclType)) {
526        // We found a compatible struct; per the standard, this initializes the
527        // struct.  (The C standard technically says that this only applies for
528        // initializers for declarations with automatic scope; however, this
529        // construct is unambiguous anyway because a struct cannot contain
530        // a type compatible with itself. We'll output an error when we check
531        // if the initializer is constant.)
532        // FIXME: Is a call to CheckSingleInitializer required here?
533        ++startIndex;
534      } else {
535        RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
536
537        // If the record is invalid, some of it's members are invalid. To avoid
538        // confusion, we forgo checking the intializer for the entire record.
539        if (structDecl->isInvalidDecl())
540          return true;
541
542        // If structDecl is a forward declaration, this loop won't do anything;
543        // That's okay, because an error should get printed out elsewhere. It
544        // might be worthwhile to skip over the rest of the initializer, though.
545        int numMembers = structDecl->getNumMembers() -
546                         structDecl->hasFlexibleArrayMember();
547        for (int i = 0; i < numMembers; i++) {
548          // Don't attempt to go past the end of the init list
549          if (startIndex >= IList->getNumInits())
550            break;
551          FieldDecl * curField = structDecl->getMember(i);
552          if (!curField->getIdentifier()) {
553            // Don't initialize unnamed fields, e.g. "int : 20;"
554            continue;
555          }
556          QualType fieldType = curField->getType();
557          Expr* expr = IList->getInit(startIndex);
558          if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
559            unsigned newStart = 0;
560            hadError |= CheckInitializerListTypes(SubInitList, fieldType,
561                                                  true, newStart);
562            ++startIndex;
563          } else {
564            hadError |= CheckInitializerListTypes(IList, fieldType,
565                                                  false, startIndex);
566          }
567          if (DeclType->isUnionType())
568            break;
569        }
570        // FIXME: Implement flexible array initialization GCC extension (it's a
571        // really messy extension to implement, unfortunately...the necessary
572        // information isn't actually even here!)
573      }
574    } else if (DeclType->isArrayType()) {
575      // Check for the special-case of initializing an array with a string.
576      if (startIndex < IList->getNumInits()) {
577        if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
578                                                     DeclType)) {
579          CheckStringLiteralInit(lit, DeclType);
580          ++startIndex;
581          if (topLevel && startIndex < IList->getNumInits()) {
582            // We have leftover initializers; warn
583            Diag(IList->getInit(startIndex)->getLocStart(),
584                 diag::err_excess_initializers_in_char_array_initializer,
585                 IList->getInit(startIndex)->getSourceRange());
586          }
587          return false;
588        }
589      }
590      int maxElements;
591      if (DeclType->isIncompleteArrayType()) {
592        // FIXME: use a proper constant
593        maxElements = 0x7FFFFFFF;
594      } else if (const VariableArrayType *VAT =
595                                DeclType->getAsVariableArrayType()) {
596        // Check for VLAs; in standard C it would be possible to check this
597        // earlier, but I don't know where clang accepts VLAs (gcc accepts
598        // them in all sorts of strange places).
599        Diag(VAT->getSizeExpr()->getLocStart(),
600             diag::err_variable_object_no_init,
601             VAT->getSizeExpr()->getSourceRange());
602        hadError = true;
603        maxElements = 0x7FFFFFFF;
604      } else {
605        const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
606        maxElements = static_cast<int>(CAT->getSize().getZExtValue());
607      }
608      QualType elementType = DeclType->getAsArrayType()->getElementType();
609      int numElements = 0;
610      for (int i = 0; i < maxElements; ++i, ++numElements) {
611        // Don't attempt to go past the end of the init list
612        if (startIndex >= IList->getNumInits())
613          break;
614        Expr* expr = IList->getInit(startIndex);
615        if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
616          unsigned newIndex = 0;
617          hadError |= CheckInitializerListTypes(SubInitList, elementType,
618                                                true, newIndex);
619          ++startIndex;
620        } else {
621          hadError |= CheckInitializerListTypes(IList, elementType,
622                                                false, startIndex);
623        }
624      }
625      if (DeclType->isIncompleteArrayType()) {
626        // If this is an incomplete array type, the actual type needs to
627        // be calculated here
628        if (numElements == 0) {
629          // Sizing an array implicitly to zero is not allowed
630          // (It could in theory be allowed, but it doesn't really matter.)
631          Diag(IList->getLocStart(),
632               diag::err_at_least_one_initializer_needed_to_size_array);
633          hadError = true;
634        } else {
635          llvm::APSInt ConstVal(32);
636          ConstVal = numElements;
637          DeclType = Context.getConstantArrayType(elementType, ConstVal,
638                                                  ArrayType::Normal, 0);
639        }
640      }
641    } else {
642      assert(0 && "Aggregate that isn't a function or array?!");
643    }
644  } else {
645    // In C, all types are either scalars or aggregates, but
646    // additional handling is needed here for C++ (and possibly others?).
647    assert(0 && "Unsupported initializer type");
648  }
649
650  // If this init list is a base list, we set the type; an initializer doesn't
651  // fundamentally have a type, but this makes the ASTs a bit easier to read
652  if (topLevel)
653    IList->setType(DeclType);
654
655  if (topLevel && startIndex < IList->getNumInits()) {
656    // We have leftover initializers; warn
657    Diag(IList->getInit(startIndex)->getLocStart(),
658         diag::warn_excess_initializers,
659         IList->getInit(startIndex)->getSourceRange());
660  }
661  return hadError;
662}
663
664bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
665  // C99 6.7.8p3: The type of the entity to be initialized shall be an array
666  // of unknown size ("[]") or an object type that is not a variable array type.
667  if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
668    return Diag(VAT->getSizeExpr()->getLocStart(),
669                diag::err_variable_object_no_init,
670                VAT->getSizeExpr()->getSourceRange());
671
672  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
673  if (!InitList) {
674    // FIXME: Handle wide strings
675    if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
676      return CheckStringLiteralInit(strLiteral, DeclType);
677
678    if (DeclType->isArrayType())
679      return Diag(Init->getLocStart(),
680                  diag::err_array_init_list_required,
681                  Init->getSourceRange());
682
683    return CheckSingleInitializer(Init, DeclType);
684  }
685  unsigned newIndex = 0;
686  return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
687}
688
689Sema::DeclTy *
690Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
691  ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
692  IdentifierInfo *II = D.getIdentifier();
693
694  // All of these full declarators require an identifier.  If it doesn't have
695  // one, the ParsedFreeStandingDeclSpec action should be used.
696  if (II == 0) {
697    Diag(D.getDeclSpec().getSourceRange().getBegin(),
698         diag::err_declarator_need_ident,
699         D.getDeclSpec().getSourceRange(), D.getSourceRange());
700    return 0;
701  }
702
703  // The scope passed in may not be a decl scope.  Zip up the scope tree until
704  // we find one that is.
705  while ((S->getFlags() & Scope::DeclScope) == 0)
706    S = S->getParent();
707
708  // See if this is a redefinition of a variable in the same scope.
709  ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
710                                          D.getIdentifierLoc(), S);
711  ScopedDecl *New;
712  bool InvalidDecl = false;
713
714  QualType R = GetTypeForDeclarator(D, S);
715  assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
716
717  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
718    TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
719    if (!NewTD) return 0;
720
721    // Handle attributes prior to checking for duplicates in MergeVarDecl
722    HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
723                         D.getAttributes());
724    // Merge the decl with the existing one if appropriate. If the decl is
725    // in an outer scope, it isn't the same thing.
726    if (PrevDecl && S->isDeclScope(PrevDecl)) {
727      NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
728      if (NewTD == 0) return 0;
729    }
730    New = NewTD;
731    if (S->getParent() == 0) {
732      // C99 6.7.7p2: If a typedef name specifies a variably modified type
733      // then it shall have block scope.
734      if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
735        // FIXME: Diagnostic needs to be fixed.
736        Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
737        InvalidDecl = true;
738      }
739    }
740  } else if (R.getTypePtr()->isFunctionType()) {
741    FunctionDecl::StorageClass SC = FunctionDecl::None;
742    switch (D.getDeclSpec().getStorageClassSpec()) {
743      default: assert(0 && "Unknown storage class!");
744      case DeclSpec::SCS_auto:
745      case DeclSpec::SCS_register:
746        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
747             R.getAsString());
748        InvalidDecl = true;
749        break;
750      case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
751      case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
752      case DeclSpec::SCS_static:      SC = FunctionDecl::Static; break;
753      case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
754    }
755
756    bool isInline = D.getDeclSpec().isInlineSpecified();
757    FunctionDecl *NewFD = FunctionDecl::Create(Context, D.getIdentifierLoc(),
758                                               II, R, SC, isInline,
759                                               LastDeclarator);
760    // Handle attributes.
761    HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
762                         D.getAttributes());
763
764    // Merge the decl with the existing one if appropriate. Since C functions
765    // are in a flat namespace, make sure we consider decls in outer scopes.
766    if (PrevDecl) {
767      NewFD = MergeFunctionDecl(NewFD, PrevDecl);
768      if (NewFD == 0) return 0;
769    }
770    New = NewFD;
771  } else {
772    if (R.getTypePtr()->isObjCInterfaceType()) {
773      Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
774           D.getIdentifier()->getName());
775      InvalidDecl = true;
776    }
777
778    VarDecl *NewVD;
779    VarDecl::StorageClass SC;
780    switch (D.getDeclSpec().getStorageClassSpec()) {
781    default: assert(0 && "Unknown storage class!");
782    case DeclSpec::SCS_unspecified:    SC = VarDecl::None; break;
783    case DeclSpec::SCS_extern:         SC = VarDecl::Extern; break;
784    case DeclSpec::SCS_static:         SC = VarDecl::Static; break;
785    case DeclSpec::SCS_auto:           SC = VarDecl::Auto; break;
786    case DeclSpec::SCS_register:       SC = VarDecl::Register; break;
787    case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
788    }
789    if (S->getParent() == 0) {
790      // C99 6.9p2: The storage-class specifiers auto and register shall not
791      // appear in the declaration specifiers in an external declaration.
792      if (SC == VarDecl::Auto || SC == VarDecl::Register) {
793        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
794             R.getAsString());
795        InvalidDecl = true;
796      }
797      NewVD = FileVarDecl::Create(Context, D.getIdentifierLoc(), II, R, SC,
798                                  LastDeclarator);
799    } else {
800      NewVD = BlockVarDecl::Create(Context, D.getIdentifierLoc(), II, R, SC,
801                                   LastDeclarator);
802    }
803    // Handle attributes prior to checking for duplicates in MergeVarDecl
804    HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
805                         D.getAttributes());
806
807    // Emit an error if an address space was applied to decl with local storage.
808    // This includes arrays of objects with address space qualifiers, but not
809    // automatic variables that point to other address spaces.
810    // ISO/IEC TR 18037 S5.1.2
811    if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
812      Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
813      InvalidDecl = true;
814    }
815    // Merge the decl with the existing one if appropriate. If the decl is
816    // in an outer scope, it isn't the same thing.
817    if (PrevDecl && S->isDeclScope(PrevDecl)) {
818      NewVD = MergeVarDecl(NewVD, PrevDecl);
819      if (NewVD == 0) return 0;
820    }
821    New = NewVD;
822  }
823
824  // If this has an identifier, add it to the scope stack.
825  if (II) {
826    New->setNext(II->getFETokenInfo<ScopedDecl>());
827    II->setFETokenInfo(New);
828    S->AddDecl(New);
829  }
830  // If any semantic error occurred, mark the decl as invalid.
831  if (D.getInvalidType() || InvalidDecl)
832    New->setInvalidDecl();
833
834  return New;
835}
836
837bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
838  SourceLocation loc;
839  // FIXME: Remove the isReference check and handle assignment to a reference.
840  if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
841    assert(loc.isValid() && "isConstantExpr didn't return a loc!");
842    Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
843    return true;
844  }
845  return false;
846}
847
848void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
849  Decl *RealDecl = static_cast<Decl *>(dcl);
850  Expr *Init = static_cast<Expr *>(init);
851  assert(Init && "missing initializer");
852
853  // If there is no declaration, there was an error parsing it.  Just ignore
854  // the initializer.
855  if (RealDecl == 0) {
856    delete Init;
857    return;
858  }
859
860  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
861  if (!VDecl) {
862    Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
863         diag::err_illegal_initializer);
864    RealDecl->setInvalidDecl();
865    return;
866  }
867  // Get the decls type and save a reference for later, since
868  // CheckInitializerTypes may change it.
869  QualType DclT = VDecl->getType(), SavT = DclT;
870  if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
871    VarDecl::StorageClass SC = BVD->getStorageClass();
872    if (SC == VarDecl::Extern) { // C99 6.7.8p5
873      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
874      BVD->setInvalidDecl();
875    } else if (!BVD->isInvalidDecl()) {
876      if (CheckInitializerTypes(Init, DclT))
877        BVD->setInvalidDecl();
878      if (SC == VarDecl::Static) // C99 6.7.8p4.
879        CheckForConstantInitializer(Init, DclT);
880    }
881  } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
882    if (FVD->getStorageClass() == VarDecl::Extern)
883      Diag(VDecl->getLocation(), diag::warn_extern_init);
884    if (!FVD->isInvalidDecl())
885      if (CheckInitializerTypes(Init, DclT))
886        FVD->setInvalidDecl();
887
888    // C99 6.7.8p4. All file scoped initializers need to be constant.
889    CheckForConstantInitializer(Init, DclT);
890  }
891  // If the type changed, it means we had an incomplete type that was
892  // completed by the initializer. For example:
893  //   int ary[] = { 1, 3, 5 };
894  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
895  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
896    VDecl->setType(DclT);
897    Init->setType(DclT);
898  }
899
900  // Attach the initializer to the decl.
901  VDecl->setInit(Init);
902  return;
903}
904
905/// The declarators are chained together backwards, reverse the list.
906Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
907  // Often we have single declarators, handle them quickly.
908  Decl *GroupDecl = static_cast<Decl*>(group);
909  if (GroupDecl == 0)
910    return 0;
911
912  ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
913  ScopedDecl *NewGroup = 0;
914  if (Group->getNextDeclarator() == 0)
915    NewGroup = Group;
916  else { // reverse the list.
917    while (Group) {
918      ScopedDecl *Next = Group->getNextDeclarator();
919      Group->setNextDeclarator(NewGroup);
920      NewGroup = Group;
921      Group = Next;
922    }
923  }
924  // Perform semantic analysis that depends on having fully processed both
925  // the declarator and initializer.
926  for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
927    VarDecl *IDecl = dyn_cast<VarDecl>(ID);
928    if (!IDecl)
929      continue;
930    FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
931    BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
932    QualType T = IDecl->getType();
933
934    // C99 6.7.5.2p2: If an identifier is declared to be an object with
935    // static storage duration, it shall not have a variable length array.
936    if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
937      if (T->getAsVariableArrayType()) {
938        Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
939        IDecl->setInvalidDecl();
940      }
941    }
942    // Block scope. C99 6.7p7: If an identifier for an object is declared with
943    // no linkage (C99 6.2.2p6), the type for the object shall be complete...
944    if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
945      if (T->isIncompleteType()) {
946        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
947             T.getAsString());
948        IDecl->setInvalidDecl();
949      }
950    }
951    // File scope. C99 6.9.2p2: A declaration of an identifier for and
952    // object that has file scope without an initializer, and without a
953    // storage-class specifier or with the storage-class specifier "static",
954    // constitutes a tentative definition. Note: A tentative definition with
955    // external linkage is valid (C99 6.2.2p5).
956    if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
957                                   FVD->getStorageClass() == VarDecl::None)) {
958      if (T->isIncompleteArrayType()) {
959        // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
960        // array to be completed. Don't issue a diagnostic.
961      } else if (T->isIncompleteType()) {
962        // C99 6.9.2p3: If the declaration of an identifier for an object is
963        // a tentative definition and has internal linkage (C99 6.2.2p3), the
964        // declared type shall not be an incomplete type.
965        Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
966             T.getAsString());
967        IDecl->setInvalidDecl();
968      }
969    }
970  }
971  return NewGroup;
972}
973
974// Called from Sema::ParseStartOfFunctionDef().
975ParmVarDecl *
976Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
977                           Scope *FnScope) {
978  IdentifierInfo *II = PI.Ident;
979  // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
980  // Can this happen for params?  We already checked that they don't conflict
981  // among each other.  Here they can only shadow globals, which is ok.
982  if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
983                                        PI.IdentLoc, FnScope)) {
984
985  }
986
987  // FIXME: Handle storage class (auto, register). No declarator?
988  // TODO: Chain to previous parameter with the prevdeclarator chain?
989
990  // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
991  // Doing the promotion here has a win and a loss. The win is the type for
992  // both Decl's and DeclRefExpr's will match (a convenient invariant for the
993  // code generator). The loss is the orginal type isn't preserved. For example:
994  //
995  // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
996  //    int blockvardecl[5];
997  //    sizeof(parmvardecl);  // size == 4
998  //    sizeof(blockvardecl); // size == 20
999  // }
1000  //
1001  // For expressions, all implicit conversions are captured using the
1002  // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1003  //
1004  // FIXME: If a source translation tool needs to see the original type, then
1005  // we need to consider storing both types (in ParmVarDecl)...
1006  //
1007  QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
1008  if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
1009    // int x[restrict 4] ->  int *restrict
1010    parmDeclType = Context.getPointerType(AT->getElementType());
1011    parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
1012  } else if (parmDeclType->isFunctionType())
1013    parmDeclType = Context.getPointerType(parmDeclType);
1014
1015  ParmVarDecl *New = ParmVarDecl::Create(Context, PI.IdentLoc, II, parmDeclType,
1016                                         VarDecl::None, 0);
1017
1018  if (PI.InvalidType)
1019    New->setInvalidDecl();
1020
1021  // If this has an identifier, add it to the scope stack.
1022  if (II) {
1023    New->setNext(II->getFETokenInfo<ScopedDecl>());
1024    II->setFETokenInfo(New);
1025    FnScope->AddDecl(New);
1026  }
1027
1028  HandleDeclAttributes(New, PI.AttrList, 0);
1029  return New;
1030}
1031
1032Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
1033  assert(CurFunctionDecl == 0 && "Function parsing confused");
1034  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1035         "Not a function declarator!");
1036  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1037
1038  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1039  // for a K&R function.
1040  if (!FTI.hasPrototype) {
1041    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1042      if (FTI.ArgInfo[i].TypeInfo == 0) {
1043        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1044             FTI.ArgInfo[i].Ident->getName());
1045        // Implicitly declare the argument as type 'int' for lack of a better
1046        // type.
1047        FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1048      }
1049    }
1050
1051    // Since this is a function definition, act as though we have information
1052    // about the arguments.
1053    if (FTI.NumArgs)
1054      FTI.hasPrototype = true;
1055  } else {
1056    // FIXME: Diagnose arguments without names in C.
1057
1058  }
1059
1060  Scope *GlobalScope = FnBodyScope->getParent();
1061
1062  // See if this is a redefinition.
1063  ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1064                                         D.getIdentifierLoc(), GlobalScope);
1065  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1066    if (FD->getBody()) {
1067      Diag(D.getIdentifierLoc(), diag::err_redefinition,
1068           D.getIdentifier()->getName());
1069      Diag(FD->getLocation(), diag::err_previous_definition);
1070    }
1071  }
1072  Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
1073  FunctionDecl *FD = cast<FunctionDecl>(decl);
1074  CurFunctionDecl = FD;
1075
1076  // Create Decl objects for each parameter, adding them to the FunctionDecl.
1077  llvm::SmallVector<ParmVarDecl*, 16> Params;
1078
1079  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1080  // no arguments, not a function that takes a single void argument.
1081  if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1082      !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
1083      QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
1084    // empty arg list, don't push any params.
1085  } else {
1086    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1087      ParmVarDecl *parmDecl;
1088
1089      parmDecl = ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
1090                                      FnBodyScope);
1091      // C99 6.7.5.3p4: the parameters in a parameter type list in a function
1092      // declarator that is part of a function definition of that function
1093      // shall not have incomplete type.
1094      if (parmDecl->getType()->isIncompleteType()) {
1095        Diag(parmDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1096             parmDecl->getType().getAsString());
1097        parmDecl->setInvalidDecl();
1098      }
1099      Params.push_back(parmDecl);
1100    }
1101  }
1102
1103  FD->setParams(&Params[0], Params.size());
1104
1105  return FD;
1106}
1107
1108Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1109  Decl *dcl = static_cast<Decl *>(D);
1110  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1111    FD->setBody((Stmt*)Body);
1112    assert(FD == CurFunctionDecl && "Function parsing confused");
1113    CurFunctionDecl = 0;
1114  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
1115    MD->setBody((Stmt*)Body);
1116    CurMethodDecl = 0;
1117  }
1118  // Verify and clean out per-function state.
1119
1120  // Check goto/label use.
1121  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1122       I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1123    // Verify that we have no forward references left.  If so, there was a goto
1124    // or address of a label taken, but no definition of it.  Label fwd
1125    // definitions are indicated with a null substmt.
1126    if (I->second->getSubStmt() == 0) {
1127      LabelStmt *L = I->second;
1128      // Emit error.
1129      Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1130
1131      // At this point, we have gotos that use the bogus label.  Stitch it into
1132      // the function body so that they aren't leaked and that the AST is well
1133      // formed.
1134      if (Body) {
1135        L->setSubStmt(new NullStmt(L->getIdentLoc()));
1136        cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1137      } else {
1138        // The whole function wasn't parsed correctly, just delete this.
1139        delete L;
1140      }
1141    }
1142  }
1143  LabelMap.clear();
1144
1145  return D;
1146}
1147
1148/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1149/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
1150ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1151                                           IdentifierInfo &II, Scope *S) {
1152  if (getLangOptions().C99)  // Extension in C99.
1153    Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1154  else  // Legal in C90, but warn about it.
1155    Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1156
1157  // FIXME: handle stuff like:
1158  // void foo() { extern float X(); }
1159  // void bar() { X(); }  <-- implicit decl for X in another scope.
1160
1161  // Set a Declarator for the implicit definition: int foo();
1162  const char *Dummy;
1163  DeclSpec DS;
1164  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1165  Error = Error; // Silence warning.
1166  assert(!Error && "Error setting up implicit decl!");
1167  Declarator D(DS, Declarator::BlockContext);
1168  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1169  D.SetIdentifier(&II, Loc);
1170
1171  // Find translation-unit scope to insert this function into.
1172  if (Scope *FnS = S->getFnParent())
1173    S = FnS->getParent();   // Skip all scopes in a function at once.
1174  while (S->getParent())
1175    S = S->getParent();
1176
1177  return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1178}
1179
1180
1181TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
1182                                    ScopedDecl *LastDeclarator) {
1183  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
1184  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1185
1186  // Scope manipulation handled by caller.
1187  TypedefDecl *NewTD = TypedefDecl::Create(Context, D.getIdentifierLoc(),
1188                                           D.getIdentifier(),
1189                                           T, LastDeclarator);
1190  if (D.getInvalidType())
1191    NewTD->setInvalidDecl();
1192  return NewTD;
1193}
1194
1195/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
1196/// former case, Name will be non-null.  In the later case, Name will be null.
1197/// TagType indicates what kind of tag this is. TK indicates whether this is a
1198/// reference/declaration/definition of a tag.
1199Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
1200                             SourceLocation KWLoc, IdentifierInfo *Name,
1201                             SourceLocation NameLoc, AttributeList *Attr) {
1202  // If this is a use of an existing tag, it must have a name.
1203  assert((Name != 0 || TK == TK_Definition) &&
1204         "Nameless record must be a definition!");
1205
1206  Decl::Kind Kind;
1207  switch (TagType) {
1208  default: assert(0 && "Unknown tag type!");
1209  case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1210  case DeclSpec::TST_union:  Kind = Decl::Union; break;
1211//case DeclSpec::TST_class:  Kind = Decl::Class; break;
1212  case DeclSpec::TST_enum:   Kind = Decl::Enum; break;
1213  }
1214
1215  // If this is a named struct, check to see if there was a previous forward
1216  // declaration or definition.
1217  if (TagDecl *PrevDecl =
1218          dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1219                                                     NameLoc, S))) {
1220
1221    // If this is a use of a previous tag, or if the tag is already declared in
1222    // the same scope (so that the definition/declaration completes or
1223    // rementions the tag), reuse the decl.
1224    if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1225      // Make sure that this wasn't declared as an enum and now used as a struct
1226      // or something similar.
1227      if (PrevDecl->getKind() != Kind) {
1228        Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1229        Diag(PrevDecl->getLocation(), diag::err_previous_use);
1230      }
1231
1232      // If this is a use or a forward declaration, we're good.
1233      if (TK != TK_Definition)
1234        return PrevDecl;
1235
1236      // Diagnose attempts to redefine a tag.
1237      if (PrevDecl->isDefinition()) {
1238        Diag(NameLoc, diag::err_redefinition, Name->getName());
1239        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1240        // If this is a redefinition, recover by making this struct be
1241        // anonymous, which will make any later references get the previous
1242        // definition.
1243        Name = 0;
1244      } else {
1245        // Okay, this is definition of a previously declared or referenced tag.
1246        // Move the location of the decl to be the definition site.
1247        PrevDecl->setLocation(NameLoc);
1248        return PrevDecl;
1249      }
1250    }
1251    // If we get here, this is a definition of a new struct type in a nested
1252    // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1253    // type.
1254  }
1255
1256  // If there is an identifier, use the location of the identifier as the
1257  // location of the decl, otherwise use the location of the struct/union
1258  // keyword.
1259  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1260
1261  // Otherwise, if this is the first time we've seen this tag, create the decl.
1262  TagDecl *New;
1263  switch (Kind) {
1264  default: assert(0 && "Unknown tag kind!");
1265  case Decl::Enum:
1266    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1267    // enum X { A, B, C } D;    D should chain to X.
1268    New = EnumDecl::Create(Context, Loc, Name, 0);
1269    // If this is an undefined enum, warn.
1270    if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1271    break;
1272  case Decl::Union:
1273  case Decl::Struct:
1274  case Decl::Class:
1275    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1276    // struct X { int A; } D;    D should chain to X.
1277    New = RecordDecl::Create(Context, Kind, Loc, Name, 0);
1278    break;
1279  }
1280
1281  // If this has an identifier, add it to the scope stack.
1282  if (Name) {
1283    // The scope passed in may not be a decl scope.  Zip up the scope tree until
1284    // we find one that is.
1285    while ((S->getFlags() & Scope::DeclScope) == 0)
1286      S = S->getParent();
1287
1288    // Add it to the decl chain.
1289    New->setNext(Name->getFETokenInfo<ScopedDecl>());
1290    Name->setFETokenInfo(New);
1291    S->AddDecl(New);
1292  }
1293
1294  HandleDeclAttributes(New, Attr, 0);
1295  return New;
1296}
1297
1298/// ActOnField - Each field of a struct/union/class is passed into this in order
1299/// to create a FieldDecl object for it.
1300Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *tagDecl,
1301                               SourceLocation DeclStart,
1302                               Declarator &D, ExprTy *BitfieldWidth) {
1303  IdentifierInfo *II = D.getIdentifier();
1304  Expr *BitWidth = (Expr*)BitfieldWidth;
1305  Decl *TagDecl = static_cast<Decl *>(tagDecl);
1306  SourceLocation Loc = DeclStart;
1307  if (II) Loc = D.getIdentifierLoc();
1308
1309  // FIXME: Unnamed fields can be handled in various different ways, for
1310  // example, unnamed unions inject all members into the struct namespace!
1311
1312
1313  if (BitWidth) {
1314    // TODO: Validate.
1315    //printf("WARNING: BITFIELDS IGNORED!\n");
1316
1317    // 6.7.2.1p3
1318    // 6.7.2.1p4
1319
1320  } else {
1321    // Not a bitfield.
1322
1323    // validate II.
1324
1325  }
1326
1327  QualType T = GetTypeForDeclarator(D, S);
1328  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1329  bool InvalidDecl = false;
1330
1331  // C99 6.7.2.1p8: A member of a structure or union may have any type other
1332  // than a variably modified type.
1333  if (T->isVariablyModifiedType()) {
1334    // FIXME: This diagnostic needs work
1335    Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1336    InvalidDecl = true;
1337  }
1338  // FIXME: Chain fielddecls together.
1339  FieldDecl *NewFD;
1340
1341  if (isa<RecordDecl>(TagDecl))
1342    NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
1343  else if (isa<ObjCInterfaceDecl>(TagDecl) ||
1344           isa<ObjCImplementationDecl>(TagDecl) ||
1345           isa<ObjCCategoryDecl>(TagDecl) ||
1346           // FIXME: ivars are currently used to model properties, and
1347           // properties can appear within a protocol.
1348           // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1349           isa<ObjCProtocolDecl>(TagDecl))
1350    NewFD = ObjCIvarDecl::Create(Context, Loc, II, T);
1351  else
1352    assert(0 && "Sema::ActOnField(): Unknown TagDecl");
1353
1354  HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1355                       D.getAttributes());
1356
1357  if (D.getInvalidType() || InvalidDecl)
1358    NewFD->setInvalidDecl();
1359  return NewFD;
1360}
1361
1362/// TranslateIvarVisibility - Translate visibility from a token ID to an
1363///  AST enum value.
1364static ObjCIvarDecl::AccessControl
1365TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
1366  switch (ivarVisibility) {
1367    case tok::objc_private: return ObjCIvarDecl::Private;
1368    case tok::objc_public: return ObjCIvarDecl::Public;
1369    case tok::objc_protected: return ObjCIvarDecl::Protected;
1370    case tok::objc_package: return ObjCIvarDecl::Package;
1371    default: assert(false && "Unknown visitibility kind");
1372  }
1373}
1374
1375void Sema::ActOnFields(Scope* S,
1376                       SourceLocation RecLoc, DeclTy *RecDecl,
1377                       DeclTy **Fields, unsigned NumFields,
1378                       SourceLocation LBrac, SourceLocation RBrac,
1379                       tok::ObjCKeywordKind *visibility) {
1380  Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1381  assert(EnclosingDecl && "missing record or interface decl");
1382  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1383
1384  if (Record && Record->isDefinition()) {
1385    // Diagnose code like:
1386    //     struct S { struct S {} X; };
1387    // We discover this when we complete the outer S.  Reject and ignore the
1388    // outer S.
1389    Diag(Record->getLocation(), diag::err_nested_redefinition,
1390         Record->getKindName());
1391    Diag(RecLoc, diag::err_previous_definition);
1392    Record->setInvalidDecl();
1393    return;
1394  }
1395  // Verify that all the fields are okay.
1396  unsigned NumNamedMembers = 0;
1397  llvm::SmallVector<FieldDecl*, 32> RecFields;
1398  llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1399
1400  for (unsigned i = 0; i != NumFields; ++i) {
1401
1402    FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1403    assert(FD && "missing field decl");
1404
1405    // Remember all fields.
1406    RecFields.push_back(FD);
1407
1408    // Get the type for the field.
1409    Type *FDTy = FD->getType().getTypePtr();
1410
1411    // If we have visibility info, make sure the AST is set accordingly.
1412    if (visibility)
1413      cast<ObjCIvarDecl>(FD)->setAccessControl(
1414                                TranslateIvarVisibility(visibility[i]));
1415
1416    // C99 6.7.2.1p2 - A field may not be a function type.
1417    if (FDTy->isFunctionType()) {
1418      Diag(FD->getLocation(), diag::err_field_declared_as_function,
1419           FD->getName());
1420      FD->setInvalidDecl();
1421      EnclosingDecl->setInvalidDecl();
1422      continue;
1423    }
1424    // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1425    if (FDTy->isIncompleteType()) {
1426      if (!Record) {  // Incomplete ivar type is always an error.
1427        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1428        FD->setInvalidDecl();
1429        EnclosingDecl->setInvalidDecl();
1430        continue;
1431      }
1432      if (i != NumFields-1 ||                   // ... that the last member ...
1433          Record->getKind() != Decl::Struct ||  // ... of a structure ...
1434          !FDTy->isArrayType()) {         //... may have incomplete array type.
1435        Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1436        FD->setInvalidDecl();
1437        EnclosingDecl->setInvalidDecl();
1438        continue;
1439      }
1440      if (NumNamedMembers < 1) {  //... must have more than named member ...
1441        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1442             FD->getName());
1443        FD->setInvalidDecl();
1444        EnclosingDecl->setInvalidDecl();
1445        continue;
1446      }
1447      // Okay, we have a legal flexible array member at the end of the struct.
1448      if (Record)
1449        Record->setHasFlexibleArrayMember(true);
1450    }
1451    /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1452    /// field of another structure or the element of an array.
1453    if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
1454      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1455        // If this is a member of a union, then entire union becomes "flexible".
1456        if (Record && Record->getKind() == Decl::Union) {
1457          Record->setHasFlexibleArrayMember(true);
1458        } else {
1459          // If this is a struct/class and this is not the last element, reject
1460          // it.  Note that GCC supports variable sized arrays in the middle of
1461          // structures.
1462          if (i != NumFields-1) {
1463            Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1464                 FD->getName());
1465            FD->setInvalidDecl();
1466            EnclosingDecl->setInvalidDecl();
1467            continue;
1468          }
1469          // We support flexible arrays at the end of structs in other structs
1470          // as an extension.
1471          Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1472               FD->getName());
1473          if (Record)
1474            Record->setHasFlexibleArrayMember(true);
1475        }
1476      }
1477    }
1478    /// A field cannot be an Objective-c object
1479    if (FDTy->isObjCInterfaceType()) {
1480      Diag(FD->getLocation(), diag::err_statically_allocated_object,
1481           FD->getName());
1482      FD->setInvalidDecl();
1483      EnclosingDecl->setInvalidDecl();
1484      continue;
1485    }
1486    // Keep track of the number of named members.
1487    if (IdentifierInfo *II = FD->getIdentifier()) {
1488      // Detect duplicate member names.
1489      if (!FieldIDs.insert(II)) {
1490        Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1491        // Find the previous decl.
1492        SourceLocation PrevLoc;
1493        for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1494          assert(i != e && "Didn't find previous def!");
1495          if (RecFields[i]->getIdentifier() == II) {
1496            PrevLoc = RecFields[i]->getLocation();
1497            break;
1498          }
1499        }
1500        Diag(PrevLoc, diag::err_previous_definition);
1501        FD->setInvalidDecl();
1502        EnclosingDecl->setInvalidDecl();
1503        continue;
1504      }
1505      ++NumNamedMembers;
1506    }
1507  }
1508
1509  // Okay, we successfully defined 'Record'.
1510  if (Record) {
1511    Record->defineBody(&RecFields[0], RecFields.size());
1512    Consumer.HandleTagDeclDefinition(Record);
1513  } else {
1514    ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1515    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1516      ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1517    else if (ObjCImplementationDecl *IMPDecl =
1518               dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
1519      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1520      IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
1521      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
1522    }
1523  }
1524}
1525
1526Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
1527                                      DeclTy *lastEnumConst,
1528                                      SourceLocation IdLoc, IdentifierInfo *Id,
1529                                      SourceLocation EqualLoc, ExprTy *val) {
1530  theEnumDecl = theEnumDecl;  // silence unused warning.
1531  EnumConstantDecl *LastEnumConst =
1532    cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1533  Expr *Val = static_cast<Expr*>(val);
1534
1535  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1536  // we find one that is.
1537  while ((S->getFlags() & Scope::DeclScope) == 0)
1538    S = S->getParent();
1539
1540  // Verify that there isn't already something declared with this name in this
1541  // scope.
1542  if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1543                                              IdLoc, S)) {
1544    if (S->isDeclScope(PrevDecl)) {
1545      if (isa<EnumConstantDecl>(PrevDecl))
1546        Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1547      else
1548        Diag(IdLoc, diag::err_redefinition, Id->getName());
1549      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1550      delete Val;
1551      return 0;
1552    }
1553  }
1554
1555  llvm::APSInt EnumVal(32);
1556  QualType EltTy;
1557  if (Val) {
1558    // Make sure to promote the operand type to int.
1559    UsualUnaryConversions(Val);
1560
1561    // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1562    SourceLocation ExpLoc;
1563    if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1564      Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1565           Id->getName());
1566      delete Val;
1567      Val = 0;  // Just forget about it.
1568    } else {
1569      EltTy = Val->getType();
1570    }
1571  }
1572
1573  if (!Val) {
1574    if (LastEnumConst) {
1575      // Assign the last value + 1.
1576      EnumVal = LastEnumConst->getInitVal();
1577      ++EnumVal;
1578
1579      // Check for overflow on increment.
1580      if (EnumVal < LastEnumConst->getInitVal())
1581        Diag(IdLoc, diag::warn_enum_value_overflow);
1582
1583      EltTy = LastEnumConst->getType();
1584    } else {
1585      // First value, set to zero.
1586      EltTy = Context.IntTy;
1587      EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
1588    }
1589  }
1590
1591  EnumConstantDecl *New =
1592    EnumConstantDecl::Create(Context, IdLoc, Id, EltTy, Val, EnumVal,
1593                             LastEnumConst);
1594
1595  // Register this decl in the current scope stack.
1596  New->setNext(Id->getFETokenInfo<ScopedDecl>());
1597  Id->setFETokenInfo(New);
1598  S->AddDecl(New);
1599  return New;
1600}
1601
1602void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1603                         DeclTy **Elements, unsigned NumElements) {
1604  EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1605  assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1606
1607  // TODO: If the result value doesn't fit in an int, it must be a long or long
1608  // long value.  ISO C does not support this, but GCC does as an extension,
1609  // emit a warning.
1610  unsigned IntWidth = Context.Target.getIntWidth();
1611
1612  // Verify that all the values are okay, compute the size of the values, and
1613  // reverse the list.
1614  unsigned NumNegativeBits = 0;
1615  unsigned NumPositiveBits = 0;
1616
1617  // Keep track of whether all elements have type int.
1618  bool AllElementsInt = true;
1619
1620  EnumConstantDecl *EltList = 0;
1621  for (unsigned i = 0; i != NumElements; ++i) {
1622    EnumConstantDecl *ECD =
1623      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1624    if (!ECD) continue;  // Already issued a diagnostic.
1625
1626    // If the enum value doesn't fit in an int, emit an extension warning.
1627    const llvm::APSInt &InitVal = ECD->getInitVal();
1628    assert(InitVal.getBitWidth() >= IntWidth &&
1629           "Should have promoted value to int");
1630    if (InitVal.getBitWidth() > IntWidth) {
1631      llvm::APSInt V(InitVal);
1632      V.trunc(IntWidth);
1633      V.extend(InitVal.getBitWidth());
1634      if (V != InitVal)
1635        Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1636             InitVal.toString());
1637    }
1638
1639    // Keep track of the size of positive and negative values.
1640    if (InitVal.isUnsigned() || InitVal.isNonNegative())
1641      NumPositiveBits = std::max(NumPositiveBits,
1642                                 (unsigned)InitVal.getActiveBits());
1643    else
1644      NumNegativeBits = std::max(NumNegativeBits,
1645                                 (unsigned)InitVal.getMinSignedBits());
1646
1647    // Keep track of whether every enum element has type int (very commmon).
1648    if (AllElementsInt)
1649      AllElementsInt = ECD->getType() == Context.IntTy;
1650
1651    ECD->setNextDeclarator(EltList);
1652    EltList = ECD;
1653  }
1654
1655  // Figure out the type that should be used for this enum.
1656  // FIXME: Support attribute(packed) on enums and -fshort-enums.
1657  QualType BestType;
1658  unsigned BestWidth;
1659
1660  if (NumNegativeBits) {
1661    // If there is a negative value, figure out the smallest integer type (of
1662    // int/long/longlong) that fits.
1663    if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
1664      BestType = Context.IntTy;
1665      BestWidth = IntWidth;
1666    } else {
1667      BestWidth = Context.Target.getLongWidth();
1668
1669      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
1670        BestType = Context.LongTy;
1671      else {
1672        BestWidth = Context.Target.getLongLongWidth();
1673
1674        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
1675          Diag(Enum->getLocation(), diag::warn_enum_too_large);
1676        BestType = Context.LongLongTy;
1677      }
1678    }
1679  } else {
1680    // If there is no negative value, figure out which of uint, ulong, ulonglong
1681    // fits.
1682    if (NumPositiveBits <= IntWidth) {
1683      BestType = Context.UnsignedIntTy;
1684      BestWidth = IntWidth;
1685    } else if (NumPositiveBits <=
1686               (BestWidth = Context.Target.getLongWidth())) {
1687      BestType = Context.UnsignedLongTy;
1688    } else {
1689      BestWidth = Context.Target.getLongLongWidth();
1690      assert(NumPositiveBits <= BestWidth &&
1691             "How could an initializer get larger than ULL?");
1692      BestType = Context.UnsignedLongLongTy;
1693    }
1694  }
1695
1696  // Loop over all of the enumerator constants, changing their types to match
1697  // the type of the enum if needed.
1698  for (unsigned i = 0; i != NumElements; ++i) {
1699    EnumConstantDecl *ECD =
1700      cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1701    if (!ECD) continue;  // Already issued a diagnostic.
1702
1703    // Standard C says the enumerators have int type, but we allow, as an
1704    // extension, the enumerators to be larger than int size.  If each
1705    // enumerator value fits in an int, type it as an int, otherwise type it the
1706    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
1707    // that X has type 'int', not 'unsigned'.
1708    if (ECD->getType() == Context.IntTy) {
1709      // Make sure the init value is signed.
1710      llvm::APSInt IV = ECD->getInitVal();
1711      IV.setIsSigned(true);
1712      ECD->setInitVal(IV);
1713      continue;  // Already int type.
1714    }
1715
1716    // Determine whether the value fits into an int.
1717    llvm::APSInt InitVal = ECD->getInitVal();
1718    bool FitsInInt;
1719    if (InitVal.isUnsigned() || !InitVal.isNegative())
1720      FitsInInt = InitVal.getActiveBits() < IntWidth;
1721    else
1722      FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1723
1724    // If it fits into an integer type, force it.  Otherwise force it to match
1725    // the enum decl type.
1726    QualType NewTy;
1727    unsigned NewWidth;
1728    bool NewSign;
1729    if (FitsInInt) {
1730      NewTy = Context.IntTy;
1731      NewWidth = IntWidth;
1732      NewSign = true;
1733    } else if (ECD->getType() == BestType) {
1734      // Already the right type!
1735      continue;
1736    } else {
1737      NewTy = BestType;
1738      NewWidth = BestWidth;
1739      NewSign = BestType->isSignedIntegerType();
1740    }
1741
1742    // Adjust the APSInt value.
1743    InitVal.extOrTrunc(NewWidth);
1744    InitVal.setIsSigned(NewSign);
1745    ECD->setInitVal(InitVal);
1746
1747    // Adjust the Expr initializer and type.
1748    ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1749    ECD->setType(NewTy);
1750  }
1751
1752  Enum->defineElements(EltList, BestType);
1753  Consumer.HandleTagDeclDefinition(Enum);
1754}
1755
1756Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1757                                          ExprTy *expr) {
1758  StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1759
1760  return FileScopeAsmDecl::Create(Context, Loc, AsmString);
1761}
1762
1763Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1764                                     SourceLocation LBrace,
1765                                     SourceLocation RBrace,
1766                                     const char *Lang,
1767                                     unsigned StrSize,
1768                                     DeclTy *D) {
1769  LinkageSpecDecl::LanguageIDs Language;
1770  Decl *dcl = static_cast<Decl *>(D);
1771  if (strncmp(Lang, "\"C\"", StrSize) == 0)
1772    Language = LinkageSpecDecl::lang_c;
1773  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1774    Language = LinkageSpecDecl::lang_cxx;
1775  else {
1776    Diag(Loc, diag::err_bad_language);
1777    return 0;
1778  }
1779
1780  // FIXME: Add all the various semantics of linkage specifications
1781  return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
1782}
1783
1784void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
1785
1786  switch (Attr->getKind()) {
1787  case AttributeList::AT_vector_size:
1788    if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1789      QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
1790      if (!newType.isNull()) // install the new vector type into the decl
1791        vDecl->setType(newType);
1792    }
1793    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1794      QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1795                                                   Attr);
1796      if (!newType.isNull()) // install the new vector type into the decl
1797        tDecl->setUnderlyingType(newType);
1798    }
1799    break;
1800  case AttributeList::AT_ocu_vector_type:
1801    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1802      HandleOCUVectorTypeAttribute(tDecl, Attr);
1803    else
1804      Diag(Attr->getLoc(),
1805           diag::err_typecheck_ocu_vector_not_typedef);
1806    break;
1807  case AttributeList::AT_address_space:
1808    if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1809      QualType newType = HandleAddressSpaceTypeAttribute(
1810                                                  tDecl->getUnderlyingType(),
1811                                                  Attr);
1812      tDecl->setUnderlyingType(newType);
1813    } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1814      QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
1815                                                         Attr);
1816      // install the new addr spaced type into the decl
1817      vDecl->setType(newType);
1818    }
1819    break;
1820  case AttributeList::AT_deprecated:
1821    HandleDeprecatedAttribute(New, Attr);
1822    break;
1823  case AttributeList::AT_visibility:
1824    HandleVisibilityAttribute(New, Attr);
1825    break;
1826  case AttributeList::AT_weak:
1827    HandleWeakAttribute(New, Attr);
1828    break;
1829  case AttributeList::AT_dllimport:
1830    HandleDLLImportAttribute(New, Attr);
1831    break;
1832  case AttributeList::AT_dllexport:
1833    HandleDLLExportAttribute(New, Attr);
1834    break;
1835  case AttributeList::AT_nothrow:
1836    HandleNothrowAttribute(New, Attr);
1837    break;
1838  case AttributeList::AT_stdcall:
1839    HandleStdCallAttribute(New, Attr);
1840    break;
1841  case AttributeList::AT_fastcall:
1842    HandleFastCallAttribute(New, Attr);
1843    break;
1844  case AttributeList::AT_aligned:
1845    HandleAlignedAttribute(New, Attr);
1846    break;
1847  case AttributeList::AT_packed:
1848    HandlePackedAttribute(New, Attr);
1849    break;
1850  case AttributeList::AT_annotate:
1851    HandleAnnotateAttribute(New, Attr);
1852    break;
1853  case AttributeList::AT_noreturn:
1854    HandleNoReturnAttribute(New, Attr);
1855    break;
1856  case AttributeList::AT_format:
1857    HandleFormatAttribute(New, Attr);
1858    break;
1859  default:
1860#if 0
1861    // TODO: when we have the full set of attributes, warn about unknown ones.
1862    Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1863         Attr->getName()->getName());
1864#endif
1865    break;
1866  }
1867}
1868
1869void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1870                                AttributeList *declarator_postfix) {
1871  while (declspec_prefix) {
1872    HandleDeclAttribute(New, declspec_prefix);
1873    declspec_prefix = declspec_prefix->getNext();
1874  }
1875  while (declarator_postfix) {
1876    HandleDeclAttribute(New, declarator_postfix);
1877    declarator_postfix = declarator_postfix->getNext();
1878  }
1879}
1880
1881void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1882                                        AttributeList *rawAttr) {
1883  QualType curType = tDecl->getUnderlyingType();
1884  // check the attribute arguments.
1885  if (rawAttr->getNumArgs() != 1) {
1886    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1887         std::string("1"));
1888    return;
1889  }
1890  Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1891  llvm::APSInt vecSize(32);
1892  if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1893    Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
1894         "ocu_vector_type", sizeExpr->getSourceRange());
1895    return;
1896  }
1897  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1898  // in conjunction with complex types (pointers, arrays, functions, etc.).
1899  Type *canonType = curType.getCanonicalType().getTypePtr();
1900  if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1901    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
1902         curType.getCanonicalType().getAsString());
1903    return;
1904  }
1905  // unlike gcc's vector_size attribute, the size is specified as the
1906  // number of elements, not the number of bytes.
1907  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1908
1909  if (vectorSize == 0) {
1910    Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
1911         sizeExpr->getSourceRange());
1912    return;
1913  }
1914  // Instantiate/Install the vector type, the number of elements is > 0.
1915  tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1916  // Remember this typedef decl, we will need it later for diagnostics.
1917  OCUVectorDecls.push_back(tDecl);
1918}
1919
1920QualType Sema::HandleVectorTypeAttribute(QualType curType,
1921                                         AttributeList *rawAttr) {
1922  // check the attribute arugments.
1923  if (rawAttr->getNumArgs() != 1) {
1924    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1925         std::string("1"));
1926    return QualType();
1927  }
1928  Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1929  llvm::APSInt vecSize(32);
1930  if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1931    Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
1932         "vector_size", sizeExpr->getSourceRange());
1933    return QualType();
1934  }
1935  // navigate to the base type - we need to provide for vector pointers,
1936  // vector arrays, and functions returning vectors.
1937  Type *canonType = curType.getCanonicalType().getTypePtr();
1938
1939  if (canonType->isPointerType() || canonType->isArrayType() ||
1940      canonType->isFunctionType()) {
1941    assert(0 && "HandleVector(): Complex type construction unimplemented");
1942    /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1943        do {
1944          if (PointerType *PT = dyn_cast<PointerType>(canonType))
1945            canonType = PT->getPointeeType().getTypePtr();
1946          else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1947            canonType = AT->getElementType().getTypePtr();
1948          else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1949            canonType = FT->getResultType().getTypePtr();
1950        } while (canonType->isPointerType() || canonType->isArrayType() ||
1951                 canonType->isFunctionType());
1952    */
1953  }
1954  // the base type must be integer or float.
1955  if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1956    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
1957         curType.getCanonicalType().getAsString());
1958    return QualType();
1959  }
1960  unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
1961  // vecSize is specified in bytes - convert to bits.
1962  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
1963
1964  // the vector size needs to be an integral multiple of the type size.
1965  if (vectorSize % typeSize) {
1966    Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
1967         sizeExpr->getSourceRange());
1968    return QualType();
1969  }
1970  if (vectorSize == 0) {
1971    Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
1972         sizeExpr->getSourceRange());
1973    return QualType();
1974  }
1975  // Instantiate the vector type, the number of elements is > 0, and not
1976  // required to be a power of 2, unlike GCC.
1977  return Context.getVectorType(curType, vectorSize/typeSize);
1978}
1979
1980void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
1981  // check the attribute arguments.
1982  if (rawAttr->getNumArgs() > 0) {
1983    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1984         std::string("0"));
1985    return;
1986  }
1987
1988  if (TagDecl *TD = dyn_cast<TagDecl>(d))
1989    TD->addAttr(new PackedAttr);
1990  else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
1991    // If the alignment is less than or equal to 8 bits, the packed attribute
1992    // has no effect.
1993    if (Context.getTypeAlign(FD->getType()) <= 8)
1994      Diag(rawAttr->getLoc(),
1995           diag::warn_attribute_ignored_for_field_of_type,
1996           rawAttr->getName()->getName(), FD->getType().getAsString());
1997    else
1998      FD->addAttr(new PackedAttr);
1999  } else
2000    Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2001         rawAttr->getName()->getName());
2002}
2003
2004void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2005  // check the attribute arguments.
2006  if (rawAttr->getNumArgs() != 0) {
2007    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2008         std::string("0"));
2009    return;
2010  }
2011
2012  FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2013
2014  if (!Fn) {
2015    Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2016         "noreturn", "function");
2017    return;
2018  }
2019
2020  d->addAttr(new NoReturnAttr());
2021}
2022
2023void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2024  // check the attribute arguments.
2025  if (rawAttr->getNumArgs() != 0) {
2026    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2027         std::string("0"));
2028    return;
2029  }
2030
2031  d->addAttr(new DeprecatedAttr());
2032}
2033
2034void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2035  // check the attribute arguments.
2036  if (rawAttr->getNumArgs() != 1) {
2037    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2038         std::string("1"));
2039    return;
2040  }
2041
2042  Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2043  Arg = Arg->IgnoreParenCasts();
2044  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2045
2046  if (Str == 0 || Str->isWide()) {
2047    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2048         "visibility", std::string("1"));
2049    return;
2050  }
2051
2052  const char *TypeStr = Str->getStrData();
2053  unsigned TypeLen = Str->getByteLength();
2054  llvm::GlobalValue::VisibilityTypes type;
2055
2056  if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
2057    type = llvm::GlobalValue::DefaultVisibility;
2058  else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
2059    type = llvm::GlobalValue::HiddenVisibility;
2060  else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
2061    type = llvm::GlobalValue::HiddenVisibility; // FIXME
2062  else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
2063    type = llvm::GlobalValue::ProtectedVisibility;
2064  else {
2065    Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2066           "visibility", TypeStr);
2067    return;
2068  }
2069
2070  d->addAttr(new VisibilityAttr(type));
2071}
2072
2073void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2074  // check the attribute arguments.
2075  if (rawAttr->getNumArgs() != 0) {
2076    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2077         std::string("0"));
2078    return;
2079  }
2080
2081  d->addAttr(new WeakAttr());
2082}
2083
2084void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2085  // check the attribute arguments.
2086  if (rawAttr->getNumArgs() != 0) {
2087    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2088         std::string("0"));
2089    return;
2090  }
2091
2092  d->addAttr(new DLLImportAttr());
2093}
2094
2095void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2096  // check the attribute arguments.
2097  if (rawAttr->getNumArgs() != 0) {
2098    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2099         std::string("0"));
2100    return;
2101  }
2102
2103  d->addAttr(new DLLExportAttr());
2104}
2105
2106void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2107  // check the attribute arguments.
2108  if (rawAttr->getNumArgs() != 0) {
2109    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2110         std::string("0"));
2111    return;
2112  }
2113
2114  d->addAttr(new StdCallAttr());
2115}
2116
2117void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2118  // check the attribute arguments.
2119  if (rawAttr->getNumArgs() != 0) {
2120    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2121         std::string("0"));
2122    return;
2123  }
2124
2125  d->addAttr(new FastCallAttr());
2126}
2127
2128void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2129  // check the attribute arguments.
2130  if (rawAttr->getNumArgs() != 0) {
2131    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2132         std::string("0"));
2133    return;
2134  }
2135
2136  d->addAttr(new NoThrowAttr());
2137}
2138
2139static const FunctionTypeProto *getFunctionProto(Decl *d) {
2140  ValueDecl *decl = dyn_cast<ValueDecl>(d);
2141  if (!decl) return 0;
2142
2143  QualType Ty = decl->getType();
2144
2145  if (Ty->isFunctionPointerType()) {
2146    const PointerType *PtrTy = Ty->getAsPointerType();
2147    Ty = PtrTy->getPointeeType();
2148  }
2149
2150  if (const FunctionType *FnTy = Ty->getAsFunctionType())
2151    return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2152
2153  return 0;
2154}
2155
2156
2157/// Handle __attribute__((format(type,idx,firstarg))) attributes
2158/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2159void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2160
2161  if (!rawAttr->getParameterName()) {
2162    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2163           "format", std::string("1"));
2164    return;
2165  }
2166
2167  if (rawAttr->getNumArgs() != 2) {
2168    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2169         std::string("3"));
2170    return;
2171  }
2172
2173  // GCC ignores the format attribute on K&R style function
2174  // prototypes, so we ignore it as well
2175  const FunctionTypeProto *proto = getFunctionProto(d);
2176
2177  if (!proto) {
2178    Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2179           "format", "function");
2180    return;
2181  }
2182
2183  // FIXME: in C++ the implicit 'this' function parameter also counts.
2184  // this is needed in order to be compatible with GCC
2185  // the index must start in 1 and the limit is numargs+1
2186  unsigned NumArgs  = proto->getNumArgs();
2187  unsigned FirstIdx = 1;
2188
2189  const char *Format = rawAttr->getParameterName()->getName();
2190  unsigned FormatLen = rawAttr->getParameterName()->getLength();
2191
2192  // Normalize the argument, __foo__ becomes foo.
2193  if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2194      Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2195    Format += 2;
2196    FormatLen -= 4;
2197  }
2198
2199  if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2200     || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2201     || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2202     || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2203    Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2204           "format", rawAttr->getParameterName()->getName());
2205    return;
2206  }
2207
2208  // checks for the 2nd argument
2209  Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
2210  llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
2211  if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2212    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2213           "format", std::string("2"), IdxExpr->getSourceRange());
2214    return;
2215  }
2216
2217  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
2218    Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2219           "format", std::string("2"), IdxExpr->getSourceRange());
2220    return;
2221  }
2222
2223  // make sure the format string is really a string
2224  QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2225  if (!Ty->isPointerType() ||
2226      !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2227    Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2228         IdxExpr->getSourceRange());
2229    return;
2230  }
2231
2232
2233  // check the 3rd argument
2234  Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
2235  llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
2236  if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2237    Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2238           "format", std::string("3"), FirstArgExpr->getSourceRange());
2239    return;
2240  }
2241
2242  // check if the function is variadic if the 3rd argument non-zero
2243  if (FirstArg != 0) {
2244    if (proto->isVariadic()) {
2245      ++NumArgs; // +1 for ...
2246    } else {
2247      Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2248      return;
2249    }
2250  }
2251
2252  // strftime requires FirstArg to be 0 because it doesn't read from any variable
2253  // the input is just the current time + the format string
2254  if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
2255    if (FirstArg != 0) {
2256      Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2257             FirstArgExpr->getSourceRange());
2258      return;
2259    }
2260  // if 0 it disables parameter checking (to use with e.g. va_list)
2261  } else if (FirstArg != 0 && FirstArg != NumArgs) {
2262    Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2263           "format", std::string("3"), FirstArgExpr->getSourceRange());
2264    return;
2265  }
2266
2267  d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2268                            Idx.getZExtValue(), FirstArg.getZExtValue()));
2269}
2270
2271void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2272  // check the attribute arguments.
2273  if (rawAttr->getNumArgs() != 1) {
2274    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2275         std::string("1"));
2276    return;
2277  }
2278  Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2279  StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
2280
2281  // Make sure that there is a string literal as the annotation's single
2282  // argument.
2283  if (!SE) {
2284    Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2285    return;
2286  }
2287  d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2288                                          SE->getByteLength())));
2289}
2290
2291void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2292{
2293  // check the attribute arguments.
2294  if (rawAttr->getNumArgs() > 1) {
2295    Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2296         std::string("1"));
2297    return;
2298  }
2299
2300  unsigned Align = 0;
2301
2302  if (rawAttr->getNumArgs() == 0) {
2303    // FIXME: This should be the target specific maximum alignment.
2304    // (For now we just use 128 bits which is the maximum on X86.
2305    Align = 128;
2306    return;
2307  } else {
2308    Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2309    llvm::APSInt alignment(32);
2310    if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
2311      Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
2312           "aligned", alignmentExpr->getSourceRange());
2313      return;
2314    }
2315
2316    Align = alignment.getZExtValue() * 8;
2317  }
2318
2319  d->addAttr(new AlignedAttr(Align));
2320}
2321