SemaType.cpp revision 433d7d2c70b9be3f9edd40579f512ecab8755049
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
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 type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/TypeLocVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Parse/DeclSpec.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/Support/ErrorHandling.h"
26using namespace clang;
27
28/// \brief Perform adjustment on the parameter type of a function.
29///
30/// This routine adjusts the given parameter type @p T to the actual
31/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
32/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
33QualType Sema::adjustParameterType(QualType T) {
34  // C99 6.7.5.3p7:
35  //   A declaration of a parameter as "array of type" shall be
36  //   adjusted to "qualified pointer to type", where the type
37  //   qualifiers (if any) are those specified within the [ and ] of
38  //   the array type derivation.
39  if (T->isArrayType())
40    return Context.getArrayDecayedType(T);
41
42  // C99 6.7.5.3p8:
43  //   A declaration of a parameter as "function returning type"
44  //   shall be adjusted to "pointer to function returning type", as
45  //   in 6.3.2.1.
46  if (T->isFunctionType())
47    return Context.getPointerType(T);
48
49  return T;
50}
51
52
53
54/// isOmittedBlockReturnType - Return true if this declarator is missing a
55/// return type because this is a omitted return type on a block literal.
56static bool isOmittedBlockReturnType(const Declarator &D) {
57  if (D.getContext() != Declarator::BlockLiteralContext ||
58      D.getDeclSpec().hasTypeSpecifier())
59    return false;
60
61  if (D.getNumTypeObjects() == 0)
62    return true;   // ^{ ... }
63
64  if (D.getNumTypeObjects() == 1 &&
65      D.getTypeObject(0).Kind == DeclaratorChunk::Function)
66    return true;   // ^(int X, float Y) { ... }
67
68  return false;
69}
70
71typedef std::pair<const AttributeList*,QualType> DelayedAttribute;
72typedef llvm::SmallVectorImpl<DelayedAttribute> DelayedAttributeSet;
73
74static void ProcessTypeAttributeList(Sema &S, QualType &Type,
75                                     bool IsDeclSpec,
76                                     const AttributeList *Attrs,
77                                     DelayedAttributeSet &DelayedFnAttrs);
78static bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr);
79
80static void ProcessDelayedFnAttrs(Sema &S, QualType &Type,
81                                  DelayedAttributeSet &Attrs) {
82  for (DelayedAttributeSet::iterator I = Attrs.begin(),
83         E = Attrs.end(); I != E; ++I)
84    if (ProcessFnAttr(S, Type, *I->first))
85      S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type)
86        << I->first->getName() << I->second;
87  Attrs.clear();
88}
89
90static void DiagnoseDelayedFnAttrs(Sema &S, DelayedAttributeSet &Attrs) {
91  for (DelayedAttributeSet::iterator I = Attrs.begin(),
92         E = Attrs.end(); I != E; ++I) {
93    S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type)
94      << I->first->getName() << I->second;
95  }
96  Attrs.clear();
97}
98
99/// \brief Convert the specified declspec to the appropriate type
100/// object.
101/// \param D  the declarator containing the declaration specifier.
102/// \returns The type described by the declaration specifiers.  This function
103/// never returns null.
104static QualType ConvertDeclSpecToType(Sema &TheSema,
105                                      Declarator &TheDeclarator,
106                                      DelayedAttributeSet &Delayed) {
107  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
108  // checking.
109  const DeclSpec &DS = TheDeclarator.getDeclSpec();
110  SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc();
111  if (DeclLoc.isInvalid())
112    DeclLoc = DS.getSourceRange().getBegin();
113
114  ASTContext &Context = TheSema.Context;
115
116  QualType Result;
117  switch (DS.getTypeSpecType()) {
118  case DeclSpec::TST_void:
119    Result = Context.VoidTy;
120    break;
121  case DeclSpec::TST_char:
122    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
123      Result = Context.CharTy;
124    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
125      Result = Context.SignedCharTy;
126    else {
127      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
128             "Unknown TSS value");
129      Result = Context.UnsignedCharTy;
130    }
131    break;
132  case DeclSpec::TST_wchar:
133    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
134      Result = Context.WCharTy;
135    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
136      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
137        << DS.getSpecifierName(DS.getTypeSpecType());
138      Result = Context.getSignedWCharType();
139    } else {
140      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
141        "Unknown TSS value");
142      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
143        << DS.getSpecifierName(DS.getTypeSpecType());
144      Result = Context.getUnsignedWCharType();
145    }
146    break;
147  case DeclSpec::TST_char16:
148      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
149        "Unknown TSS value");
150      Result = Context.Char16Ty;
151    break;
152  case DeclSpec::TST_char32:
153      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
154        "Unknown TSS value");
155      Result = Context.Char32Ty;
156    break;
157  case DeclSpec::TST_unspecified:
158    // "<proto1,proto2>" is an objc qualified ID with a missing id.
159    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
160      Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
161                                                (ObjCProtocolDecl**)PQ,
162                                                DS.getNumProtocolQualifiers());
163      break;
164    }
165
166    // If this is a missing declspec in a block literal return context, then it
167    // is inferred from the return statements inside the block.
168    if (isOmittedBlockReturnType(TheDeclarator)) {
169      Result = Context.DependentTy;
170      break;
171    }
172
173    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
174    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
175    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
176    // Note that the one exception to this is function definitions, which are
177    // allowed to be completely missing a declspec.  This is handled in the
178    // parser already though by it pretending to have seen an 'int' in this
179    // case.
180    if (TheSema.getLangOptions().ImplicitInt) {
181      // In C89 mode, we only warn if there is a completely missing declspec
182      // when one is not allowed.
183      if (DS.isEmpty()) {
184        TheSema.Diag(DeclLoc, diag::ext_missing_declspec)
185          << DS.getSourceRange()
186        << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
187                                                 "int");
188      }
189    } else if (!DS.hasTypeSpecifier()) {
190      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
191      // "At least one type specifier shall be given in the declaration
192      // specifiers in each declaration, and in the specifier-qualifier list in
193      // each struct declaration and type name."
194      // FIXME: Does Microsoft really have the implicit int extension in C++?
195      if (TheSema.getLangOptions().CPlusPlus &&
196          !TheSema.getLangOptions().Microsoft) {
197        TheSema.Diag(DeclLoc, diag::err_missing_type_specifier)
198          << DS.getSourceRange();
199
200        // When this occurs in C++ code, often something is very broken with the
201        // value being declared, poison it as invalid so we don't get chains of
202        // errors.
203        TheDeclarator.setInvalidType(true);
204      } else {
205        TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier)
206          << DS.getSourceRange();
207      }
208    }
209
210    // FALL THROUGH.
211  case DeclSpec::TST_int: {
212    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
213      switch (DS.getTypeSpecWidth()) {
214      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
215      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
216      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
217      case DeclSpec::TSW_longlong:
218        Result = Context.LongLongTy;
219
220        // long long is a C99 feature.
221        if (!TheSema.getLangOptions().C99 &&
222            !TheSema.getLangOptions().CPlusPlus0x)
223          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
224        break;
225      }
226    } else {
227      switch (DS.getTypeSpecWidth()) {
228      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
229      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
230      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
231      case DeclSpec::TSW_longlong:
232        Result = Context.UnsignedLongLongTy;
233
234        // long long is a C99 feature.
235        if (!TheSema.getLangOptions().C99 &&
236            !TheSema.getLangOptions().CPlusPlus0x)
237          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
238        break;
239      }
240    }
241    break;
242  }
243  case DeclSpec::TST_float: Result = Context.FloatTy; break;
244  case DeclSpec::TST_double:
245    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
246      Result = Context.LongDoubleTy;
247    else
248      Result = Context.DoubleTy;
249    break;
250  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
251  case DeclSpec::TST_decimal32:    // _Decimal32
252  case DeclSpec::TST_decimal64:    // _Decimal64
253  case DeclSpec::TST_decimal128:   // _Decimal128
254    TheSema.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
255    Result = Context.IntTy;
256    TheDeclarator.setInvalidType(true);
257    break;
258  case DeclSpec::TST_class:
259  case DeclSpec::TST_enum:
260  case DeclSpec::TST_union:
261  case DeclSpec::TST_struct: {
262    TypeDecl *D
263      = dyn_cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep()));
264    if (!D) {
265      // This can happen in C++ with ambiguous lookups.
266      Result = Context.IntTy;
267      TheDeclarator.setInvalidType(true);
268      break;
269    }
270
271    // If the type is deprecated or unavailable, diagnose it.
272    TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc());
273
274    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
275           DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
276
277    // TypeQuals handled by caller.
278    Result = Context.getTypeDeclType(D);
279
280    // In C++, make an ElaboratedType.
281    if (TheSema.getLangOptions().CPlusPlus) {
282      TagDecl::TagKind Tag
283        = TagDecl::getTagKindForTypeSpec(DS.getTypeSpecType());
284      Result = Context.getElaboratedType(Result, Tag);
285    }
286
287    if (D->isInvalidDecl())
288      TheDeclarator.setInvalidType(true);
289    break;
290  }
291  case DeclSpec::TST_typename: {
292    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
293           DS.getTypeSpecSign() == 0 &&
294           "Can't handle qualifiers on typedef names yet!");
295    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
296
297    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
298      if (const ObjCInterfaceType *
299            Interface = Result->getAs<ObjCInterfaceType>()) {
300        // It would be nice if protocol qualifiers were only stored with the
301        // ObjCObjectPointerType. Unfortunately, this isn't possible due
302        // to the following typedef idiom (which is uncommon, but allowed):
303        //
304        // typedef Foo<P> T;
305        // static void func() {
306        //   Foo<P> *yy;
307        //   T *zz;
308        // }
309        Result = Context.getObjCInterfaceType(Interface->getDecl(),
310                                              (ObjCProtocolDecl**)PQ,
311                                              DS.getNumProtocolQualifiers());
312      } else if (Result->isObjCIdType())
313        // id<protocol-list>
314        Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
315                        (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
316      else if (Result->isObjCClassType()) {
317        // Class<protocol-list>
318        Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy,
319                        (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
320      } else {
321        TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
322          << DS.getSourceRange();
323        TheDeclarator.setInvalidType(true);
324      }
325    }
326
327    // TypeQuals handled by caller.
328    break;
329  }
330  case DeclSpec::TST_typeofType:
331    // FIXME: Preserve type source info.
332    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
333    assert(!Result.isNull() && "Didn't get a type for typeof?");
334    // TypeQuals handled by caller.
335    Result = Context.getTypeOfType(Result);
336    break;
337  case DeclSpec::TST_typeofExpr: {
338    Expr *E = static_cast<Expr *>(DS.getTypeRep());
339    assert(E && "Didn't get an expression for typeof?");
340    // TypeQuals handled by caller.
341    Result = TheSema.BuildTypeofExprType(E);
342    if (Result.isNull()) {
343      Result = Context.IntTy;
344      TheDeclarator.setInvalidType(true);
345    }
346    break;
347  }
348  case DeclSpec::TST_decltype: {
349    Expr *E = static_cast<Expr *>(DS.getTypeRep());
350    assert(E && "Didn't get an expression for decltype?");
351    // TypeQuals handled by caller.
352    Result = TheSema.BuildDecltypeType(E);
353    if (Result.isNull()) {
354      Result = Context.IntTy;
355      TheDeclarator.setInvalidType(true);
356    }
357    break;
358  }
359  case DeclSpec::TST_auto: {
360    // TypeQuals handled by caller.
361    Result = Context.UndeducedAutoTy;
362    break;
363  }
364
365  case DeclSpec::TST_error:
366    Result = Context.IntTy;
367    TheDeclarator.setInvalidType(true);
368    break;
369  }
370
371  // Handle complex types.
372  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
373    if (TheSema.getLangOptions().Freestanding)
374      TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
375    Result = Context.getComplexType(Result);
376  } else if (DS.isTypeAltiVecVector()) {
377    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
378    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
379    Result = Context.getVectorType(Result, 128/typeSize, true,
380      DS.isTypeAltiVecPixel());
381  }
382
383  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
384         "FIXME: imaginary types not supported yet!");
385
386  // See if there are any attributes on the declspec that apply to the type (as
387  // opposed to the decl).
388  if (const AttributeList *AL = DS.getAttributes())
389    ProcessTypeAttributeList(TheSema, Result, true, AL, Delayed);
390
391  // Apply const/volatile/restrict qualifiers to T.
392  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
393
394    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
395    // or incomplete types shall not be restrict-qualified."  C++ also allows
396    // restrict-qualified references.
397    if (TypeQuals & DeclSpec::TQ_restrict) {
398      if (Result->isAnyPointerType() || Result->isReferenceType()) {
399        QualType EltTy;
400        if (Result->isObjCObjectPointerType())
401          EltTy = Result;
402        else
403          EltTy = Result->isPointerType() ?
404                    Result->getAs<PointerType>()->getPointeeType() :
405                    Result->getAs<ReferenceType>()->getPointeeType();
406
407        // If we have a pointer or reference, the pointee must have an object
408        // incomplete type.
409        if (!EltTy->isIncompleteOrObjectType()) {
410          TheSema.Diag(DS.getRestrictSpecLoc(),
411               diag::err_typecheck_invalid_restrict_invalid_pointee)
412            << EltTy << DS.getSourceRange();
413          TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
414        }
415      } else {
416        TheSema.Diag(DS.getRestrictSpecLoc(),
417             diag::err_typecheck_invalid_restrict_not_pointer)
418          << Result << DS.getSourceRange();
419        TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
420      }
421    }
422
423    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
424    // of a function type includes any type qualifiers, the behavior is
425    // undefined."
426    if (Result->isFunctionType() && TypeQuals) {
427      // Get some location to point at, either the C or V location.
428      SourceLocation Loc;
429      if (TypeQuals & DeclSpec::TQ_const)
430        Loc = DS.getConstSpecLoc();
431      else if (TypeQuals & DeclSpec::TQ_volatile)
432        Loc = DS.getVolatileSpecLoc();
433      else {
434        assert((TypeQuals & DeclSpec::TQ_restrict) &&
435               "Has CVR quals but not C, V, or R?");
436        Loc = DS.getRestrictSpecLoc();
437      }
438      TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers)
439        << Result << DS.getSourceRange();
440    }
441
442    // C++ [dcl.ref]p1:
443    //   Cv-qualified references are ill-formed except when the
444    //   cv-qualifiers are introduced through the use of a typedef
445    //   (7.1.3) or of a template type argument (14.3), in which
446    //   case the cv-qualifiers are ignored.
447    // FIXME: Shouldn't we be checking SCS_typedef here?
448    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
449        TypeQuals && Result->isReferenceType()) {
450      TypeQuals &= ~DeclSpec::TQ_const;
451      TypeQuals &= ~DeclSpec::TQ_volatile;
452    }
453
454    Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
455    Result = Context.getQualifiedType(Result, Quals);
456  }
457
458  return Result;
459}
460
461static std::string getPrintableNameForEntity(DeclarationName Entity) {
462  if (Entity)
463    return Entity.getAsString();
464
465  return "type name";
466}
467
468/// \brief Build a pointer type.
469///
470/// \param T The type to which we'll be building a pointer.
471///
472/// \param Quals The cvr-qualifiers to be applied to the pointer type.
473///
474/// \param Loc The location of the entity whose type involves this
475/// pointer type or, if there is no such entity, the location of the
476/// type that will have pointer type.
477///
478/// \param Entity The name of the entity that involves the pointer
479/// type, if known.
480///
481/// \returns A suitable pointer type, if there are no
482/// errors. Otherwise, returns a NULL type.
483QualType Sema::BuildPointerType(QualType T, unsigned Quals,
484                                SourceLocation Loc, DeclarationName Entity) {
485  if (T->isReferenceType()) {
486    // C++ 8.3.2p4: There shall be no ... pointers to references ...
487    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
488      << getPrintableNameForEntity(Entity) << T;
489    return QualType();
490  }
491
492  Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
493
494  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
495  // object or incomplete types shall not be restrict-qualified."
496  if (Qs.hasRestrict() && !T->isIncompleteOrObjectType()) {
497    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
498      << T;
499    Qs.removeRestrict();
500  }
501
502  // Build the pointer type.
503  return Context.getQualifiedType(Context.getPointerType(T), Qs);
504}
505
506/// \brief Build a reference type.
507///
508/// \param T The type to which we'll be building a reference.
509///
510/// \param CVR The cvr-qualifiers to be applied to the reference type.
511///
512/// \param Loc The location of the entity whose type involves this
513/// reference type or, if there is no such entity, the location of the
514/// type that will have reference type.
515///
516/// \param Entity The name of the entity that involves the reference
517/// type, if known.
518///
519/// \returns A suitable reference type, if there are no
520/// errors. Otherwise, returns a NULL type.
521QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
522                                  unsigned CVR, SourceLocation Loc,
523                                  DeclarationName Entity) {
524  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
525
526  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
527
528  // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
529  //   reference to a type T, and attempt to create the type "lvalue
530  //   reference to cv TD" creates the type "lvalue reference to T".
531  // We use the qualifiers (restrict or none) of the original reference,
532  // not the new ones. This is consistent with GCC.
533
534  // C++ [dcl.ref]p4: There shall be no references to references.
535  //
536  // According to C++ DR 106, references to references are only
537  // diagnosed when they are written directly (e.g., "int & &"),
538  // but not when they happen via a typedef:
539  //
540  //   typedef int& intref;
541  //   typedef intref& intref2;
542  //
543  // Parser::ParseDeclaratorInternal diagnoses the case where
544  // references are written directly; here, we handle the
545  // collapsing of references-to-references as described in C++
546  // DR 106 and amended by C++ DR 540.
547
548  // C++ [dcl.ref]p1:
549  //   A declarator that specifies the type "reference to cv void"
550  //   is ill-formed.
551  if (T->isVoidType()) {
552    Diag(Loc, diag::err_reference_to_void);
553    return QualType();
554  }
555
556  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
557  // object or incomplete types shall not be restrict-qualified."
558  if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
559    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
560      << T;
561    Quals.removeRestrict();
562  }
563
564  // C++ [dcl.ref]p1:
565  //   [...] Cv-qualified references are ill-formed except when the
566  //   cv-qualifiers are introduced through the use of a typedef
567  //   (7.1.3) or of a template type argument (14.3), in which case
568  //   the cv-qualifiers are ignored.
569  //
570  // We diagnose extraneous cv-qualifiers for the non-typedef,
571  // non-template type argument case within the parser. Here, we just
572  // ignore any extraneous cv-qualifiers.
573  Quals.removeConst();
574  Quals.removeVolatile();
575
576  // Handle restrict on references.
577  if (LValueRef)
578    return Context.getQualifiedType(
579               Context.getLValueReferenceType(T, SpelledAsLValue), Quals);
580  return Context.getQualifiedType(Context.getRValueReferenceType(T), Quals);
581}
582
583/// \brief Build an array type.
584///
585/// \param T The type of each element in the array.
586///
587/// \param ASM C99 array size modifier (e.g., '*', 'static').
588///
589/// \param ArraySize Expression describing the size of the array.
590///
591/// \param Quals The cvr-qualifiers to be applied to the array's
592/// element type.
593///
594/// \param Loc The location of the entity whose type involves this
595/// array type or, if there is no such entity, the location of the
596/// type that will have array type.
597///
598/// \param Entity The name of the entity that involves the array
599/// type, if known.
600///
601/// \returns A suitable array type, if there are no errors. Otherwise,
602/// returns a NULL type.
603QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
604                              Expr *ArraySize, unsigned Quals,
605                              SourceRange Brackets, DeclarationName Entity) {
606
607  SourceLocation Loc = Brackets.getBegin();
608  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
609  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
610  // Not in C++, though. There we only dislike void.
611  if (getLangOptions().CPlusPlus) {
612    if (T->isVoidType()) {
613      Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
614      return QualType();
615    }
616  } else {
617    if (RequireCompleteType(Loc, T,
618                            diag::err_illegal_decl_array_incomplete_type))
619      return QualType();
620  }
621
622  if (T->isFunctionType()) {
623    Diag(Loc, diag::err_illegal_decl_array_of_functions)
624      << getPrintableNameForEntity(Entity) << T;
625    return QualType();
626  }
627
628  // C++ 8.3.2p4: There shall be no ... arrays of references ...
629  if (T->isReferenceType()) {
630    Diag(Loc, diag::err_illegal_decl_array_of_references)
631      << getPrintableNameForEntity(Entity) << T;
632    return QualType();
633  }
634
635  if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
636    Diag(Loc,  diag::err_illegal_decl_array_of_auto)
637      << getPrintableNameForEntity(Entity);
638    return QualType();
639  }
640
641  if (const RecordType *EltTy = T->getAs<RecordType>()) {
642    // If the element type is a struct or union that contains a variadic
643    // array, accept it as a GNU extension: C99 6.7.2.1p2.
644    if (EltTy->getDecl()->hasFlexibleArrayMember())
645      Diag(Loc, diag::ext_flexible_array_in_array) << T;
646  } else if (T->isObjCInterfaceType()) {
647    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
648    return QualType();
649  }
650
651  // C99 6.7.5.2p1: The size expression shall have integer type.
652  if (ArraySize && !ArraySize->isTypeDependent() &&
653      !ArraySize->getType()->isIntegerType()) {
654    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
655      << ArraySize->getType() << ArraySize->getSourceRange();
656    ArraySize->Destroy(Context);
657    return QualType();
658  }
659  llvm::APSInt ConstVal(32);
660  if (!ArraySize) {
661    if (ASM == ArrayType::Star)
662      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
663    else
664      T = Context.getIncompleteArrayType(T, ASM, Quals);
665  } else if (ArraySize->isValueDependent()) {
666    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
667  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
668             (!T->isDependentType() && !T->isIncompleteType() &&
669              !T->isConstantSizeType())) {
670    // Per C99, a variable array is an array with either a non-constant
671    // size or an element type that has a non-constant-size
672    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
673  } else {
674    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
675    // have a value greater than zero.
676    if (ConstVal.isSigned() && ConstVal.isNegative()) {
677      Diag(ArraySize->getLocStart(),
678           diag::err_typecheck_negative_array_size)
679        << ArraySize->getSourceRange();
680      return QualType();
681    }
682    if (ConstVal == 0) {
683      // GCC accepts zero sized static arrays. We allow them when
684      // we're not in a SFINAE context.
685      Diag(ArraySize->getLocStart(),
686           isSFINAEContext()? diag::err_typecheck_zero_array_size
687                            : diag::ext_typecheck_zero_array_size)
688        << ArraySize->getSourceRange();
689    }
690    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
691  }
692  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
693  if (!getLangOptions().C99) {
694    if (ArraySize && !ArraySize->isTypeDependent() &&
695        !ArraySize->isValueDependent() &&
696        !ArraySize->isIntegerConstantExpr(Context))
697      Diag(Loc, getLangOptions().CPlusPlus? diag::err_vla_cxx : diag::ext_vla);
698    else if (ASM != ArrayType::Normal || Quals != 0)
699      Diag(Loc,
700           getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
701                                     : diag::ext_c99_array_usage);
702  }
703
704  return T;
705}
706
707/// \brief Build an ext-vector type.
708///
709/// Run the required checks for the extended vector type.
710QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
711                                  SourceLocation AttrLoc) {
712
713  Expr *Arg = (Expr *)ArraySize.get();
714
715  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
716  // in conjunction with complex types (pointers, arrays, functions, etc.).
717  if (!T->isDependentType() &&
718      !T->isIntegerType() && !T->isRealFloatingType()) {
719    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
720    return QualType();
721  }
722
723  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
724    llvm::APSInt vecSize(32);
725    if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
726      Diag(AttrLoc, diag::err_attribute_argument_not_int)
727      << "ext_vector_type" << Arg->getSourceRange();
728      return QualType();
729    }
730
731    // unlike gcc's vector_size attribute, the size is specified as the
732    // number of elements, not the number of bytes.
733    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
734
735    if (vectorSize == 0) {
736      Diag(AttrLoc, diag::err_attribute_zero_size)
737      << Arg->getSourceRange();
738      return QualType();
739    }
740
741    if (!T->isDependentType())
742      return Context.getExtVectorType(T, vectorSize);
743  }
744
745  return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
746                                                AttrLoc);
747}
748
749/// \brief Build a function type.
750///
751/// This routine checks the function type according to C++ rules and
752/// under the assumption that the result type and parameter types have
753/// just been instantiated from a template. It therefore duplicates
754/// some of the behavior of GetTypeForDeclarator, but in a much
755/// simpler form that is only suitable for this narrow use case.
756///
757/// \param T The return type of the function.
758///
759/// \param ParamTypes The parameter types of the function. This array
760/// will be modified to account for adjustments to the types of the
761/// function parameters.
762///
763/// \param NumParamTypes The number of parameter types in ParamTypes.
764///
765/// \param Variadic Whether this is a variadic function type.
766///
767/// \param Quals The cvr-qualifiers to be applied to the function type.
768///
769/// \param Loc The location of the entity whose type involves this
770/// function type or, if there is no such entity, the location of the
771/// type that will have function type.
772///
773/// \param Entity The name of the entity that involves the function
774/// type, if known.
775///
776/// \returns A suitable function type, if there are no
777/// errors. Otherwise, returns a NULL type.
778QualType Sema::BuildFunctionType(QualType T,
779                                 QualType *ParamTypes,
780                                 unsigned NumParamTypes,
781                                 bool Variadic, unsigned Quals,
782                                 SourceLocation Loc, DeclarationName Entity) {
783  if (T->isArrayType() || T->isFunctionType()) {
784    Diag(Loc, diag::err_func_returning_array_function)
785      << T->isFunctionType() << T;
786    return QualType();
787  }
788
789  bool Invalid = false;
790  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
791    QualType ParamType = adjustParameterType(ParamTypes[Idx]);
792    if (ParamType->isVoidType()) {
793      Diag(Loc, diag::err_param_with_void_type);
794      Invalid = true;
795    }
796
797    ParamTypes[Idx] = ParamType;
798  }
799
800  if (Invalid)
801    return QualType();
802
803  return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
804                                 Quals, false, false, 0, 0,
805                                 FunctionType::ExtInfo());
806}
807
808/// \brief Build a member pointer type \c T Class::*.
809///
810/// \param T the type to which the member pointer refers.
811/// \param Class the class type into which the member pointer points.
812/// \param CVR Qualifiers applied to the member pointer type
813/// \param Loc the location where this type begins
814/// \param Entity the name of the entity that will have this member pointer type
815///
816/// \returns a member pointer type, if successful, or a NULL type if there was
817/// an error.
818QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
819                                      unsigned CVR, SourceLocation Loc,
820                                      DeclarationName Entity) {
821  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
822
823  // Verify that we're not building a pointer to pointer to function with
824  // exception specification.
825  if (CheckDistantExceptionSpec(T)) {
826    Diag(Loc, diag::err_distant_exception_spec);
827
828    // FIXME: If we're doing this as part of template instantiation,
829    // we should return immediately.
830
831    // Build the type anyway, but use the canonical type so that the
832    // exception specifiers are stripped off.
833    T = Context.getCanonicalType(T);
834  }
835
836  // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
837  //   with reference type, or "cv void."
838  if (T->isReferenceType()) {
839    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
840      << (Entity? Entity.getAsString() : "type name") << T;
841    return QualType();
842  }
843
844  if (T->isVoidType()) {
845    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
846      << (Entity? Entity.getAsString() : "type name");
847    return QualType();
848  }
849
850  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
851  // object or incomplete types shall not be restrict-qualified."
852  if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
853    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
854      << T;
855
856    // FIXME: If we're doing this as part of template instantiation,
857    // we should return immediately.
858    Quals.removeRestrict();
859  }
860
861  if (!Class->isDependentType() && !Class->isRecordType()) {
862    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
863    return QualType();
864  }
865
866  return Context.getQualifiedType(
867           Context.getMemberPointerType(T, Class.getTypePtr()), Quals);
868}
869
870/// \brief Build a block pointer type.
871///
872/// \param T The type to which we'll be building a block pointer.
873///
874/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
875///
876/// \param Loc The location of the entity whose type involves this
877/// block pointer type or, if there is no such entity, the location of the
878/// type that will have block pointer type.
879///
880/// \param Entity The name of the entity that involves the block pointer
881/// type, if known.
882///
883/// \returns A suitable block pointer type, if there are no
884/// errors. Otherwise, returns a NULL type.
885QualType Sema::BuildBlockPointerType(QualType T, unsigned CVR,
886                                     SourceLocation Loc,
887                                     DeclarationName Entity) {
888  if (!T->isFunctionType()) {
889    Diag(Loc, diag::err_nonfunction_block_type);
890    return QualType();
891  }
892
893  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
894  return Context.getQualifiedType(Context.getBlockPointerType(T), Quals);
895}
896
897QualType Sema::GetTypeFromParser(TypeTy *Ty, TypeSourceInfo **TInfo) {
898  QualType QT = QualType::getFromOpaquePtr(Ty);
899  if (QT.isNull()) {
900    if (TInfo) *TInfo = 0;
901    return QualType();
902  }
903
904  TypeSourceInfo *DI = 0;
905  if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
906    QT = LIT->getType();
907    DI = LIT->getTypeSourceInfo();
908  }
909
910  if (TInfo) *TInfo = DI;
911  return QT;
912}
913
914/// GetTypeForDeclarator - Convert the type for the specified
915/// declarator to Type instances.
916///
917/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
918/// owns the declaration of a type (e.g., the definition of a struct
919/// type), then *OwnedDecl will receive the owned declaration.
920QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
921                                    TypeSourceInfo **TInfo,
922                                    TagDecl **OwnedDecl) {
923  // Determine the type of the declarator. Not all forms of declarator
924  // have a type.
925  QualType T;
926
927  llvm::SmallVector<DelayedAttribute,4> FnAttrsFromDeclSpec;
928
929  switch (D.getName().getKind()) {
930  case UnqualifiedId::IK_Identifier:
931  case UnqualifiedId::IK_OperatorFunctionId:
932  case UnqualifiedId::IK_LiteralOperatorId:
933  case UnqualifiedId::IK_TemplateId:
934    T = ConvertDeclSpecToType(*this, D, FnAttrsFromDeclSpec);
935
936    if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
937      TagDecl* Owned = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
938      // Owned is embedded if it was defined here, or if it is the
939      // very first (i.e., canonical) declaration of this tag type.
940      Owned->setEmbeddedInDeclarator(Owned->isDefinition() ||
941                                     Owned->isCanonicalDecl());
942      if (OwnedDecl) *OwnedDecl = Owned;
943    }
944    break;
945
946  case UnqualifiedId::IK_ConstructorName:
947  case UnqualifiedId::IK_ConstructorTemplateId:
948  case UnqualifiedId::IK_DestructorName:
949    // Constructors and destructors don't have return types. Use
950    // "void" instead.
951    T = Context.VoidTy;
952    break;
953
954  case UnqualifiedId::IK_ConversionFunctionId:
955    // The result type of a conversion function is the type that it
956    // converts to.
957    T = GetTypeFromParser(D.getName().ConversionFunctionId);
958    break;
959  }
960
961  if (T.isNull())
962    return T;
963
964  if (T == Context.UndeducedAutoTy) {
965    int Error = -1;
966
967    switch (D.getContext()) {
968    case Declarator::KNRTypeListContext:
969      assert(0 && "K&R type lists aren't allowed in C++");
970      break;
971    case Declarator::PrototypeContext:
972      Error = 0; // Function prototype
973      break;
974    case Declarator::MemberContext:
975      switch (cast<TagDecl>(CurContext)->getTagKind()) {
976      case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
977      case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
978      case TagDecl::TK_union:  Error = 2; /* Union member */ break;
979      case TagDecl::TK_class:  Error = 3; /* Class member */ break;
980      }
981      break;
982    case Declarator::CXXCatchContext:
983      Error = 4; // Exception declaration
984      break;
985    case Declarator::TemplateParamContext:
986      Error = 5; // Template parameter
987      break;
988    case Declarator::BlockLiteralContext:
989      Error = 6;  // Block literal
990      break;
991    case Declarator::FileContext:
992    case Declarator::BlockContext:
993    case Declarator::ForContext:
994    case Declarator::ConditionContext:
995    case Declarator::TypeNameContext:
996      break;
997    }
998
999    if (Error != -1) {
1000      Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1001        << Error;
1002      T = Context.IntTy;
1003      D.setInvalidType(true);
1004    }
1005  }
1006
1007  // The name we're declaring, if any.
1008  DeclarationName Name;
1009  if (D.getIdentifier())
1010    Name = D.getIdentifier();
1011
1012  llvm::SmallVector<DelayedAttribute,4> FnAttrsFromPreviousChunk;
1013
1014  // Walk the DeclTypeInfo, building the recursive type as we go.
1015  // DeclTypeInfos are ordered from the identifier out, which is
1016  // opposite of what we want :).
1017  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1018    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
1019    switch (DeclType.Kind) {
1020    default: assert(0 && "Unknown decltype!");
1021    case DeclaratorChunk::BlockPointer:
1022      // If blocks are disabled, emit an error.
1023      if (!LangOpts.Blocks)
1024        Diag(DeclType.Loc, diag::err_blocks_disable);
1025
1026      T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
1027                                Name);
1028      break;
1029    case DeclaratorChunk::Pointer:
1030      // Verify that we're not building a pointer to pointer to function with
1031      // exception specification.
1032      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1033        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1034        D.setInvalidType(true);
1035        // Build the type anyway.
1036      }
1037      if (getLangOptions().ObjC1 && T->isObjCInterfaceType()) {
1038        const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>();
1039        T = Context.getObjCObjectPointerType(T,
1040                                         (ObjCProtocolDecl **)OIT->qual_begin(),
1041                                         OIT->getNumProtocols(),
1042                                         DeclType.Ptr.TypeQuals);
1043        break;
1044      }
1045      T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
1046      break;
1047    case DeclaratorChunk::Reference: {
1048      Qualifiers Quals;
1049      if (DeclType.Ref.HasRestrict) Quals.addRestrict();
1050
1051      // Verify that we're not building a reference to pointer to function with
1052      // exception specification.
1053      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1054        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1055        D.setInvalidType(true);
1056        // Build the type anyway.
1057      }
1058      T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals,
1059                             DeclType.Loc, Name);
1060      break;
1061    }
1062    case DeclaratorChunk::Array: {
1063      // Verify that we're not building an array of pointers to function with
1064      // exception specification.
1065      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1066        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1067        D.setInvalidType(true);
1068        // Build the type anyway.
1069      }
1070      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1071      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1072      ArrayType::ArraySizeModifier ASM;
1073      if (ATI.isStar)
1074        ASM = ArrayType::Star;
1075      else if (ATI.hasStatic)
1076        ASM = ArrayType::Static;
1077      else
1078        ASM = ArrayType::Normal;
1079      if (ASM == ArrayType::Star &&
1080          D.getContext() != Declarator::PrototypeContext) {
1081        // FIXME: This check isn't quite right: it allows star in prototypes
1082        // for function definitions, and disallows some edge cases detailed
1083        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1084        Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1085        ASM = ArrayType::Normal;
1086        D.setInvalidType(true);
1087      }
1088      T = BuildArrayType(T, ASM, ArraySize,
1089                         Qualifiers::fromCVRMask(ATI.TypeQuals),
1090                         SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1091      break;
1092    }
1093    case DeclaratorChunk::Function: {
1094      // If the function declarator has a prototype (i.e. it is not () and
1095      // does not have a K&R-style identifier list), then the arguments are part
1096      // of the type, otherwise the argument list is ().
1097      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1098
1099      // C99 6.7.5.3p1: The return type may not be a function or array type.
1100      // For conversion functions, we'll diagnose this particular error later.
1101      if ((T->isArrayType() || T->isFunctionType()) &&
1102          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
1103        Diag(DeclType.Loc, diag::err_func_returning_array_function)
1104          << T->isFunctionType() << T;
1105        T = Context.IntTy;
1106        D.setInvalidType(true);
1107      }
1108
1109      if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1110        // C++ [dcl.fct]p6:
1111        //   Types shall not be defined in return or parameter types.
1112        TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
1113        if (Tag->isDefinition())
1114          Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1115            << Context.getTypeDeclType(Tag);
1116      }
1117
1118      // Exception specs are not allowed in typedefs. Complain, but add it
1119      // anyway.
1120      if (FTI.hasExceptionSpec &&
1121          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1122        Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1123
1124      if (FTI.NumArgs == 0) {
1125        if (getLangOptions().CPlusPlus) {
1126          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
1127          // function takes no arguments.
1128          llvm::SmallVector<QualType, 4> Exceptions;
1129          Exceptions.reserve(FTI.NumExceptions);
1130          for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1131            // FIXME: Preserve type source info.
1132            QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1133            // Check that the type is valid for an exception spec, and drop it
1134            // if not.
1135            if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1136              Exceptions.push_back(ET);
1137          }
1138          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
1139                                      FTI.hasExceptionSpec,
1140                                      FTI.hasAnyExceptionSpec,
1141                                      Exceptions.size(), Exceptions.data(),
1142                                      FunctionType::ExtInfo());
1143        } else if (FTI.isVariadic) {
1144          // We allow a zero-parameter variadic function in C if the
1145          // function is marked with the "overloadable"
1146          // attribute. Scan for this attribute now.
1147          bool Overloadable = false;
1148          for (const AttributeList *Attrs = D.getAttributes();
1149               Attrs; Attrs = Attrs->getNext()) {
1150            if (Attrs->getKind() == AttributeList::AT_overloadable) {
1151              Overloadable = true;
1152              break;
1153            }
1154          }
1155
1156          if (!Overloadable)
1157            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1158          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0,
1159                                      false, false, 0, 0,
1160                                      FunctionType::ExtInfo());
1161        } else {
1162          // Simple void foo(), where the incoming T is the result type.
1163          T = Context.getFunctionNoProtoType(T);
1164        }
1165      } else if (FTI.ArgInfo[0].Param == 0) {
1166        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
1167        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1168        D.setInvalidType(true);
1169      } else {
1170        // Otherwise, we have a function with an argument list that is
1171        // potentially variadic.
1172        llvm::SmallVector<QualType, 16> ArgTys;
1173
1174        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1175          ParmVarDecl *Param =
1176            cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1177          QualType ArgTy = Param->getType();
1178          assert(!ArgTy.isNull() && "Couldn't parse type?");
1179
1180          // Adjust the parameter type.
1181          assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1182
1183          // Look for 'void'.  void is allowed only as a single argument to a
1184          // function with no other parameters (C99 6.7.5.3p10).  We record
1185          // int(void) as a FunctionProtoType with an empty argument list.
1186          if (ArgTy->isVoidType()) {
1187            // If this is something like 'float(int, void)', reject it.  'void'
1188            // is an incomplete type (C99 6.2.5p19) and function decls cannot
1189            // have arguments of incomplete type.
1190            if (FTI.NumArgs != 1 || FTI.isVariadic) {
1191              Diag(DeclType.Loc, diag::err_void_only_param);
1192              ArgTy = Context.IntTy;
1193              Param->setType(ArgTy);
1194            } else if (FTI.ArgInfo[i].Ident) {
1195              // Reject, but continue to parse 'int(void abc)'.
1196              Diag(FTI.ArgInfo[i].IdentLoc,
1197                   diag::err_param_with_void_type);
1198              ArgTy = Context.IntTy;
1199              Param->setType(ArgTy);
1200            } else {
1201              // Reject, but continue to parse 'float(const void)'.
1202              if (ArgTy.hasQualifiers())
1203                Diag(DeclType.Loc, diag::err_void_param_qualified);
1204
1205              // Do not add 'void' to the ArgTys list.
1206              break;
1207            }
1208          } else if (!FTI.hasPrototype) {
1209            if (ArgTy->isPromotableIntegerType()) {
1210              ArgTy = Context.getPromotedIntegerType(ArgTy);
1211            } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1212              if (BTy->getKind() == BuiltinType::Float)
1213                ArgTy = Context.DoubleTy;
1214            }
1215          }
1216
1217          ArgTys.push_back(ArgTy);
1218        }
1219
1220        llvm::SmallVector<QualType, 4> Exceptions;
1221        Exceptions.reserve(FTI.NumExceptions);
1222        for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1223          // FIXME: Preserve type source info.
1224          QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1225          // Check that the type is valid for an exception spec, and drop it if
1226          // not.
1227          if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1228            Exceptions.push_back(ET);
1229        }
1230
1231        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1232                                    FTI.isVariadic, FTI.TypeQuals,
1233                                    FTI.hasExceptionSpec,
1234                                    FTI.hasAnyExceptionSpec,
1235                                    Exceptions.size(), Exceptions.data(),
1236                                    FunctionType::ExtInfo());
1237      }
1238
1239      // For GCC compatibility, we allow attributes that apply only to
1240      // function types to be placed on a function's return type
1241      // instead (as long as that type doesn't happen to be function
1242      // or function-pointer itself).
1243      ProcessDelayedFnAttrs(*this, T, FnAttrsFromPreviousChunk);
1244
1245      break;
1246    }
1247    case DeclaratorChunk::MemberPointer:
1248      // Verify that we're not building a pointer to pointer to function with
1249      // exception specification.
1250      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1251        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1252        D.setInvalidType(true);
1253        // Build the type anyway.
1254      }
1255      // The scope spec must refer to a class, or be dependent.
1256      QualType ClsType;
1257      if (isDependentScopeSpecifier(DeclType.Mem.Scope())
1258            || dyn_cast_or_null<CXXRecordDecl>(
1259                                   computeDeclContext(DeclType.Mem.Scope()))) {
1260        NestedNameSpecifier *NNS
1261          = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1262        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1263        switch (NNS->getKind()) {
1264        case NestedNameSpecifier::Identifier:
1265          ClsType = Context.getTypenameType(NNSPrefix, NNS->getAsIdentifier());
1266          break;
1267
1268        case NestedNameSpecifier::Namespace:
1269        case NestedNameSpecifier::Global:
1270          llvm_unreachable("Nested-name-specifier must name a type");
1271          break;
1272
1273        case NestedNameSpecifier::TypeSpec:
1274        case NestedNameSpecifier::TypeSpecWithTemplate:
1275          ClsType = QualType(NNS->getAsType(), 0);
1276          if (NNSPrefix)
1277            ClsType = Context.getQualifiedNameType(NNSPrefix, ClsType);
1278          break;
1279        }
1280      } else {
1281        Diag(DeclType.Mem.Scope().getBeginLoc(),
1282             diag::err_illegal_decl_mempointer_in_nonclass)
1283          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1284          << DeclType.Mem.Scope().getRange();
1285        D.setInvalidType(true);
1286      }
1287
1288      if (!ClsType.isNull())
1289        T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1290                                   DeclType.Loc, D.getIdentifier());
1291      if (T.isNull()) {
1292        T = Context.IntTy;
1293        D.setInvalidType(true);
1294      }
1295      break;
1296    }
1297
1298    if (T.isNull()) {
1299      D.setInvalidType(true);
1300      T = Context.IntTy;
1301    }
1302
1303    DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
1304
1305    // See if there are any attributes on this declarator chunk.
1306    if (const AttributeList *AL = DeclType.getAttrs())
1307      ProcessTypeAttributeList(*this, T, false, AL, FnAttrsFromPreviousChunk);
1308  }
1309
1310  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1311    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
1312    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
1313
1314    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1315    // for a nonstatic member function, the function type to which a pointer
1316    // to member refers, or the top-level function type of a function typedef
1317    // declaration.
1318    if (FnTy->getTypeQuals() != 0 &&
1319        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1320        ((D.getContext() != Declarator::MemberContext &&
1321          (!D.getCXXScopeSpec().isSet() ||
1322           !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true)
1323              ->isRecord())) ||
1324         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1325      if (D.isFunctionDeclarator())
1326        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1327      else
1328        Diag(D.getIdentifierLoc(),
1329             diag::err_invalid_qualified_typedef_function_type_use);
1330
1331      // Strip the cv-quals from the type.
1332      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1333                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0,
1334                                  false, false, 0, 0, FunctionType::ExtInfo());
1335    }
1336  }
1337
1338  // Process any function attributes we might have delayed from the
1339  // declaration-specifiers.
1340  ProcessDelayedFnAttrs(*this, T, FnAttrsFromDeclSpec);
1341
1342  // If there were any type attributes applied to the decl itself, not
1343  // the type, apply them to the result type.  But don't do this for
1344  // block-literal expressions, which are parsed wierdly.
1345  if (D.getContext() != Declarator::BlockLiteralContext)
1346    if (const AttributeList *Attrs = D.getAttributes())
1347      ProcessTypeAttributeList(*this, T, false, Attrs,
1348                               FnAttrsFromPreviousChunk);
1349
1350  DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
1351
1352  if (TInfo) {
1353    if (D.isInvalidType())
1354      *TInfo = 0;
1355    else
1356      *TInfo = GetTypeSourceInfoForDeclarator(D, T);
1357  }
1358
1359  return T;
1360}
1361
1362namespace {
1363  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
1364    const DeclSpec &DS;
1365
1366  public:
1367    TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {}
1368
1369    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1370      Visit(TL.getUnqualifiedLoc());
1371    }
1372    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1373      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1374    }
1375    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1376      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1377
1378      if (DS.getProtocolQualifiers()) {
1379        assert(TL.getNumProtocols() > 0);
1380        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1381        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1382        TL.setRAngleLoc(DS.getSourceRange().getEnd());
1383        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1384          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1385      } else {
1386        assert(TL.getNumProtocols() == 0);
1387        TL.setLAngleLoc(SourceLocation());
1388        TL.setRAngleLoc(SourceLocation());
1389      }
1390    }
1391    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1392      assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1393
1394      TL.setStarLoc(SourceLocation());
1395
1396      if (DS.getProtocolQualifiers()) {
1397        assert(TL.getNumProtocols() > 0);
1398        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1399        TL.setHasProtocolsAsWritten(true);
1400        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1401        TL.setRAngleLoc(DS.getSourceRange().getEnd());
1402        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1403          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1404
1405      } else {
1406        assert(TL.getNumProtocols() == 0);
1407        TL.setHasProtocolsAsWritten(false);
1408        TL.setLAngleLoc(SourceLocation());
1409        TL.setRAngleLoc(SourceLocation());
1410      }
1411
1412      // This might not have been written with an inner type.
1413      if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1414        TL.setHasBaseTypeAsWritten(false);
1415        TL.getBaseTypeLoc().initialize(SourceLocation());
1416      } else {
1417        TL.setHasBaseTypeAsWritten(true);
1418        Visit(TL.getBaseTypeLoc());
1419      }
1420    }
1421    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
1422      TypeSourceInfo *TInfo = 0;
1423      Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1424
1425      // If we got no declarator info from previous Sema routines,
1426      // just fill with the typespec loc.
1427      if (!TInfo) {
1428        TL.initialize(DS.getTypeSpecTypeLoc());
1429        return;
1430      }
1431
1432      TemplateSpecializationTypeLoc OldTL =
1433        cast<TemplateSpecializationTypeLoc>(TInfo->getTypeLoc());
1434      TL.copy(OldTL);
1435    }
1436    void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1437      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
1438      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1439      TL.setParensRange(DS.getTypeofParensRange());
1440    }
1441    void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1442      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
1443      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1444      TL.setParensRange(DS.getTypeofParensRange());
1445      assert(DS.getTypeRep());
1446      TypeSourceInfo *TInfo = 0;
1447      Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1448      TL.setUnderlyingTInfo(TInfo);
1449    }
1450    void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1451      // By default, use the source location of the type specifier.
1452      TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
1453      if (TL.needsExtraLocalData()) {
1454        // Set info for the written builtin specifiers.
1455        TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
1456        // Try to have a meaningful source location.
1457        if (TL.getWrittenSignSpec() != TSS_unspecified)
1458          // Sign spec loc overrides the others (e.g., 'unsigned long').
1459          TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
1460        else if (TL.getWrittenWidthSpec() != TSW_unspecified)
1461          // Width spec loc overrides type spec loc (e.g., 'short int').
1462          TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
1463      }
1464    }
1465    void VisitTypeLoc(TypeLoc TL) {
1466      // FIXME: add other typespec types and change this to an assert.
1467      TL.initialize(DS.getTypeSpecTypeLoc());
1468    }
1469  };
1470
1471  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
1472    const DeclaratorChunk &Chunk;
1473
1474  public:
1475    DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
1476
1477    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1478      llvm_unreachable("qualified type locs not expected here!");
1479    }
1480
1481    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1482      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
1483      TL.setCaretLoc(Chunk.Loc);
1484    }
1485    void VisitPointerTypeLoc(PointerTypeLoc TL) {
1486      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1487      TL.setStarLoc(Chunk.Loc);
1488    }
1489    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1490      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1491      TL.setStarLoc(Chunk.Loc);
1492      TL.setHasBaseTypeAsWritten(true);
1493      TL.setHasProtocolsAsWritten(false);
1494      TL.setLAngleLoc(SourceLocation());
1495      TL.setRAngleLoc(SourceLocation());
1496    }
1497    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1498      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
1499      TL.setStarLoc(Chunk.Loc);
1500      // FIXME: nested name specifier
1501    }
1502    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1503      assert(Chunk.Kind == DeclaratorChunk::Reference);
1504      // 'Amp' is misleading: this might have been originally
1505      /// spelled with AmpAmp.
1506      TL.setAmpLoc(Chunk.Loc);
1507    }
1508    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1509      assert(Chunk.Kind == DeclaratorChunk::Reference);
1510      assert(!Chunk.Ref.LValueRef);
1511      TL.setAmpAmpLoc(Chunk.Loc);
1512    }
1513    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
1514      assert(Chunk.Kind == DeclaratorChunk::Array);
1515      TL.setLBracketLoc(Chunk.Loc);
1516      TL.setRBracketLoc(Chunk.EndLoc);
1517      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
1518    }
1519    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
1520      assert(Chunk.Kind == DeclaratorChunk::Function);
1521      TL.setLParenLoc(Chunk.Loc);
1522      TL.setRParenLoc(Chunk.EndLoc);
1523
1524      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
1525      for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
1526        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1527        TL.setArg(tpi++, Param);
1528      }
1529      // FIXME: exception specs
1530    }
1531
1532    void VisitTypeLoc(TypeLoc TL) {
1533      llvm_unreachable("unsupported TypeLoc kind in declarator!");
1534    }
1535  };
1536}
1537
1538/// \brief Create and instantiate a TypeSourceInfo with type source information.
1539///
1540/// \param T QualType referring to the type as written in source code.
1541TypeSourceInfo *
1542Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T) {
1543  TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
1544  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
1545
1546  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1547    DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
1548    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
1549  }
1550
1551  TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL);
1552
1553  return TInfo;
1554}
1555
1556/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
1557QualType Sema::CreateLocInfoType(QualType T, TypeSourceInfo *TInfo) {
1558  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1559  // and Sema during declaration parsing. Try deallocating/caching them when
1560  // it's appropriate, instead of allocating them and keeping them around.
1561  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1562  new (LocT) LocInfoType(T, TInfo);
1563  assert(LocT->getTypeClass() != T->getTypeClass() &&
1564         "LocInfoType's TypeClass conflicts with an existing Type class");
1565  return QualType(LocT, 0);
1566}
1567
1568void LocInfoType::getAsStringInternal(std::string &Str,
1569                                      const PrintingPolicy &Policy) const {
1570  assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1571         " was used directly instead of getting the QualType through"
1572         " GetTypeFromParser");
1573}
1574
1575/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
1576/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1577/// they point to and return true. If T1 and T2 aren't pointer types
1578/// or pointer-to-member types, or if they are not similar at this
1579/// level, returns false and leaves T1 and T2 unchanged. Top-level
1580/// qualifiers on T1 and T2 are ignored. This function will typically
1581/// be called in a loop that successively "unwraps" pointer and
1582/// pointer-to-member types to compare them at each level.
1583bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1584  const PointerType *T1PtrType = T1->getAs<PointerType>(),
1585                    *T2PtrType = T2->getAs<PointerType>();
1586  if (T1PtrType && T2PtrType) {
1587    T1 = T1PtrType->getPointeeType();
1588    T2 = T2PtrType->getPointeeType();
1589    return true;
1590  }
1591
1592  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1593                          *T2MPType = T2->getAs<MemberPointerType>();
1594  if (T1MPType && T2MPType &&
1595      Context.getCanonicalType(T1MPType->getClass()) ==
1596      Context.getCanonicalType(T2MPType->getClass())) {
1597    T1 = T1MPType->getPointeeType();
1598    T2 = T2MPType->getPointeeType();
1599    return true;
1600  }
1601  return false;
1602}
1603
1604Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1605  // C99 6.7.6: Type names have no identifier.  This is already validated by
1606  // the parser.
1607  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1608
1609  TypeSourceInfo *TInfo = 0;
1610  TagDecl *OwnedTag = 0;
1611  QualType T = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
1612  if (D.isInvalidType())
1613    return true;
1614
1615  if (getLangOptions().CPlusPlus) {
1616    // Check that there are no default arguments (C++ only).
1617    CheckExtraCXXDefaultArguments(D);
1618
1619    // C++0x [dcl.type]p3:
1620    //   A type-specifier-seq shall not define a class or enumeration
1621    //   unless it appears in the type-id of an alias-declaration
1622    //   (7.1.3).
1623    if (OwnedTag && OwnedTag->isDefinition())
1624      Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1625        << Context.getTypeDeclType(OwnedTag);
1626  }
1627
1628  if (TInfo)
1629    T = CreateLocInfoType(T, TInfo);
1630
1631  return T.getAsOpaquePtr();
1632}
1633
1634
1635
1636//===----------------------------------------------------------------------===//
1637// Type Attribute Processing
1638//===----------------------------------------------------------------------===//
1639
1640/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1641/// specified type.  The attribute contains 1 argument, the id of the address
1642/// space for the type.
1643static void HandleAddressSpaceTypeAttribute(QualType &Type,
1644                                            const AttributeList &Attr, Sema &S){
1645
1646  // If this type is already address space qualified, reject it.
1647  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1648  // for two or more different address spaces."
1649  if (Type.getAddressSpace()) {
1650    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1651    return;
1652  }
1653
1654  // Check the attribute arguments.
1655  if (Attr.getNumArgs() != 1) {
1656    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1657    return;
1658  }
1659  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1660  llvm::APSInt addrSpace(32);
1661  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1662    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1663      << ASArgExpr->getSourceRange();
1664    return;
1665  }
1666
1667  // Bounds checking.
1668  if (addrSpace.isSigned()) {
1669    if (addrSpace.isNegative()) {
1670      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1671        << ASArgExpr->getSourceRange();
1672      return;
1673    }
1674    addrSpace.setIsSigned(false);
1675  }
1676  llvm::APSInt max(addrSpace.getBitWidth());
1677  max = Qualifiers::MaxAddressSpace;
1678  if (addrSpace > max) {
1679    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1680      << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1681    return;
1682  }
1683
1684  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1685  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1686}
1687
1688/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1689/// specified type.  The attribute contains 1 argument, weak or strong.
1690static void HandleObjCGCTypeAttribute(QualType &Type,
1691                                      const AttributeList &Attr, Sema &S) {
1692  if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1693    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1694    return;
1695  }
1696
1697  // Check the attribute arguments.
1698  if (!Attr.getParameterName()) {
1699    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1700      << "objc_gc" << 1;
1701    return;
1702  }
1703  Qualifiers::GC GCAttr;
1704  if (Attr.getNumArgs() != 0) {
1705    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1706    return;
1707  }
1708  if (Attr.getParameterName()->isStr("weak"))
1709    GCAttr = Qualifiers::Weak;
1710  else if (Attr.getParameterName()->isStr("strong"))
1711    GCAttr = Qualifiers::Strong;
1712  else {
1713    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1714      << "objc_gc" << Attr.getParameterName();
1715    return;
1716  }
1717
1718  Type = S.Context.getObjCGCQualType(Type, GCAttr);
1719}
1720
1721/// Process an individual function attribute.  Returns true if the
1722/// attribute does not make sense to apply to this type.
1723bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr) {
1724  if (Attr.getKind() == AttributeList::AT_noreturn) {
1725    // Complain immediately if the arg count is wrong.
1726    if (Attr.getNumArgs() != 0) {
1727      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1728      return false;
1729    }
1730
1731    // Delay if this is not a function or pointer to block.
1732    if (!Type->isFunctionPointerType()
1733        && !Type->isBlockPointerType()
1734        && !Type->isFunctionType())
1735      return true;
1736
1737    // Otherwise we can process right away.
1738    Type = S.Context.getNoReturnType(Type);
1739    return false;
1740  }
1741
1742  // Otherwise, a calling convention.
1743  if (Attr.getNumArgs() != 0) {
1744    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1745    return false;
1746  }
1747
1748  QualType T = Type;
1749  if (const PointerType *PT = Type->getAs<PointerType>())
1750    T = PT->getPointeeType();
1751  const FunctionType *Fn = T->getAs<FunctionType>();
1752
1753  // Delay if the type didn't work out to a function.
1754  if (!Fn) return true;
1755
1756  // TODO: diagnose uses of these conventions on the wrong target.
1757  CallingConv CC;
1758  switch (Attr.getKind()) {
1759  case AttributeList::AT_cdecl: CC = CC_C; break;
1760  case AttributeList::AT_fastcall: CC = CC_X86FastCall; break;
1761  case AttributeList::AT_stdcall: CC = CC_X86StdCall; break;
1762  default: llvm_unreachable("unexpected attribute kind"); return false;
1763  }
1764
1765  CallingConv CCOld = Fn->getCallConv();
1766  if (S.Context.getCanonicalCallConv(CC) ==
1767      S.Context.getCanonicalCallConv(CCOld)) return false;
1768
1769  if (CCOld != CC_Default) {
1770    // Should we diagnose reapplications of the same convention?
1771    S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1772      << FunctionType::getNameForCallConv(CC)
1773      << FunctionType::getNameForCallConv(CCOld);
1774    return false;
1775  }
1776
1777  // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
1778  if (CC == CC_X86FastCall) {
1779    if (isa<FunctionNoProtoType>(Fn)) {
1780      S.Diag(Attr.getLoc(), diag::err_cconv_knr)
1781        << FunctionType::getNameForCallConv(CC);
1782      return false;
1783    }
1784
1785    const FunctionProtoType *FnP = cast<FunctionProtoType>(Fn);
1786    if (FnP->isVariadic()) {
1787      S.Diag(Attr.getLoc(), diag::err_cconv_varargs)
1788        << FunctionType::getNameForCallConv(CC);
1789      return false;
1790    }
1791  }
1792
1793  Type = S.Context.getCallConvType(Type, CC);
1794  return false;
1795}
1796
1797/// HandleVectorSizeAttribute - this attribute is only applicable to integral
1798/// and float scalars, although arrays, pointers, and function return values are
1799/// allowed in conjunction with this construct. Aggregates with this attribute
1800/// are invalid, even if they are of the same size as a corresponding scalar.
1801/// The raw attribute should contain precisely 1 argument, the vector size for
1802/// the variable, measured in bytes. If curType and rawAttr are well formed,
1803/// this routine will return a new vector type.
1804static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, Sema &S) {
1805  // Check the attribute arugments.
1806  if (Attr.getNumArgs() != 1) {
1807    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1808    return;
1809  }
1810  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
1811  llvm::APSInt vecSize(32);
1812  if (!sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
1813    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1814      << "vector_size" << sizeExpr->getSourceRange();
1815    return;
1816  }
1817  // the base type must be integer or float, and can't already be a vector.
1818  if (CurType->isVectorType() ||
1819      (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
1820    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
1821    return;
1822  }
1823  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
1824  // vecSize is specified in bytes - convert to bits.
1825  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
1826
1827  // the vector size needs to be an integral multiple of the type size.
1828  if (vectorSize % typeSize) {
1829    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
1830      << sizeExpr->getSourceRange();
1831    return;
1832  }
1833  if (vectorSize == 0) {
1834    S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
1835      << sizeExpr->getSourceRange();
1836    return;
1837  }
1838
1839  // Success! Instantiate the vector type, the number of elements is > 0, and
1840  // not required to be a power of 2, unlike GCC.
1841  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, false, false);
1842}
1843
1844void ProcessTypeAttributeList(Sema &S, QualType &Result,
1845                              bool IsDeclSpec, const AttributeList *AL,
1846                              DelayedAttributeSet &FnAttrs) {
1847  // Scan through and apply attributes to this type where it makes sense.  Some
1848  // attributes (such as __address_space__, __vector_size__, etc) apply to the
1849  // type, but others can be present in the type specifiers even though they
1850  // apply to the decl.  Here we apply type attributes and ignore the rest.
1851  for (; AL; AL = AL->getNext()) {
1852    // If this is an attribute we can handle, do so now, otherwise, add it to
1853    // the LeftOverAttrs list for rechaining.
1854    switch (AL->getKind()) {
1855    default: break;
1856
1857    case AttributeList::AT_address_space:
1858      HandleAddressSpaceTypeAttribute(Result, *AL, S);
1859      break;
1860    case AttributeList::AT_objc_gc:
1861      HandleObjCGCTypeAttribute(Result, *AL, S);
1862      break;
1863    case AttributeList::AT_vector_size:
1864      HandleVectorSizeAttr(Result, *AL, S);
1865      break;
1866
1867    case AttributeList::AT_noreturn:
1868    case AttributeList::AT_cdecl:
1869    case AttributeList::AT_fastcall:
1870    case AttributeList::AT_stdcall:
1871      // Don't process these on the DeclSpec.
1872      if (IsDeclSpec ||
1873          ProcessFnAttr(S, Result, *AL))
1874        FnAttrs.push_back(DelayedAttribute(AL, Result));
1875      break;
1876    }
1877  }
1878}
1879
1880/// @brief Ensure that the type T is a complete type.
1881///
1882/// This routine checks whether the type @p T is complete in any
1883/// context where a complete type is required. If @p T is a complete
1884/// type, returns false. If @p T is a class template specialization,
1885/// this routine then attempts to perform class template
1886/// instantiation. If instantiation fails, or if @p T is incomplete
1887/// and cannot be completed, issues the diagnostic @p diag (giving it
1888/// the type @p T) and returns true.
1889///
1890/// @param Loc  The location in the source that the incomplete type
1891/// diagnostic should refer to.
1892///
1893/// @param T  The type that this routine is examining for completeness.
1894///
1895/// @param PD The partial diagnostic that will be printed out if T is not a
1896/// complete type.
1897///
1898/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1899/// @c false otherwise.
1900bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
1901                               const PartialDiagnostic &PD,
1902                               std::pair<SourceLocation,
1903                                         PartialDiagnostic> Note) {
1904  unsigned diag = PD.getDiagID();
1905
1906  // FIXME: Add this assertion to make sure we always get instantiation points.
1907  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
1908  // FIXME: Add this assertion to help us flush out problems with
1909  // checking for dependent types and type-dependent expressions.
1910  //
1911  //  assert(!T->isDependentType() &&
1912  //         "Can't ask whether a dependent type is complete");
1913
1914  // If we have a complete type, we're done.
1915  if (!T->isIncompleteType())
1916    return false;
1917
1918  // If we have a class template specialization or a class member of a
1919  // class template specialization, or an array with known size of such,
1920  // try to instantiate it.
1921  QualType MaybeTemplate = T;
1922  if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
1923    MaybeTemplate = Array->getElementType();
1924  if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
1925    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1926          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1927      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
1928        return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
1929                                                      TSK_ImplicitInstantiation,
1930                                                      /*Complain=*/diag != 0);
1931    } else if (CXXRecordDecl *Rec
1932                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1933      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1934        MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
1935        assert(MSInfo && "Missing member specialization information?");
1936        // This record was instantiated from a class within a template.
1937        if (MSInfo->getTemplateSpecializationKind()
1938                                               != TSK_ExplicitSpecialization)
1939          return InstantiateClass(Loc, Rec, Pattern,
1940                                  getTemplateInstantiationArgs(Rec),
1941                                  TSK_ImplicitInstantiation,
1942                                  /*Complain=*/diag != 0);
1943      }
1944    }
1945  }
1946
1947  if (diag == 0)
1948    return true;
1949
1950  const TagType *Tag = 0;
1951  if (const RecordType *Record = T->getAs<RecordType>())
1952    Tag = Record;
1953  else if (const EnumType *Enum = T->getAs<EnumType>())
1954    Tag = Enum;
1955
1956  // Avoid diagnosing invalid decls as incomplete.
1957  if (Tag && Tag->getDecl()->isInvalidDecl())
1958    return true;
1959
1960  // We have an incomplete type. Produce a diagnostic.
1961  Diag(Loc, PD) << T;
1962
1963  // If we have a note, produce it.
1964  if (!Note.first.isInvalid())
1965    Diag(Note.first, Note.second);
1966
1967  // If the type was a forward declaration of a class/struct/union
1968  // type, produce a note.
1969  if (Tag && !Tag->getDecl()->isInvalidDecl())
1970    Diag(Tag->getDecl()->getLocation(),
1971         Tag->isBeingDefined() ? diag::note_type_being_defined
1972                               : diag::note_forward_declaration)
1973        << QualType(Tag, 0);
1974
1975  return true;
1976}
1977
1978bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
1979                               const PartialDiagnostic &PD) {
1980  return RequireCompleteType(Loc, T, PD,
1981                             std::make_pair(SourceLocation(), PDiag(0)));
1982}
1983
1984bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
1985                               unsigned DiagID) {
1986  return RequireCompleteType(Loc, T, PDiag(DiagID),
1987                             std::make_pair(SourceLocation(), PDiag(0)));
1988}
1989
1990/// \brief Retrieve a version of the type 'T' that is qualified by the
1991/// nested-name-specifier contained in SS.
1992QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1993  if (!SS.isSet() || SS.isInvalid() || T.isNull())
1994    return T;
1995
1996  NestedNameSpecifier *NNS
1997    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1998  return Context.getQualifiedNameType(NNS, T);
1999}
2000
2001QualType Sema::BuildTypeofExprType(Expr *E) {
2002  if (E->getType() == Context.OverloadTy) {
2003    // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2004    // function template specialization wherever deduction cannot occur.
2005    if (FunctionDecl *Specialization
2006        = ResolveSingleFunctionTemplateSpecialization(E)) {
2007      E = FixOverloadedFunctionReference(E, Specialization);
2008      if (!E)
2009        return QualType();
2010    } else {
2011      Diag(E->getLocStart(),
2012           diag::err_cannot_determine_declared_type_of_overloaded_function)
2013        << false << E->getSourceRange();
2014      return QualType();
2015    }
2016  }
2017
2018  return Context.getTypeOfExprType(E);
2019}
2020
2021QualType Sema::BuildDecltypeType(Expr *E) {
2022  if (E->getType() == Context.OverloadTy) {
2023    // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2024    // function template specialization wherever deduction cannot occur.
2025    if (FunctionDecl *Specialization
2026          = ResolveSingleFunctionTemplateSpecialization(E)) {
2027      E = FixOverloadedFunctionReference(E, Specialization);
2028      if (!E)
2029        return QualType();
2030    } else {
2031      Diag(E->getLocStart(),
2032           diag::err_cannot_determine_declared_type_of_overloaded_function)
2033        << true << E->getSourceRange();
2034      return QualType();
2035    }
2036  }
2037
2038  return Context.getDecltypeType(E);
2039}
2040