SemaType.cpp revision 225d6ca735de81dfb9bdc95645e30c6ba9514f43
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/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 (ObjCProtocolListLoc *PLL = dyn_cast<ObjCProtocolListLoc>(&TSL)) {
1303    assert(PLL->getNumProtocols() == DS.getNumProtocolQualifiers());
1304    PLL->setLAngleLoc(DS.getProtocolLAngleLoc());
1305    PLL->setRAngleLoc(DS.getSourceRange().getEnd());
1306    for (unsigned i = 0; i != DS.getNumProtocolQualifiers(); ++i)
1307      PLL->setProtocolLoc(i, DS.getProtocolLocs()[i]);
1308    FillTypeSpecLoc(PLL->getBaseTypeLoc(), DS);
1309
1310  } else {
1311    //FIXME: Other typespecs.
1312    DefaultTypeSpecLoc &DTL = cast<DefaultTypeSpecLoc>(TSL);
1313    DTL.setStartLoc(DS.getSourceRange().getBegin());
1314  }
1315}
1316
1317/// \brief Create and instantiate a DeclaratorInfo with type source information.
1318///
1319/// \param T QualType referring to the type as written in source code.
1320DeclaratorInfo *
1321Sema::GetDeclaratorInfoForDeclarator(Declarator &D, QualType T, unsigned Skip) {
1322  DeclaratorInfo *DInfo = Context.CreateDeclaratorInfo(T);
1323  TypeLoc CurrTL = DInfo->getTypeLoc();
1324
1325  for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
1326    assert(!CurrTL.isNull());
1327
1328    DeclaratorChunk &DeclType = D.getTypeObject(i);
1329    switch (DeclType.Kind) {
1330    default: assert(0 && "Unknown decltype!");
1331    case DeclaratorChunk::BlockPointer: {
1332      BlockPointerLoc &BPL = cast<BlockPointerLoc>(CurrTL);
1333      BPL.setCaretLoc(DeclType.Loc);
1334      break;
1335    }
1336    case DeclaratorChunk::Pointer: {
1337      //FIXME: ObjCObject pointers.
1338      PointerLoc &PL = cast<PointerLoc>(CurrTL);
1339      PL.setStarLoc(DeclType.Loc);
1340      break;
1341    }
1342    case DeclaratorChunk::Reference: {
1343      ReferenceLoc &RL = cast<ReferenceLoc>(CurrTL);
1344      RL.setAmpLoc(DeclType.Loc);
1345      break;
1346    }
1347    case DeclaratorChunk::Array: {
1348      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1349      ArrayLoc &AL = cast<ArrayLoc>(CurrTL);
1350      AL.setLBracketLoc(DeclType.Loc);
1351      AL.setRBracketLoc(DeclType.EndLoc);
1352      AL.setSizeExpr(static_cast<Expr*>(ATI.NumElts));
1353      //FIXME: Star location for [*].
1354      break;
1355    }
1356    case DeclaratorChunk::Function: {
1357      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1358      FunctionLoc &FL = cast<FunctionLoc>(CurrTL);
1359      FL.setLParenLoc(DeclType.Loc);
1360      FL.setRParenLoc(DeclType.EndLoc);
1361      for (unsigned i = 0, e = FTI.NumArgs, tpi = 0; i != e; ++i) {
1362        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1363        if (Param) {
1364          assert(tpi < FL.getNumArgs());
1365          FL.setArg(tpi++, Param);
1366        }
1367      }
1368      break;
1369      //FIXME: Exception specs.
1370    }
1371    case DeclaratorChunk::MemberPointer: {
1372      MemberPointerLoc &MPL = cast<MemberPointerLoc>(CurrTL);
1373      MPL.setStarLoc(DeclType.Loc);
1374      //FIXME: Class location.
1375      break;
1376    }
1377
1378    }
1379
1380    CurrTL = CurrTL.getNextTypeLoc();
1381  }
1382
1383  FillTypeSpecLoc(CurrTL, D.getDeclSpec());
1384
1385  return DInfo;
1386}
1387
1388/// \brief Create a LocInfoType to hold the given QualType and DeclaratorInfo.
1389QualType Sema::CreateLocInfoType(QualType T, DeclaratorInfo *DInfo) {
1390  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1391  // and Sema during declaration parsing. Try deallocating/caching them when
1392  // it's appropriate, instead of allocating them and keeping them around.
1393  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1394  new (LocT) LocInfoType(T, DInfo);
1395  assert(LocT->getTypeClass() != T->getTypeClass() &&
1396         "LocInfoType's TypeClass conflicts with an existing Type class");
1397  return QualType(LocT, 0);
1398}
1399
1400void LocInfoType::getAsStringInternal(std::string &Str,
1401                                      const PrintingPolicy &Policy) const {
1402  assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1403         " was used directly instead of getting the QualType through"
1404         " GetTypeFromParser");
1405}
1406
1407/// CheckSpecifiedExceptionType - Check if the given type is valid in an
1408/// exception specification. Incomplete types, or pointers to incomplete types
1409/// other than void are not allowed.
1410bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
1411  // FIXME: This may not correctly work with the fix for core issue 437,
1412  // where a class's own type is considered complete within its body.
1413
1414  // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1415  //   an incomplete type.
1416  if (T->isIncompleteType())
1417    return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1418      << Range << T << /*direct*/0;
1419
1420  // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1421  //   an incomplete type a pointer or reference to an incomplete type, other
1422  //   than (cv) void*.
1423  int kind;
1424  if (const PointerType* IT = T->getAs<PointerType>()) {
1425    T = IT->getPointeeType();
1426    kind = 1;
1427  } else if (const ReferenceType* IT = T->getAs<ReferenceType>()) {
1428    T = IT->getPointeeType();
1429    kind = 2;
1430  } else
1431    return false;
1432
1433  if (T->isIncompleteType() && !T->isVoidType())
1434    return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1435      << Range << T << /*indirect*/kind;
1436
1437  return false;
1438}
1439
1440/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
1441/// to member to a function with an exception specification. This means that
1442/// it is invalid to add another level of indirection.
1443bool Sema::CheckDistantExceptionSpec(QualType T) {
1444  if (const PointerType *PT = T->getAs<PointerType>())
1445    T = PT->getPointeeType();
1446  else if (const MemberPointerType *PT = T->getAs<MemberPointerType>())
1447    T = PT->getPointeeType();
1448  else
1449    return false;
1450
1451  const FunctionProtoType *FnT = T->getAs<FunctionProtoType>();
1452  if (!FnT)
1453    return false;
1454
1455  return FnT->hasExceptionSpec();
1456}
1457
1458/// CheckEquivalentExceptionSpec - Check if the two types have equivalent
1459/// exception specifications. Exception specifications are equivalent if
1460/// they allow exactly the same set of exception types. It does not matter how
1461/// that is achieved. See C++ [except.spec]p2.
1462bool Sema::CheckEquivalentExceptionSpec(
1463    const FunctionProtoType *Old, SourceLocation OldLoc,
1464    const FunctionProtoType *New, SourceLocation NewLoc) {
1465  bool OldAny = !Old->hasExceptionSpec() || Old->hasAnyExceptionSpec();
1466  bool NewAny = !New->hasExceptionSpec() || New->hasAnyExceptionSpec();
1467  if (OldAny && NewAny)
1468    return false;
1469  if (OldAny || NewAny) {
1470    Diag(NewLoc, diag::err_mismatched_exception_spec);
1471    Diag(OldLoc, diag::note_previous_declaration);
1472    return true;
1473  }
1474
1475  bool Success = true;
1476  // Both have a definite exception spec. Collect the first set, then compare
1477  // to the second.
1478  llvm::SmallPtrSet<const Type*, 8> Types;
1479  for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
1480       E = Old->exception_end(); I != E; ++I)
1481    Types.insert(Context.getCanonicalType(*I).getTypePtr());
1482
1483  for (FunctionProtoType::exception_iterator I = New->exception_begin(),
1484       E = New->exception_end(); I != E && Success; ++I)
1485    Success = Types.erase(Context.getCanonicalType(*I).getTypePtr());
1486
1487  Success = Success && Types.empty();
1488
1489  if (Success) {
1490    return false;
1491  }
1492  Diag(NewLoc, diag::err_mismatched_exception_spec);
1493  Diag(OldLoc, diag::note_previous_declaration);
1494  return true;
1495}
1496
1497/// CheckExceptionSpecSubset - Check whether the second function type's
1498/// exception specification is a subset (or equivalent) of the first function
1499/// type. This is used by override and pointer assignment checks.
1500bool Sema::CheckExceptionSpecSubset(unsigned DiagID, unsigned NoteID,
1501    const FunctionProtoType *Superset, SourceLocation SuperLoc,
1502    const FunctionProtoType *Subset, SourceLocation SubLoc) {
1503  // FIXME: As usual, we could be more specific in our error messages, but
1504  // that better waits until we've got types with source locations.
1505
1506  // If superset contains everything, we're done.
1507  if (!Superset->hasExceptionSpec() || Superset->hasAnyExceptionSpec())
1508    return false;
1509
1510  // It does not. If the subset contains everything, we've failed.
1511  if (!Subset->hasExceptionSpec() || Subset->hasAnyExceptionSpec()) {
1512    Diag(SubLoc, DiagID);
1513    Diag(SuperLoc, NoteID);
1514    return true;
1515  }
1516
1517  // Neither contains everything. Do a proper comparison.
1518  for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(),
1519       SubE = Subset->exception_end(); SubI != SubE; ++SubI) {
1520    // Take one type from the subset.
1521    QualType CanonicalSubT = Context.getCanonicalType(*SubI);
1522    bool SubIsPointer = false;
1523    if (const ReferenceType *RefTy = CanonicalSubT->getAs<ReferenceType>())
1524      CanonicalSubT = RefTy->getPointeeType();
1525    if (const PointerType *PtrTy = CanonicalSubT->getAs<PointerType>()) {
1526      CanonicalSubT = PtrTy->getPointeeType();
1527      SubIsPointer = true;
1528    }
1529    bool SubIsClass = CanonicalSubT->isRecordType();
1530    CanonicalSubT = CanonicalSubT.getUnqualifiedType();
1531
1532    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1533                    /*DetectVirtual=*/false);
1534
1535    bool Contained = false;
1536    // Make sure it's in the superset.
1537    for (FunctionProtoType::exception_iterator SuperI =
1538           Superset->exception_begin(), SuperE = Superset->exception_end();
1539         SuperI != SuperE; ++SuperI) {
1540      QualType CanonicalSuperT = Context.getCanonicalType(*SuperI);
1541      // SubT must be SuperT or derived from it, or pointer or reference to
1542      // such types.
1543      if (const ReferenceType *RefTy = CanonicalSuperT->getAs<ReferenceType>())
1544        CanonicalSuperT = RefTy->getPointeeType();
1545      if (SubIsPointer) {
1546        if (const PointerType *PtrTy = CanonicalSuperT->getAs<PointerType>())
1547          CanonicalSuperT = PtrTy->getPointeeType();
1548        else {
1549          continue;
1550        }
1551      }
1552      CanonicalSuperT = CanonicalSuperT.getUnqualifiedType();
1553      // If the types are the same, move on to the next type in the subset.
1554      if (CanonicalSubT == CanonicalSuperT) {
1555        Contained = true;
1556        break;
1557      }
1558
1559      // Otherwise we need to check the inheritance.
1560      if (!SubIsClass || !CanonicalSuperT->isRecordType())
1561        continue;
1562
1563      Paths.clear();
1564      if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths))
1565        continue;
1566
1567      if (Paths.isAmbiguous(CanonicalSuperT))
1568        continue;
1569
1570      if (FindInaccessibleBase(CanonicalSubT, CanonicalSuperT, Paths, true))
1571        continue;
1572
1573      Contained = true;
1574      break;
1575    }
1576    if (!Contained) {
1577      Diag(SubLoc, DiagID);
1578      Diag(SuperLoc, NoteID);
1579      return true;
1580    }
1581  }
1582  // We've run the gauntlet.
1583  return false;
1584}
1585
1586/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1587/// declarator
1588QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1589  ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1590  QualType T = MDecl->getResultType();
1591  llvm::SmallVector<QualType, 16> ArgTys;
1592
1593  // Add the first two invisible argument types for self and _cmd.
1594  if (MDecl->isInstanceMethod()) {
1595    QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1596    selfTy = Context.getPointerType(selfTy);
1597    ArgTys.push_back(selfTy);
1598  } else
1599    ArgTys.push_back(Context.getObjCIdType());
1600  ArgTys.push_back(Context.getObjCSelType());
1601
1602  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1603       E = MDecl->param_end(); PI != E; ++PI) {
1604    QualType ArgTy = (*PI)->getType();
1605    assert(!ArgTy.isNull() && "Couldn't parse type?");
1606    ArgTy = adjustParameterType(ArgTy);
1607    ArgTys.push_back(ArgTy);
1608  }
1609  T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1610                              MDecl->isVariadic(), 0);
1611  return T;
1612}
1613
1614/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
1615/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1616/// they point to and return true. If T1 and T2 aren't pointer types
1617/// or pointer-to-member types, or if they are not similar at this
1618/// level, returns false and leaves T1 and T2 unchanged. Top-level
1619/// qualifiers on T1 and T2 are ignored. This function will typically
1620/// be called in a loop that successively "unwraps" pointer and
1621/// pointer-to-member types to compare them at each level.
1622bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1623  const PointerType *T1PtrType = T1->getAs<PointerType>(),
1624                    *T2PtrType = T2->getAs<PointerType>();
1625  if (T1PtrType && T2PtrType) {
1626    T1 = T1PtrType->getPointeeType();
1627    T2 = T2PtrType->getPointeeType();
1628    return true;
1629  }
1630
1631  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1632                          *T2MPType = T2->getAs<MemberPointerType>();
1633  if (T1MPType && T2MPType &&
1634      Context.getCanonicalType(T1MPType->getClass()) ==
1635      Context.getCanonicalType(T2MPType->getClass())) {
1636    T1 = T1MPType->getPointeeType();
1637    T2 = T2MPType->getPointeeType();
1638    return true;
1639  }
1640  return false;
1641}
1642
1643Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1644  // C99 6.7.6: Type names have no identifier.  This is already validated by
1645  // the parser.
1646  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1647
1648  DeclaratorInfo *DInfo = 0;
1649  TagDecl *OwnedTag = 0;
1650  QualType T = GetTypeForDeclarator(D, S, &DInfo, /*Skip=*/0, &OwnedTag);
1651  if (D.isInvalidType())
1652    return true;
1653
1654  if (getLangOptions().CPlusPlus) {
1655    // Check that there are no default arguments (C++ only).
1656    CheckExtraCXXDefaultArguments(D);
1657
1658    // C++0x [dcl.type]p3:
1659    //   A type-specifier-seq shall not define a class or enumeration
1660    //   unless it appears in the type-id of an alias-declaration
1661    //   (7.1.3).
1662    if (OwnedTag && OwnedTag->isDefinition())
1663      Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1664        << Context.getTypeDeclType(OwnedTag);
1665  }
1666
1667  if (DInfo)
1668    T = CreateLocInfoType(T, DInfo);
1669
1670  return T.getAsOpaquePtr();
1671}
1672
1673
1674
1675//===----------------------------------------------------------------------===//
1676// Type Attribute Processing
1677//===----------------------------------------------------------------------===//
1678
1679/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1680/// specified type.  The attribute contains 1 argument, the id of the address
1681/// space for the type.
1682static void HandleAddressSpaceTypeAttribute(QualType &Type,
1683                                            const AttributeList &Attr, Sema &S){
1684
1685  // If this type is already address space qualified, reject it.
1686  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1687  // for two or more different address spaces."
1688  if (Type.getAddressSpace()) {
1689    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1690    return;
1691  }
1692
1693  // Check the attribute arguments.
1694  if (Attr.getNumArgs() != 1) {
1695    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1696    return;
1697  }
1698  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1699  llvm::APSInt addrSpace(32);
1700  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1701    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1702      << ASArgExpr->getSourceRange();
1703    return;
1704  }
1705
1706  // Bounds checking.
1707  if (addrSpace.isSigned()) {
1708    if (addrSpace.isNegative()) {
1709      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1710        << ASArgExpr->getSourceRange();
1711      return;
1712    }
1713    addrSpace.setIsSigned(false);
1714  }
1715  llvm::APSInt max(addrSpace.getBitWidth());
1716  max = Qualifiers::MaxAddressSpace;
1717  if (addrSpace > max) {
1718    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1719      << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1720    return;
1721  }
1722
1723  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1724  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1725}
1726
1727/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1728/// specified type.  The attribute contains 1 argument, weak or strong.
1729static void HandleObjCGCTypeAttribute(QualType &Type,
1730                                      const AttributeList &Attr, Sema &S) {
1731  if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1732    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1733    return;
1734  }
1735
1736  // Check the attribute arguments.
1737  if (!Attr.getParameterName()) {
1738    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1739      << "objc_gc" << 1;
1740    return;
1741  }
1742  Qualifiers::GC GCAttr;
1743  if (Attr.getNumArgs() != 0) {
1744    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1745    return;
1746  }
1747  if (Attr.getParameterName()->isStr("weak"))
1748    GCAttr = Qualifiers::Weak;
1749  else if (Attr.getParameterName()->isStr("strong"))
1750    GCAttr = Qualifiers::Strong;
1751  else {
1752    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1753      << "objc_gc" << Attr.getParameterName();
1754    return;
1755  }
1756
1757  Type = S.Context.getObjCGCQualType(Type, GCAttr);
1758}
1759
1760/// HandleNoReturnTypeAttribute - Process the noreturn attribute on the
1761/// specified type.  The attribute contains 0 arguments.
1762static void HandleNoReturnTypeAttribute(QualType &Type,
1763                                        const AttributeList &Attr, Sema &S) {
1764  if (Attr.getNumArgs() != 0)
1765    return;
1766
1767  // We only apply this to a pointer to function or a pointer to block.
1768  if (!Type->isFunctionPointerType()
1769      && !Type->isBlockPointerType()
1770      && !Type->isFunctionType())
1771    return;
1772
1773  Type = S.Context.getNoReturnType(Type);
1774}
1775
1776void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1777  // Scan through and apply attributes to this type where it makes sense.  Some
1778  // attributes (such as __address_space__, __vector_size__, etc) apply to the
1779  // type, but others can be present in the type specifiers even though they
1780  // apply to the decl.  Here we apply type attributes and ignore the rest.
1781  for (; AL; AL = AL->getNext()) {
1782    // If this is an attribute we can handle, do so now, otherwise, add it to
1783    // the LeftOverAttrs list for rechaining.
1784    switch (AL->getKind()) {
1785    default: break;
1786    case AttributeList::AT_address_space:
1787      HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1788      break;
1789    case AttributeList::AT_objc_gc:
1790      HandleObjCGCTypeAttribute(Result, *AL, *this);
1791      break;
1792    case AttributeList::AT_noreturn:
1793      HandleNoReturnTypeAttribute(Result, *AL, *this);
1794      break;
1795    }
1796  }
1797}
1798
1799/// @brief Ensure that the type T is a complete type.
1800///
1801/// This routine checks whether the type @p T is complete in any
1802/// context where a complete type is required. If @p T is a complete
1803/// type, returns false. If @p T is a class template specialization,
1804/// this routine then attempts to perform class template
1805/// instantiation. If instantiation fails, or if @p T is incomplete
1806/// and cannot be completed, issues the diagnostic @p diag (giving it
1807/// the type @p T) and returns true.
1808///
1809/// @param Loc  The location in the source that the incomplete type
1810/// diagnostic should refer to.
1811///
1812/// @param T  The type that this routine is examining for completeness.
1813///
1814/// @param PD The partial diagnostic that will be printed out if T is not a
1815/// complete type.
1816///
1817/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1818/// @c false otherwise.
1819bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
1820                               const PartialDiagnostic &PD) {
1821  unsigned diag = PD.getDiagID();
1822
1823  // FIXME: Add this assertion to help us flush out problems with
1824  // checking for dependent types and type-dependent expressions.
1825  //
1826  //  assert(!T->isDependentType() &&
1827  //         "Can't ask whether a dependent type is complete");
1828
1829  // If we have a complete type, we're done.
1830  if (!T->isIncompleteType())
1831    return false;
1832
1833  // If we have a class template specialization or a class member of a
1834  // class template specialization, try to instantiate it.
1835  if (const RecordType *Record = T->getAs<RecordType>()) {
1836    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1837          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1838      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1839        if (Loc.isValid())
1840          ClassTemplateSpec->setPointOfInstantiation(Loc);
1841        return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1842                                                      TSK_ImplicitInstantiation,
1843                                                      /*Complain=*/diag != 0);
1844      }
1845    } else if (CXXRecordDecl *Rec
1846                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1847      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1848        // This record was instantiated from a class within a template.
1849        return InstantiateClass(Loc, Rec, Pattern,
1850                                getTemplateInstantiationArgs(Rec),
1851                                TSK_ImplicitInstantiation,
1852                                /*Complain=*/diag != 0);
1853      }
1854    }
1855  }
1856
1857  if (diag == 0)
1858    return true;
1859
1860  // We have an incomplete type. Produce a diagnostic.
1861  Diag(Loc, PD) << T;
1862
1863  // If the type was a forward declaration of a class/struct/union
1864  // type, produce
1865  const TagType *Tag = 0;
1866  if (const RecordType *Record = T->getAs<RecordType>())
1867    Tag = Record;
1868  else if (const EnumType *Enum = T->getAs<EnumType>())
1869    Tag = Enum;
1870
1871  if (Tag && !Tag->getDecl()->isInvalidDecl())
1872    Diag(Tag->getDecl()->getLocation(),
1873         Tag->isBeingDefined() ? diag::note_type_being_defined
1874                               : diag::note_forward_declaration)
1875        << QualType(Tag, 0);
1876
1877  return true;
1878}
1879
1880/// \brief Retrieve a version of the type 'T' that is qualified by the
1881/// nested-name-specifier contained in SS.
1882QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1883  if (!SS.isSet() || SS.isInvalid() || T.isNull())
1884    return T;
1885
1886  NestedNameSpecifier *NNS
1887    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1888  return Context.getQualifiedNameType(NNS, T);
1889}
1890
1891QualType Sema::BuildTypeofExprType(Expr *E) {
1892  return Context.getTypeOfExprType(E);
1893}
1894
1895QualType Sema::BuildDecltypeType(Expr *E) {
1896  if (E->getType() == Context.OverloadTy) {
1897    Diag(E->getLocStart(),
1898         diag::err_cannot_determine_declared_type_of_overloaded_function);
1899    return QualType();
1900  }
1901  return Context.getDecltypeType(E);
1902}
1903