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