SemaType.cpp revision 2865474261a608c7873b87ba4af110d17907896d
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/TypeLocVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Parse/DeclSpec.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/Support/ErrorHandling.h"
26using namespace clang;
27
28#include <iostream>
29
30/// \brief Perform adjustment on the parameter type of a function.
31///
32/// This routine adjusts the given parameter type @p T to the actual
33/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
34/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
35QualType Sema::adjustParameterType(QualType T) {
36  // C99 6.7.5.3p7:
37  //   A declaration of a parameter as "array of type" shall be
38  //   adjusted to "qualified pointer to type", where the type
39  //   qualifiers (if any) are those specified within the [ and ] of
40  //   the array type derivation.
41  if (T->isArrayType())
42    return Context.getArrayDecayedType(T);
43
44  // C99 6.7.5.3p8:
45  //   A declaration of a parameter as "function returning type"
46  //   shall be adjusted to "pointer to function returning type", as
47  //   in 6.3.2.1.
48  if (T->isFunctionType())
49    return Context.getPointerType(T);
50
51  return T;
52}
53
54
55
56/// isOmittedBlockReturnType - Return true if this declarator is missing a
57/// return type because this is a omitted return type on a block literal.
58static bool isOmittedBlockReturnType(const Declarator &D) {
59  if (D.getContext() != Declarator::BlockLiteralContext ||
60      D.getDeclSpec().hasTypeSpecifier())
61    return false;
62
63  if (D.getNumTypeObjects() == 0)
64    return true;   // ^{ ... }
65
66  if (D.getNumTypeObjects() == 1 &&
67      D.getTypeObject(0).Kind == DeclaratorChunk::Function)
68    return true;   // ^(int X, float Y) { ... }
69
70  return false;
71}
72
73typedef std::pair<const AttributeList*,QualType> DelayedAttribute;
74typedef llvm::SmallVectorImpl<DelayedAttribute> DelayedAttributeSet;
75
76static void ProcessTypeAttributeList(Sema &S, QualType &Type,
77                                     bool IsDeclSpec,
78                                     const AttributeList *Attrs,
79                                     DelayedAttributeSet &DelayedFnAttrs);
80static bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr);
81
82static void ProcessDelayedFnAttrs(Sema &S, QualType &Type,
83                                  DelayedAttributeSet &Attrs) {
84  for (DelayedAttributeSet::iterator I = Attrs.begin(),
85         E = Attrs.end(); I != E; ++I)
86    if (ProcessFnAttr(S, Type, *I->first)) {
87      S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type)
88        << I->first->getName() << I->second;
89      // Avoid any further processing of this attribute.
90      I->first->setInvalid();
91    }
92  Attrs.clear();
93}
94
95static void DiagnoseDelayedFnAttrs(Sema &S, DelayedAttributeSet &Attrs) {
96  for (DelayedAttributeSet::iterator I = Attrs.begin(),
97         E = Attrs.end(); I != E; ++I) {
98    S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type)
99      << I->first->getName() << I->second;
100    // Avoid any further processing of this attribute.
101    I->first->setInvalid();
102  }
103  Attrs.clear();
104}
105
106/// \brief Convert the specified declspec to the appropriate type
107/// object.
108/// \param D  the declarator containing the declaration specifier.
109/// \returns The type described by the declaration specifiers.  This function
110/// never returns null.
111static QualType ConvertDeclSpecToType(Sema &TheSema,
112                                      Declarator &TheDeclarator,
113                                      DelayedAttributeSet &Delayed) {
114  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
115  // checking.
116  const DeclSpec &DS = TheDeclarator.getDeclSpec();
117  SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc();
118  if (DeclLoc.isInvalid())
119    DeclLoc = DS.getSourceRange().getBegin();
120
121  ASTContext &Context = TheSema.Context;
122
123  QualType Result;
124  switch (DS.getTypeSpecType()) {
125  case DeclSpec::TST_void:
126    Result = Context.VoidTy;
127    break;
128  case DeclSpec::TST_char:
129    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
130      Result = Context.CharTy;
131    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
132      Result = Context.SignedCharTy;
133    else {
134      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
135             "Unknown TSS value");
136      Result = Context.UnsignedCharTy;
137    }
138    break;
139  case DeclSpec::TST_wchar:
140    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
141      Result = Context.WCharTy;
142    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
143      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
144        << DS.getSpecifierName(DS.getTypeSpecType());
145      Result = Context.getSignedWCharType();
146    } else {
147      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
148        "Unknown TSS value");
149      TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
150        << DS.getSpecifierName(DS.getTypeSpecType());
151      Result = Context.getUnsignedWCharType();
152    }
153    break;
154  case DeclSpec::TST_char16:
155      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
156        "Unknown TSS value");
157      Result = Context.Char16Ty;
158    break;
159  case DeclSpec::TST_char32:
160      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
161        "Unknown TSS value");
162      Result = Context.Char32Ty;
163    break;
164  case DeclSpec::TST_unspecified:
165    // "<proto1,proto2>" is an objc qualified ID with a missing id.
166    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
167      Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
168                                         (ObjCProtocolDecl**)PQ,
169                                         DS.getNumProtocolQualifiers());
170      Result = Context.getObjCObjectPointerType(Result);
171      break;
172    }
173
174    // If this is a missing declspec in a block literal return context, then it
175    // is inferred from the return statements inside the block.
176    if (isOmittedBlockReturnType(TheDeclarator)) {
177      Result = Context.DependentTy;
178      break;
179    }
180
181    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
182    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
183    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
184    // Note that the one exception to this is function definitions, which are
185    // allowed to be completely missing a declspec.  This is handled in the
186    // parser already though by it pretending to have seen an 'int' in this
187    // case.
188    if (TheSema.getLangOptions().ImplicitInt) {
189      // In C89 mode, we only warn if there is a completely missing declspec
190      // when one is not allowed.
191      if (DS.isEmpty()) {
192        TheSema.Diag(DeclLoc, diag::ext_missing_declspec)
193          << DS.getSourceRange()
194        << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
195      }
196    } else if (!DS.hasTypeSpecifier()) {
197      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
198      // "At least one type specifier shall be given in the declaration
199      // specifiers in each declaration, and in the specifier-qualifier list in
200      // each struct declaration and type name."
201      // FIXME: Does Microsoft really have the implicit int extension in C++?
202      if (TheSema.getLangOptions().CPlusPlus &&
203          !TheSema.getLangOptions().Microsoft) {
204        TheSema.Diag(DeclLoc, diag::err_missing_type_specifier)
205          << DS.getSourceRange();
206
207        // When this occurs in C++ code, often something is very broken with the
208        // value being declared, poison it as invalid so we don't get chains of
209        // errors.
210        TheDeclarator.setInvalidType(true);
211      } else {
212        TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier)
213          << DS.getSourceRange();
214      }
215    }
216
217    // FALL THROUGH.
218  case DeclSpec::TST_int: {
219    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
220      switch (DS.getTypeSpecWidth()) {
221      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
222      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
223      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
224      case DeclSpec::TSW_longlong:
225        Result = Context.LongLongTy;
226
227        // long long is a C99 feature.
228        if (!TheSema.getLangOptions().C99 &&
229            !TheSema.getLangOptions().CPlusPlus0x)
230          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
231        break;
232      }
233    } else {
234      switch (DS.getTypeSpecWidth()) {
235      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
236      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
237      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
238      case DeclSpec::TSW_longlong:
239        Result = Context.UnsignedLongLongTy;
240
241        // long long is a C99 feature.
242        if (!TheSema.getLangOptions().C99 &&
243            !TheSema.getLangOptions().CPlusPlus0x)
244          TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
245        break;
246      }
247    }
248    break;
249  }
250  case DeclSpec::TST_float: Result = Context.FloatTy; break;
251  case DeclSpec::TST_double:
252    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
253      Result = Context.LongDoubleTy;
254    else
255      Result = Context.DoubleTy;
256    break;
257  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
258  case DeclSpec::TST_decimal32:    // _Decimal32
259  case DeclSpec::TST_decimal64:    // _Decimal64
260  case DeclSpec::TST_decimal128:   // _Decimal128
261    TheSema.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
262    Result = Context.IntTy;
263    TheDeclarator.setInvalidType(true);
264    break;
265  case DeclSpec::TST_class:
266  case DeclSpec::TST_enum:
267  case DeclSpec::TST_union:
268  case DeclSpec::TST_struct: {
269    TypeDecl *D
270      = dyn_cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep()));
271    if (!D) {
272      // This can happen in C++ with ambiguous lookups.
273      Result = Context.IntTy;
274      TheDeclarator.setInvalidType(true);
275      break;
276    }
277
278    // If the type is deprecated or unavailable, diagnose it.
279    TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc());
280
281    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
282           DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
283
284    // TypeQuals handled by caller.
285    Result = Context.getTypeDeclType(D);
286
287    // In C++, make an ElaboratedType.
288    if (TheSema.getLangOptions().CPlusPlus) {
289      ElaboratedTypeKeyword Keyword
290        = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
291      Result = TheSema.getElaboratedType(Keyword, DS.getTypeSpecScope(),
292                                         Result);
293    }
294    if (D->isInvalidDecl())
295      TheDeclarator.setInvalidType(true);
296    break;
297  }
298  case DeclSpec::TST_typename: {
299    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
300           DS.getTypeSpecSign() == 0 &&
301           "Can't handle qualifiers on typedef names yet!");
302    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
303
304    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
305      if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
306        // Silently drop any existing protocol qualifiers.
307        // TODO: determine whether that's the right thing to do.
308        if (ObjT->getNumProtocols())
309          Result = ObjT->getBaseType();
310
311        if (DS.getNumProtocolQualifiers())
312          Result = Context.getObjCObjectType(Result,
313                                             (ObjCProtocolDecl**) PQ,
314                                             DS.getNumProtocolQualifiers());
315      } else if (Result->isObjCIdType()) {
316        // id<protocol-list>
317        Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
318                                           (ObjCProtocolDecl**) PQ,
319                                           DS.getNumProtocolQualifiers());
320        Result = Context.getObjCObjectPointerType(Result);
321      } else if (Result->isObjCClassType()) {
322        // Class<protocol-list>
323        Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
324                                           (ObjCProtocolDecl**) PQ,
325                                           DS.getNumProtocolQualifiers());
326        Result = Context.getObjCObjectPointerType(Result);
327      } else {
328        TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
329          << DS.getSourceRange();
330        TheDeclarator.setInvalidType(true);
331      }
332    }
333
334    // TypeQuals handled by caller.
335    break;
336  }
337  case DeclSpec::TST_typeofType:
338    // FIXME: Preserve type source info.
339    Result = TheSema.GetTypeFromParser(DS.getTypeRep());
340    assert(!Result.isNull() && "Didn't get a type for typeof?");
341    // TypeQuals handled by caller.
342    Result = Context.getTypeOfType(Result);
343    break;
344  case DeclSpec::TST_typeofExpr: {
345    Expr *E = static_cast<Expr *>(DS.getTypeRep());
346    assert(E && "Didn't get an expression for typeof?");
347    // TypeQuals handled by caller.
348    Result = TheSema.BuildTypeofExprType(E);
349    if (Result.isNull()) {
350      Result = Context.IntTy;
351      TheDeclarator.setInvalidType(true);
352    }
353    break;
354  }
355  case DeclSpec::TST_decltype: {
356    Expr *E = static_cast<Expr *>(DS.getTypeRep());
357    assert(E && "Didn't get an expression for decltype?");
358    // TypeQuals handled by caller.
359    Result = TheSema.BuildDecltypeType(E);
360    if (Result.isNull()) {
361      Result = Context.IntTy;
362      TheDeclarator.setInvalidType(true);
363    }
364    break;
365  }
366  case DeclSpec::TST_auto: {
367    // TypeQuals handled by caller.
368    Result = Context.UndeducedAutoTy;
369    break;
370  }
371
372  case DeclSpec::TST_error:
373    Result = Context.IntTy;
374    TheDeclarator.setInvalidType(true);
375    break;
376  }
377
378  // Handle complex types.
379  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
380    if (TheSema.getLangOptions().Freestanding)
381      TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
382    Result = Context.getComplexType(Result);
383  } else if (DS.isTypeAltiVecVector()) {
384    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
385    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
386    Result = Context.getVectorType(Result, 128/typeSize, true,
387      DS.isTypeAltiVecPixel());
388  }
389
390  assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
391         "FIXME: imaginary types not supported yet!");
392
393  // See if there are any attributes on the declspec that apply to the type (as
394  // opposed to the decl).
395  if (const AttributeList *AL = DS.getAttributes())
396    ProcessTypeAttributeList(TheSema, Result, true, AL, Delayed);
397
398  // Apply const/volatile/restrict qualifiers to T.
399  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
400
401    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
402    // or incomplete types shall not be restrict-qualified."  C++ also allows
403    // restrict-qualified references.
404    if (TypeQuals & DeclSpec::TQ_restrict) {
405      if (Result->isAnyPointerType() || Result->isReferenceType()) {
406        QualType EltTy;
407        if (Result->isObjCObjectPointerType())
408          EltTy = Result;
409        else
410          EltTy = Result->isPointerType() ?
411                    Result->getAs<PointerType>()->getPointeeType() :
412                    Result->getAs<ReferenceType>()->getPointeeType();
413
414        // If we have a pointer or reference, the pointee must have an object
415        // incomplete type.
416        if (!EltTy->isIncompleteOrObjectType()) {
417          TheSema.Diag(DS.getRestrictSpecLoc(),
418               diag::err_typecheck_invalid_restrict_invalid_pointee)
419            << EltTy << DS.getSourceRange();
420          TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
421        }
422      } else {
423        TheSema.Diag(DS.getRestrictSpecLoc(),
424             diag::err_typecheck_invalid_restrict_not_pointer)
425          << Result << DS.getSourceRange();
426        TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
427      }
428    }
429
430    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
431    // of a function type includes any type qualifiers, the behavior is
432    // undefined."
433    if (Result->isFunctionType() && TypeQuals) {
434      // Get some location to point at, either the C or V location.
435      SourceLocation Loc;
436      if (TypeQuals & DeclSpec::TQ_const)
437        Loc = DS.getConstSpecLoc();
438      else if (TypeQuals & DeclSpec::TQ_volatile)
439        Loc = DS.getVolatileSpecLoc();
440      else {
441        assert((TypeQuals & DeclSpec::TQ_restrict) &&
442               "Has CVR quals but not C, V, or R?");
443        Loc = DS.getRestrictSpecLoc();
444      }
445      TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers)
446        << Result << DS.getSourceRange();
447    }
448
449    // C++ [dcl.ref]p1:
450    //   Cv-qualified references are ill-formed except when the
451    //   cv-qualifiers are introduced through the use of a typedef
452    //   (7.1.3) or of a template type argument (14.3), in which
453    //   case the cv-qualifiers are ignored.
454    // FIXME: Shouldn't we be checking SCS_typedef here?
455    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
456        TypeQuals && Result->isReferenceType()) {
457      TypeQuals &= ~DeclSpec::TQ_const;
458      TypeQuals &= ~DeclSpec::TQ_volatile;
459    }
460
461    Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
462    Result = Context.getQualifiedType(Result, Quals);
463  }
464
465  return Result;
466}
467
468static std::string getPrintableNameForEntity(DeclarationName Entity) {
469  if (Entity)
470    return Entity.getAsString();
471
472  return "type name";
473}
474
475QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
476                                  Qualifiers Qs) {
477  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
478  // object or incomplete types shall not be restrict-qualified."
479  if (Qs.hasRestrict()) {
480    unsigned DiagID = 0;
481    QualType ProblemTy;
482
483    const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
484    if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
485      if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
486        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
487        ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
488      }
489    } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
490      if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
491        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
492        ProblemTy = T->getAs<PointerType>()->getPointeeType();
493      }
494    } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
495      if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
496        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
497        ProblemTy = T->getAs<PointerType>()->getPointeeType();
498      }
499    } else if (!Ty->isDependentType()) {
500      // FIXME: this deserves a proper diagnostic
501      DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
502      ProblemTy = T;
503    }
504
505    if (DiagID) {
506      Diag(Loc, DiagID) << ProblemTy;
507      Qs.removeRestrict();
508    }
509  }
510
511  return Context.getQualifiedType(T, Qs);
512}
513
514/// \brief Build a pointer type.
515///
516/// \param T The type to which we'll be building a pointer.
517///
518/// \param Loc The location of the entity whose type involves this
519/// pointer type or, if there is no such entity, the location of the
520/// type that will have pointer type.
521///
522/// \param Entity The name of the entity that involves the pointer
523/// type, if known.
524///
525/// \returns A suitable pointer type, if there are no
526/// errors. Otherwise, returns a NULL type.
527QualType Sema::BuildPointerType(QualType T,
528                                SourceLocation Loc, DeclarationName Entity) {
529  if (T->isReferenceType()) {
530    // C++ 8.3.2p4: There shall be no ... pointers to references ...
531    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
532      << getPrintableNameForEntity(Entity) << T;
533    return QualType();
534  }
535
536  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
537
538  // Build the pointer type.
539  return Context.getPointerType(T);
540}
541
542/// \brief Build a reference type.
543///
544/// \param T The type to which we'll be building a reference.
545///
546/// \param Loc The location of the entity whose type involves this
547/// reference type or, if there is no such entity, the location of the
548/// type that will have reference type.
549///
550/// \param Entity The name of the entity that involves the reference
551/// type, if known.
552///
553/// \returns A suitable reference type, if there are no
554/// errors. Otherwise, returns a NULL type.
555QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
556                                  SourceLocation Loc,
557                                  DeclarationName Entity) {
558  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
559
560  // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
561  //   reference to a type T, and attempt to create the type "lvalue
562  //   reference to cv TD" creates the type "lvalue reference to T".
563  // We use the qualifiers (restrict or none) of the original reference,
564  // not the new ones. This is consistent with GCC.
565
566  // C++ [dcl.ref]p4: There shall be no references to references.
567  //
568  // According to C++ DR 106, references to references are only
569  // diagnosed when they are written directly (e.g., "int & &"),
570  // but not when they happen via a typedef:
571  //
572  //   typedef int& intref;
573  //   typedef intref& intref2;
574  //
575  // Parser::ParseDeclaratorInternal diagnoses the case where
576  // references are written directly; here, we handle the
577  // collapsing of references-to-references as described in C++
578  // DR 106 and amended by C++ DR 540.
579
580  // C++ [dcl.ref]p1:
581  //   A declarator that specifies the type "reference to cv void"
582  //   is ill-formed.
583  if (T->isVoidType()) {
584    Diag(Loc, diag::err_reference_to_void);
585    return QualType();
586  }
587
588  // Handle restrict on references.
589  if (LValueRef)
590    return Context.getLValueReferenceType(T, SpelledAsLValue);
591  return Context.getRValueReferenceType(T);
592}
593
594/// \brief Build an array type.
595///
596/// \param T The type of each element in the array.
597///
598/// \param ASM C99 array size modifier (e.g., '*', 'static').
599///
600/// \param ArraySize Expression describing the size of the array.
601///
602/// \param Loc The location of the entity whose type involves this
603/// array type or, if there is no such entity, the location of the
604/// type that will have array type.
605///
606/// \param Entity The name of the entity that involves the array
607/// type, if known.
608///
609/// \returns A suitable array type, if there are no errors. Otherwise,
610/// returns a NULL type.
611QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
612                              Expr *ArraySize, unsigned Quals,
613                              SourceRange Brackets, DeclarationName Entity) {
614
615  SourceLocation Loc = Brackets.getBegin();
616  if (getLangOptions().CPlusPlus) {
617    // C++ [dcl.array]p1:
618    //   T is called the array element type; this type shall not be a reference
619    //   type, the (possibly cv-qualified) type void, a function type or an
620    //   abstract class type.
621    //
622    // Note: function types are handled in the common path with C.
623    if (T->isReferenceType()) {
624      Diag(Loc, diag::err_illegal_decl_array_of_references)
625      << getPrintableNameForEntity(Entity) << T;
626      return QualType();
627    }
628
629    if (T->isVoidType()) {
630      Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
631      return QualType();
632    }
633
634    if (RequireNonAbstractType(Brackets.getBegin(), T,
635                               diag::err_array_of_abstract_type))
636      return QualType();
637
638  } else {
639    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
640    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
641    if (RequireCompleteType(Loc, T,
642                            diag::err_illegal_decl_array_incomplete_type))
643      return QualType();
644  }
645
646  if (T->isFunctionType()) {
647    Diag(Loc, diag::err_illegal_decl_array_of_functions)
648      << getPrintableNameForEntity(Entity) << T;
649    return QualType();
650  }
651
652  if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
653    Diag(Loc,  diag::err_illegal_decl_array_of_auto)
654      << getPrintableNameForEntity(Entity);
655    return QualType();
656  }
657
658  if (const RecordType *EltTy = T->getAs<RecordType>()) {
659    // If the element type is a struct or union that contains a variadic
660    // array, accept it as a GNU extension: C99 6.7.2.1p2.
661    if (EltTy->getDecl()->hasFlexibleArrayMember())
662      Diag(Loc, diag::ext_flexible_array_in_array) << T;
663  } else if (T->isObjCObjectType()) {
664    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
665    return QualType();
666  }
667
668  // C99 6.7.5.2p1: The size expression shall have integer type.
669  if (ArraySize && !ArraySize->isTypeDependent() &&
670      !ArraySize->getType()->isIntegerType()) {
671    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
672      << ArraySize->getType() << ArraySize->getSourceRange();
673    ArraySize->Destroy(Context);
674    return QualType();
675  }
676  llvm::APSInt ConstVal(32);
677  if (!ArraySize) {
678    if (ASM == ArrayType::Star)
679      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
680    else
681      T = Context.getIncompleteArrayType(T, ASM, Quals);
682  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
683    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
684  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
685             (!T->isDependentType() && !T->isIncompleteType() &&
686              !T->isConstantSizeType())) {
687    // Per C99, a variable array is an array with either a non-constant
688    // size or an element type that has a non-constant-size
689    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
690  } else {
691    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
692    // have a value greater than zero.
693    if (ConstVal.isSigned() && ConstVal.isNegative()) {
694      Diag(ArraySize->getLocStart(),
695           diag::err_typecheck_negative_array_size)
696        << ArraySize->getSourceRange();
697      return QualType();
698    }
699    if (ConstVal == 0) {
700      // GCC accepts zero sized static arrays. We allow them when
701      // we're not in a SFINAE context.
702      Diag(ArraySize->getLocStart(),
703           isSFINAEContext()? diag::err_typecheck_zero_array_size
704                            : diag::ext_typecheck_zero_array_size)
705        << ArraySize->getSourceRange();
706    }
707    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
708  }
709  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
710  if (!getLangOptions().C99) {
711    if (T->isVariableArrayType()) {
712      // Prohibit the use of non-POD types in VLAs.
713      if (!T->isDependentType() &&
714          !Context.getBaseElementType(T)->isPODType()) {
715        Diag(Loc, diag::err_vla_non_pod)
716          << Context.getBaseElementType(T);
717        return QualType();
718      }
719      // Prohibit the use of VLAs during template argument deduction.
720      else if (isSFINAEContext()) {
721        Diag(Loc, diag::err_vla_in_sfinae);
722        return QualType();
723      }
724      // Just extwarn about VLAs.
725      else
726        Diag(Loc, diag::ext_vla);
727    } else if (ASM != ArrayType::Normal || Quals != 0)
728      Diag(Loc,
729           getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
730                                     : diag::ext_c99_array_usage);
731  }
732
733  return T;
734}
735
736/// \brief Build an ext-vector type.
737///
738/// Run the required checks for the extended vector type.
739QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
740                                  SourceLocation AttrLoc) {
741
742  Expr *Arg = (Expr *)ArraySize.get();
743
744  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
745  // in conjunction with complex types (pointers, arrays, functions, etc.).
746  if (!T->isDependentType() &&
747      !T->isIntegerType() && !T->isRealFloatingType()) {
748    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
749    return QualType();
750  }
751
752  if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
753    llvm::APSInt vecSize(32);
754    if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
755      Diag(AttrLoc, diag::err_attribute_argument_not_int)
756      << "ext_vector_type" << Arg->getSourceRange();
757      return QualType();
758    }
759
760    // unlike gcc's vector_size attribute, the size is specified as the
761    // number of elements, not the number of bytes.
762    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
763
764    if (vectorSize == 0) {
765      Diag(AttrLoc, diag::err_attribute_zero_size)
766      << Arg->getSourceRange();
767      return QualType();
768    }
769
770    if (!T->isDependentType())
771      return Context.getExtVectorType(T, vectorSize);
772  }
773
774  return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
775                                                AttrLoc);
776}
777
778/// \brief Build a function type.
779///
780/// This routine checks the function type according to C++ rules and
781/// under the assumption that the result type and parameter types have
782/// just been instantiated from a template. It therefore duplicates
783/// some of the behavior of GetTypeForDeclarator, but in a much
784/// simpler form that is only suitable for this narrow use case.
785///
786/// \param T The return type of the function.
787///
788/// \param ParamTypes The parameter types of the function. This array
789/// will be modified to account for adjustments to the types of the
790/// function parameters.
791///
792/// \param NumParamTypes The number of parameter types in ParamTypes.
793///
794/// \param Variadic Whether this is a variadic function type.
795///
796/// \param Quals The cvr-qualifiers to be applied to the function type.
797///
798/// \param Loc The location of the entity whose type involves this
799/// function type or, if there is no such entity, the location of the
800/// type that will have function type.
801///
802/// \param Entity The name of the entity that involves the function
803/// type, if known.
804///
805/// \returns A suitable function type, if there are no
806/// errors. Otherwise, returns a NULL type.
807QualType Sema::BuildFunctionType(QualType T,
808                                 QualType *ParamTypes,
809                                 unsigned NumParamTypes,
810                                 bool Variadic, unsigned Quals,
811                                 SourceLocation Loc, DeclarationName Entity) {
812  if (T->isArrayType() || T->isFunctionType()) {
813    Diag(Loc, diag::err_func_returning_array_function)
814      << T->isFunctionType() << T;
815    return QualType();
816  }
817
818  bool Invalid = false;
819  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
820    QualType ParamType = adjustParameterType(ParamTypes[Idx]);
821    if (ParamType->isVoidType()) {
822      Diag(Loc, diag::err_param_with_void_type);
823      Invalid = true;
824    }
825
826    ParamTypes[Idx] = ParamType;
827  }
828
829  if (Invalid)
830    return QualType();
831
832  return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
833                                 Quals, false, false, 0, 0,
834                                 FunctionType::ExtInfo());
835}
836
837/// \brief Build a member pointer type \c T Class::*.
838///
839/// \param T the type to which the member pointer refers.
840/// \param Class the class type into which the member pointer points.
841/// \param CVR Qualifiers applied to the member pointer type
842/// \param Loc the location where this type begins
843/// \param Entity the name of the entity that will have this member pointer type
844///
845/// \returns a member pointer type, if successful, or a NULL type if there was
846/// an error.
847QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
848                                      SourceLocation Loc,
849                                      DeclarationName Entity) {
850  // Verify that we're not building a pointer to pointer to function with
851  // exception specification.
852  if (CheckDistantExceptionSpec(T)) {
853    Diag(Loc, diag::err_distant_exception_spec);
854
855    // FIXME: If we're doing this as part of template instantiation,
856    // we should return immediately.
857
858    // Build the type anyway, but use the canonical type so that the
859    // exception specifiers are stripped off.
860    T = Context.getCanonicalType(T);
861  }
862
863  // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
864  //   with reference type, or "cv void."
865  if (T->isReferenceType()) {
866    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
867      << (Entity? Entity.getAsString() : "type name") << T;
868    return QualType();
869  }
870
871  if (T->isVoidType()) {
872    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
873      << (Entity? Entity.getAsString() : "type name");
874    return QualType();
875  }
876
877  if (!Class->isDependentType() && !Class->isRecordType()) {
878    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
879    return QualType();
880  }
881
882  return Context.getMemberPointerType(T, Class.getTypePtr());
883}
884
885/// \brief Build a block pointer type.
886///
887/// \param T The type to which we'll be building a block pointer.
888///
889/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
890///
891/// \param Loc The location of the entity whose type involves this
892/// block pointer type or, if there is no such entity, the location of the
893/// type that will have block pointer type.
894///
895/// \param Entity The name of the entity that involves the block pointer
896/// type, if known.
897///
898/// \returns A suitable block pointer type, if there are no
899/// errors. Otherwise, returns a NULL type.
900QualType Sema::BuildBlockPointerType(QualType T,
901                                     SourceLocation Loc,
902                                     DeclarationName Entity) {
903  if (!T->isFunctionType()) {
904    Diag(Loc, diag::err_nonfunction_block_type);
905    return QualType();
906  }
907
908  return Context.getBlockPointerType(T);
909}
910
911QualType Sema::GetTypeFromParser(TypeTy *Ty, TypeSourceInfo **TInfo) {
912  QualType QT = QualType::getFromOpaquePtr(Ty);
913  if (QT.isNull()) {
914    if (TInfo) *TInfo = 0;
915    return QualType();
916  }
917
918  TypeSourceInfo *DI = 0;
919  if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
920    QT = LIT->getType();
921    DI = LIT->getTypeSourceInfo();
922  }
923
924  if (TInfo) *TInfo = DI;
925  return QT;
926}
927
928/// GetTypeForDeclarator - Convert the type for the specified
929/// declarator to Type instances.
930///
931/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
932/// owns the declaration of a type (e.g., the definition of a struct
933/// type), then *OwnedDecl will receive the owned declaration.
934///
935/// The result of this call will never be null, but the associated
936/// type may be a null type if there's an unrecoverable error.
937TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
938                                           TagDecl **OwnedDecl) {
939  // Determine the type of the declarator. Not all forms of declarator
940  // have a type.
941  QualType T;
942  TypeSourceInfo *ReturnTypeInfo = 0;
943
944  llvm::SmallVector<DelayedAttribute,4> FnAttrsFromDeclSpec;
945
946  switch (D.getName().getKind()) {
947  case UnqualifiedId::IK_Identifier:
948  case UnqualifiedId::IK_OperatorFunctionId:
949  case UnqualifiedId::IK_LiteralOperatorId:
950  case UnqualifiedId::IK_TemplateId:
951    T = ConvertDeclSpecToType(*this, D, FnAttrsFromDeclSpec);
952
953    if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
954      TagDecl* Owned = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
955      // Owned is embedded if it was defined here, or if it is the
956      // very first (i.e., canonical) declaration of this tag type.
957      Owned->setEmbeddedInDeclarator(Owned->isDefinition() ||
958                                     Owned->isCanonicalDecl());
959      if (OwnedDecl) *OwnedDecl = Owned;
960    }
961    break;
962
963  case UnqualifiedId::IK_ConstructorName:
964  case UnqualifiedId::IK_ConstructorTemplateId:
965  case UnqualifiedId::IK_DestructorName:
966    // Constructors and destructors don't have return types. Use
967    // "void" instead.
968    T = Context.VoidTy;
969    break;
970
971  case UnqualifiedId::IK_ConversionFunctionId:
972    // The result type of a conversion function is the type that it
973    // converts to.
974    T = GetTypeFromParser(D.getName().ConversionFunctionId,
975                          &ReturnTypeInfo);
976    break;
977  }
978
979  if (T.isNull())
980    return Context.getNullTypeSourceInfo();
981
982  if (T == Context.UndeducedAutoTy) {
983    int Error = -1;
984
985    switch (D.getContext()) {
986    case Declarator::KNRTypeListContext:
987      assert(0 && "K&R type lists aren't allowed in C++");
988      break;
989    case Declarator::PrototypeContext:
990      Error = 0; // Function prototype
991      break;
992    case Declarator::MemberContext:
993      switch (cast<TagDecl>(CurContext)->getTagKind()) {
994      case TTK_Enum: assert(0 && "unhandled tag kind"); break;
995      case TTK_Struct: Error = 1; /* Struct member */ break;
996      case TTK_Union:  Error = 2; /* Union member */ break;
997      case TTK_Class:  Error = 3; /* Class member */ break;
998      }
999      break;
1000    case Declarator::CXXCatchContext:
1001      Error = 4; // Exception declaration
1002      break;
1003    case Declarator::TemplateParamContext:
1004      Error = 5; // Template parameter
1005      break;
1006    case Declarator::BlockLiteralContext:
1007      Error = 6;  // Block literal
1008      break;
1009    case Declarator::FileContext:
1010    case Declarator::BlockContext:
1011    case Declarator::ForContext:
1012    case Declarator::ConditionContext:
1013    case Declarator::TypeNameContext:
1014      break;
1015    }
1016
1017    if (Error != -1) {
1018      Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1019        << Error;
1020      T = Context.IntTy;
1021      D.setInvalidType(true);
1022    }
1023  }
1024
1025  // The name we're declaring, if any.
1026  DeclarationName Name;
1027  if (D.getIdentifier())
1028    Name = D.getIdentifier();
1029
1030  llvm::SmallVector<DelayedAttribute,4> FnAttrsFromPreviousChunk;
1031
1032  // Walk the DeclTypeInfo, building the recursive type as we go.
1033  // DeclTypeInfos are ordered from the identifier out, which is
1034  // opposite of what we want :).
1035  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1036    DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
1037    switch (DeclType.Kind) {
1038    default: assert(0 && "Unknown decltype!");
1039    case DeclaratorChunk::BlockPointer:
1040      // If blocks are disabled, emit an error.
1041      if (!LangOpts.Blocks)
1042        Diag(DeclType.Loc, diag::err_blocks_disable);
1043
1044      T = BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
1045      if (DeclType.Cls.TypeQuals)
1046        T = BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
1047      break;
1048    case DeclaratorChunk::Pointer:
1049      // Verify that we're not building a pointer to pointer to function with
1050      // exception specification.
1051      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1052        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1053        D.setInvalidType(true);
1054        // Build the type anyway.
1055      }
1056      if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) {
1057        T = Context.getObjCObjectPointerType(T);
1058        if (DeclType.Ptr.TypeQuals)
1059          T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1060        break;
1061      }
1062      T = BuildPointerType(T, DeclType.Loc, Name);
1063      if (DeclType.Ptr.TypeQuals)
1064        T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1065      break;
1066    case DeclaratorChunk::Reference: {
1067      // Verify that we're not building a reference to pointer to function with
1068      // exception specification.
1069      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1070        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1071        D.setInvalidType(true);
1072        // Build the type anyway.
1073      }
1074      T = BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
1075
1076      Qualifiers Quals;
1077      if (DeclType.Ref.HasRestrict)
1078        T = BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
1079      break;
1080    }
1081    case DeclaratorChunk::Array: {
1082      // Verify that we're not building an array of pointers to function with
1083      // exception specification.
1084      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1085        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1086        D.setInvalidType(true);
1087        // Build the type anyway.
1088      }
1089      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1090      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1091      ArrayType::ArraySizeModifier ASM;
1092      if (ATI.isStar)
1093        ASM = ArrayType::Star;
1094      else if (ATI.hasStatic)
1095        ASM = ArrayType::Static;
1096      else
1097        ASM = ArrayType::Normal;
1098      if (ASM == ArrayType::Star &&
1099          D.getContext() != Declarator::PrototypeContext) {
1100        // FIXME: This check isn't quite right: it allows star in prototypes
1101        // for function definitions, and disallows some edge cases detailed
1102        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1103        Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1104        ASM = ArrayType::Normal;
1105        D.setInvalidType(true);
1106      }
1107      T = BuildArrayType(T, ASM, ArraySize,
1108                         Qualifiers::fromCVRMask(ATI.TypeQuals),
1109                         SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1110      break;
1111    }
1112    case DeclaratorChunk::Function: {
1113      // If the function declarator has a prototype (i.e. it is not () and
1114      // does not have a K&R-style identifier list), then the arguments are part
1115      // of the type, otherwise the argument list is ().
1116      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1117
1118      // C99 6.7.5.3p1: The return type may not be a function or array type.
1119      // For conversion functions, we'll diagnose this particular error later.
1120      if ((T->isArrayType() || T->isFunctionType()) &&
1121          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
1122        Diag(DeclType.Loc, diag::err_func_returning_array_function)
1123          << T->isFunctionType() << T;
1124        T = Context.IntTy;
1125        D.setInvalidType(true);
1126      }
1127
1128      if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1129        // C++ [dcl.fct]p6:
1130        //   Types shall not be defined in return or parameter types.
1131        TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
1132        if (Tag->isDefinition())
1133          Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1134            << Context.getTypeDeclType(Tag);
1135      }
1136
1137      // Exception specs are not allowed in typedefs. Complain, but add it
1138      // anyway.
1139      if (FTI.hasExceptionSpec &&
1140          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1141        Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1142
1143      if (!FTI.NumArgs && !FTI.isVariadic && !getLangOptions().CPlusPlus) {
1144        // Simple void foo(), where the incoming T is the result type.
1145        T = Context.getFunctionNoProtoType(T);
1146      } else {
1147        // We allow a zero-parameter variadic function in C if the
1148        // function is marked with the "overloadable" attribute. Scan
1149        // for this attribute now.
1150        if (!FTI.NumArgs && FTI.isVariadic && !getLangOptions().CPlusPlus) {
1151          bool Overloadable = false;
1152          for (const AttributeList *Attrs = D.getAttributes();
1153               Attrs; Attrs = Attrs->getNext()) {
1154            if (Attrs->getKind() == AttributeList::AT_overloadable) {
1155              Overloadable = true;
1156              break;
1157            }
1158          }
1159
1160          if (!Overloadable)
1161            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1162        }
1163
1164        if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
1165          // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
1166          Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1167          D.setInvalidType(true);
1168          break;
1169        }
1170
1171        // Otherwise, we have a function with an argument list that is
1172        // potentially variadic.
1173        llvm::SmallVector<QualType, 16> ArgTys;
1174        ArgTys.reserve(FTI.NumArgs);
1175
1176        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1177          ParmVarDecl *Param =
1178            cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1179          QualType ArgTy = Param->getType();
1180          assert(!ArgTy.isNull() && "Couldn't parse type?");
1181
1182          // Adjust the parameter type.
1183          assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1184
1185          // Look for 'void'.  void is allowed only as a single argument to a
1186          // function with no other parameters (C99 6.7.5.3p10).  We record
1187          // int(void) as a FunctionProtoType with an empty argument list.
1188          if (ArgTy->isVoidType()) {
1189            // If this is something like 'float(int, void)', reject it.  'void'
1190            // is an incomplete type (C99 6.2.5p19) and function decls cannot
1191            // have arguments of incomplete type.
1192            if (FTI.NumArgs != 1 || FTI.isVariadic) {
1193              Diag(DeclType.Loc, diag::err_void_only_param);
1194              ArgTy = Context.IntTy;
1195              Param->setType(ArgTy);
1196            } else if (FTI.ArgInfo[i].Ident) {
1197              // Reject, but continue to parse 'int(void abc)'.
1198              Diag(FTI.ArgInfo[i].IdentLoc,
1199                   diag::err_param_with_void_type);
1200              ArgTy = Context.IntTy;
1201              Param->setType(ArgTy);
1202            } else {
1203              // Reject, but continue to parse 'float(const void)'.
1204              if (ArgTy.hasQualifiers())
1205                Diag(DeclType.Loc, diag::err_void_param_qualified);
1206
1207              // Do not add 'void' to the ArgTys list.
1208              break;
1209            }
1210          } else if (!FTI.hasPrototype) {
1211            if (ArgTy->isPromotableIntegerType()) {
1212              ArgTy = Context.getPromotedIntegerType(ArgTy);
1213            } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1214              if (BTy->getKind() == BuiltinType::Float)
1215                ArgTy = Context.DoubleTy;
1216            }
1217          }
1218
1219          ArgTys.push_back(ArgTy);
1220        }
1221
1222        llvm::SmallVector<QualType, 4> Exceptions;
1223        Exceptions.reserve(FTI.NumExceptions);
1224        for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1225          // FIXME: Preserve type source info.
1226          QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1227          // Check that the type is valid for an exception spec, and drop it if
1228          // not.
1229          if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1230            Exceptions.push_back(ET);
1231        }
1232
1233        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1234                                    FTI.isVariadic, FTI.TypeQuals,
1235                                    FTI.hasExceptionSpec,
1236                                    FTI.hasAnyExceptionSpec,
1237                                    Exceptions.size(), Exceptions.data(),
1238                                    FunctionType::ExtInfo());
1239      }
1240
1241      // For GCC compatibility, we allow attributes that apply only to
1242      // function types to be placed on a function's return type
1243      // instead (as long as that type doesn't happen to be function
1244      // or function-pointer itself).
1245      ProcessDelayedFnAttrs(*this, T, FnAttrsFromPreviousChunk);
1246
1247      break;
1248    }
1249    case DeclaratorChunk::MemberPointer:
1250      // The scope spec must refer to a class, or be dependent.
1251      QualType ClsType;
1252      if (DeclType.Mem.Scope().isInvalid()) {
1253        // Avoid emitting extra errors if we already errored on the scope.
1254        D.setInvalidType(true);
1255      } else if (isDependentScopeSpecifier(DeclType.Mem.Scope())
1256                 || dyn_cast_or_null<CXXRecordDecl>(
1257                                   computeDeclContext(DeclType.Mem.Scope()))) {
1258        NestedNameSpecifier *NNS
1259          = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1260        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1261        switch (NNS->getKind()) {
1262        case NestedNameSpecifier::Identifier:
1263          ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
1264                                                 NNS->getAsIdentifier());
1265          break;
1266
1267        case NestedNameSpecifier::Namespace:
1268        case NestedNameSpecifier::Global:
1269          llvm_unreachable("Nested-name-specifier must name a type");
1270          break;
1271
1272        case NestedNameSpecifier::TypeSpec:
1273        case NestedNameSpecifier::TypeSpecWithTemplate:
1274          ClsType = QualType(NNS->getAsType(), 0);
1275          if (NNSPrefix)
1276            ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
1277          break;
1278        }
1279      } else {
1280        Diag(DeclType.Mem.Scope().getBeginLoc(),
1281             diag::err_illegal_decl_mempointer_in_nonclass)
1282          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1283          << DeclType.Mem.Scope().getRange();
1284        D.setInvalidType(true);
1285      }
1286
1287      if (!ClsType.isNull())
1288        T = BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
1289      if (T.isNull()) {
1290        T = Context.IntTy;
1291        D.setInvalidType(true);
1292      } else if (DeclType.Mem.TypeQuals) {
1293        T = BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
1294      }
1295      break;
1296    }
1297
1298    if (T.isNull()) {
1299      D.setInvalidType(true);
1300      T = Context.IntTy;
1301    }
1302
1303    DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
1304
1305    // See if there are any attributes on this declarator chunk.
1306    if (const AttributeList *AL = DeclType.getAttrs())
1307      ProcessTypeAttributeList(*this, T, false, AL, FnAttrsFromPreviousChunk);
1308  }
1309
1310  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1311    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
1312    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
1313
1314    // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1315    // for a nonstatic member function, the function type to which a pointer
1316    // to member refers, or the top-level function type of a function typedef
1317    // declaration.
1318    if (FnTy->getTypeQuals() != 0 &&
1319        D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1320        ((D.getContext() != Declarator::MemberContext &&
1321          (!D.getCXXScopeSpec().isSet() ||
1322           !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true)
1323              ->isRecord())) ||
1324         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1325      if (D.isFunctionDeclarator())
1326        Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1327      else
1328        Diag(D.getIdentifierLoc(),
1329             diag::err_invalid_qualified_typedef_function_type_use);
1330
1331      // Strip the cv-quals from the type.
1332      T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1333                                  FnTy->getNumArgs(), FnTy->isVariadic(), 0,
1334                                  false, false, 0, 0, FunctionType::ExtInfo());
1335    }
1336  }
1337
1338  // Process any function attributes we might have delayed from the
1339  // declaration-specifiers.
1340  ProcessDelayedFnAttrs(*this, T, FnAttrsFromDeclSpec);
1341
1342  // If there were any type attributes applied to the decl itself, not
1343  // the type, apply them to the result type.  But don't do this for
1344  // block-literal expressions, which are parsed wierdly.
1345  if (D.getContext() != Declarator::BlockLiteralContext)
1346    if (const AttributeList *Attrs = D.getAttributes())
1347      ProcessTypeAttributeList(*this, T, false, Attrs,
1348                               FnAttrsFromPreviousChunk);
1349
1350  DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk);
1351
1352  if (T.isNull())
1353    return Context.getNullTypeSourceInfo();
1354  else if (D.isInvalidType())
1355    return Context.getTrivialTypeSourceInfo(T);
1356  return GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo);
1357}
1358
1359namespace {
1360  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
1361    const DeclSpec &DS;
1362
1363  public:
1364    TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {}
1365
1366    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1367      Visit(TL.getUnqualifiedLoc());
1368    }
1369    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1370      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1371    }
1372    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1373      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1374    }
1375    void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1376      // Handle the base type, which might not have been written explicitly.
1377      if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1378        TL.setHasBaseTypeAsWritten(false);
1379        TL.getBaseLoc().initialize(SourceLocation());
1380      } else {
1381        TL.setHasBaseTypeAsWritten(true);
1382        Visit(TL.getBaseLoc());
1383      }
1384
1385      // Protocol qualifiers.
1386      if (DS.getProtocolQualifiers()) {
1387        assert(TL.getNumProtocols() > 0);
1388        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1389        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1390        TL.setRAngleLoc(DS.getSourceRange().getEnd());
1391        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1392          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1393      } else {
1394        assert(TL.getNumProtocols() == 0);
1395        TL.setLAngleLoc(SourceLocation());
1396        TL.setRAngleLoc(SourceLocation());
1397      }
1398    }
1399    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1400      TL.setStarLoc(SourceLocation());
1401      Visit(TL.getPointeeLoc());
1402    }
1403    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
1404      TypeSourceInfo *TInfo = 0;
1405      Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1406
1407      // If we got no declarator info from previous Sema routines,
1408      // just fill with the typespec loc.
1409      if (!TInfo) {
1410        TL.initialize(DS.getTypeSpecTypeLoc());
1411        return;
1412      }
1413
1414      TypeLoc OldTL = TInfo->getTypeLoc();
1415      if (TInfo->getType()->getAs<ElaboratedType>()) {
1416        ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
1417        TemplateSpecializationTypeLoc NamedTL =
1418          cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
1419        TL.copy(NamedTL);
1420      }
1421      else
1422        TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
1423    }
1424    void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1425      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
1426      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1427      TL.setParensRange(DS.getTypeofParensRange());
1428    }
1429    void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1430      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
1431      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
1432      TL.setParensRange(DS.getTypeofParensRange());
1433      assert(DS.getTypeRep());
1434      TypeSourceInfo *TInfo = 0;
1435      Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1436      TL.setUnderlyingTInfo(TInfo);
1437    }
1438    void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1439      // By default, use the source location of the type specifier.
1440      TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
1441      if (TL.needsExtraLocalData()) {
1442        // Set info for the written builtin specifiers.
1443        TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
1444        // Try to have a meaningful source location.
1445        if (TL.getWrittenSignSpec() != TSS_unspecified)
1446          // Sign spec loc overrides the others (e.g., 'unsigned long').
1447          TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
1448        else if (TL.getWrittenWidthSpec() != TSW_unspecified)
1449          // Width spec loc overrides type spec loc (e.g., 'short int').
1450          TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
1451      }
1452    }
1453    void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
1454      ElaboratedTypeKeyword Keyword
1455        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
1456      if (Keyword == ETK_Typename) {
1457        TypeSourceInfo *TInfo = 0;
1458        Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1459        if (TInfo) {
1460          TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
1461          return;
1462        }
1463      }
1464      TL.setKeywordLoc(Keyword != ETK_None
1465                       ? DS.getTypeSpecTypeLoc()
1466                       : SourceLocation());
1467      const CXXScopeSpec& SS = DS.getTypeSpecScope();
1468      TL.setQualifierRange(SS.isEmpty() ? SourceRange(): SS.getRange());
1469      Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
1470    }
1471    void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
1472      ElaboratedTypeKeyword Keyword
1473        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
1474      if (Keyword == ETK_Typename) {
1475        TypeSourceInfo *TInfo = 0;
1476        Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo);
1477        if (TInfo) {
1478          TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
1479          return;
1480        }
1481      }
1482      TL.setKeywordLoc(Keyword != ETK_None
1483                       ? DS.getTypeSpecTypeLoc()
1484                       : SourceLocation());
1485      const CXXScopeSpec& SS = DS.getTypeSpecScope();
1486      TL.setQualifierRange(SS.isEmpty() ? SourceRange() : SS.getRange());
1487      // FIXME: load appropriate source location.
1488      TL.setNameLoc(DS.getTypeSpecTypeLoc());
1489    }
1490
1491    void VisitTypeLoc(TypeLoc TL) {
1492      // FIXME: add other typespec types and change this to an assert.
1493      TL.initialize(DS.getTypeSpecTypeLoc());
1494    }
1495  };
1496
1497  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
1498    const DeclaratorChunk &Chunk;
1499
1500  public:
1501    DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
1502
1503    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1504      llvm_unreachable("qualified type locs not expected here!");
1505    }
1506
1507    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1508      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
1509      TL.setCaretLoc(Chunk.Loc);
1510    }
1511    void VisitPointerTypeLoc(PointerTypeLoc TL) {
1512      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1513      TL.setStarLoc(Chunk.Loc);
1514    }
1515    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1516      assert(Chunk.Kind == DeclaratorChunk::Pointer);
1517      TL.setStarLoc(Chunk.Loc);
1518    }
1519    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1520      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
1521      TL.setStarLoc(Chunk.Loc);
1522      // FIXME: nested name specifier
1523    }
1524    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1525      assert(Chunk.Kind == DeclaratorChunk::Reference);
1526      // 'Amp' is misleading: this might have been originally
1527      /// spelled with AmpAmp.
1528      TL.setAmpLoc(Chunk.Loc);
1529    }
1530    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1531      assert(Chunk.Kind == DeclaratorChunk::Reference);
1532      assert(!Chunk.Ref.LValueRef);
1533      TL.setAmpAmpLoc(Chunk.Loc);
1534    }
1535    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
1536      assert(Chunk.Kind == DeclaratorChunk::Array);
1537      TL.setLBracketLoc(Chunk.Loc);
1538      TL.setRBracketLoc(Chunk.EndLoc);
1539      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
1540    }
1541    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
1542      assert(Chunk.Kind == DeclaratorChunk::Function);
1543      TL.setLParenLoc(Chunk.Loc);
1544      TL.setRParenLoc(Chunk.EndLoc);
1545
1546      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
1547      for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
1548        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1549        TL.setArg(tpi++, Param);
1550      }
1551      // FIXME: exception specs
1552    }
1553
1554    void VisitTypeLoc(TypeLoc TL) {
1555      llvm_unreachable("unsupported TypeLoc kind in declarator!");
1556    }
1557  };
1558}
1559
1560/// \brief Create and instantiate a TypeSourceInfo with type source information.
1561///
1562/// \param T QualType referring to the type as written in source code.
1563///
1564/// \param ReturnTypeInfo For declarators whose return type does not show
1565/// up in the normal place in the declaration specifiers (such as a C++
1566/// conversion function), this pointer will refer to a type source information
1567/// for that return type.
1568TypeSourceInfo *
1569Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1570                                     TypeSourceInfo *ReturnTypeInfo) {
1571  TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
1572  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
1573
1574  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1575    DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
1576    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
1577  }
1578
1579  TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL);
1580
1581  // We have source information for the return type that was not in the
1582  // declaration specifiers; copy that information into the current type
1583  // location so that it will be retained. This occurs, for example, with
1584  // a C++ conversion function, where the return type occurs within the
1585  // declarator-id rather than in the declaration specifiers.
1586  if (ReturnTypeInfo && D.getDeclSpec().getTypeSpecType() == TST_unspecified) {
1587    TypeLoc TL = ReturnTypeInfo->getTypeLoc();
1588    assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
1589    memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
1590  }
1591
1592  return TInfo;
1593}
1594
1595/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
1596QualType Sema::CreateLocInfoType(QualType T, TypeSourceInfo *TInfo) {
1597  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1598  // and Sema during declaration parsing. Try deallocating/caching them when
1599  // it's appropriate, instead of allocating them and keeping them around.
1600  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1601  new (LocT) LocInfoType(T, TInfo);
1602  assert(LocT->getTypeClass() != T->getTypeClass() &&
1603         "LocInfoType's TypeClass conflicts with an existing Type class");
1604  return QualType(LocT, 0);
1605}
1606
1607void LocInfoType::getAsStringInternal(std::string &Str,
1608                                      const PrintingPolicy &Policy) const {
1609  assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1610         " was used directly instead of getting the QualType through"
1611         " GetTypeFromParser");
1612}
1613
1614/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
1615/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1616/// they point to and return true. If T1 and T2 aren't pointer types
1617/// or pointer-to-member types, or if they are not similar at this
1618/// level, returns false and leaves T1 and T2 unchanged. Top-level
1619/// qualifiers on T1 and T2 are ignored. This function will typically
1620/// be called in a loop that successively "unwraps" pointer and
1621/// pointer-to-member types to compare them at each level.
1622bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1623  const PointerType *T1PtrType = T1->getAs<PointerType>(),
1624                    *T2PtrType = T2->getAs<PointerType>();
1625  if (T1PtrType && T2PtrType) {
1626    T1 = T1PtrType->getPointeeType();
1627    T2 = T2PtrType->getPointeeType();
1628    return true;
1629  }
1630
1631  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1632                          *T2MPType = T2->getAs<MemberPointerType>();
1633  if (T1MPType && T2MPType &&
1634      Context.getCanonicalType(T1MPType->getClass()) ==
1635      Context.getCanonicalType(T2MPType->getClass())) {
1636    T1 = T1MPType->getPointeeType();
1637    T2 = T2MPType->getPointeeType();
1638    return true;
1639  }
1640
1641  if (getLangOptions().ObjC1) {
1642    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
1643                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
1644    if (T1OPType && T2OPType) {
1645      T1 = T1OPType->getPointeeType();
1646      T2 = T2OPType->getPointeeType();
1647      return true;
1648    }
1649  }
1650  return false;
1651}
1652
1653Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1654  // C99 6.7.6: Type names have no identifier.  This is already validated by
1655  // the parser.
1656  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1657
1658  TagDecl *OwnedTag = 0;
1659  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
1660  QualType T = TInfo->getType();
1661  if (D.isInvalidType())
1662    return true;
1663
1664  if (getLangOptions().CPlusPlus) {
1665    // Check that there are no default arguments (C++ only).
1666    CheckExtraCXXDefaultArguments(D);
1667
1668    // C++0x [dcl.type]p3:
1669    //   A type-specifier-seq shall not define a class or enumeration
1670    //   unless it appears in the type-id of an alias-declaration
1671    //   (7.1.3).
1672    if (OwnedTag && OwnedTag->isDefinition())
1673      Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1674        << Context.getTypeDeclType(OwnedTag);
1675  }
1676
1677  T = CreateLocInfoType(T, TInfo);
1678  return T.getAsOpaquePtr();
1679}
1680
1681
1682
1683//===----------------------------------------------------------------------===//
1684// Type Attribute Processing
1685//===----------------------------------------------------------------------===//
1686
1687/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1688/// specified type.  The attribute contains 1 argument, the id of the address
1689/// space for the type.
1690static void HandleAddressSpaceTypeAttribute(QualType &Type,
1691                                            const AttributeList &Attr, Sema &S){
1692
1693  // If this type is already address space qualified, reject it.
1694  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1695  // for two or more different address spaces."
1696  if (Type.getAddressSpace()) {
1697    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1698    Attr.setInvalid();
1699    return;
1700  }
1701
1702  // Check the attribute arguments.
1703  if (Attr.getNumArgs() != 1) {
1704    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1705    Attr.setInvalid();
1706    return;
1707  }
1708  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1709  llvm::APSInt addrSpace(32);
1710  if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
1711      !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1712    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1713      << ASArgExpr->getSourceRange();
1714    Attr.setInvalid();
1715    return;
1716  }
1717
1718  // Bounds checking.
1719  if (addrSpace.isSigned()) {
1720    if (addrSpace.isNegative()) {
1721      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1722        << ASArgExpr->getSourceRange();
1723      Attr.setInvalid();
1724      return;
1725    }
1726    addrSpace.setIsSigned(false);
1727  }
1728  llvm::APSInt max(addrSpace.getBitWidth());
1729  max = Qualifiers::MaxAddressSpace;
1730  if (addrSpace > max) {
1731    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1732      << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1733    Attr.setInvalid();
1734    return;
1735  }
1736
1737  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1738  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1739}
1740
1741/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1742/// specified type.  The attribute contains 1 argument, weak or strong.
1743static void HandleObjCGCTypeAttribute(QualType &Type,
1744                                      const AttributeList &Attr, Sema &S) {
1745  if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1746    S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1747    Attr.setInvalid();
1748    return;
1749  }
1750
1751  // Check the attribute arguments.
1752  if (!Attr.getParameterName()) {
1753    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1754      << "objc_gc" << 1;
1755    Attr.setInvalid();
1756    return;
1757  }
1758  Qualifiers::GC GCAttr;
1759  if (Attr.getNumArgs() != 0) {
1760    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1761    Attr.setInvalid();
1762    return;
1763  }
1764  if (Attr.getParameterName()->isStr("weak"))
1765    GCAttr = Qualifiers::Weak;
1766  else if (Attr.getParameterName()->isStr("strong"))
1767    GCAttr = Qualifiers::Strong;
1768  else {
1769    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1770      << "objc_gc" << Attr.getParameterName();
1771    Attr.setInvalid();
1772    return;
1773  }
1774
1775  Type = S.Context.getObjCGCQualType(Type, GCAttr);
1776}
1777
1778/// Process an individual function attribute.  Returns true if the
1779/// attribute does not make sense to apply to this type.
1780bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr) {
1781  if (Attr.getKind() == AttributeList::AT_noreturn) {
1782    // Complain immediately if the arg count is wrong.
1783    if (Attr.getNumArgs() != 0) {
1784      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1785      Attr.setInvalid();
1786      return false;
1787    }
1788
1789    // Delay if this is not a function or pointer to block.
1790    if (!Type->isFunctionPointerType()
1791        && !Type->isBlockPointerType()
1792        && !Type->isFunctionType())
1793      return true;
1794
1795    // Otherwise we can process right away.
1796    Type = S.Context.getNoReturnType(Type);
1797    return false;
1798  }
1799
1800  if (Attr.getKind() == AttributeList::AT_regparm) {
1801    // The warning is emitted elsewhere
1802    if (Attr.getNumArgs() != 1) {
1803      return false;
1804    }
1805
1806    // Delay if this is not a function or pointer to block.
1807    if (!Type->isFunctionPointerType()
1808        && !Type->isBlockPointerType()
1809        && !Type->isFunctionType())
1810      return true;
1811
1812    // Otherwise we can process right away.
1813    Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArg(0));
1814    llvm::APSInt NumParams(32);
1815
1816    // The warning is emitted elsewhere
1817    if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
1818        !NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context))
1819      return false;
1820
1821    Type = S.Context.getRegParmType(Type, NumParams.getZExtValue());
1822    return false;
1823  }
1824
1825  // Otherwise, a calling convention.
1826  if (Attr.getNumArgs() != 0) {
1827    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1828    Attr.setInvalid();
1829    return false;
1830  }
1831
1832  QualType T = Type;
1833  if (const PointerType *PT = Type->getAs<PointerType>())
1834    T = PT->getPointeeType();
1835  const FunctionType *Fn = T->getAs<FunctionType>();
1836
1837  // Delay if the type didn't work out to a function.
1838  if (!Fn) return true;
1839
1840  // TODO: diagnose uses of these conventions on the wrong target.
1841  CallingConv CC;
1842  switch (Attr.getKind()) {
1843  case AttributeList::AT_cdecl: CC = CC_C; break;
1844  case AttributeList::AT_fastcall: CC = CC_X86FastCall; break;
1845  case AttributeList::AT_stdcall: CC = CC_X86StdCall; break;
1846  case AttributeList::AT_thiscall: CC = CC_X86ThisCall; break;
1847  default: llvm_unreachable("unexpected attribute kind"); return false;
1848  }
1849
1850  CallingConv CCOld = Fn->getCallConv();
1851  if (S.Context.getCanonicalCallConv(CC) ==
1852      S.Context.getCanonicalCallConv(CCOld)) {
1853    Attr.setInvalid();
1854    return false;
1855  }
1856
1857  if (CCOld != CC_Default) {
1858    // Should we diagnose reapplications of the same convention?
1859    S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1860      << FunctionType::getNameForCallConv(CC)
1861      << FunctionType::getNameForCallConv(CCOld);
1862    Attr.setInvalid();
1863    return false;
1864  }
1865
1866  // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
1867  if (CC == CC_X86FastCall) {
1868    if (isa<FunctionNoProtoType>(Fn)) {
1869      S.Diag(Attr.getLoc(), diag::err_cconv_knr)
1870        << FunctionType::getNameForCallConv(CC);
1871      Attr.setInvalid();
1872      return false;
1873    }
1874
1875    const FunctionProtoType *FnP = cast<FunctionProtoType>(Fn);
1876    if (FnP->isVariadic()) {
1877      S.Diag(Attr.getLoc(), diag::err_cconv_varargs)
1878        << FunctionType::getNameForCallConv(CC);
1879      Attr.setInvalid();
1880      return false;
1881    }
1882  }
1883
1884  Type = S.Context.getCallConvType(Type, CC);
1885  return false;
1886}
1887
1888/// HandleVectorSizeAttribute - this attribute is only applicable to integral
1889/// and float scalars, although arrays, pointers, and function return values are
1890/// allowed in conjunction with this construct. Aggregates with this attribute
1891/// are invalid, even if they are of the same size as a corresponding scalar.
1892/// The raw attribute should contain precisely 1 argument, the vector size for
1893/// the variable, measured in bytes. If curType and rawAttr are well formed,
1894/// this routine will return a new vector type.
1895static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, Sema &S) {
1896  // Check the attribute arugments.
1897  if (Attr.getNumArgs() != 1) {
1898    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1899    Attr.setInvalid();
1900    return;
1901  }
1902  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
1903  llvm::APSInt vecSize(32);
1904  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
1905      !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
1906    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1907      << "vector_size" << sizeExpr->getSourceRange();
1908    Attr.setInvalid();
1909    return;
1910  }
1911  // the base type must be integer or float, and can't already be a vector.
1912  if (CurType->isVectorType() ||
1913      (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
1914    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
1915    Attr.setInvalid();
1916    return;
1917  }
1918  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
1919  // vecSize is specified in bytes - convert to bits.
1920  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
1921
1922  // the vector size needs to be an integral multiple of the type size.
1923  if (vectorSize % typeSize) {
1924    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
1925      << sizeExpr->getSourceRange();
1926    Attr.setInvalid();
1927    return;
1928  }
1929  if (vectorSize == 0) {
1930    S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
1931      << sizeExpr->getSourceRange();
1932    Attr.setInvalid();
1933    return;
1934  }
1935
1936  // Success! Instantiate the vector type, the number of elements is > 0, and
1937  // not required to be a power of 2, unlike GCC.
1938  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, false, false);
1939}
1940
1941void ProcessTypeAttributeList(Sema &S, QualType &Result,
1942                              bool IsDeclSpec, const AttributeList *AL,
1943                              DelayedAttributeSet &FnAttrs) {
1944  // Scan through and apply attributes to this type where it makes sense.  Some
1945  // attributes (such as __address_space__, __vector_size__, etc) apply to the
1946  // type, but others can be present in the type specifiers even though they
1947  // apply to the decl.  Here we apply type attributes and ignore the rest.
1948  for (; AL; AL = AL->getNext()) {
1949    // Skip attributes that were marked to be invalid.
1950    if (AL->isInvalid())
1951      continue;
1952
1953    // If this is an attribute we can handle, do so now,
1954    // otherwise, add it to the FnAttrs list for rechaining.
1955    switch (AL->getKind()) {
1956    default: break;
1957
1958    case AttributeList::AT_address_space:
1959      HandleAddressSpaceTypeAttribute(Result, *AL, S);
1960      break;
1961    case AttributeList::AT_objc_gc:
1962      HandleObjCGCTypeAttribute(Result, *AL, S);
1963      break;
1964    case AttributeList::AT_vector_size:
1965      HandleVectorSizeAttr(Result, *AL, S);
1966      break;
1967
1968    case AttributeList::AT_noreturn:
1969    case AttributeList::AT_cdecl:
1970    case AttributeList::AT_fastcall:
1971    case AttributeList::AT_stdcall:
1972    case AttributeList::AT_thiscall:
1973    case AttributeList::AT_regparm:
1974      // Don't process these on the DeclSpec.
1975      if (IsDeclSpec ||
1976          ProcessFnAttr(S, Result, *AL))
1977        FnAttrs.push_back(DelayedAttribute(AL, Result));
1978      break;
1979    }
1980  }
1981}
1982
1983/// @brief Ensure that the type T is a complete type.
1984///
1985/// This routine checks whether the type @p T is complete in any
1986/// context where a complete type is required. If @p T is a complete
1987/// type, returns false. If @p T is a class template specialization,
1988/// this routine then attempts to perform class template
1989/// instantiation. If instantiation fails, or if @p T is incomplete
1990/// and cannot be completed, issues the diagnostic @p diag (giving it
1991/// the type @p T) and returns true.
1992///
1993/// @param Loc  The location in the source that the incomplete type
1994/// diagnostic should refer to.
1995///
1996/// @param T  The type that this routine is examining for completeness.
1997///
1998/// @param PD The partial diagnostic that will be printed out if T is not a
1999/// complete type.
2000///
2001/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
2002/// @c false otherwise.
2003bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2004                               const PartialDiagnostic &PD,
2005                               std::pair<SourceLocation,
2006                                         PartialDiagnostic> Note) {
2007  unsigned diag = PD.getDiagID();
2008
2009  // FIXME: Add this assertion to make sure we always get instantiation points.
2010  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
2011  // FIXME: Add this assertion to help us flush out problems with
2012  // checking for dependent types and type-dependent expressions.
2013  //
2014  //  assert(!T->isDependentType() &&
2015  //         "Can't ask whether a dependent type is complete");
2016
2017  // If we have a complete type, we're done.
2018  if (!T->isIncompleteType())
2019    return false;
2020
2021  // If we have a class template specialization or a class member of a
2022  // class template specialization, or an array with known size of such,
2023  // try to instantiate it.
2024  QualType MaybeTemplate = T;
2025  if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
2026    MaybeTemplate = Array->getElementType();
2027  if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
2028    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
2029          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
2030      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
2031        return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
2032                                                      TSK_ImplicitInstantiation,
2033                                                      /*Complain=*/diag != 0);
2034    } else if (CXXRecordDecl *Rec
2035                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
2036      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
2037        MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
2038        assert(MSInfo && "Missing member specialization information?");
2039        // This record was instantiated from a class within a template.
2040        if (MSInfo->getTemplateSpecializationKind()
2041                                               != TSK_ExplicitSpecialization)
2042          return InstantiateClass(Loc, Rec, Pattern,
2043                                  getTemplateInstantiationArgs(Rec),
2044                                  TSK_ImplicitInstantiation,
2045                                  /*Complain=*/diag != 0);
2046      }
2047    }
2048  }
2049
2050  if (diag == 0)
2051    return true;
2052
2053  const TagType *Tag = 0;
2054  if (const RecordType *Record = T->getAs<RecordType>())
2055    Tag = Record;
2056  else if (const EnumType *Enum = T->getAs<EnumType>())
2057    Tag = Enum;
2058
2059  // Avoid diagnosing invalid decls as incomplete.
2060  if (Tag && Tag->getDecl()->isInvalidDecl())
2061    return true;
2062
2063  // We have an incomplete type. Produce a diagnostic.
2064  Diag(Loc, PD) << T;
2065
2066  // If we have a note, produce it.
2067  if (!Note.first.isInvalid())
2068    Diag(Note.first, Note.second);
2069
2070  // If the type was a forward declaration of a class/struct/union
2071  // type, produce a note.
2072  if (Tag && !Tag->getDecl()->isInvalidDecl())
2073    Diag(Tag->getDecl()->getLocation(),
2074         Tag->isBeingDefined() ? diag::note_type_being_defined
2075                               : diag::note_forward_declaration)
2076        << QualType(Tag, 0);
2077
2078  return true;
2079}
2080
2081bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2082                               const PartialDiagnostic &PD) {
2083  return RequireCompleteType(Loc, T, PD,
2084                             std::make_pair(SourceLocation(), PDiag(0)));
2085}
2086
2087bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2088                               unsigned DiagID) {
2089  return RequireCompleteType(Loc, T, PDiag(DiagID),
2090                             std::make_pair(SourceLocation(), PDiag(0)));
2091}
2092
2093/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
2094/// and qualified by the nested-name-specifier contained in SS.
2095QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
2096                                 const CXXScopeSpec &SS, QualType T) {
2097  if (T.isNull())
2098    return T;
2099  NestedNameSpecifier *NNS;
2100  if (SS.isValid())
2101    NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2102  else {
2103    if (Keyword == ETK_None)
2104      return T;
2105    NNS = 0;
2106  }
2107  return Context.getElaboratedType(Keyword, NNS, T);
2108}
2109
2110QualType Sema::BuildTypeofExprType(Expr *E) {
2111  if (E->getType() == Context.OverloadTy) {
2112    // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2113    // function template specialization wherever deduction cannot occur.
2114    if (FunctionDecl *Specialization
2115        = ResolveSingleFunctionTemplateSpecialization(E)) {
2116      // The access doesn't really matter in this case.
2117      DeclAccessPair Found = DeclAccessPair::make(Specialization,
2118                                                  Specialization->getAccess());
2119      E = FixOverloadedFunctionReference(E, Found, Specialization);
2120      if (!E)
2121        return QualType();
2122    } else {
2123      Diag(E->getLocStart(),
2124           diag::err_cannot_determine_declared_type_of_overloaded_function)
2125        << false << E->getSourceRange();
2126      return QualType();
2127    }
2128  }
2129
2130  return Context.getTypeOfExprType(E);
2131}
2132
2133QualType Sema::BuildDecltypeType(Expr *E) {
2134  if (E->getType() == Context.OverloadTy) {
2135    // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a
2136    // function template specialization wherever deduction cannot occur.
2137    if (FunctionDecl *Specialization
2138          = ResolveSingleFunctionTemplateSpecialization(E)) {
2139      // The access doesn't really matter in this case.
2140      DeclAccessPair Found = DeclAccessPair::make(Specialization,
2141                                                  Specialization->getAccess());
2142      E = FixOverloadedFunctionReference(E, Found, Specialization);
2143      if (!E)
2144        return QualType();
2145    } else {
2146      Diag(E->getLocStart(),
2147           diag::err_cannot_determine_declared_type_of_overloaded_function)
2148        << true << E->getSourceRange();
2149      return QualType();
2150    }
2151  }
2152
2153  return Context.getDecltypeType(E);
2154}
2155