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