SemaType.cpp revision efadb7768e7c7418185f5a4010ecd8b21ca9731b
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 "SemaInherit.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/Parse/DeclSpec.h"
21#include "llvm/ADT/SmallPtrSet.h"
22using namespace clang;
23
24/// \brief Perform adjustment on the parameter type of a function.
25///
26/// This routine adjusts the given parameter type @p T to the actual
27/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
28/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
29QualType Sema::adjustParameterType(QualType T) {
30  // C99 6.7.5.3p7:
31  if (T->isArrayType()) {
32    // C99 6.7.5.3p7:
33    //   A declaration of a parameter as "array of type" shall be
34    //   adjusted to "qualified pointer to type", where the type
35    //   qualifiers (if any) are those specified within the [ and ] of
36    //   the array type derivation.
37    return Context.getArrayDecayedType(T);
38  } else if (T->isFunctionType())
39    // C99 6.7.5.3p8:
40    //   A declaration of a parameter as "function returning type"
41    //   shall be adjusted to "pointer to function returning type", as
42    //   in 6.3.2.1.
43    return Context.getPointerType(T);
44
45  return T;
46}
47
48/// \brief Convert the specified declspec to the appropriate type
49/// object.
50/// \param DS  the declaration specifiers
51/// \param DeclLoc The location of the declarator identifier or invalid if none.
52/// \returns The type described by the declaration specifiers.  This function
53/// never returns null.
54QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS,
55                                     SourceLocation DeclLoc,
56                                     bool &isInvalid) {
57  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
58  // checking.
59  QualType Result;
60
61  switch (DS.getTypeSpecType()) {
62  case DeclSpec::TST_void:
63    Result = Context.VoidTy;
64    break;
65  case DeclSpec::TST_char:
66    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
67      Result = Context.CharTy;
68    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
69      Result = Context.SignedCharTy;
70    else {
71      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
72             "Unknown TSS value");
73      Result = Context.UnsignedCharTy;
74    }
75    break;
76  case DeclSpec::TST_wchar:
77    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
78      Result = Context.WCharTy;
79    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
80      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
81        << DS.getSpecifierName(DS.getTypeSpecType());
82      Result = Context.getSignedWCharType();
83    } else {
84      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
85        "Unknown TSS value");
86      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
87        << DS.getSpecifierName(DS.getTypeSpecType());
88      Result = Context.getUnsignedWCharType();
89    }
90    break;
91  case DeclSpec::TST_char16:
92      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
93        "Unknown TSS value");
94      Result = Context.Char16Ty;
95    break;
96  case DeclSpec::TST_char32:
97      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
98        "Unknown TSS value");
99      Result = Context.Char32Ty;
100    break;
101  case DeclSpec::TST_unspecified:
102    // "<proto1,proto2>" is an objc qualified ID with a missing id.
103    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
104      Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
105                                                (ObjCProtocolDecl**)PQ,
106                                                DS.getNumProtocolQualifiers());
107      break;
108    }
109
110    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
111    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
112    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
113    // Note that the one exception to this is function definitions, which are
114    // allowed to be completely missing a declspec.  This is handled in the
115    // parser already though by it pretending to have seen an 'int' in this
116    // case.
117    if (getLangOptions().ImplicitInt) {
118      // In C89 mode, we only warn if there is a completely missing declspec
119      // when one is not allowed.
120      if (DS.isEmpty()) {
121        if (DeclLoc.isInvalid())
122          DeclLoc = DS.getSourceRange().getBegin();
123        Diag(DeclLoc, diag::ext_missing_declspec)
124          << DS.getSourceRange()
125        << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
126                                                 "int");
127      }
128    } else if (!DS.hasTypeSpecifier()) {
129      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
130      // "At least one type specifier shall be given in the declaration
131      // specifiers in each declaration, and in the specifier-qualifier list in
132      // each struct declaration and type name."
133      // FIXME: Does Microsoft really have the implicit int extension in C++?
134      if (DeclLoc.isInvalid())
135        DeclLoc = DS.getSourceRange().getBegin();
136
137      if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft) {
138        Diag(DeclLoc, diag::err_missing_type_specifier)
139          << DS.getSourceRange();
140
141        // When this occurs in C++ code, often something is very broken with the
142        // value being declared, poison it as invalid so we don't get chains of
143        // errors.
144        isInvalid = true;
145      } else {
146        Diag(DeclLoc, diag::ext_missing_type_specifier)
147          << DS.getSourceRange();
148      }
149    }
150
151    // FALL THROUGH.
152  case DeclSpec::TST_int: {
153    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
154      switch (DS.getTypeSpecWidth()) {
155      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
156      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
157      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
158      case DeclSpec::TSW_longlong:    Result = Context.LongLongTy; break;
159      }
160    } else {
161      switch (DS.getTypeSpecWidth()) {
162      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
163      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
164      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
165      case DeclSpec::TSW_longlong:    Result =Context.UnsignedLongLongTy; break;
166      }
167    }
168    break;
169  }
170  case DeclSpec::TST_float: Result = Context.FloatTy; break;
171  case DeclSpec::TST_double:
172    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
173      Result = Context.LongDoubleTy;
174    else
175      Result = Context.DoubleTy;
176    break;
177  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
178  case DeclSpec::TST_decimal32:    // _Decimal32
179  case DeclSpec::TST_decimal64:    // _Decimal64
180  case DeclSpec::TST_decimal128:   // _Decimal128
181    Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
182    Result = Context.IntTy;
183    isInvalid = true;
184    break;
185  case DeclSpec::TST_class:
186  case DeclSpec::TST_enum:
187  case DeclSpec::TST_union:
188  case DeclSpec::TST_struct: {
189    Decl *D = static_cast<Decl *>(DS.getTypeRep());
190    assert(D && "Didn't get a decl for a class/enum/union/struct?");
191    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
192           DS.getTypeSpecSign() == 0 &&
193           "Can't handle qualifiers on typedef names yet!");
194    // TypeQuals handled by caller.
195    Result = Context.getTypeDeclType(cast<TypeDecl>(D));
196
197    if (D->isInvalidDecl())
198      isInvalid = true;
199    break;
200  }
201  case DeclSpec::TST_typename: {
202    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
203           DS.getTypeSpecSign() == 0 &&
204           "Can't handle qualifiers on typedef names yet!");
205    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
206
207    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
208      if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType())
209        // It would be nice if protocol qualifiers were only stored with the
210        // ObjCObjectPointerType. Unfortunately, this isn't possible due
211        // to the following typedef idiom (which is uncommon, but allowed):
212        //
213        // typedef Foo<P> T;
214        // static void func() {
215        //   Foo<P> *yy;
216        //   T *zz;
217        // }
218        Result = Context.getObjCInterfaceType(Interface->getDecl(),
219                                              (ObjCProtocolDecl**)PQ,
220                                              DS.getNumProtocolQualifiers());
221      else if (Result->isObjCIdType())
222        // id<protocol-list>
223        Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
224                        (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
225      else if (Result->isObjCClassType()) {
226        if (DeclLoc.isInvalid())
227          DeclLoc = DS.getSourceRange().getBegin();
228        // Class<protocol-list>
229        Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy,
230                        (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
231      } else {
232        if (DeclLoc.isInvalid())
233          DeclLoc = DS.getSourceRange().getBegin();
234        Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
235          << DS.getSourceRange();
236        isInvalid = true;
237      }
238    }
239
240    // If this is a reference to an invalid typedef, propagate the invalidity.
241    if (TypedefType *TDT = dyn_cast<TypedefType>(Result))
242      if (TDT->getDecl()->isInvalidDecl())
243        isInvalid = true;
244
245    // TypeQuals handled by caller.
246    break;
247  }
248  case DeclSpec::TST_typeofType:
249    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
250    assert(!Result.isNull() && "Didn't get a type for typeof?");
251    // TypeQuals handled by caller.
252    Result = Context.getTypeOfType(Result);
253    break;
254  case DeclSpec::TST_typeofExpr: {
255    Expr *E = static_cast<Expr *>(DS.getTypeRep());
256    assert(E && "Didn't get an expression for typeof?");
257    // TypeQuals handled by caller.
258    Result = Context.getTypeOfExprType(E);
259    break;
260  }
261  case DeclSpec::TST_decltype: {
262    Expr *E = static_cast<Expr *>(DS.getTypeRep());
263    assert(E && "Didn't get an expression for decltype?");
264    // TypeQuals handled by caller.
265    Result = BuildDecltypeType(E);
266    if (Result.isNull()) {
267      Result = Context.IntTy;
268      isInvalid = true;
269    }
270    break;
271  }
272  case DeclSpec::TST_auto: {
273    // TypeQuals handled by caller.
274    Result = Context.UndeducedAutoTy;
275    break;
276  }
277
278  case DeclSpec::TST_error:
279    Result = Context.IntTy;
280    isInvalid = true;
281    break;
282  }
283
284  // Handle complex types.
285  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
286    if (getLangOptions().Freestanding)
287      Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
288    Result = Context.getComplexType(Result);
289  }
290
291  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
292         "FIXME: imaginary types not supported yet!");
293
294  // See if there are any attributes on the declspec that apply to the type (as
295  // opposed to the decl).
296  if (const AttributeList *AL = DS.getAttributes())
297    ProcessTypeAttributeList(Result, AL);
298
299  // Apply const/volatile/restrict qualifiers to T.
300  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
301
302    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
303    // or incomplete types shall not be restrict-qualified."  C++ also allows
304    // restrict-qualified references.
305    if (TypeQuals & QualType::Restrict) {
306      if (Result->isPointerType() || Result->isReferenceType()) {
307        QualType EltTy = Result->isPointerType() ?
308          Result->getAsPointerType()->getPointeeType() :
309          Result->getAsReferenceType()->getPointeeType();
310
311        // If we have a pointer or reference, the pointee must have an object
312        // incomplete type.
313        if (!EltTy->isIncompleteOrObjectType()) {
314          Diag(DS.getRestrictSpecLoc(),
315               diag::err_typecheck_invalid_restrict_invalid_pointee)
316            << EltTy << DS.getSourceRange();
317          TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
318        }
319      } else {
320        Diag(DS.getRestrictSpecLoc(),
321             diag::err_typecheck_invalid_restrict_not_pointer)
322          << Result << DS.getSourceRange();
323        TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
324      }
325    }
326
327    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
328    // of a function type includes any type qualifiers, the behavior is
329    // undefined."
330    if (Result->isFunctionType() && TypeQuals) {
331      // Get some location to point at, either the C or V location.
332      SourceLocation Loc;
333      if (TypeQuals & QualType::Const)
334        Loc = DS.getConstSpecLoc();
335      else {
336        assert((TypeQuals & QualType::Volatile) &&
337               "Has CV quals but not C or V?");
338        Loc = DS.getVolatileSpecLoc();
339      }
340      Diag(Loc, diag::warn_typecheck_function_qualifiers)
341        << Result << DS.getSourceRange();
342    }
343
344    // C++ [dcl.ref]p1:
345    //   Cv-qualified references are ill-formed except when the
346    //   cv-qualifiers are introduced through the use of a typedef
347    //   (7.1.3) or of a template type argument (14.3), in which
348    //   case the cv-qualifiers are ignored.
349    // FIXME: Shouldn't we be checking SCS_typedef here?
350    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
351        TypeQuals && Result->isReferenceType()) {
352      TypeQuals &= ~QualType::Const;
353      TypeQuals &= ~QualType::Volatile;
354    }
355
356    Result = Result.getQualifiedType(TypeQuals);
357  }
358  return Result;
359}
360
361static std::string getPrintableNameForEntity(DeclarationName Entity) {
362  if (Entity)
363    return Entity.getAsString();
364
365  return "type name";
366}
367
368/// \brief Build a pointer type.
369///
370/// \param T The type to which we'll be building a pointer.
371///
372/// \param Quals The cvr-qualifiers to be applied to the pointer type.
373///
374/// \param Loc The location of the entity whose type involves this
375/// pointer type or, if there is no such entity, the location of the
376/// type that will have pointer type.
377///
378/// \param Entity The name of the entity that involves the pointer
379/// type, if known.
380///
381/// \returns A suitable pointer type, if there are no
382/// errors. Otherwise, returns a NULL type.
383QualType Sema::BuildPointerType(QualType T, unsigned Quals,
384                                SourceLocation Loc, DeclarationName Entity) {
385  if (T->isReferenceType()) {
386    // C++ 8.3.2p4: There shall be no ... pointers to references ...
387    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
388      << getPrintableNameForEntity(Entity);
389    return QualType();
390  }
391
392  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
393  // object or incomplete types shall not be restrict-qualified."
394  if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
395    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
396      << T;
397    Quals &= ~QualType::Restrict;
398  }
399
400  // Build the pointer type.
401  return Context.getPointerType(T).getQualifiedType(Quals);
402}
403
404/// \brief Build a reference type.
405///
406/// \param T The type to which we'll be building a reference.
407///
408/// \param Quals The cvr-qualifiers to be applied to the reference type.
409///
410/// \param Loc The location of the entity whose type involves this
411/// reference type or, if there is no such entity, the location of the
412/// type that will have reference type.
413///
414/// \param Entity The name of the entity that involves the reference
415/// type, if known.
416///
417/// \returns A suitable reference type, if there are no
418/// errors. Otherwise, returns a NULL type.
419QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals,
420                                  SourceLocation Loc, DeclarationName Entity) {
421  if (LValueRef) {
422    if (const RValueReferenceType *R = T->getAsRValueReferenceType()) {
423      // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
424      //   reference to a type T, and attempt to create the type "lvalue
425      //   reference to cv TD" creates the type "lvalue reference to T".
426      // We use the qualifiers (restrict or none) of the original reference,
427      // not the new ones. This is consistent with GCC.
428      return Context.getLValueReferenceType(R->getPointeeType()).
429               getQualifiedType(T.getCVRQualifiers());
430    }
431  }
432  if (T->isReferenceType()) {
433    // C++ [dcl.ref]p4: There shall be no references to references.
434    //
435    // According to C++ DR 106, references to references are only
436    // diagnosed when they are written directly (e.g., "int & &"),
437    // but not when they happen via a typedef:
438    //
439    //   typedef int& intref;
440    //   typedef intref& intref2;
441    //
442    // Parser::ParserDeclaratorInternal diagnoses the case where
443    // references are written directly; here, we handle the
444    // collapsing of references-to-references as described in C++
445    // DR 106 and amended by C++ DR 540.
446    return T;
447  }
448
449  // C++ [dcl.ref]p1:
450  //   A declarator that specifies the type “reference to cv void”
451  //   is ill-formed.
452  if (T->isVoidType()) {
453    Diag(Loc, diag::err_reference_to_void);
454    return QualType();
455  }
456
457  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
458  // object or incomplete types shall not be restrict-qualified."
459  if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
460    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
461      << T;
462    Quals &= ~QualType::Restrict;
463  }
464
465  // C++ [dcl.ref]p1:
466  //   [...] Cv-qualified references are ill-formed except when the
467  //   cv-qualifiers are introduced through the use of a typedef
468  //   (7.1.3) or of a template type argument (14.3), in which case
469  //   the cv-qualifiers are ignored.
470  //
471  // We diagnose extraneous cv-qualifiers for the non-typedef,
472  // non-template type argument case within the parser. Here, we just
473  // ignore any extraneous cv-qualifiers.
474  Quals &= ~QualType::Const;
475  Quals &= ~QualType::Volatile;
476
477  // Handle restrict on references.
478  if (LValueRef)
479    return Context.getLValueReferenceType(T).getQualifiedType(Quals);
480  return Context.getRValueReferenceType(T).getQualifiedType(Quals);
481}
482
483/// \brief Build an array type.
484///
485/// \param T The type of each element in the array.
486///
487/// \param ASM C99 array size modifier (e.g., '*', 'static').
488///
489/// \param ArraySize Expression describing the size of the array.
490///
491/// \param Quals The cvr-qualifiers to be applied to the array's
492/// element type.
493///
494/// \param Loc The location of the entity whose type involves this
495/// array type or, if there is no such entity, the location of the
496/// type that will have array type.
497///
498/// \param Entity The name of the entity that involves the array
499/// type, if known.
500///
501/// \returns A suitable array type, if there are no errors. Otherwise,
502/// returns a NULL type.
503QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
504                              Expr *ArraySize, unsigned Quals,
505                              SourceRange Brackets, DeclarationName Entity) {
506  SourceLocation Loc = Brackets.getBegin();
507  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
508  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
509  if (RequireCompleteType(Loc, T,
510                             diag::err_illegal_decl_array_incomplete_type))
511    return QualType();
512
513  if (T->isFunctionType()) {
514    Diag(Loc, diag::err_illegal_decl_array_of_functions)
515      << getPrintableNameForEntity(Entity);
516    return QualType();
517  }
518
519  // C++ 8.3.2p4: There shall be no ... arrays of references ...
520  if (T->isReferenceType()) {
521    Diag(Loc, diag::err_illegal_decl_array_of_references)
522      << getPrintableNameForEntity(Entity);
523    return QualType();
524  }
525
526  if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
527    Diag(Loc,  diag::err_illegal_decl_array_of_auto)
528      << getPrintableNameForEntity(Entity);
529    return QualType();
530  }
531
532  if (const RecordType *EltTy = T->getAsRecordType()) {
533    // If the element type is a struct or union that contains a variadic
534    // array, accept it as a GNU extension: C99 6.7.2.1p2.
535    if (EltTy->getDecl()->hasFlexibleArrayMember())
536      Diag(Loc, diag::ext_flexible_array_in_array) << T;
537  } else if (T->isObjCInterfaceType()) {
538    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
539    return QualType();
540  }
541
542  // C99 6.7.5.2p1: The size expression shall have integer type.
543  if (ArraySize && !ArraySize->isTypeDependent() &&
544      !ArraySize->getType()->isIntegerType()) {
545    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
546      << ArraySize->getType() << ArraySize->getSourceRange();
547    ArraySize->Destroy(Context);
548    return QualType();
549  }
550  llvm::APSInt ConstVal(32);
551  if (!ArraySize) {
552    if (ASM == ArrayType::Star)
553      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
554    else
555      T = Context.getIncompleteArrayType(T, ASM, Quals);
556  } else if (ArraySize->isValueDependent()) {
557    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
558  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
559             (!T->isDependentType() && !T->isConstantSizeType())) {
560    // Per C99, a variable array is an array with either a non-constant
561    // size or an element type that has a non-constant-size
562    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
563  } else {
564    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
565    // have a value greater than zero.
566    if (ConstVal.isSigned()) {
567      if (ConstVal.isNegative()) {
568        Diag(ArraySize->getLocStart(),
569             diag::err_typecheck_negative_array_size)
570          << ArraySize->getSourceRange();
571        return QualType();
572      } else if (ConstVal == 0) {
573        // GCC accepts zero sized static arrays.
574        Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
575          << ArraySize->getSourceRange();
576      }
577    }
578    T = Context.getConstantArrayWithExprType(T, ConstVal, ArraySize,
579                                             ASM, Quals, Brackets);
580  }
581  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
582  if (!getLangOptions().C99) {
583    if (ArraySize && !ArraySize->isTypeDependent() &&
584        !ArraySize->isValueDependent() &&
585        !ArraySize->isIntegerConstantExpr(Context))
586      Diag(Loc, diag::ext_vla);
587    else if (ASM != ArrayType::Normal || Quals != 0)
588      Diag(Loc, diag::ext_c99_array_usage);
589  }
590
591  return T;
592}
593
594/// \brief Build an ext-vector type.
595///
596/// Run the required checks for the extended vector type.
597QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
598                                  SourceLocation AttrLoc) {
599
600  Expr *Arg = (Expr *)ArraySize.get();
601
602  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
603  // in conjunction with complex types (pointers, arrays, functions, etc.).
604  if (!T->isDependentType() &&
605      !T->isIntegerType() && !T->isRealFloatingType()) {
606    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
607    return QualType();
608  }
609
610  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
611    llvm::APSInt vecSize(32);
612    if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
613      Diag(AttrLoc, diag::err_attribute_argument_not_int)
614      << "ext_vector_type" << Arg->getSourceRange();
615      return QualType();
616    }
617
618    // unlike gcc's vector_size attribute, the size is specified as the
619    // number of elements, not the number of bytes.
620    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
621
622    if (vectorSize == 0) {
623      Diag(AttrLoc, diag::err_attribute_zero_size)
624      << Arg->getSourceRange();
625      return QualType();
626    }
627
628    if (!T->isDependentType())
629      return Context.getExtVectorType(T, vectorSize);
630  }
631
632  return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
633                                                AttrLoc);
634}
635
636/// \brief Build a function type.
637///
638/// This routine checks the function type according to C++ rules and
639/// under the assumption that the result type and parameter types have
640/// just been instantiated from a template. It therefore duplicates
641/// some of the behavior of GetTypeForDeclarator, but in a much
642/// simpler form that is only suitable for this narrow use case.
643///
644/// \param T The return type of the function.
645///
646/// \param ParamTypes The parameter types of the function. This array
647/// will be modified to account for adjustments to the types of the
648/// function parameters.
649///
650/// \param NumParamTypes The number of parameter types in ParamTypes.
651///
652/// \param Variadic Whether this is a variadic function type.
653///
654/// \param Quals The cvr-qualifiers to be applied to the function type.
655///
656/// \param Loc The location of the entity whose type involves this
657/// function type or, if there is no such entity, the location of the
658/// type that will have function type.
659///
660/// \param Entity The name of the entity that involves the function
661/// type, if known.
662///
663/// \returns A suitable function type, if there are no
664/// errors. Otherwise, returns a NULL type.
665QualType Sema::BuildFunctionType(QualType T,
666                                 QualType *ParamTypes,
667                                 unsigned NumParamTypes,
668                                 bool Variadic, unsigned Quals,
669                                 SourceLocation Loc, DeclarationName Entity) {
670  if (T->isArrayType() || T->isFunctionType()) {
671    Diag(Loc, diag::err_func_returning_array_function) << T;
672    return QualType();
673  }
674
675  bool Invalid = false;
676  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
677    QualType ParamType = adjustParameterType(ParamTypes[Idx]);
678    if (ParamType->isVoidType()) {
679      Diag(Loc, diag::err_param_with_void_type);
680      Invalid = true;
681    }
682
683    ParamTypes[Idx] = ParamType;
684  }
685
686  if (Invalid)
687    return QualType();
688
689  return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
690                                 Quals);
691}
692
693/// \brief Build a member pointer type \c T Class::*.
694///
695/// \param T the type to which the member pointer refers.
696/// \param Class the class type into which the member pointer points.
697/// \param Quals Qualifiers applied to the member pointer type
698/// \param Loc the location where this type begins
699/// \param Entity the name of the entity that will have this member pointer type
700///
701/// \returns a member pointer type, if successful, or a NULL type if there was
702/// an error.
703QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
704                                      unsigned Quals, SourceLocation Loc,
705                                      DeclarationName Entity) {
706  // Verify that we're not building a pointer to pointer to function with
707  // exception specification.
708  if (CheckDistantExceptionSpec(T)) {
709    Diag(Loc, diag::err_distant_exception_spec);
710
711    // FIXME: If we're doing this as part of template instantiation,
712    // we should return immediately.
713
714    // Build the type anyway, but use the canonical type so that the
715    // exception specifiers are stripped off.
716    T = Context.getCanonicalType(T);
717  }
718
719  // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
720  //   with reference type, or "cv void."
721  if (T->isReferenceType()) {
722    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
723      << (Entity? Entity.getAsString() : "type name");
724    return QualType();
725  }
726
727  if (T->isVoidType()) {
728    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
729      << (Entity? Entity.getAsString() : "type name");
730    return QualType();
731  }
732
733  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
734  // object or incomplete types shall not be restrict-qualified."
735  if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
736    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
737      << T;
738
739    // FIXME: If we're doing this as part of template instantiation,
740    // we should return immediately.
741    Quals &= ~QualType::Restrict;
742  }
743
744  if (!Class->isDependentType() && !Class->isRecordType()) {
745    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
746    return QualType();
747  }
748
749  return Context.getMemberPointerType(T, Class.getTypePtr())
750           .getQualifiedType(Quals);
751}
752
753/// \brief Build a block pointer type.
754///
755/// \param T The type to which we'll be building a block pointer.
756///
757/// \param Quals The cvr-qualifiers to be applied to the block pointer type.
758///
759/// \param Loc The location of the entity whose type involves this
760/// block pointer type or, if there is no such entity, the location of the
761/// type that will have block pointer type.
762///
763/// \param Entity The name of the entity that involves the block pointer
764/// type, if known.
765///
766/// \returns A suitable block pointer type, if there are no
767/// errors. Otherwise, returns a NULL type.
768QualType Sema::BuildBlockPointerType(QualType T, unsigned Quals,
769                                     SourceLocation Loc,
770                                     DeclarationName Entity) {
771  if (!T.getTypePtr()->isFunctionType()) {
772    Diag(Loc, diag::err_nonfunction_block_type);
773    return QualType();
774  }
775
776  return Context.getBlockPointerType(T).getQualifiedType(Quals);
777}
778
779/// GetTypeForDeclarator - Convert the type for the specified
780/// declarator to Type instances. Skip the outermost Skip type
781/// objects.
782///
783/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
784/// owns the declaration of a type (e.g., the definition of a struct
785/// type), then *OwnedDecl will receive the owned declaration.
786QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip,
787                                    TagDecl **OwnedDecl) {
788  bool OmittedReturnType = false;
789
790  if (D.getContext() == Declarator::BlockLiteralContext
791      && Skip == 0
792      && !D.getDeclSpec().hasTypeSpecifier()
793      && (D.getNumTypeObjects() == 0
794          || (D.getNumTypeObjects() == 1
795              && D.getTypeObject(0).Kind == DeclaratorChunk::Function)))
796    OmittedReturnType = true;
797
798  // long long is a C99 feature.
799  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
800      D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
801    Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
802
803  // Determine the type of the declarator. Not all forms of declarator
804  // have a type.
805  QualType T;
806  switch (D.getKind()) {
807  case Declarator::DK_Abstract:
808  case Declarator::DK_Normal:
809  case Declarator::DK_Operator: {
810    const DeclSpec &DS = D.getDeclSpec();
811    if (OmittedReturnType) {
812      // We default to a dependent type initially.  Can be modified by
813      // the first return statement.
814      T = Context.DependentTy;
815    } else {
816      bool isInvalid = false;
817      T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid);
818      if (isInvalid)
819        D.setInvalidType(true);
820      else if (OwnedDecl && DS.isTypeSpecOwned())
821        *OwnedDecl = cast<TagDecl>((Decl *)DS.getTypeRep());
822    }
823    break;
824  }
825
826  case Declarator::DK_Constructor:
827  case Declarator::DK_Destructor:
828  case Declarator::DK_Conversion:
829    // Constructors and destructors don't have return types. Use
830    // "void" instead. Conversion operators will check their return
831    // types separately.
832    T = Context.VoidTy;
833    break;
834  }
835
836  if (T == Context.UndeducedAutoTy) {
837    int Error = -1;
838
839    switch (D.getContext()) {
840    case Declarator::KNRTypeListContext:
841      assert(0 && "K&R type lists aren't allowed in C++");
842      break;
843    case Declarator::PrototypeContext:
844      Error = 0; // Function prototype
845      break;
846    case Declarator::MemberContext:
847      switch (cast<TagDecl>(CurContext)->getTagKind()) {
848      case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
849      case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
850      case TagDecl::TK_union:  Error = 2; /* Union member */ break;
851      case TagDecl::TK_class:  Error = 3; /* Class member */ break;
852      }
853      break;
854    case Declarator::CXXCatchContext:
855      Error = 4; // Exception declaration
856      break;
857    case Declarator::TemplateParamContext:
858      Error = 5; // Template parameter
859      break;
860    case Declarator::BlockLiteralContext:
861      Error = 6;  // Block literal
862      break;
863    case Declarator::FileContext:
864    case Declarator::BlockContext:
865    case Declarator::ForContext:
866    case Declarator::ConditionContext:
867    case Declarator::TypeNameContext:
868      break;
869    }
870
871    if (Error != -1) {
872      Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
873        << Error;
874      T = Context.IntTy;
875      D.setInvalidType(true);
876    }
877  }
878
879  // The name we're declaring, if any.
880  DeclarationName Name;
881  if (D.getIdentifier())
882    Name = D.getIdentifier();
883
884  // Walk the DeclTypeInfo, building the recursive type as we go.
885  // DeclTypeInfos are ordered from the identifier out, which is
886  // opposite of what we want :).
887  for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
888    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
889    switch (DeclType.Kind) {
890    default: assert(0 && "Unknown decltype!");
891    case DeclaratorChunk::BlockPointer:
892      // If blocks are disabled, emit an error.
893      if (!LangOpts.Blocks)
894        Diag(DeclType.Loc, diag::err_blocks_disable);
895
896      T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
897                                Name);
898      break;
899    case DeclaratorChunk::Pointer:
900      // Verify that we're not building a pointer to pointer to function with
901      // exception specification.
902      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
903        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
904        D.setInvalidType(true);
905        // Build the type anyway.
906      }
907      if (getLangOptions().ObjC1 && T->isObjCInterfaceType()) {
908        const ObjCInterfaceType *OIT = T->getAsObjCInterfaceType();
909        T = Context.getObjCObjectPointerType(T,
910                                         (ObjCProtocolDecl **)OIT->qual_begin(),
911                                         OIT->getNumProtocols());
912        break;
913      }
914      T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
915      break;
916    case DeclaratorChunk::Reference:
917      // Verify that we're not building a reference to pointer to function with
918      // exception specification.
919      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
920        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
921        D.setInvalidType(true);
922        // Build the type anyway.
923      }
924      T = BuildReferenceType(T, DeclType.Ref.LValueRef,
925                             DeclType.Ref.HasRestrict ? QualType::Restrict : 0,
926                             DeclType.Loc, Name);
927      break;
928    case DeclaratorChunk::Array: {
929      // Verify that we're not building an array of pointers to function with
930      // exception specification.
931      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
932        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
933        D.setInvalidType(true);
934        // Build the type anyway.
935      }
936      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
937      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
938      ArrayType::ArraySizeModifier ASM;
939      if (ATI.isStar)
940        ASM = ArrayType::Star;
941      else if (ATI.hasStatic)
942        ASM = ArrayType::Static;
943      else
944        ASM = ArrayType::Normal;
945      if (ASM == ArrayType::Star &&
946          D.getContext() != Declarator::PrototypeContext) {
947        // FIXME: This check isn't quite right: it allows star in prototypes
948        // for function definitions, and disallows some edge cases detailed
949        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
950        Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
951        ASM = ArrayType::Normal;
952        D.setInvalidType(true);
953      }
954      T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
955                         SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
956      break;
957    }
958    case DeclaratorChunk::Function: {
959      // If the function declarator has a prototype (i.e. it is not () and
960      // does not have a K&R-style identifier list), then the arguments are part
961      // of the type, otherwise the argument list is ().
962      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
963
964      // C99 6.7.5.3p1: The return type may not be a function or array type.
965      if (T->isArrayType() || T->isFunctionType()) {
966        Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
967        T = Context.IntTy;
968        D.setInvalidType(true);
969      }
970
971      if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
972        // C++ [dcl.fct]p6:
973        //   Types shall not be defined in return or parameter types.
974        TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
975        if (Tag->isDefinition())
976          Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
977            << Context.getTypeDeclType(Tag);
978      }
979
980      // Exception specs are not allowed in typedefs. Complain, but add it
981      // anyway.
982      if (FTI.hasExceptionSpec &&
983          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
984        Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
985
986      if (FTI.NumArgs == 0) {
987        if (getLangOptions().CPlusPlus) {
988          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
989          // function takes no arguments.
990          llvm::SmallVector<QualType, 4> Exceptions;
991          Exceptions.reserve(FTI.NumExceptions);
992          for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
993            QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
994            // Check that the type is valid for an exception spec, and drop it
995            // if not.
996            if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
997              Exceptions.push_back(ET);
998          }
999          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
1000                                      FTI.hasExceptionSpec,
1001                                      FTI.hasAnyExceptionSpec,
1002                                      Exceptions.size(), Exceptions.data());
1003        } else if (FTI.isVariadic) {
1004          // We allow a zero-parameter variadic function in C if the
1005          // function is marked with the "overloadable"
1006          // attribute. Scan for this attribute now.
1007          bool Overloadable = false;
1008          for (const AttributeList *Attrs = D.getAttributes();
1009               Attrs; Attrs = Attrs->getNext()) {
1010            if (Attrs->getKind() == AttributeList::AT_overloadable) {
1011              Overloadable = true;
1012              break;
1013            }
1014          }
1015
1016          if (!Overloadable)
1017            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1018          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
1019        } else {
1020          // Simple void foo(), where the incoming T is the result type.
1021          T = Context.getFunctionNoProtoType(T);
1022        }
1023      } else if (FTI.ArgInfo[0].Param == 0) {
1024        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
1025        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1026      } else {
1027        // Otherwise, we have a function with an argument list that is
1028        // potentially variadic.
1029        llvm::SmallVector<QualType, 16> ArgTys;
1030
1031        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1032          ParmVarDecl *Param =
1033            cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1034          QualType ArgTy = Param->getType();
1035          assert(!ArgTy.isNull() && "Couldn't parse type?");
1036
1037          // Adjust the parameter type.
1038          assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1039
1040          // Look for 'void'.  void is allowed only as a single argument to a
1041          // function with no other parameters (C99 6.7.5.3p10).  We record
1042          // int(void) as a FunctionProtoType with an empty argument list.
1043          if (ArgTy->isVoidType()) {
1044            // If this is something like 'float(int, void)', reject it.  'void'
1045            // is an incomplete type (C99 6.2.5p19) and function decls cannot
1046            // have arguments of incomplete type.
1047            if (FTI.NumArgs != 1 || FTI.isVariadic) {
1048              Diag(DeclType.Loc, diag::err_void_only_param);
1049              ArgTy = Context.IntTy;
1050              Param->setType(ArgTy);
1051            } else if (FTI.ArgInfo[i].Ident) {
1052              // Reject, but continue to parse 'int(void abc)'.
1053              Diag(FTI.ArgInfo[i].IdentLoc,
1054                   diag::err_param_with_void_type);
1055              ArgTy = Context.IntTy;
1056              Param->setType(ArgTy);
1057            } else {
1058              // Reject, but continue to parse 'float(const void)'.
1059              if (ArgTy.getCVRQualifiers())
1060                Diag(DeclType.Loc, diag::err_void_param_qualified);
1061
1062              // Do not add 'void' to the ArgTys list.
1063              break;
1064            }
1065          } else if (!FTI.hasPrototype) {
1066            if (ArgTy->isPromotableIntegerType()) {
1067              ArgTy = Context.IntTy;
1068            } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
1069              if (BTy->getKind() == BuiltinType::Float)
1070                ArgTy = Context.DoubleTy;
1071            }
1072          }
1073
1074          ArgTys.push_back(ArgTy);
1075        }
1076
1077        llvm::SmallVector<QualType, 4> Exceptions;
1078        Exceptions.reserve(FTI.NumExceptions);
1079        for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1080          QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
1081          // Check that the type is valid for an exception spec, and drop it if
1082          // not.
1083          if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1084            Exceptions.push_back(ET);
1085        }
1086
1087        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1088                                    FTI.isVariadic, FTI.TypeQuals,
1089                                    FTI.hasExceptionSpec,
1090                                    FTI.hasAnyExceptionSpec,
1091                                    Exceptions.size(), Exceptions.data());
1092      }
1093      break;
1094    }
1095    case DeclaratorChunk::MemberPointer:
1096      // Verify that we're not building a pointer to pointer to function with
1097      // exception specification.
1098      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1099        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1100        D.setInvalidType(true);
1101        // Build the type anyway.
1102      }
1103      // The scope spec must refer to a class, or be dependent.
1104      QualType ClsType;
1105      if (isDependentScopeSpecifier(DeclType.Mem.Scope())) {
1106        NestedNameSpecifier *NNS
1107          = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1108        assert(NNS->getAsType() && "Nested-name-specifier must name a type");
1109        ClsType = QualType(NNS->getAsType(), 0);
1110      } else if (CXXRecordDecl *RD
1111                   = dyn_cast_or_null<CXXRecordDecl>(
1112                                    computeDeclContext(DeclType.Mem.Scope()))) {
1113        ClsType = Context.getTagDeclType(RD);
1114      } else {
1115        Diag(DeclType.Mem.Scope().getBeginLoc(),
1116             diag::err_illegal_decl_mempointer_in_nonclass)
1117          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1118          << DeclType.Mem.Scope().getRange();
1119        D.setInvalidType(true);
1120      }
1121
1122      if (!ClsType.isNull())
1123        T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1124                                   DeclType.Loc, D.getIdentifier());
1125      if (T.isNull()) {
1126        T = Context.IntTy;
1127        D.setInvalidType(true);
1128      }
1129      break;
1130    }
1131
1132    if (T.isNull()) {
1133      D.setInvalidType(true);
1134      T = Context.IntTy;
1135    }
1136
1137    // See if there are any attributes on this declarator chunk.
1138    if (const AttributeList *AL = DeclType.getAttrs())
1139      ProcessTypeAttributeList(T, AL);
1140  }
1141
1142  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1143    const FunctionProtoType *FnTy = T->getAsFunctionProtoType();
1144    assert(FnTy && "Why oh why is there not a FunctionProtoType here ?");
1145
1146    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1147    // for a nonstatic member function, the function type to which a pointer
1148    // to member refers, or the top-level function type of a function typedef
1149    // declaration.
1150    if (FnTy->getTypeQuals() != 0 &&
1151        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1152        ((D.getContext() != Declarator::MemberContext &&
1153          (!D.getCXXScopeSpec().isSet() ||
1154           !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true)
1155              ->isRecord())) ||
1156         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1157      if (D.isFunctionDeclarator())
1158        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1159      else
1160        Diag(D.getIdentifierLoc(),
1161             diag::err_invalid_qualified_typedef_function_type_use);
1162
1163      // Strip the cv-quals from the type.
1164      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1165                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1166    }
1167  }
1168
1169  // If there were any type attributes applied to the decl itself (not the
1170  // type, apply the type attribute to the type!)
1171  if (const AttributeList *Attrs = D.getAttributes())
1172    ProcessTypeAttributeList(T, Attrs);
1173
1174  return T;
1175}
1176
1177/// CheckSpecifiedExceptionType - Check if the given type is valid in an
1178/// exception specification. Incomplete types, or pointers to incomplete types
1179/// other than void are not allowed.
1180bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
1181  // FIXME: This may not correctly work with the fix for core issue 437,
1182  // where a class's own type is considered complete within its body.
1183
1184  // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1185  //   an incomplete type.
1186  if (T->isIncompleteType())
1187    return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1188      << Range << T << /*direct*/0;
1189
1190  // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1191  //   an incomplete type a pointer or reference to an incomplete type, other
1192  //   than (cv) void*.
1193  int kind;
1194  if (const PointerType* IT = T->getAsPointerType()) {
1195    T = IT->getPointeeType();
1196    kind = 1;
1197  } else if (const ReferenceType* IT = T->getAsReferenceType()) {
1198    T = IT->getPointeeType();
1199    kind = 2;
1200  } else
1201    return false;
1202
1203  if (T->isIncompleteType() && !T->isVoidType())
1204    return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1205      << Range << T << /*indirect*/kind;
1206
1207  return false;
1208}
1209
1210/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
1211/// to member to a function with an exception specification. This means that
1212/// it is invalid to add another level of indirection.
1213bool Sema::CheckDistantExceptionSpec(QualType T) {
1214  if (const PointerType *PT = T->getAsPointerType())
1215    T = PT->getPointeeType();
1216  else if (const MemberPointerType *PT = T->getAsMemberPointerType())
1217    T = PT->getPointeeType();
1218  else
1219    return false;
1220
1221  const FunctionProtoType *FnT = T->getAsFunctionProtoType();
1222  if (!FnT)
1223    return false;
1224
1225  return FnT->hasExceptionSpec();
1226}
1227
1228/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
1229/// exception specifications. Exception specifications are equivalent if
1230/// they allow exactly the same set of exception types. It does not matter how
1231/// that is achieved. See C++ [except.spec]p2.
1232bool Sema::CheckEquivalentExceptionSpec(
1233    const FunctionProtoType *Old, SourceLocation OldLoc,
1234    const FunctionProtoType *New, SourceLocation NewLoc) {
1235  bool OldAny = !Old->hasExceptionSpec() || Old->hasAnyExceptionSpec();
1236  bool NewAny = !New->hasExceptionSpec() || New->hasAnyExceptionSpec();
1237  if (OldAny && NewAny)
1238    return false;
1239  if (OldAny || NewAny) {
1240    Diag(NewLoc, diag::err_mismatched_exception_spec);
1241    Diag(OldLoc, diag::note_previous_declaration);
1242    return true;
1243  }
1244
1245  bool Success = true;
1246  // Both have a definite exception spec. Collect the first set, then compare
1247  // to the second.
1248  llvm::SmallPtrSet<const Type*, 8> Types;
1249  for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
1250       E = Old->exception_end(); I != E; ++I)
1251    Types.insert(Context.getCanonicalType(*I).getTypePtr());
1252
1253  for (FunctionProtoType::exception_iterator I = New->exception_begin(),
1254       E = New->exception_end(); I != E && Success; ++I)
1255    Success = Types.erase(Context.getCanonicalType(*I).getTypePtr());
1256
1257  Success = Success && Types.empty();
1258
1259  if (Success) {
1260    return false;
1261  }
1262  Diag(NewLoc, diag::err_mismatched_exception_spec);
1263  Diag(OldLoc, diag::note_previous_declaration);
1264  return true;
1265}
1266
1267/// CheckExceptionSpecSubset - Check whether the second function type's
1268/// exception specification is a subset (or equivalent) of the first function
1269/// type. This is used by override and pointer assignment checks.
1270bool Sema::CheckExceptionSpecSubset(unsigned DiagID, unsigned NoteID,
1271    const FunctionProtoType *Superset, SourceLocation SuperLoc,
1272    const FunctionProtoType *Subset, SourceLocation SubLoc)
1273{
1274  // FIXME: As usual, we could be more specific in our error messages, but
1275  // that better waits until we've got types with source locations.
1276
1277  // If superset contains everything, we're done.
1278  if (!Superset->hasExceptionSpec() || Superset->hasAnyExceptionSpec())
1279    return false;
1280
1281  // It does not. If the subset contains everything, we've failed.
1282  if (!Subset->hasExceptionSpec() || Subset->hasAnyExceptionSpec()) {
1283    Diag(SubLoc, DiagID);
1284    Diag(SuperLoc, NoteID);
1285    return true;
1286  }
1287
1288  // Neither contains everything. Do a proper comparison.
1289  for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
1290       SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
1291    // Take one type from the subset.
1292    QualType CanonicalSubT = Context.getCanonicalType(*SubI);
1293    bool SubIsPointer = false;
1294    if (const ReferenceType *RefTy = CanonicalSubT->getAsReferenceType())
1295      CanonicalSubT = RefTy->getPointeeType();
1296    if (const PointerType *PtrTy = CanonicalSubT->getAsPointerType()) {
1297      CanonicalSubT = PtrTy->getPointeeType();
1298      SubIsPointer = true;
1299    }
1300    bool SubIsClass = CanonicalSubT->isRecordType();
1301    CanonicalSubT.setCVRQualifiers(0);
1302
1303    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1304                    /*DetectVirtual=*/false);
1305
1306    bool Contained = false;
1307    // Make sure it's in the superset.
1308    for (FunctionProtoType::exception_iterator SuperI =
1309           Superset->exception_begin(), SuperE = Superset->exception_end();
1310         SuperI != SuperE; ++SuperI) {
1311      QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
1312      // SubT must be SuperT or derived from it, or pointer or reference to
1313      // such types.
1314      if (const ReferenceType *RefTy = CanonicalSuperT->getAsReferenceType())
1315        CanonicalSuperT = RefTy->getPointeeType();
1316      if (SubIsPointer) {
1317        if (const PointerType *PtrTy = CanonicalSuperT->getAsPointerType())
1318          CanonicalSuperT = PtrTy->getPointeeType();
1319        else {
1320          continue;
1321        }
1322      }
1323      CanonicalSuperT.setCVRQualifiers(0);
1324      // If the types are the same, move on to the next type in the subset.
1325      if (CanonicalSubT == CanonicalSuperT) {
1326        Contained = true;
1327        break;
1328      }
1329
1330      // Otherwise we need to check the inheritance.
1331      if (!SubIsClass || !CanonicalSuperT->isRecordType())
1332        continue;
1333
1334      Paths.clear();
1335      if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
1336        continue;
1337
1338      if (Paths.isAmbiguous(CanonicalSuperT))
1339        continue;
1340
1341      if (FindInaccessibleBase(CanonicalSubT, CanonicalSuperT, Paths, true))
1342        continue;
1343
1344      Contained = true;
1345      break;
1346    }
1347    if (!Contained) {
1348      Diag(SubLoc, DiagID);
1349      Diag(SuperLoc, NoteID);
1350      return true;
1351    }
1352  }
1353  // We've run the gauntlet.
1354  return false;
1355}
1356
1357/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1358/// declarator
1359QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1360  ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1361  QualType T = MDecl->getResultType();
1362  llvm::SmallVector<QualType, 16> ArgTys;
1363
1364  // Add the first two invisible argument types for self and _cmd.
1365  if (MDecl->isInstanceMethod()) {
1366    QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1367    selfTy = Context.getPointerType(selfTy);
1368    ArgTys.push_back(selfTy);
1369  } else
1370    ArgTys.push_back(Context.getObjCIdType());
1371  ArgTys.push_back(Context.getObjCSelType());
1372
1373  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1374       E = MDecl->param_end(); PI != E; ++PI) {
1375    QualType ArgTy = (*PI)->getType();
1376    assert(!ArgTy.isNull() && "Couldn't parse type?");
1377    ArgTy = adjustParameterType(ArgTy);
1378    ArgTys.push_back(ArgTy);
1379  }
1380  T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1381                              MDecl->isVariadic(), 0);
1382  return T;
1383}
1384
1385/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
1386/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1387/// they point to and return true. If T1 and T2 aren't pointer types
1388/// or pointer-to-member types, or if they are not similar at this
1389/// level, returns false and leaves T1 and T2 unchanged. Top-level
1390/// qualifiers on T1 and T2 are ignored. This function will typically
1391/// be called in a loop that successively "unwraps" pointer and
1392/// pointer-to-member types to compare them at each level.
1393bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1394  const PointerType *T1PtrType = T1->getAsPointerType(),
1395                    *T2PtrType = T2->getAsPointerType();
1396  if (T1PtrType && T2PtrType) {
1397    T1 = T1PtrType->getPointeeType();
1398    T2 = T2PtrType->getPointeeType();
1399    return true;
1400  }
1401
1402  const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
1403                          *T2MPType = T2->getAsMemberPointerType();
1404  if (T1MPType && T2MPType &&
1405      Context.getCanonicalType(T1MPType->getClass()) ==
1406      Context.getCanonicalType(T2MPType->getClass())) {
1407    T1 = T1MPType->getPointeeType();
1408    T2 = T2MPType->getPointeeType();
1409    return true;
1410  }
1411  return false;
1412}
1413
1414Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1415  // C99 6.7.6: Type names have no identifier.  This is already validated by
1416  // the parser.
1417  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1418
1419  TagDecl *OwnedTag = 0;
1420  QualType T = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag);
1421  if (D.isInvalidType())
1422    return true;
1423
1424  if (getLangOptions().CPlusPlus) {
1425    // Check that there are no default arguments (C++ only).
1426    CheckExtraCXXDefaultArguments(D);
1427
1428    // C++0x [dcl.type]p3:
1429    //   A type-specifier-seq shall not define a class or enumeration
1430    //   unless it appears in the type-id of an alias-declaration
1431    //   (7.1.3).
1432    if (OwnedTag && OwnedTag->isDefinition())
1433      Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1434        << Context.getTypeDeclType(OwnedTag);
1435  }
1436
1437  return T.getAsOpaquePtr();
1438}
1439
1440
1441
1442//===----------------------------------------------------------------------===//
1443// Type Attribute Processing
1444//===----------------------------------------------------------------------===//
1445
1446/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1447/// specified type.  The attribute contains 1 argument, the id of the address
1448/// space for the type.
1449static void HandleAddressSpaceTypeAttribute(QualType &Type,
1450                                            const AttributeList &Attr, Sema &S){
1451  // If this type is already address space qualified, reject it.
1452  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1453  // for two or more different address spaces."
1454  if (Type.getAddressSpace()) {
1455    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1456    return;
1457  }
1458
1459  // Check the attribute arguments.
1460  if (Attr.getNumArgs() != 1) {
1461    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1462    return;
1463  }
1464  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1465  llvm::APSInt addrSpace(32);
1466  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1467    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1468      << ASArgExpr->getSourceRange();
1469    return;
1470  }
1471
1472  // Bounds checking.
1473  if (addrSpace.isSigned()) {
1474    if (addrSpace.isNegative()) {
1475      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1476        << ASArgExpr->getSourceRange();
1477      return;
1478    }
1479    addrSpace.setIsSigned(false);
1480  }
1481  llvm::APSInt max(addrSpace.getBitWidth());
1482  max = QualType::MaxAddressSpace;
1483  if (addrSpace > max) {
1484    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1485      << QualType::MaxAddressSpace << ASArgExpr->getSourceRange();
1486    return;
1487  }
1488
1489  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1490  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1491}
1492
1493/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1494/// specified type.  The attribute contains 1 argument, weak or strong.
1495static void HandleObjCGCTypeAttribute(QualType &Type,
1496                                      const AttributeList &Attr, Sema &S) {
1497  if (Type.getObjCGCAttr() != QualType::GCNone) {
1498    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1499    return;
1500  }
1501
1502  // Check the attribute arguments.
1503  if (!Attr.getParameterName()) {
1504    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1505      << "objc_gc" << 1;
1506    return;
1507  }
1508  QualType::GCAttrTypes GCAttr;
1509  if (Attr.getNumArgs() != 0) {
1510    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1511    return;
1512  }
1513  if (Attr.getParameterName()->isStr("weak"))
1514    GCAttr = QualType::Weak;
1515  else if (Attr.getParameterName()->isStr("strong"))
1516    GCAttr = QualType::Strong;
1517  else {
1518    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1519      << "objc_gc" << Attr.getParameterName();
1520    return;
1521  }
1522
1523  Type = S.Context.getObjCGCQualType(Type, GCAttr);
1524}
1525
1526/// HandleNoReturnTypeAttribute - Process the noreturn attribute on the
1527/// specified type.  The attribute contains 0 arguments.
1528static void HandleNoReturnTypeAttribute(QualType &Type,
1529                                        const AttributeList &Attr, Sema &S) {
1530  if (Attr.getNumArgs() != 0)
1531    return;
1532
1533  // We only apply this to a pointer to function or a pointer to block.
1534  if (!Type->isFunctionPointerType()
1535      && !Type->isBlockPointerType()
1536      && !Type->isFunctionType())
1537    return;
1538
1539  Type = S.Context.getNoReturnType(Type);
1540}
1541
1542void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1543  // Scan through and apply attributes to this type where it makes sense.  Some
1544  // attributes (such as __address_space__, __vector_size__, etc) apply to the
1545  // type, but others can be present in the type specifiers even though they
1546  // apply to the decl.  Here we apply type attributes and ignore the rest.
1547  for (; AL; AL = AL->getNext()) {
1548    // If this is an attribute we can handle, do so now, otherwise, add it to
1549    // the LeftOverAttrs list for rechaining.
1550    switch (AL->getKind()) {
1551    default: break;
1552    case AttributeList::AT_address_space:
1553      HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1554      break;
1555    case AttributeList::AT_objc_gc:
1556      HandleObjCGCTypeAttribute(Result, *AL, *this);
1557      break;
1558    case AttributeList::AT_noreturn:
1559      HandleNoReturnTypeAttribute(Result, *AL, *this);
1560      break;
1561    }
1562  }
1563}
1564
1565/// @brief Ensure that the type T is a complete type.
1566///
1567/// This routine checks whether the type @p T is complete in any
1568/// context where a complete type is required. If @p T is a complete
1569/// type, returns false. If @p T is a class template specialization,
1570/// this routine then attempts to perform class template
1571/// instantiation. If instantiation fails, or if @p T is incomplete
1572/// and cannot be completed, issues the diagnostic @p diag (giving it
1573/// the type @p T) and returns true.
1574///
1575/// @param Loc  The location in the source that the incomplete type
1576/// diagnostic should refer to.
1577///
1578/// @param T  The type that this routine is examining for completeness.
1579///
1580/// @param diag The diagnostic value (e.g.,
1581/// @c diag::err_typecheck_decl_incomplete_type) that will be used
1582/// for the error message if @p T is incomplete.
1583///
1584/// @param Range1  An optional range in the source code that will be a
1585/// part of the "incomplete type" error message.
1586///
1587/// @param Range2  An optional range in the source code that will be a
1588/// part of the "incomplete type" error message.
1589///
1590/// @param PrintType If non-NULL, the type that should be printed
1591/// instead of @p T. This parameter should be used when the type that
1592/// we're checking for incompleteness isn't the type that should be
1593/// displayed to the user, e.g., when T is a type and PrintType is a
1594/// pointer to T.
1595///
1596/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1597/// @c false otherwise.
1598bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag,
1599                               SourceRange Range1, SourceRange Range2,
1600                               QualType PrintType) {
1601  // FIXME: Add this assertion to help us flush out problems with
1602  // checking for dependent types and type-dependent expressions.
1603  //
1604  //  assert(!T->isDependentType() &&
1605  //         "Can't ask whether a dependent type is complete");
1606
1607  // If we have a complete type, we're done.
1608  if (!T->isIncompleteType())
1609    return false;
1610
1611  // If we have a class template specialization or a class member of a
1612  // class template specialization, try to instantiate it.
1613  if (const RecordType *Record = T->getAsRecordType()) {
1614    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1615          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1616      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1617        // Update the class template specialization's location to
1618        // refer to the point of instantiation.
1619        if (Loc.isValid())
1620          ClassTemplateSpec->setLocation(Loc);
1621        return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1622                                             /*ExplicitInstantiation=*/false);
1623      }
1624    } else if (CXXRecordDecl *Rec
1625                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1626      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1627        // Find the class template specialization that surrounds this
1628        // member class.
1629        ClassTemplateSpecializationDecl *Spec = 0;
1630        for (DeclContext *Parent = Rec->getDeclContext();
1631             Parent && !Spec; Parent = Parent->getParent())
1632          Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent);
1633        assert(Spec && "Not a member of a class template specialization?");
1634        return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(),
1635                                /*ExplicitInstantiation=*/false);
1636      }
1637    }
1638  }
1639
1640  if (PrintType.isNull())
1641    PrintType = T;
1642
1643  // We have an incomplete type. Produce a diagnostic.
1644  Diag(Loc, diag) << PrintType << Range1 << Range2;
1645
1646  // If the type was a forward declaration of a class/struct/union
1647  // type, produce
1648  const TagType *Tag = 0;
1649  if (const RecordType *Record = T->getAsRecordType())
1650    Tag = Record;
1651  else if (const EnumType *Enum = T->getAsEnumType())
1652    Tag = Enum;
1653
1654  if (Tag && !Tag->getDecl()->isInvalidDecl())
1655    Diag(Tag->getDecl()->getLocation(),
1656         Tag->isBeingDefined() ? diag::note_type_being_defined
1657                               : diag::note_forward_declaration)
1658        << QualType(Tag, 0);
1659
1660  return true;
1661}
1662
1663/// \brief Retrieve a version of the type 'T' that is qualified by the
1664/// nested-name-specifier contained in SS.
1665QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1666  if (!SS.isSet() || SS.isInvalid() || T.isNull())
1667    return T;
1668
1669  NestedNameSpecifier *NNS
1670    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1671  return Context.getQualifiedNameType(NNS, T);
1672}
1673
1674QualType Sema::BuildTypeofExprType(Expr *E) {
1675  return Context.getTypeOfExprType(E);
1676}
1677
1678QualType Sema::BuildDecltypeType(Expr *E) {
1679  if (E->getType() == Context.OverloadTy) {
1680    Diag(E->getLocStart(),
1681         diag::err_cannot_determine_declared_type_of_overloaded_function);
1682    return QualType();
1683  }
1684  return Context.getDecltypeType(E);
1685}
1686