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