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