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