SemaType.cpp revision 5fd818bec0c21e3072679d1a9a522be2649405d8
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/Expr.h"
18#include "clang/Parse/DeclSpec.h"
19using namespace clang;
20
21/// \brief Convert the specified declspec to the appropriate type
22/// object.
23/// \param DS  the declaration specifiers
24/// \returns The type described by the declaration specifiers, or NULL
25/// if there was an error.
26QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS) {
27  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
28  // checking.
29  QualType Result;
30
31  switch (DS.getTypeSpecType()) {
32  case DeclSpec::TST_void:
33    Result = Context.VoidTy;
34    break;
35  case DeclSpec::TST_char:
36    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
37      Result = Context.CharTy;
38    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
39      Result = Context.SignedCharTy;
40    else {
41      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
42             "Unknown TSS value");
43      Result = Context.UnsignedCharTy;
44    }
45    break;
46  case DeclSpec::TST_wchar:
47    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
48      Result = Context.WCharTy;
49    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
50      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
51        << DS.getSpecifierName(DS.getTypeSpecType());
52      Result = Context.getSignedWCharType();
53    } else {
54      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
55        "Unknown TSS value");
56      Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
57        << DS.getSpecifierName(DS.getTypeSpecType());
58      Result = Context.getUnsignedWCharType();
59    }
60    break;
61  case DeclSpec::TST_unspecified:
62    // "<proto1,proto2>" is an objc qualified ID with a missing id.
63    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
64      Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
65                                              DS.getNumProtocolQualifiers());
66      break;
67    }
68
69    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
70    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
71    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
72    // Note that the one exception to this is function definitions, which are
73    // allowed to be completely missing a declspec.  This is handled in the
74    // parser already though by it pretending to have seen an 'int' in this
75    // case.
76    if (getLangOptions().ImplicitInt) {
77      if ((DS.getParsedSpecifiers() & (DeclSpec::PQ_StorageClassSpecifier |
78                                       DeclSpec::PQ_TypeSpecifier |
79                                       DeclSpec::PQ_TypeQualifier)) == 0)
80        Diag(DS.getSourceRange().getBegin(), diag::ext_missing_declspec);
81    } else if (!DS.hasTypeSpecifier()) {
82      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
83      // "At least one type specifier shall be given in the declaration
84      // specifiers in each declaration, and in the specifier-qualifier list in
85      // each struct declaration and type name."
86      // FIXME: Does Microsoft really have the implicit int extension in C++?
87      unsigned DK = getLangOptions().CPlusPlus && !getLangOptions().Microsoft?
88          diag::err_missing_type_specifier
89        : diag::ext_missing_type_specifier;
90      Diag(DS.getSourceRange().getBegin(), DK);
91    }
92
93    // FALL THROUGH.
94  case DeclSpec::TST_int: {
95    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
96      switch (DS.getTypeSpecWidth()) {
97      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
98      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
99      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
100      case DeclSpec::TSW_longlong:    Result = Context.LongLongTy; break;
101      }
102    } else {
103      switch (DS.getTypeSpecWidth()) {
104      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
105      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
106      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
107      case DeclSpec::TSW_longlong:    Result =Context.UnsignedLongLongTy; break;
108      }
109    }
110    break;
111  }
112  case DeclSpec::TST_float: Result = Context.FloatTy; break;
113  case DeclSpec::TST_double:
114    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
115      Result = Context.LongDoubleTy;
116    else
117      Result = Context.DoubleTy;
118    break;
119  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
120  case DeclSpec::TST_decimal32:    // _Decimal32
121  case DeclSpec::TST_decimal64:    // _Decimal64
122  case DeclSpec::TST_decimal128:   // _Decimal128
123    assert(0 && "FIXME: GNU decimal extensions not supported yet!");
124  case DeclSpec::TST_class:
125  case DeclSpec::TST_enum:
126  case DeclSpec::TST_union:
127  case DeclSpec::TST_struct: {
128    Decl *D = static_cast<Decl *>(DS.getTypeRep());
129    assert(D && "Didn't get a decl for a class/enum/union/struct?");
130    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
131           DS.getTypeSpecSign() == 0 &&
132           "Can't handle qualifiers on typedef names yet!");
133    // TypeQuals handled by caller.
134    Result = Context.getTypeDeclType(cast<TypeDecl>(D));
135    break;
136  }
137  case DeclSpec::TST_typename: {
138    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
139           DS.getTypeSpecSign() == 0 &&
140           "Can't handle qualifiers on typedef names yet!");
141    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
142
143    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
144      // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so
145      // we have this "hack" for now...
146      if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType())
147        Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(),
148                                                       (ObjCProtocolDecl**)PQ,
149                                               DS.getNumProtocolQualifiers());
150      else if (Result == Context.getObjCIdType())
151        // id<protocol-list>
152        Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
153                                                DS.getNumProtocolQualifiers());
154      else if (Result == Context.getObjCClassType())
155        // Class<protocol-list>
156        Diag(DS.getSourceRange().getBegin(),
157             diag::err_qualified_class_unsupported) << DS.getSourceRange();
158      else
159        Diag(DS.getSourceRange().getBegin(),
160             diag::err_invalid_protocol_qualifiers) << DS.getSourceRange();
161    }
162    // TypeQuals handled by caller.
163    break;
164  }
165  case DeclSpec::TST_typeofType:
166    Result = QualType::getFromOpaquePtr(DS.getTypeRep());
167    assert(!Result.isNull() && "Didn't get a type for typeof?");
168    // TypeQuals handled by caller.
169    Result = Context.getTypeOfType(Result);
170    break;
171  case DeclSpec::TST_typeofExpr: {
172    Expr *E = static_cast<Expr *>(DS.getTypeRep());
173    assert(E && "Didn't get an expression for typeof?");
174    // TypeQuals handled by caller.
175    Result = Context.getTypeOfExpr(E);
176    break;
177  }
178  case DeclSpec::TST_error:
179    return QualType();
180  }
181
182  // Handle complex types.
183  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
184    if (getLangOptions().Freestanding)
185      Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
186    Result = Context.getComplexType(Result);
187  }
188
189  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
190         "FIXME: imaginary types not supported yet!");
191
192  // See if there are any attributes on the declspec that apply to the type (as
193  // opposed to the decl).
194  if (const AttributeList *AL = DS.getAttributes())
195    ProcessTypeAttributeList(Result, AL);
196
197  // Apply const/volatile/restrict qualifiers to T.
198  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
199
200    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
201    // or incomplete types shall not be restrict-qualified."  C++ also allows
202    // restrict-qualified references.
203    if (TypeQuals & QualType::Restrict) {
204      if (const PointerLikeType *PT = Result->getAsPointerLikeType()) {
205        QualType EltTy = PT->getPointeeType();
206
207        // If we have a pointer or reference, the pointee must have an object or
208        // incomplete type.
209        if (!EltTy->isIncompleteOrObjectType()) {
210          Diag(DS.getRestrictSpecLoc(),
211               diag::err_typecheck_invalid_restrict_invalid_pointee)
212            << EltTy << DS.getSourceRange();
213          TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
214        }
215      } else {
216        Diag(DS.getRestrictSpecLoc(),
217             diag::err_typecheck_invalid_restrict_not_pointer)
218          << Result << DS.getSourceRange();
219        TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
220      }
221    }
222
223    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
224    // of a function type includes any type qualifiers, the behavior is
225    // undefined."
226    if (Result->isFunctionType() && TypeQuals) {
227      // Get some location to point at, either the C or V location.
228      SourceLocation Loc;
229      if (TypeQuals & QualType::Const)
230        Loc = DS.getConstSpecLoc();
231      else {
232        assert((TypeQuals & QualType::Volatile) &&
233               "Has CV quals but not C or V?");
234        Loc = DS.getVolatileSpecLoc();
235      }
236      Diag(Loc, diag::warn_typecheck_function_qualifiers)
237        << Result << DS.getSourceRange();
238    }
239
240    // C++ [dcl.ref]p1:
241    //   Cv-qualified references are ill-formed except when the
242    //   cv-qualifiers are introduced through the use of a typedef
243    //   (7.1.3) or of a template type argument (14.3), in which
244    //   case the cv-qualifiers are ignored.
245    // FIXME: Shouldn't we be checking SCS_typedef here?
246    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
247        TypeQuals && Result->isReferenceType()) {
248      TypeQuals &= ~QualType::Const;
249      TypeQuals &= ~QualType::Volatile;
250    }
251
252    Result = Result.getQualifiedType(TypeQuals);
253  }
254  return Result;
255}
256
257/// GetTypeForDeclarator - Convert the type for the specified
258/// declarator to Type instances. Skip the outermost Skip type
259/// objects.
260QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip) {
261  bool OmittedReturnType = false;
262
263  if (D.getContext() == Declarator::BlockLiteralContext
264      && Skip == 0
265      && !D.getDeclSpec().hasTypeSpecifier()
266      && (D.getNumTypeObjects() == 0
267          || (D.getNumTypeObjects() == 1
268              && D.getTypeObject(0).Kind == DeclaratorChunk::Function)))
269    OmittedReturnType = true;
270
271  // long long is a C99 feature.
272  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
273      D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
274    Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
275
276  // Determine the type of the declarator. Not all forms of declarator
277  // have a type.
278  QualType T;
279  switch (D.getKind()) {
280  case Declarator::DK_Abstract:
281  case Declarator::DK_Normal:
282  case Declarator::DK_Operator: {
283    const DeclSpec& DS = D.getDeclSpec();
284    if (OmittedReturnType)
285      // We default to a dependent type initially.  Can be modified by
286      // the first return statement.
287      T = Context.DependentTy;
288    else {
289      T = ConvertDeclSpecToType(DS);
290      if (T.isNull())
291        return T;
292    }
293    break;
294  }
295
296  case Declarator::DK_Constructor:
297  case Declarator::DK_Destructor:
298  case Declarator::DK_Conversion:
299    // Constructors and destructors don't have return types. Use
300    // "void" instead. Conversion operators will check their return
301    // types separately.
302    T = Context.VoidTy;
303    break;
304  }
305
306  // Walk the DeclTypeInfo, building the recursive type as we go.
307  // DeclTypeInfos are ordered from the identifier out, which is
308  // opposite of what we want :).
309  for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
310    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
311    switch (DeclType.Kind) {
312    default: assert(0 && "Unknown decltype!");
313    case DeclaratorChunk::BlockPointer:
314      if (DeclType.Cls.TypeQuals)
315        Diag(D.getIdentifierLoc(), diag::err_qualified_block_pointer_type);
316      if (!T.getTypePtr()->isFunctionType())
317        Diag(D.getIdentifierLoc(), diag::err_nonfunction_block_type);
318      else
319        T = Context.getBlockPointerType(T);
320      break;
321    case DeclaratorChunk::Pointer:
322      if (T->isReferenceType()) {
323        // C++ 8.3.2p4: There shall be no ... pointers to references ...
324        Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference)
325         << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
326        D.setInvalidType(true);
327        T = Context.IntTy;
328      }
329
330      // Enforce C99 6.7.3p2: "Types other than pointer types derived from
331      // object or incomplete types shall not be restrict-qualified."
332      if ((DeclType.Ptr.TypeQuals & QualType::Restrict) &&
333          !T->isIncompleteOrObjectType()) {
334        Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
335          << T;
336        DeclType.Ptr.TypeQuals &= ~QualType::Restrict;
337      }
338
339      // Apply the pointer typequals to the pointer object.
340      T = Context.getPointerType(T).getQualifiedType(DeclType.Ptr.TypeQuals);
341      break;
342    case DeclaratorChunk::Reference: {
343      // Whether we should suppress the creation of the reference.
344      bool SuppressReference = false;
345      if (T->isReferenceType()) {
346        // C++ [dcl.ref]p4: There shall be no references to references.
347        //
348        // According to C++ DR 106, references to references are only
349        // diagnosed when they are written directly (e.g., "int & &"),
350        // but not when they happen via a typedef:
351        //
352        //   typedef int& intref;
353        //   typedef intref& intref2;
354        //
355        // Parser::ParserDeclaratorInternal diagnoses the case where
356        // references are written directly; here, we handle the
357        // collapsing of references-to-references as described in C++
358        // DR 106 and amended by C++ DR 540.
359        SuppressReference = true;
360      }
361
362      // C++ [dcl.ref]p1:
363      //   A declarator that specifies the type “reference to cv void”
364      //   is ill-formed.
365      if (T->isVoidType()) {
366        Diag(DeclType.Loc, diag::err_reference_to_void);
367        D.setInvalidType(true);
368        T = Context.IntTy;
369      }
370
371      // Enforce C99 6.7.3p2: "Types other than pointer types derived from
372      // object or incomplete types shall not be restrict-qualified."
373      if (DeclType.Ref.HasRestrict &&
374          !T->isIncompleteOrObjectType()) {
375        Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
376          << T;
377        DeclType.Ref.HasRestrict = false;
378      }
379
380      if (!SuppressReference)
381        T = Context.getReferenceType(T);
382
383      // Handle restrict on references.
384      if (DeclType.Ref.HasRestrict)
385        T.addRestrict();
386      break;
387    }
388    case DeclaratorChunk::Array: {
389      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
390      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
391      ArrayType::ArraySizeModifier ASM;
392      if (ATI.isStar)
393        ASM = ArrayType::Star;
394      else if (ATI.hasStatic)
395        ASM = ArrayType::Static;
396      else
397        ASM = ArrayType::Normal;
398
399      // C99 6.7.5.2p1: If the element type is an incomplete or function type,
400      // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
401      if (DiagnoseIncompleteType(D.getIdentifierLoc(), T,
402                                 diag::err_illegal_decl_array_incomplete_type)) {
403        T = Context.IntTy;
404        D.setInvalidType(true);
405      } else if (T->isFunctionType()) {
406        Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_functions)
407          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
408        T = Context.getPointerType(T);
409        D.setInvalidType(true);
410      } else if (const ReferenceType *RT = T->getAsReferenceType()) {
411        // C++ 8.3.2p4: There shall be no ... arrays of references ...
412        Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_references)
413          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
414        T = RT->getPointeeType();
415        D.setInvalidType(true);
416      } else if (const RecordType *EltTy = T->getAsRecordType()) {
417        // If the element type is a struct or union that contains a variadic
418        // array, accept it as a GNU extension: C99 6.7.2.1p2.
419        if (EltTy->getDecl()->hasFlexibleArrayMember())
420          Diag(DeclType.Loc, diag::ext_flexible_array_in_array) << T;
421      } else if (T->isObjCInterfaceType()) {
422        Diag(DeclType.Loc, diag::warn_objc_array_of_interfaces) << T;
423      }
424
425      // C99 6.7.5.2p1: The size expression shall have integer type.
426      if (ArraySize && !ArraySize->getType()->isIntegerType()) {
427        Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
428          << ArraySize->getType() << ArraySize->getSourceRange();
429        D.setInvalidType(true);
430        ArraySize->Destroy(Context);
431        ATI.NumElts = ArraySize = 0;
432      }
433      llvm::APSInt ConstVal(32);
434      if (!ArraySize) {
435        T = Context.getIncompleteArrayType(T, ASM, ATI.TypeQuals);
436      } else if (ArraySize->isValueDependent()) {
437        T = Context.getDependentSizedArrayType(T, ArraySize, ASM, ATI.TypeQuals);
438      } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
439                 !T->isConstantSizeType()) {
440        // Per C99, a variable array is an array with either a non-constant
441        // size or an element type that has a non-constant-size
442        T = Context.getVariableArrayType(T, ArraySize, ASM, ATI.TypeQuals);
443      } else {
444        // C99 6.7.5.2p1: If the expression is a constant expression, it shall
445        // have a value greater than zero.
446        if (ConstVal.isSigned()) {
447          if (ConstVal.isNegative()) {
448            Diag(ArraySize->getLocStart(),
449                 diag::err_typecheck_negative_array_size)
450              << ArraySize->getSourceRange();
451            D.setInvalidType(true);
452          } else if (ConstVal == 0) {
453            // GCC accepts zero sized static arrays.
454            Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
455              << ArraySize->getSourceRange();
456          }
457        }
458        T = Context.getConstantArrayType(T, ConstVal, ASM, ATI.TypeQuals);
459      }
460      // If this is not C99, extwarn about VLA's and C99 array size modifiers.
461      if (!getLangOptions().C99) {
462        if (ArraySize && !ArraySize->isValueDependent() &&
463            !ArraySize->isIntegerConstantExpr(Context))
464          Diag(D.getIdentifierLoc(), diag::ext_vla);
465        else if (ASM != ArrayType::Normal || ATI.TypeQuals != 0)
466          Diag(D.getIdentifierLoc(), diag::ext_c99_array_usage);
467      }
468      break;
469    }
470    case DeclaratorChunk::Function: {
471      // If the function declarator has a prototype (i.e. it is not () and
472      // does not have a K&R-style identifier list), then the arguments are part
473      // of the type, otherwise the argument list is ().
474      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
475
476      // C99 6.7.5.3p1: The return type may not be a function or array type.
477      if (T->isArrayType() || T->isFunctionType()) {
478        Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
479        T = Context.IntTy;
480        D.setInvalidType(true);
481      }
482
483      if (FTI.NumArgs == 0) {
484        if (getLangOptions().CPlusPlus) {
485          // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
486          // function takes no arguments.
487          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic,FTI.TypeQuals);
488        } else if (FTI.isVariadic) {
489          // We allow a zero-parameter variadic function in C if the
490          // function is marked with the "overloadable"
491          // attribute. Scan for this attribute now.
492          bool Overloadable = false;
493          for (const AttributeList *Attrs = D.getAttributes();
494               Attrs; Attrs = Attrs->getNext()) {
495            if (Attrs->getKind() == AttributeList::AT_overloadable) {
496              Overloadable = true;
497              break;
498            }
499          }
500
501          if (!Overloadable)
502            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
503          T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
504        } else {
505          // Simple void foo(), where the incoming T is the result type.
506          T = Context.getFunctionTypeNoProto(T);
507        }
508      } else if (FTI.ArgInfo[0].Param == 0) {
509        // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
510        Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
511      } else {
512        // Otherwise, we have a function with an argument list that is
513        // potentially variadic.
514        llvm::SmallVector<QualType, 16> ArgTys;
515
516        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
517          ParmVarDecl *Param = (ParmVarDecl *)FTI.ArgInfo[i].Param;
518          QualType ArgTy = Param->getType();
519          assert(!ArgTy.isNull() && "Couldn't parse type?");
520          //
521          // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
522          // This matches the conversion that is done in
523          // Sema::ActOnParamDeclarator(). Without this conversion, the
524          // argument type in the function prototype *will not* match the
525          // type in ParmVarDecl (which makes the code generator unhappy).
526          //
527          // FIXME: We still apparently need the conversion in
528          // Sema::ActOnParamDeclarator(). This doesn't make any sense, since
529          // it should be driving off the type being created here.
530          //
531          // FIXME: If a source translation tool needs to see the original type,
532          // then we need to consider storing both types somewhere...
533          //
534          if (ArgTy->isArrayType()) {
535            ArgTy = Context.getArrayDecayedType(ArgTy);
536          } else if (ArgTy->isFunctionType())
537            ArgTy = Context.getPointerType(ArgTy);
538
539          // Look for 'void'.  void is allowed only as a single argument to a
540          // function with no other parameters (C99 6.7.5.3p10).  We record
541          // int(void) as a FunctionTypeProto with an empty argument list.
542          else if (ArgTy->isVoidType()) {
543            // If this is something like 'float(int, void)', reject it.  'void'
544            // is an incomplete type (C99 6.2.5p19) and function decls cannot
545            // have arguments of incomplete type.
546            if (FTI.NumArgs != 1 || FTI.isVariadic) {
547              Diag(DeclType.Loc, diag::err_void_only_param);
548              ArgTy = Context.IntTy;
549              Param->setType(ArgTy);
550            } else if (FTI.ArgInfo[i].Ident) {
551              // Reject, but continue to parse 'int(void abc)'.
552              Diag(FTI.ArgInfo[i].IdentLoc,
553                   diag::err_param_with_void_type);
554              ArgTy = Context.IntTy;
555              Param->setType(ArgTy);
556            } else {
557              // Reject, but continue to parse 'float(const void)'.
558              if (ArgTy.getCVRQualifiers())
559                Diag(DeclType.Loc, diag::err_void_param_qualified);
560
561              // Do not add 'void' to the ArgTys list.
562              break;
563            }
564          } else if (!FTI.hasPrototype) {
565            if (ArgTy->isPromotableIntegerType()) {
566              ArgTy = Context.IntTy;
567            } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
568              if (BTy->getKind() == BuiltinType::Float)
569                ArgTy = Context.DoubleTy;
570            }
571          }
572
573          ArgTys.push_back(ArgTy);
574        }
575        T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
576                                    FTI.isVariadic, FTI.TypeQuals);
577      }
578      break;
579    }
580    case DeclaratorChunk::MemberPointer:
581      // The scope spec must refer to a class, or be dependent.
582      DeclContext *DC = static_cast<DeclContext*>(
583        DeclType.Mem.Scope().getScopeRep());
584      QualType ClsType;
585      // FIXME: Extend for dependent types when it's actually supported.
586      // See ActOnCXXNestedNameSpecifier.
587      if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(DC)) {
588        ClsType = Context.getTagDeclType(RD);
589      } else {
590        if (DC) {
591          Diag(DeclType.Mem.Scope().getBeginLoc(),
592               diag::err_illegal_decl_mempointer_in_nonclass)
593            << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
594            << DeclType.Mem.Scope().getRange();
595        }
596        D.setInvalidType(true);
597        ClsType = Context.IntTy;
598      }
599
600      // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
601      //   with reference type, or "cv void."
602      if (T->isReferenceType()) {
603        Diag(DeclType.Loc, diag::err_illegal_decl_pointer_to_reference)
604          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
605        D.setInvalidType(true);
606        T = Context.IntTy;
607      }
608      if (T->isVoidType()) {
609        Diag(DeclType.Loc, diag::err_illegal_decl_mempointer_to_void)
610          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
611        T = Context.IntTy;
612      }
613
614      // Enforce C99 6.7.3p2: "Types other than pointer types derived from
615      // object or incomplete types shall not be restrict-qualified."
616      if ((DeclType.Mem.TypeQuals & QualType::Restrict) &&
617          !T->isIncompleteOrObjectType()) {
618        Diag(DeclType.Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
619          << T;
620        DeclType.Mem.TypeQuals &= ~QualType::Restrict;
621      }
622
623      T = Context.getMemberPointerType(T, ClsType.getTypePtr()).
624                    getQualifiedType(DeclType.Mem.TypeQuals);
625
626      break;
627    }
628
629    // See if there are any attributes on this declarator chunk.
630    if (const AttributeList *AL = DeclType.getAttrs())
631      ProcessTypeAttributeList(T, AL);
632  }
633
634  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
635    const FunctionTypeProto *FnTy = T->getAsFunctionTypeProto();
636    assert(FnTy && "Why oh why is there not a FunctionTypeProto here ?");
637
638    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
639    // for a nonstatic member function, the function type to which a pointer
640    // to member refers, or the top-level function type of a function typedef
641    // declaration.
642    if (FnTy->getTypeQuals() != 0 &&
643        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
644        ((D.getContext() != Declarator::MemberContext &&
645          (!D.getCXXScopeSpec().isSet() ||
646           !static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep())
647              ->isRecord())) ||
648         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
649      if (D.isFunctionDeclarator())
650        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
651      else
652        Diag(D.getIdentifierLoc(),
653             diag::err_invalid_qualified_typedef_function_type_use);
654
655      // Strip the cv-quals from the type.
656      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
657                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0);
658    }
659  }
660
661  // If there were any type attributes applied to the decl itself (not the
662  // type, apply the type attribute to the type!)
663  if (const AttributeList *Attrs = D.getAttributes())
664    ProcessTypeAttributeList(T, Attrs);
665
666  return T;
667}
668
669/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
670/// declarator
671QualType Sema::ObjCGetTypeForMethodDefinition(DeclTy *D) {
672  ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(static_cast<Decl *>(D));
673  QualType T = MDecl->getResultType();
674  llvm::SmallVector<QualType, 16> ArgTys;
675
676  // Add the first two invisible argument types for self and _cmd.
677  if (MDecl->isInstanceMethod()) {
678    QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
679    selfTy = Context.getPointerType(selfTy);
680    ArgTys.push_back(selfTy);
681  } else
682    ArgTys.push_back(Context.getObjCIdType());
683  ArgTys.push_back(Context.getObjCSelType());
684
685  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
686       E = MDecl->param_end(); PI != E; ++PI) {
687    QualType ArgTy = (*PI)->getType();
688    assert(!ArgTy.isNull() && "Couldn't parse type?");
689    // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
690    // This matches the conversion that is done in
691    // Sema::ActOnParamDeclarator().
692    if (ArgTy->isArrayType())
693      ArgTy = Context.getArrayDecayedType(ArgTy);
694    else if (ArgTy->isFunctionType())
695      ArgTy = Context.getPointerType(ArgTy);
696    ArgTys.push_back(ArgTy);
697  }
698  T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
699                              MDecl->isVariadic(), 0);
700  return T;
701}
702
703/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
704/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
705/// they point to and return true. If T1 and T2 aren't pointer types
706/// or pointer-to-member types, or if they are not similar at this
707/// level, returns false and leaves T1 and T2 unchanged. Top-level
708/// qualifiers on T1 and T2 are ignored. This function will typically
709/// be called in a loop that successively "unwraps" pointer and
710/// pointer-to-member types to compare them at each level.
711bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
712  const PointerType *T1PtrType = T1->getAsPointerType(),
713                    *T2PtrType = T2->getAsPointerType();
714  if (T1PtrType && T2PtrType) {
715    T1 = T1PtrType->getPointeeType();
716    T2 = T2PtrType->getPointeeType();
717    return true;
718  }
719
720  const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
721                          *T2MPType = T2->getAsMemberPointerType();
722  if (T1MPType && T2MPType &&
723      Context.getCanonicalType(T1MPType->getClass()) ==
724      Context.getCanonicalType(T2MPType->getClass())) {
725    T1 = T1MPType->getPointeeType();
726    T2 = T2MPType->getPointeeType();
727    return true;
728  }
729  return false;
730}
731
732Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
733  // C99 6.7.6: Type names have no identifier.  This is already validated by
734  // the parser.
735  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
736
737  QualType T = GetTypeForDeclarator(D, S);
738  if (T.isNull())
739    return true;
740
741  // Check that there are no default arguments (C++ only).
742  if (getLangOptions().CPlusPlus)
743    CheckExtraCXXDefaultArguments(D);
744
745  return T.getAsOpaquePtr();
746}
747
748
749
750//===----------------------------------------------------------------------===//
751// Type Attribute Processing
752//===----------------------------------------------------------------------===//
753
754/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
755/// specified type.  The attribute contains 1 argument, the id of the address
756/// space for the type.
757static void HandleAddressSpaceTypeAttribute(QualType &Type,
758                                            const AttributeList &Attr, Sema &S){
759  // If this type is already address space qualified, reject it.
760  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
761  // for two or more different address spaces."
762  if (Type.getAddressSpace()) {
763    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
764    return;
765  }
766
767  // Check the attribute arguments.
768  if (Attr.getNumArgs() != 1) {
769    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
770    return;
771  }
772  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
773  llvm::APSInt addrSpace(32);
774  if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
775    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
776      << ASArgExpr->getSourceRange();
777    return;
778  }
779
780  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
781  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
782}
783
784/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
785/// specified type.  The attribute contains 1 argument, weak or strong.
786static void HandleObjCGCTypeAttribute(QualType &Type,
787                                      const AttributeList &Attr, Sema &S) {
788  if (Type.getObjCGCAttr() != QualType::GCNone) {
789    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
790    return;
791  }
792
793  // Check the attribute arguments.
794  if (!Attr.getParameterName()) {
795    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
796      << "objc_gc" << 1;
797    return;
798  }
799  QualType::GCAttrTypes GCAttr;
800  if (Attr.getNumArgs() != 0) {
801    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
802    return;
803  }
804  if (Attr.getParameterName()->isStr("weak"))
805    GCAttr = QualType::Weak;
806  else if (Attr.getParameterName()->isStr("strong"))
807    GCAttr = QualType::Strong;
808  else {
809    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
810      << "objc_gc" << Attr.getParameterName();
811    return;
812  }
813
814  Type = S.Context.getObjCGCQualType(Type, GCAttr);
815}
816
817void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
818  // Scan through and apply attributes to this type where it makes sense.  Some
819  // attributes (such as __address_space__, __vector_size__, etc) apply to the
820  // type, but others can be present in the type specifiers even though they
821  // apply to the decl.  Here we apply type attributes and ignore the rest.
822  for (; AL; AL = AL->getNext()) {
823    // If this is an attribute we can handle, do so now, otherwise, add it to
824    // the LeftOverAttrs list for rechaining.
825    switch (AL->getKind()) {
826    default: break;
827    case AttributeList::AT_address_space:
828      HandleAddressSpaceTypeAttribute(Result, *AL, *this);
829      break;
830    case AttributeList::AT_objc_gc:
831      HandleObjCGCTypeAttribute(Result, *AL, *this);
832      break;
833    }
834  }
835}
836
837/// @brief If the type T is incomplete and cannot be completed,
838/// produce a suitable diagnostic.
839///
840/// This routine checks whether the type @p T is complete in any
841/// context where a complete type is required. If @p T is a complete
842/// type, returns false. If @p T is incomplete, issues the diagnostic
843/// @p diag (giving it the type @p T) and returns true.
844///
845/// @param Loc  The location in the source that the incomplete type
846/// diagnostic should refer to.
847///
848/// @param T  The type that this routine is examining for completeness.
849///
850/// @param diag The diagnostic value (e.g.,
851/// @c diag::err_typecheck_decl_incomplete_type) that will be used
852/// for the error message if @p T is incomplete.
853///
854/// @param Range1  An optional range in the source code that will be a
855/// part of the "incomplete type" error message.
856///
857/// @param Range2  An optional range in the source code that will be a
858/// part of the "incomplete type" error message.
859///
860/// @param PrintType If non-NULL, the type that should be printed
861/// instead of @p T. This parameter should be used when the type that
862/// we're checking for incompleteness isn't the type that should be
863/// displayed to the user, e.g., when T is a type and PrintType is a
864/// pointer to T.
865///
866/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
867/// @c false otherwise.
868///
869/// @todo When Clang gets proper support for C++ templates, this
870/// routine will also be able perform template instantiation when @p T
871/// is a class template specialization.
872bool Sema::DiagnoseIncompleteType(SourceLocation Loc, QualType T, unsigned diag,
873                                  SourceRange Range1, SourceRange Range2,
874                                  QualType PrintType) {
875  // If we have a complete type, we're done.
876  if (!T->isIncompleteType())
877    return false;
878
879  if (PrintType.isNull())
880    PrintType = T;
881
882  // We have an incomplete type. Produce a diagnostic.
883  Diag(Loc, diag) << PrintType << Range1 << Range2;
884
885  // If the type was a forward declaration of a class/struct/union
886  // type, produce
887  const TagType *Tag = 0;
888  if (const RecordType *Record = T->getAsRecordType())
889    Tag = Record;
890  else if (const EnumType *Enum = T->getAsEnumType())
891    Tag = Enum;
892
893  if (Tag && !Tag->getDecl()->isInvalidDecl())
894    Diag(Tag->getDecl()->getLocation(),
895         Tag->isBeingDefined() ? diag::note_type_being_defined
896                               : diag::note_forward_declaration)
897        << QualType(Tag, 0);
898
899  return true;
900}
901