SemaType.cpp revision c7c11b1ba6a110f2416889cc3576fe33277b2a33
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/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/Parse/DeclSpec.h"
20using namespace clang;
21
22/// \brief Perform adjustment on the parameter type of a function.
23///
24/// This routine adjusts the given parameter type @p T to the actual
25/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
26/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
27QualType Sema::adjustParameterType(QualType T) {
28  // C99 6.7.5.3p7:
29  if (T->isArrayType()) {
30    // C99 6.7.5.3p7:
31    //   A declaration of a parameter as "array of type" shall be
32    //   adjusted to "qualified pointer to type", where the type
33    //   qualifiers (if any) are those specified within the [ and ] of
34    //   the array type derivation.
35    return Context.getArrayDecayedType(T);
36  } else if (T->isFunctionType())
37    // C99 6.7.5.3p8:
38    //   A declaration of a parameter as "function returning type"
39    //   shall be adjusted to "pointer to function returning type", as
40    //   in 6.3.2.1.
41    return Context.getPointerType(T);
42
43  return T;
44}
45
46/// \brief Convert the specified declspec to the appropriate type
47/// object.
48/// \param DS  the declaration specifiers
49/// \param DeclLoc The location of the declarator identifier or invalid if none.
50/// \returns The type described by the declaration specifiers.  This function
51/// never returns null.
52QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS,
53                                     SourceLocation DeclLoc,
54                                     bool &isInvalid) {
55  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
56  // checking.
57  QualType Result;
58
59  switch (DS.getTypeSpecType()) {
60  case DeclSpec::TST_void:
61    Result = Context.VoidTy;
62    break;
63  case DeclSpec::TST_char:
64    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
65      Result = Context.CharTy;
66    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
67      Result = Context.SignedCharTy;
68    else {
69      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
70             "Unknown TSS value");
71      Result = Context.UnsignedCharTy;
72    }
73    break;
74  case DeclSpec::TST_wchar:
75    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
76      Result = Context.WCharTy;
77    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
78      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
79        << DS.getSpecifierName(DS.getTypeSpecType());
80      Result = Context.getSignedWCharType();
81    } else {
82      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
83        "Unknown TSS value");
84      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
85        << DS.getSpecifierName(DS.getTypeSpecType());
86      Result = Context.getUnsignedWCharType();
87    }
88    break;
89  case DeclSpec::TST_unspecified:
90    // "<proto1,proto2>" is an objc qualified ID with a missing id.
91    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
92      Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
93                                              DS.getNumProtocolQualifiers());
94      break;
95    }
96
97    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
98    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
99    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
100    // Note that the one exception to this is function definitions, which are
101    // allowed to be completely missing a declspec.  This is handled in the
102    // parser already though by it pretending to have seen an 'int' in this
103    // case.
104    if (getLangOptions().ImplicitInt) {
105      // In C89 mode, we only warn if there is a completely missing declspec
106      // when one is not allowed.
107      if (DS.isEmpty()) {
108        if (DeclLoc.isInvalid())
109          DeclLoc = DS.getSourceRange().getBegin();
110        Diag(DeclLoc, diag::warn_missing_declspec)
111          << DS.getSourceRange()
112        << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
113                                                 "int");
114      }
115    } else if (!DS.hasTypeSpecifier()) {
116      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
117      // "At least one type specifier shall be given in the declaration
118      // specifiers in each declaration, and in the specifier-qualifier list in
119      // each struct declaration and type name."
120      // FIXME: Does Microsoft really have the implicit int extension in C++?
121      if (DeclLoc.isInvalid())
122        DeclLoc = DS.getSourceRange().getBegin();
123
124      if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft)
125        Diag(DeclLoc, diag::err_missing_type_specifier)
126          << DS.getSourceRange();
127      else
128        Diag(DeclLoc, diag::warn_missing_type_specifier)
129          << DS.getSourceRange();
130
131      // FIXME: If we could guarantee that the result would be
132      // well-formed, it would be useful to have a code insertion hint
133      // here. However, after emitting this warning/error, we often
134      // emit other errors.
135    }
136
137    // FALL THROUGH.
138  case DeclSpec::TST_int: {
139    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
140      switch (DS.getTypeSpecWidth()) {
141      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
142      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
143      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
144      case DeclSpec::TSW_longlong:    Result = Context.LongLongTy; break;
145      }
146    } else {
147      switch (DS.getTypeSpecWidth()) {
148      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
149      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
150      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
151      case DeclSpec::TSW_longlong:    Result =Context.UnsignedLongLongTy; break;
152      }
153    }
154    break;
155  }
156  case DeclSpec::TST_float: Result = Context.FloatTy; break;
157  case DeclSpec::TST_double:
158    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
159      Result = Context.LongDoubleTy;
160    else
161      Result = Context.DoubleTy;
162    break;
163  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
164  case DeclSpec::TST_decimal32:    // _Decimal32
165  case DeclSpec::TST_decimal64:    // _Decimal64
166  case DeclSpec::TST_decimal128:   // _Decimal128
167    assert(0 && "FIXME: GNU decimal extensions not supported yet!");
168  case DeclSpec::TST_class:
169  case DeclSpec::TST_enum:
170  case DeclSpec::TST_union:
171  case DeclSpec::TST_struct: {
172    Decl *D = static_cast<Decl *>(DS.getTypeRep());
173    assert(D && "Didn't get a decl for a class/enum/union/struct?");
174    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
175           DS.getTypeSpecSign() == 0 &&
176           "Can't handle qualifiers on typedef names yet!");
177    // TypeQuals handled by caller.
178    Result = Context.getTypeDeclType(cast<TypeDecl>(D));
179
180    if (D->isInvalidDecl())
181      isInvalid = true;
182    break;
183  }
184  case DeclSpec::TST_typename: {
185    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
186           DS.getTypeSpecSign() == 0 &&
187           "Can't handle qualifiers on typedef names yet!");
188    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
189
190    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
191      // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so
192      // we have this "hack" for now...
193      if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType())
194        Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(),
195                                                       (ObjCProtocolDecl**)PQ,
196                                               DS.getNumProtocolQualifiers());
197      else if (Result == Context.getObjCIdType())
198        // id<protocol-list>
199        Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
200                                                DS.getNumProtocolQualifiers());
201      else if (Result == Context.getObjCClassType()) {
202        if (DeclLoc.isInvalid())
203          DeclLoc = DS.getSourceRange().getBegin();
204        // Class<protocol-list>
205        Diag(DeclLoc, diag::err_qualified_class_unsupported)
206          << DS.getSourceRange();
207      } else {
208        if (DeclLoc.isInvalid())
209          DeclLoc = DS.getSourceRange().getBegin();
210        Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
211          << DS.getSourceRange();
212        isInvalid = true;
213      }
214    }
215
216    // If this is a reference to an invalid typedef, propagate the invalidity.
217    if (TypedefType *TDT = dyn_cast<TypedefType>(Result))
218      if (TDT->getDecl()->isInvalidDecl())
219        isInvalid = true;
220
221    // TypeQuals handled by caller.
222    break;
223  }
224  case DeclSpec::TST_typeofType:
225    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
226    assert(!Result.isNull() && "Didn't get a type for typeof?");
227    // TypeQuals handled by caller.
228    Result = Context.getTypeOfType(Result);
229    break;
230  case DeclSpec::TST_typeofExpr: {
231    Expr *E = static_cast<Expr *>(DS.getTypeRep());
232    assert(E && "Didn't get an expression for typeof?");
233    // TypeQuals handled by caller.
234    Result = Context.getTypeOfExprType(E);
235    break;
236  }
237  case DeclSpec::TST_error:
238    Result = Context.IntTy;
239    isInvalid = true;
240    break;
241  }
242
243  // Handle complex types.
244  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
245    if (getLangOptions().Freestanding)
246      Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
247    Result = Context.getComplexType(Result);
248  }
249
250  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
251         "FIXME: imaginary types not supported yet!");
252
253  // See if there are any attributes on the declspec that apply to the type (as
254  // opposed to the decl).
255  if (const AttributeList *AL = DS.getAttributes())
256    ProcessTypeAttributeList(Result, AL);
257
258  // Apply const/volatile/restrict qualifiers to T.
259  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
260
261    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
262    // or incomplete types shall not be restrict-qualified."  C++ also allows
263    // restrict-qualified references.
264    if (TypeQuals & QualType::Restrict) {
265      if (Result->isPointerType() || Result->isReferenceType()) {
266        QualType EltTy = Result->isPointerType() ?
267          Result->getAsPointerType()->getPointeeType() :
268          Result->getAsReferenceType()->getPointeeType();
269
270        // If we have a pointer or reference, the pointee must have an object
271        // incomplete type.
272        if (!EltTy->isIncompleteOrObjectType()) {
273          Diag(DS.getRestrictSpecLoc(),
274               diag::err_typecheck_invalid_restrict_invalid_pointee)
275            << EltTy << DS.getSourceRange();
276          TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
277        }
278      } else {
279        Diag(DS.getRestrictSpecLoc(),
280             diag::err_typecheck_invalid_restrict_not_pointer)
281          << Result << DS.getSourceRange();
282        TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
283      }
284    }
285
286    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
287    // of a function type includes any type qualifiers, the behavior is
288    // undefined."
289    if (Result->isFunctionType() && TypeQuals) {
290      // Get some location to point at, either the C or V location.
291      SourceLocation Loc;
292      if (TypeQuals & QualType::Const)
293        Loc = DS.getConstSpecLoc();
294      else {
295        assert((TypeQuals & QualType::Volatile) &&
296               "Has CV quals but not C or V?");
297        Loc = DS.getVolatileSpecLoc();
298      }
299      Diag(Loc, diag::warn_typecheck_function_qualifiers)
300        << Result << DS.getSourceRange();
301    }
302
303    // C++ [dcl.ref]p1:
304    //   Cv-qualified references are ill-formed except when the
305    //   cv-qualifiers are introduced through the use of a typedef
306    //   (7.1.3) or of a template type argument (14.3), in which
307    //   case the cv-qualifiers are ignored.
308    // FIXME: Shouldn't we be checking SCS_typedef here?
309    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
310        TypeQuals && Result->isReferenceType()) {
311      TypeQuals &= ~QualType::Const;
312      TypeQuals &= ~QualType::Volatile;
313    }
314
315    Result = Result.getQualifiedType(TypeQuals);
316  }
317  return Result;
318}
319
320static std::string getPrintableNameForEntity(DeclarationName Entity) {
321  if (Entity)
322    return Entity.getAsString();
323
324  return "type name";
325}
326
327/// \brief Build a pointer type.
328///
329/// \param T The type to which we'll be building a pointer.
330///
331/// \param Quals The cvr-qualifiers to be applied to the pointer type.
332///
333/// \param Loc The location of the entity whose type involves this
334/// pointer type or, if there is no such entity, the location of the
335/// type that will have pointer type.
336///
337/// \param Entity The name of the entity that involves the pointer
338/// type, if known.
339///
340/// \returns A suitable pointer type, if there are no
341/// errors. Otherwise, returns a NULL type.
342QualType Sema::BuildPointerType(QualType T, unsigned Quals,
343                                SourceLocation Loc, DeclarationName Entity) {
344  if (T->isReferenceType()) {
345    // C++ 8.3.2p4: There shall be no ... pointers to references ...
346    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
347      << getPrintableNameForEntity(Entity);
348    return QualType();
349  }
350
351  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
352  // object or incomplete types shall not be restrict-qualified."
353  if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
354    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
355      << T;
356    Quals &= ~QualType::Restrict;
357  }
358
359  // Build the pointer type.
360  return Context.getPointerType(T).getQualifiedType(Quals);
361}
362
363/// \brief Build a reference type.
364///
365/// \param T The type to which we'll be building a reference.
366///
367/// \param Quals The cvr-qualifiers to be applied to the reference type.
368///
369/// \param Loc The location of the entity whose type involves this
370/// reference type or, if there is no such entity, the location of the
371/// type that will have reference type.
372///
373/// \param Entity The name of the entity that involves the reference
374/// type, if known.
375///
376/// \returns A suitable reference type, if there are no
377/// errors. Otherwise, returns a NULL type.
378QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals,
379                                  SourceLocation Loc, DeclarationName Entity) {
380  if (LValueRef) {
381    if (const RValueReferenceType *R = T->getAsRValueReferenceType()) {
382      // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
383      //   reference to a type T, and attempt to create the type "lvalue
384      //   reference to cv TD" creates the type "lvalue reference to T".
385      // We use the qualifiers (restrict or none) of the original reference,
386      // not the new ones. This is consistent with GCC.
387      return Context.getLValueReferenceType(R->getPointeeType()).
388               getQualifiedType(T.getCVRQualifiers());
389    }
390  }
391  if (T->isReferenceType()) {
392    // C++ [dcl.ref]p4: There shall be no references to references.
393    //
394    // According to C++ DR 106, references to references are only
395    // diagnosed when they are written directly (e.g., "int & &"),
396    // but not when they happen via a typedef:
397    //
398    //   typedef int& intref;
399    //   typedef intref& intref2;
400    //
401    // Parser::ParserDeclaratorInternal diagnoses the case where
402    // references are written directly; here, we handle the
403    // collapsing of references-to-references as described in C++
404    // DR 106 and amended by C++ DR 540.
405    return T;
406  }
407
408  // C++ [dcl.ref]p1:
409  //   A declarator that specifies the type “reference to cv void”
410  //   is ill-formed.
411  if (T->isVoidType()) {
412    Diag(Loc, diag::err_reference_to_void);
413    return QualType();
414  }
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 ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
419    Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
420      << T;
421    Quals &= ~QualType::Restrict;
422  }
423
424  // C++ [dcl.ref]p1:
425  //   [...] Cv-qualified references are ill-formed except when the
426  //   cv-qualifiers are introduced through the use of a typedef
427  //   (7.1.3) or of a template type argument (14.3), in which case
428  //   the cv-qualifiers are ignored.
429  //
430  // We diagnose extraneous cv-qualifiers for the non-typedef,
431  // non-template type argument case within the parser. Here, we just
432  // ignore any extraneous cv-qualifiers.
433  Quals &= ~QualType::Const;
434  Quals &= ~QualType::Volatile;
435
436  // Handle restrict on references.
437  if (LValueRef)
438    return Context.getLValueReferenceType(T).getQualifiedType(Quals);
439  return Context.getRValueReferenceType(T).getQualifiedType(Quals);
440}
441
442/// \brief Build an array type.
443///
444/// \param T The type of each element in the array.
445///
446/// \param ASM C99 array size modifier (e.g., '*', 'static').
447///
448/// \param ArraySize Expression describing the size of the array.
449///
450/// \param Quals The cvr-qualifiers to be applied to the array's
451/// element type.
452///
453/// \param Loc The location of the entity whose type involves this
454/// array type or, if there is no such entity, the location of the
455/// type that will have array type.
456///
457/// \param Entity The name of the entity that involves the array
458/// type, if known.
459///
460/// \returns A suitable array type, if there are no errors. Otherwise,
461/// returns a NULL type.
462QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
463                              Expr *ArraySize, unsigned Quals,
464                              SourceLocation Loc, DeclarationName Entity) {
465  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
466  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
467  if (RequireCompleteType(Loc, T,
468                             diag::err_illegal_decl_array_incomplete_type))
469    return QualType();
470
471  if (T->isFunctionType()) {
472    Diag(Loc, diag::err_illegal_decl_array_of_functions)
473      << getPrintableNameForEntity(Entity);
474    return QualType();
475  }
476
477  // C++ 8.3.2p4: There shall be no ... arrays of references ...
478  if (T->isReferenceType()) {
479    Diag(Loc, diag::err_illegal_decl_array_of_references)
480      << getPrintableNameForEntity(Entity);
481    return QualType();
482  }
483
484  if (const RecordType *EltTy = T->getAsRecordType()) {
485    // If the element type is a struct or union that contains a variadic
486    // array, accept it as a GNU extension: C99 6.7.2.1p2.
487    if (EltTy->getDecl()->hasFlexibleArrayMember())
488      Diag(Loc, diag::ext_flexible_array_in_array) << T;
489  } else if (T->isObjCInterfaceType()) {
490    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
491    return QualType();
492  }
493
494  // C99 6.7.5.2p1: The size expression shall have integer type.
495  if (ArraySize && !ArraySize->isTypeDependent() &&
496      !ArraySize->getType()->isIntegerType()) {
497    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
498      << ArraySize->getType() << ArraySize->getSourceRange();
499    ArraySize->Destroy(Context);
500    return QualType();
501  }
502  llvm::APSInt ConstVal(32);
503  if (!ArraySize) {
504    if (ASM == ArrayType::Star)
505      T = Context.getVariableArrayType(T, 0, ASM, Quals);
506    else
507      T = Context.getIncompleteArrayType(T, ASM, Quals);
508  } else if (ArraySize->isValueDependent()) {
509    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
510  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
511             (!T->isDependentType() && !T->isConstantSizeType())) {
512    // Per C99, a variable array is an array with either a non-constant
513    // size or an element type that has a non-constant-size
514    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
515  } else {
516    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
517    // have a value greater than zero.
518    if (ConstVal.isSigned()) {
519      if (ConstVal.isNegative()) {
520        Diag(ArraySize->getLocStart(),
521             diag::err_typecheck_negative_array_size)
522          << ArraySize->getSourceRange();
523        return QualType();
524      } else if (ConstVal == 0) {
525        // GCC accepts zero sized static arrays.
526        Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
527          << ArraySize->getSourceRange();
528      }
529    }
530    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
531  }
532  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
533  if (!getLangOptions().C99) {
534    if (ArraySize && !ArraySize->isTypeDependent() &&
535        !ArraySize->isValueDependent() &&
536        !ArraySize->isIntegerConstantExpr(Context))
537      Diag(Loc, diag::ext_vla);
538    else if (ASM != ArrayType::Normal || Quals != 0)
539      Diag(Loc, diag::ext_c99_array_usage);
540  }
541
542  return T;
543}
544
545/// \brief Build a function type.
546///
547/// This routine checks the function type according to C++ rules and
548/// under the assumption that the result type and parameter types have
549/// just been instantiated from a template. It therefore duplicates
550/// some of the behavior of GetTypeForDeclarator, but in a much
551/// simpler form that is only suitable for this narrow use case.
552///
553/// \param T The return type of the function.
554///
555/// \param ParamTypes The parameter types of the function. This array
556/// will be modified to account for adjustments to the types of the
557/// function parameters.
558///
559/// \param NumParamTypes The number of parameter types in ParamTypes.
560///
561/// \param Variadic Whether this is a variadic function type.
562///
563/// \param Quals The cvr-qualifiers to be applied to the function type.
564///
565/// \param Loc The location of the entity whose type involves this
566/// function type or, if there is no such entity, the location of the
567/// type that will have function type.
568///
569/// \param Entity The name of the entity that involves the function
570/// type, if known.
571///
572/// \returns A suitable function type, if there are no
573/// errors. Otherwise, returns a NULL type.
574QualType Sema::BuildFunctionType(QualType T,
575                                 QualType *ParamTypes,
576                                 unsigned NumParamTypes,
577                                 bool Variadic, unsigned Quals,
578                                 SourceLocation Loc, DeclarationName Entity) {
579  if (T->isArrayType() || T->isFunctionType()) {
580    Diag(Loc, diag::err_func_returning_array_function) << T;
581    return QualType();
582  }
583
584  bool Invalid = false;
585  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
586    QualType ParamType = adjustParameterType(ParamTypes[Idx]);
587    if (ParamType->isVoidType()) {
588      Diag(Loc, diag::err_param_with_void_type);
589      Invalid = true;
590    }
591
592    ParamTypes[Idx] = ParamType;
593  }
594
595  if (Invalid)
596    return QualType();
597
598  return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
599                                 Quals);
600}
601
602/// GetTypeForDeclarator - Convert the type for the specified
603/// declarator to Type instances. Skip the outermost Skip type
604/// objects.
605QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip) {
606  bool OmittedReturnType = false;
607
608  if (D.getContext() == Declarator::BlockLiteralContext
609      && Skip == 0
610      && !D.getDeclSpec().hasTypeSpecifier()
611      && (D.getNumTypeObjects() == 0
612          || (D.getNumTypeObjects() == 1
613              && D.getTypeObject(0).Kind == DeclaratorChunk::Function)))
614    OmittedReturnType = true;
615
616  // long long is a C99 feature.
617  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
618      D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
619    Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
620
621  // Determine the type of the declarator. Not all forms of declarator
622  // have a type.
623  QualType T;
624  switch (D.getKind()) {
625  case Declarator::DK_Abstract:
626  case Declarator::DK_Normal:
627  case Declarator::DK_Operator: {
628    const DeclSpec &DS = D.getDeclSpec();
629    if (OmittedReturnType) {
630      // We default to a dependent type initially.  Can be modified by
631      // the first return statement.
632      T = Context.DependentTy;
633    } else {
634      bool isInvalid = false;
635      T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid);
636      if (isInvalid)
637        D.setInvalidType(true);
638    }
639    break;
640  }
641
642  case Declarator::DK_Constructor:
643  case Declarator::DK_Destructor:
644  case Declarator::DK_Conversion:
645    // Constructors and destructors don't have return types. Use
646    // "void" instead. Conversion operators will check their return
647    // types separately.
648    T = Context.VoidTy;
649    break;
650  }
651
652  // The name we're declaring, if any.
653  DeclarationName Name;
654  if (D.getIdentifier())
655    Name = D.getIdentifier();
656
657  // Walk the DeclTypeInfo, building the recursive type as we go.
658  // DeclTypeInfos are ordered from the identifier out, which is
659  // opposite of what we want :).
660  for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
661    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
662    switch (DeclType.Kind) {
663    default: assert(0 && "Unknown decltype!");
664    case DeclaratorChunk::BlockPointer:
665      // If blocks are disabled, emit an error.
666      if (!LangOpts.Blocks)
667        Diag(DeclType.Loc, diag::err_blocks_disable);
668
669      if (DeclType.Cls.TypeQuals)
670        Diag(D.getIdentifierLoc(), diag::err_qualified_block_pointer_type);
671      if (!T.getTypePtr()->isFunctionType())
672        Diag(D.getIdentifierLoc(), diag::err_nonfunction_block_type);
673      else
674        T = Context.getBlockPointerType(T);
675      break;
676    case DeclaratorChunk::Pointer:
677      T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
678      break;
679    case DeclaratorChunk::Reference:
680      T = BuildReferenceType(T, DeclType.Ref.LValueRef,
681                             DeclType.Ref.HasRestrict ? QualType::Restrict : 0,
682                             DeclType.Loc, Name);
683      break;
684    case DeclaratorChunk::Array: {
685      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
686      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
687      ArrayType::ArraySizeModifier ASM;
688      if (ATI.isStar)
689        ASM = ArrayType::Star;
690      else if (ATI.hasStatic)
691        ASM = ArrayType::Static;
692      else
693        ASM = ArrayType::Normal;
694      if (ASM == ArrayType::Star &&
695          D.getContext() != Declarator::PrototypeContext) {
696        // FIXME: This check isn't quite right: it allows star in prototypes
697        // for function definitions, and disallows some edge cases detailed
698        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
699        Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
700        ASM = ArrayType::Normal;
701        D.setInvalidType(true);
702      }
703      T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, DeclType.Loc, Name);
704      break;
705    }
706    case DeclaratorChunk::Function: {
707      // If the function declarator has a prototype (i.e. it is not () and
708      // does not have a K&R-style identifier list), then the arguments are part
709      // of the type, otherwise the argument list is ().
710      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
711
712      // C99 6.7.5.3p1: The return type may not be a function or array type.
713      if (T->isArrayType() || T->isFunctionType()) {
714        Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
715        T = Context.IntTy;
716        D.setInvalidType(true);
717      }
718
719      if (FTI.NumArgs == 0) {
720        if (getLangOptions().CPlusPlus) {
721          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
722          // function takes no arguments.
723          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic,FTI.TypeQuals);
724        } else if (FTI.isVariadic) {
725          // We allow a zero-parameter variadic function in C if the
726          // function is marked with the "overloadable"
727          // attribute. Scan for this attribute now.
728          bool Overloadable = false;
729          for (const AttributeList *Attrs = D.getAttributes();
730               Attrs; Attrs = Attrs->getNext()) {
731            if (Attrs->getKind() == AttributeList::AT_overloadable) {
732              Overloadable = true;
733              break;
734            }
735          }
736
737          if (!Overloadable)
738            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
739          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
740        } else {
741          // Simple void foo(), where the incoming T is the result type.
742          T = Context.getFunctionNoProtoType(T);
743        }
744      } else if (FTI.ArgInfo[0].Param == 0) {
745        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
746        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
747      } else {
748        // Otherwise, we have a function with an argument list that is
749        // potentially variadic.
750        llvm::SmallVector<QualType, 16> ArgTys;
751
752        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
753          ParmVarDecl *Param =
754            cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
755          QualType ArgTy = Param->getType();
756          assert(!ArgTy.isNull() && "Couldn't parse type?");
757
758          // Adjust the parameter type.
759          assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
760
761          // Look for 'void'.  void is allowed only as a single argument to a
762          // function with no other parameters (C99 6.7.5.3p10).  We record
763          // int(void) as a FunctionProtoType with an empty argument list.
764          if (ArgTy->isVoidType()) {
765            // If this is something like 'float(int, void)', reject it.  'void'
766            // is an incomplete type (C99 6.2.5p19) and function decls cannot
767            // have arguments of incomplete type.
768            if (FTI.NumArgs != 1 || FTI.isVariadic) {
769              Diag(DeclType.Loc, diag::err_void_only_param);
770              ArgTy = Context.IntTy;
771              Param->setType(ArgTy);
772            } else if (FTI.ArgInfo[i].Ident) {
773              // Reject, but continue to parse 'int(void abc)'.
774              Diag(FTI.ArgInfo[i].IdentLoc,
775                   diag::err_param_with_void_type);
776              ArgTy = Context.IntTy;
777              Param->setType(ArgTy);
778            } else {
779              // Reject, but continue to parse 'float(const void)'.
780              if (ArgTy.getCVRQualifiers())
781                Diag(DeclType.Loc, diag::err_void_param_qualified);
782
783              // Do not add 'void' to the ArgTys list.
784              break;
785            }
786          } else if (!FTI.hasPrototype) {
787            if (ArgTy->isPromotableIntegerType()) {
788              ArgTy = Context.IntTy;
789            } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
790              if (BTy->getKind() == BuiltinType::Float)
791                ArgTy = Context.DoubleTy;
792            }
793          }
794
795          ArgTys.push_back(ArgTy);
796        }
797        T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
798                                    FTI.isVariadic, FTI.TypeQuals);
799      }
800      break;
801    }
802    case DeclaratorChunk::MemberPointer:
803      // The scope spec must refer to a class, or be dependent.
804      DeclContext *DC = computeDeclContext(DeclType.Mem.Scope());
805      QualType ClsType;
806      // FIXME: Extend for dependent types when it's actually supported.
807      // See ActOnCXXNestedNameSpecifier.
808      if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC)) {
809        ClsType = Context.getTagDeclType(RD);
810      } else {
811        if (DC) {
812          Diag(DeclType.Mem.Scope().getBeginLoc(),
813               diag::err_illegal_decl_mempointer_in_nonclass)
814            << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
815            << DeclType.Mem.Scope().getRange();
816        }
817        D.setInvalidType(true);
818        ClsType = Context.IntTy;
819      }
820
821      // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
822      //   with reference type, or "cv void."
823      if (T->isReferenceType()) {
824        Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference)
825          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
826        D.setInvalidType(true);
827        T = Context.IntTy;
828      }
829      if (T->isVoidType()) {
830        Diag(DeclType.Loc, diag::err_illegal_decl_mempointer_to_void)
831          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
832        T = Context.IntTy;
833      }
834
835      // Enforce C99 6.7.3p2: "Types other than pointer types derived from
836      // object or incomplete types shall not be restrict-qualified."
837      if ((DeclType.Mem.TypeQuals & QualType::Restrict) &&
838          !T->isIncompleteOrObjectType()) {
839        Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
840          << T;
841        DeclType.Mem.TypeQuals &= ~QualType::Restrict;
842      }
843
844      T = Context.getMemberPointerType(T, ClsType.getTypePtr()).
845                    getQualifiedType(DeclType.Mem.TypeQuals);
846
847      break;
848    }
849
850    if (T.isNull()) {
851      D.setInvalidType(true);
852      T = Context.IntTy;
853    }
854
855    // See if there are any attributes on this declarator chunk.
856    if (const AttributeList *AL = DeclType.getAttrs())
857      ProcessTypeAttributeList(T, AL);
858  }
859
860  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
861    const FunctionProtoType *FnTy = T->getAsFunctionProtoType();
862    assert(FnTy && "Why oh why is there not a FunctionProtoType here ?");
863
864    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
865    // for a nonstatic member function, the function type to which a pointer
866    // to member refers, or the top-level function type of a function typedef
867    // declaration.
868    if (FnTy->getTypeQuals() != 0 &&
869        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
870        ((D.getContext() != Declarator::MemberContext &&
871          (!D.getCXXScopeSpec().isSet() ||
872           !computeDeclContext(D.getCXXScopeSpec())->isRecord())) ||
873         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
874      if (D.isFunctionDeclarator())
875        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
876      else
877        Diag(D.getIdentifierLoc(),
878             diag::err_invalid_qualified_typedef_function_type_use);
879
880      // Strip the cv-quals from the type.
881      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
882                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0);
883    }
884  }
885
886  // If there were any type attributes applied to the decl itself (not the
887  // type, apply the type attribute to the type!)
888  if (const AttributeList *Attrs = D.getAttributes())
889    ProcessTypeAttributeList(T, Attrs);
890
891  return T;
892}
893
894/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
895/// declarator
896QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
897  ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
898  QualType T = MDecl->getResultType();
899  llvm::SmallVector<QualType, 16> ArgTys;
900
901  // Add the first two invisible argument types for self and _cmd.
902  if (MDecl->isInstanceMethod()) {
903    QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
904    selfTy = Context.getPointerType(selfTy);
905    ArgTys.push_back(selfTy);
906  } else
907    ArgTys.push_back(Context.getObjCIdType());
908  ArgTys.push_back(Context.getObjCSelType());
909
910  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
911       E = MDecl->param_end(); PI != E; ++PI) {
912    QualType ArgTy = (*PI)->getType();
913    assert(!ArgTy.isNull() && "Couldn't parse type?");
914    ArgTy = adjustParameterType(ArgTy);
915    ArgTys.push_back(ArgTy);
916  }
917  T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
918                              MDecl->isVariadic(), 0);
919  return T;
920}
921
922/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
923/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
924/// they point to and return true. If T1 and T2 aren't pointer types
925/// or pointer-to-member types, or if they are not similar at this
926/// level, returns false and leaves T1 and T2 unchanged. Top-level
927/// qualifiers on T1 and T2 are ignored. This function will typically
928/// be called in a loop that successively "unwraps" pointer and
929/// pointer-to-member types to compare them at each level.
930bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
931  const PointerType *T1PtrType = T1->getAsPointerType(),
932                    *T2PtrType = T2->getAsPointerType();
933  if (T1PtrType && T2PtrType) {
934    T1 = T1PtrType->getPointeeType();
935    T2 = T2PtrType->getPointeeType();
936    return true;
937  }
938
939  const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
940                          *T2MPType = T2->getAsMemberPointerType();
941  if (T1MPType && T2MPType &&
942      Context.getCanonicalType(T1MPType->getClass()) ==
943      Context.getCanonicalType(T2MPType->getClass())) {
944    T1 = T1MPType->getPointeeType();
945    T2 = T2MPType->getPointeeType();
946    return true;
947  }
948  return false;
949}
950
951Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
952  // C99 6.7.6: Type names have no identifier.  This is already validated by
953  // the parser.
954  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
955
956  QualType T = GetTypeForDeclarator(D, S);
957  if (D.isInvalidType())
958    return true;
959
960  // Check that there are no default arguments (C++ only).
961  if (getLangOptions().CPlusPlus)
962    CheckExtraCXXDefaultArguments(D);
963
964  return T.getAsOpaquePtr();
965}
966
967
968
969//===----------------------------------------------------------------------===//
970// Type Attribute Processing
971//===----------------------------------------------------------------------===//
972
973/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
974/// specified type.  The attribute contains 1 argument, the id of the address
975/// space for the type.
976static void HandleAddressSpaceTypeAttribute(QualType &Type,
977                                            const AttributeList &Attr, Sema &S){
978  // If this type is already address space qualified, reject it.
979  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
980  // for two or more different address spaces."
981  if (Type.getAddressSpace()) {
982    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
983    return;
984  }
985
986  // Check the attribute arguments.
987  if (Attr.getNumArgs() != 1) {
988    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
989    return;
990  }
991  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
992  llvm::APSInt addrSpace(32);
993  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
994    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
995      << ASArgExpr->getSourceRange();
996    return;
997  }
998
999  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1000  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1001}
1002
1003/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1004/// specified type.  The attribute contains 1 argument, weak or strong.
1005static void HandleObjCGCTypeAttribute(QualType &Type,
1006                                      const AttributeList &Attr, Sema &S) {
1007  if (Type.getObjCGCAttr() != QualType::GCNone) {
1008    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1009    return;
1010  }
1011
1012  // Check the attribute arguments.
1013  if (!Attr.getParameterName()) {
1014    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1015      << "objc_gc" << 1;
1016    return;
1017  }
1018  QualType::GCAttrTypes GCAttr;
1019  if (Attr.getNumArgs() != 0) {
1020    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1021    return;
1022  }
1023  if (Attr.getParameterName()->isStr("weak"))
1024    GCAttr = QualType::Weak;
1025  else if (Attr.getParameterName()->isStr("strong"))
1026    GCAttr = QualType::Strong;
1027  else {
1028    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1029      << "objc_gc" << Attr.getParameterName();
1030    return;
1031  }
1032
1033  Type = S.Context.getObjCGCQualType(Type, GCAttr);
1034}
1035
1036void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1037  // Scan through and apply attributes to this type where it makes sense.  Some
1038  // attributes (such as __address_space__, __vector_size__, etc) apply to the
1039  // type, but others can be present in the type specifiers even though they
1040  // apply to the decl.  Here we apply type attributes and ignore the rest.
1041  for (; AL; AL = AL->getNext()) {
1042    // If this is an attribute we can handle, do so now, otherwise, add it to
1043    // the LeftOverAttrs list for rechaining.
1044    switch (AL->getKind()) {
1045    default: break;
1046    case AttributeList::AT_address_space:
1047      HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1048      break;
1049    case AttributeList::AT_objc_gc:
1050      HandleObjCGCTypeAttribute(Result, *AL, *this);
1051      break;
1052    }
1053  }
1054}
1055
1056/// @brief Ensure that the type T is a complete type.
1057///
1058/// This routine checks whether the type @p T is complete in any
1059/// context where a complete type is required. If @p T is a complete
1060/// type, returns false. If @p T is a class template specialization,
1061/// this routine then attempts to perform class template
1062/// instantiation. If instantiation fails, or if @p T is incomplete
1063/// and cannot be completed, issues the diagnostic @p diag (giving it
1064/// the type @p T) and returns true.
1065///
1066/// @param Loc  The location in the source that the incomplete type
1067/// diagnostic should refer to.
1068///
1069/// @param T  The type that this routine is examining for completeness.
1070///
1071/// @param diag The diagnostic value (e.g.,
1072/// @c diag::err_typecheck_decl_incomplete_type) that will be used
1073/// for the error message if @p T is incomplete.
1074///
1075/// @param Range1  An optional range in the source code that will be a
1076/// part of the "incomplete type" error message.
1077///
1078/// @param Range2  An optional range in the source code that will be a
1079/// part of the "incomplete type" error message.
1080///
1081/// @param PrintType If non-NULL, the type that should be printed
1082/// instead of @p T. This parameter should be used when the type that
1083/// we're checking for incompleteness isn't the type that should be
1084/// displayed to the user, e.g., when T is a type and PrintType is a
1085/// pointer to T.
1086///
1087/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1088/// @c false otherwise.
1089bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag,
1090                               SourceRange Range1, SourceRange Range2,
1091                               QualType PrintType) {
1092  // If we have a complete type, we're done.
1093  if (!T->isIncompleteType())
1094    return false;
1095
1096  // If we have a class template specialization or a class member of a
1097  // class template specialization, try to instantiate it.
1098  if (const RecordType *Record = T->getAsRecordType()) {
1099    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1100          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1101      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1102        // Update the class template specialization's location to
1103        // refer to the point of instantiation.
1104        if (Loc.isValid())
1105          ClassTemplateSpec->setLocation(Loc);
1106        return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1107                                             /*ExplicitInstantiation=*/false);
1108      }
1109    } else if (CXXRecordDecl *Rec
1110                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1111      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1112        // Find the class template specialization that surrounds this
1113        // member class.
1114        ClassTemplateSpecializationDecl *Spec = 0;
1115        for (DeclContext *Parent = Rec->getDeclContext();
1116             Parent && !Spec; Parent = Parent->getParent())
1117          Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent);
1118        assert(Spec && "Not a member of a class template specialization?");
1119        return InstantiateClass(Loc, Rec, Pattern,
1120                                Spec->getTemplateArgs(),
1121                                Spec->getNumTemplateArgs());
1122      }
1123    }
1124  }
1125
1126  if (PrintType.isNull())
1127    PrintType = T;
1128
1129  // We have an incomplete type. Produce a diagnostic.
1130  Diag(Loc, diag) << PrintType << Range1 << Range2;
1131
1132  // If the type was a forward declaration of a class/struct/union
1133  // type, produce
1134  const TagType *Tag = 0;
1135  if (const RecordType *Record = T->getAsRecordType())
1136    Tag = Record;
1137  else if (const EnumType *Enum = T->getAsEnumType())
1138    Tag = Enum;
1139
1140  if (Tag && !Tag->getDecl()->isInvalidDecl())
1141    Diag(Tag->getDecl()->getLocation(),
1142         Tag->isBeingDefined() ? diag::note_type_being_defined
1143                               : diag::note_forward_declaration)
1144        << QualType(Tag, 0);
1145
1146  return true;
1147}
1148
1149/// \brief Retrieve a version of the type 'T' that is qualified by the
1150/// nested-name-specifier contained in SS.
1151QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1152  if (!SS.isSet() || SS.isInvalid() || T.isNull())
1153    return T;
1154
1155  NestedNameSpecifier *NNS
1156    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1157  return Context.getQualifiedNameType(NNS, T);
1158}
1159