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