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