SemaType.cpp revision 7a614d8380297fcd2bc23986241905d97222948c
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/Basic/OpenCL.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/TypeLoc.h"
23#include "clang/AST/TypeLocVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/Basic/PartialDiagnostic.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Lex/Preprocessor.h"
28#include "clang/Sema/DeclSpec.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/Support/ErrorHandling.h"
31using namespace clang;
32
33/// \brief Perform adjustment on the parameter type of a function.
34///
35/// This routine adjusts the given parameter type @p T to the actual
36/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
37/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
38QualType Sema::adjustParameterType(QualType T) {
39  // C99 6.7.5.3p7:
40  //   A declaration of a parameter as "array of type" shall be
41  //   adjusted to "qualified pointer to type", where the type
42  //   qualifiers (if any) are those specified within the [ and ] of
43  //   the array type derivation.
44  if (T->isArrayType())
45    return Context.getArrayDecayedType(T);
46
47  // C99 6.7.5.3p8:
48  //   A declaration of a parameter as "function returning type"
49  //   shall be adjusted to "pointer to function returning type", as
50  //   in 6.3.2.1.
51  if (T->isFunctionType())
52    return Context.getPointerType(T);
53
54  return T;
55}
56
57
58
59/// isOmittedBlockReturnType - Return true if this declarator is missing a
60/// return type because this is a omitted return type on a block literal.
61static bool isOmittedBlockReturnType(const Declarator &D) {
62  if (D.getContext() != Declarator::BlockLiteralContext ||
63      D.getDeclSpec().hasTypeSpecifier())
64    return false;
65
66  if (D.getNumTypeObjects() == 0)
67    return true;   // ^{ ... }
68
69  if (D.getNumTypeObjects() == 1 &&
70      D.getTypeObject(0).Kind == DeclaratorChunk::Function)
71    return true;   // ^(int X, float Y) { ... }
72
73  return false;
74}
75
76/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
77/// doesn't apply to the given type.
78static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
79                                     QualType type) {
80  bool useInstantiationLoc = false;
81
82  unsigned diagID = 0;
83  switch (attr.getKind()) {
84  case AttributeList::AT_objc_gc:
85    diagID = diag::warn_pointer_attribute_wrong_type;
86    useInstantiationLoc = true;
87    break;
88
89  default:
90    // Assume everything else was a function attribute.
91    diagID = diag::warn_function_attribute_wrong_type;
92    break;
93  }
94
95  SourceLocation loc = attr.getLoc();
96  llvm::StringRef name = attr.getName()->getName();
97
98  // The GC attributes are usually written with macros;  special-case them.
99  if (useInstantiationLoc && loc.isMacroID() && attr.getParameterName()) {
100    if (attr.getParameterName()->isStr("strong")) {
101      if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
102    } else if (attr.getParameterName()->isStr("weak")) {
103      if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
104    }
105  }
106
107  S.Diag(loc, diagID) << name << type;
108}
109
110// objc_gc applies to Objective-C pointers or, otherwise, to the
111// smallest available pointer type (i.e. 'void*' in 'void**').
112#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
113    case AttributeList::AT_objc_gc
114
115// Function type attributes.
116#define FUNCTION_TYPE_ATTRS_CASELIST \
117    case AttributeList::AT_noreturn: \
118    case AttributeList::AT_cdecl: \
119    case AttributeList::AT_fastcall: \
120    case AttributeList::AT_stdcall: \
121    case AttributeList::AT_thiscall: \
122    case AttributeList::AT_pascal: \
123    case AttributeList::AT_regparm: \
124    case AttributeList::AT_pcs \
125
126namespace {
127  /// An object which stores processing state for the entire
128  /// GetTypeForDeclarator process.
129  class TypeProcessingState {
130    Sema &sema;
131
132    /// The declarator being processed.
133    Declarator &declarator;
134
135    /// The index of the declarator chunk we're currently processing.
136    /// May be the total number of valid chunks, indicating the
137    /// DeclSpec.
138    unsigned chunkIndex;
139
140    /// Whether there are non-trivial modifications to the decl spec.
141    bool trivial;
142
143    /// Whether we saved the attributes in the decl spec.
144    bool hasSavedAttrs;
145
146    /// The original set of attributes on the DeclSpec.
147    llvm::SmallVector<AttributeList*, 2> savedAttrs;
148
149    /// A list of attributes to diagnose the uselessness of when the
150    /// processing is complete.
151    llvm::SmallVector<AttributeList*, 2> ignoredTypeAttrs;
152
153  public:
154    TypeProcessingState(Sema &sema, Declarator &declarator)
155      : sema(sema), declarator(declarator),
156        chunkIndex(declarator.getNumTypeObjects()),
157        trivial(true), hasSavedAttrs(false) {}
158
159    Sema &getSema() const {
160      return sema;
161    }
162
163    Declarator &getDeclarator() const {
164      return declarator;
165    }
166
167    unsigned getCurrentChunkIndex() const {
168      return chunkIndex;
169    }
170
171    void setCurrentChunkIndex(unsigned idx) {
172      assert(idx <= declarator.getNumTypeObjects());
173      chunkIndex = idx;
174    }
175
176    AttributeList *&getCurrentAttrListRef() const {
177      assert(chunkIndex <= declarator.getNumTypeObjects());
178      if (chunkIndex == declarator.getNumTypeObjects())
179        return getMutableDeclSpec().getAttributes().getListRef();
180      return declarator.getTypeObject(chunkIndex).getAttrListRef();
181    }
182
183    /// Save the current set of attributes on the DeclSpec.
184    void saveDeclSpecAttrs() {
185      // Don't try to save them multiple times.
186      if (hasSavedAttrs) return;
187
188      DeclSpec &spec = getMutableDeclSpec();
189      for (AttributeList *attr = spec.getAttributes().getList(); attr;
190             attr = attr->getNext())
191        savedAttrs.push_back(attr);
192      trivial &= savedAttrs.empty();
193      hasSavedAttrs = true;
194    }
195
196    /// Record that we had nowhere to put the given type attribute.
197    /// We will diagnose such attributes later.
198    void addIgnoredTypeAttr(AttributeList &attr) {
199      ignoredTypeAttrs.push_back(&attr);
200    }
201
202    /// Diagnose all the ignored type attributes, given that the
203    /// declarator worked out to the given type.
204    void diagnoseIgnoredTypeAttrs(QualType type) const {
205      for (llvm::SmallVectorImpl<AttributeList*>::const_iterator
206             i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
207           i != e; ++i)
208        diagnoseBadTypeAttribute(getSema(), **i, type);
209    }
210
211    ~TypeProcessingState() {
212      if (trivial) return;
213
214      restoreDeclSpecAttrs();
215    }
216
217  private:
218    DeclSpec &getMutableDeclSpec() const {
219      return const_cast<DeclSpec&>(declarator.getDeclSpec());
220    }
221
222    void restoreDeclSpecAttrs() {
223      assert(hasSavedAttrs);
224
225      if (savedAttrs.empty()) {
226        getMutableDeclSpec().getAttributes().set(0);
227        return;
228      }
229
230      getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
231      for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
232        savedAttrs[i]->setNext(savedAttrs[i+1]);
233      savedAttrs.back()->setNext(0);
234    }
235  };
236
237  /// Basically std::pair except that we really want to avoid an
238  /// implicit operator= for safety concerns.  It's also a minor
239  /// link-time optimization for this to be a private type.
240  struct AttrAndList {
241    /// The attribute.
242    AttributeList &first;
243
244    /// The head of the list the attribute is currently in.
245    AttributeList *&second;
246
247    AttrAndList(AttributeList &attr, AttributeList *&head)
248      : first(attr), second(head) {}
249  };
250}
251
252namespace llvm {
253  template <> struct isPodLike<AttrAndList> {
254    static const bool value = true;
255  };
256}
257
258static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
259  attr.setNext(head);
260  head = &attr;
261}
262
263static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
264  if (head == &attr) {
265    head = attr.getNext();
266    return;
267  }
268
269  AttributeList *cur = head;
270  while (true) {
271    assert(cur && cur->getNext() && "ran out of attrs?");
272    if (cur->getNext() == &attr) {
273      cur->setNext(attr.getNext());
274      return;
275    }
276    cur = cur->getNext();
277  }
278}
279
280static void moveAttrFromListToList(AttributeList &attr,
281                                   AttributeList *&fromList,
282                                   AttributeList *&toList) {
283  spliceAttrOutOfList(attr, fromList);
284  spliceAttrIntoList(attr, toList);
285}
286
287static void processTypeAttrs(TypeProcessingState &state,
288                             QualType &type, bool isDeclSpec,
289                             AttributeList *attrs);
290
291static bool handleFunctionTypeAttr(TypeProcessingState &state,
292                                   AttributeList &attr,
293                                   QualType &type);
294
295static bool handleObjCGCTypeAttr(TypeProcessingState &state,
296                                 AttributeList &attr, QualType &type);
297
298static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
299                                      AttributeList &attr, QualType &type) {
300  // Right now, we have exactly one of these attributes: objc_gc.
301  assert(attr.getKind() == AttributeList::AT_objc_gc);
302  return handleObjCGCTypeAttr(state, attr, type);
303}
304
305/// Given that an objc_gc attribute was written somewhere on a
306/// declaration *other* than on the declarator itself (for which, use
307/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
308/// didn't apply in whatever position it was written in, try to move
309/// it to a more appropriate position.
310static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
311                                          AttributeList &attr,
312                                          QualType type) {
313  Declarator &declarator = state.getDeclarator();
314  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
315    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
316    switch (chunk.Kind) {
317    case DeclaratorChunk::Pointer:
318    case DeclaratorChunk::BlockPointer:
319      moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
320                             chunk.getAttrListRef());
321      return;
322
323    case DeclaratorChunk::Paren:
324    case DeclaratorChunk::Array:
325      continue;
326
327    // Don't walk through these.
328    case DeclaratorChunk::Reference:
329    case DeclaratorChunk::Function:
330    case DeclaratorChunk::MemberPointer:
331      goto error;
332    }
333  }
334 error:
335
336  diagnoseBadTypeAttribute(state.getSema(), attr, type);
337}
338
339/// Distribute an objc_gc type attribute that was written on the
340/// declarator.
341static void
342distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
343                                            AttributeList &attr,
344                                            QualType &declSpecType) {
345  Declarator &declarator = state.getDeclarator();
346
347  // objc_gc goes on the innermost pointer to something that's not a
348  // pointer.
349  unsigned innermost = -1U;
350  bool considerDeclSpec = true;
351  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
352    DeclaratorChunk &chunk = declarator.getTypeObject(i);
353    switch (chunk.Kind) {
354    case DeclaratorChunk::Pointer:
355    case DeclaratorChunk::BlockPointer:
356      innermost = i;
357      continue;
358
359    case DeclaratorChunk::Reference:
360    case DeclaratorChunk::MemberPointer:
361    case DeclaratorChunk::Paren:
362    case DeclaratorChunk::Array:
363      continue;
364
365    case DeclaratorChunk::Function:
366      considerDeclSpec = false;
367      goto done;
368    }
369  }
370 done:
371
372  // That might actually be the decl spec if we weren't blocked by
373  // anything in the declarator.
374  if (considerDeclSpec) {
375    if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
376      // Splice the attribute into the decl spec.  Prevents the
377      // attribute from being applied multiple times and gives
378      // the source-location-filler something to work with.
379      state.saveDeclSpecAttrs();
380      moveAttrFromListToList(attr, declarator.getAttrListRef(),
381               declarator.getMutableDeclSpec().getAttributes().getListRef());
382      return;
383    }
384  }
385
386  // Otherwise, if we found an appropriate chunk, splice the attribute
387  // into it.
388  if (innermost != -1U) {
389    moveAttrFromListToList(attr, declarator.getAttrListRef(),
390                       declarator.getTypeObject(innermost).getAttrListRef());
391    return;
392  }
393
394  // Otherwise, diagnose when we're done building the type.
395  spliceAttrOutOfList(attr, declarator.getAttrListRef());
396  state.addIgnoredTypeAttr(attr);
397}
398
399/// A function type attribute was written somewhere in a declaration
400/// *other* than on the declarator itself or in the decl spec.  Given
401/// that it didn't apply in whatever position it was written in, try
402/// to move it to a more appropriate position.
403static void distributeFunctionTypeAttr(TypeProcessingState &state,
404                                       AttributeList &attr,
405                                       QualType type) {
406  Declarator &declarator = state.getDeclarator();
407
408  // Try to push the attribute from the return type of a function to
409  // the function itself.
410  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
411    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
412    switch (chunk.Kind) {
413    case DeclaratorChunk::Function:
414      moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
415                             chunk.getAttrListRef());
416      return;
417
418    case DeclaratorChunk::Paren:
419    case DeclaratorChunk::Pointer:
420    case DeclaratorChunk::BlockPointer:
421    case DeclaratorChunk::Array:
422    case DeclaratorChunk::Reference:
423    case DeclaratorChunk::MemberPointer:
424      continue;
425    }
426  }
427
428  diagnoseBadTypeAttribute(state.getSema(), attr, type);
429}
430
431/// Try to distribute a function type attribute to the innermost
432/// function chunk or type.  Returns true if the attribute was
433/// distributed, false if no location was found.
434static bool
435distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
436                                      AttributeList &attr,
437                                      AttributeList *&attrList,
438                                      QualType &declSpecType) {
439  Declarator &declarator = state.getDeclarator();
440
441  // Put it on the innermost function chunk, if there is one.
442  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
443    DeclaratorChunk &chunk = declarator.getTypeObject(i);
444    if (chunk.Kind != DeclaratorChunk::Function) continue;
445
446    moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
447    return true;
448  }
449
450  return handleFunctionTypeAttr(state, attr, declSpecType);
451}
452
453/// A function type attribute was written in the decl spec.  Try to
454/// apply it somewhere.
455static void
456distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
457                                       AttributeList &attr,
458                                       QualType &declSpecType) {
459  state.saveDeclSpecAttrs();
460
461  // Try to distribute to the innermost.
462  if (distributeFunctionTypeAttrToInnermost(state, attr,
463                                            state.getCurrentAttrListRef(),
464                                            declSpecType))
465    return;
466
467  // If that failed, diagnose the bad attribute when the declarator is
468  // fully built.
469  state.addIgnoredTypeAttr(attr);
470}
471
472/// A function type attribute was written on the declarator.  Try to
473/// apply it somewhere.
474static void
475distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
476                                         AttributeList &attr,
477                                         QualType &declSpecType) {
478  Declarator &declarator = state.getDeclarator();
479
480  // Try to distribute to the innermost.
481  if (distributeFunctionTypeAttrToInnermost(state, attr,
482                                            declarator.getAttrListRef(),
483                                            declSpecType))
484    return;
485
486  // If that failed, diagnose the bad attribute when the declarator is
487  // fully built.
488  spliceAttrOutOfList(attr, declarator.getAttrListRef());
489  state.addIgnoredTypeAttr(attr);
490}
491
492/// \brief Given that there are attributes written on the declarator
493/// itself, try to distribute any type attributes to the appropriate
494/// declarator chunk.
495///
496/// These are attributes like the following:
497///   int f ATTR;
498///   int (f ATTR)();
499/// but not necessarily this:
500///   int f() ATTR;
501static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
502                                              QualType &declSpecType) {
503  // Collect all the type attributes from the declarator itself.
504  assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
505  AttributeList *attr = state.getDeclarator().getAttributes();
506  AttributeList *next;
507  do {
508    next = attr->getNext();
509
510    switch (attr->getKind()) {
511    OBJC_POINTER_TYPE_ATTRS_CASELIST:
512      distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
513      break;
514
515    FUNCTION_TYPE_ATTRS_CASELIST:
516      distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
517      break;
518
519    default:
520      break;
521    }
522  } while ((attr = next));
523}
524
525/// Add a synthetic '()' to a block-literal declarator if it is
526/// required, given the return type.
527static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
528                                          QualType declSpecType) {
529  Declarator &declarator = state.getDeclarator();
530
531  // First, check whether the declarator would produce a function,
532  // i.e. whether the innermost semantic chunk is a function.
533  if (declarator.isFunctionDeclarator()) {
534    // If so, make that declarator a prototyped declarator.
535    declarator.getFunctionTypeInfo().hasPrototype = true;
536    return;
537  }
538
539  // If there are any type objects, the type as written won't name a
540  // function, regardless of the decl spec type.  This is because a
541  // block signature declarator is always an abstract-declarator, and
542  // abstract-declarators can't just be parentheses chunks.  Therefore
543  // we need to build a function chunk unless there are no type
544  // objects and the decl spec type is a function.
545  if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
546    return;
547
548  // Note that there *are* cases with invalid declarators where
549  // declarators consist solely of parentheses.  In general, these
550  // occur only in failed efforts to make function declarators, so
551  // faking up the function chunk is still the right thing to do.
552
553  // Otherwise, we need to fake up a function declarator.
554  SourceLocation loc = declarator.getSourceRange().getBegin();
555
556  // ...and *prepend* it to the declarator.
557  declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
558                             /*proto*/ true,
559                             /*variadic*/ false, SourceLocation(),
560                             /*args*/ 0, 0,
561                             /*type quals*/ 0,
562                             /*ref-qualifier*/true, SourceLocation(),
563                             /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
564                             /*parens*/ loc, loc,
565                             declarator));
566
567  // For consistency, make sure the state still has us as processing
568  // the decl spec.
569  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
570  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
571}
572
573/// \brief Convert the specified declspec to the appropriate type
574/// object.
575/// \param D  the declarator containing the declaration specifier.
576/// \returns The type described by the declaration specifiers.  This function
577/// never returns null.
578static QualType ConvertDeclSpecToType(Sema &S, TypeProcessingState &state) {
579  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
580  // checking.
581
582  Declarator &declarator = state.getDeclarator();
583  const DeclSpec &DS = declarator.getDeclSpec();
584  SourceLocation DeclLoc = declarator.getIdentifierLoc();
585  if (DeclLoc.isInvalid())
586    DeclLoc = DS.getSourceRange().getBegin();
587
588  ASTContext &Context = S.Context;
589
590  QualType Result;
591  switch (DS.getTypeSpecType()) {
592  case DeclSpec::TST_void:
593    Result = Context.VoidTy;
594    break;
595  case DeclSpec::TST_char:
596    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
597      Result = Context.CharTy;
598    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
599      Result = Context.SignedCharTy;
600    else {
601      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
602             "Unknown TSS value");
603      Result = Context.UnsignedCharTy;
604    }
605    break;
606  case DeclSpec::TST_wchar:
607    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
608      Result = Context.WCharTy;
609    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
610      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
611        << DS.getSpecifierName(DS.getTypeSpecType());
612      Result = Context.getSignedWCharType();
613    } else {
614      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
615        "Unknown TSS value");
616      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
617        << DS.getSpecifierName(DS.getTypeSpecType());
618      Result = Context.getUnsignedWCharType();
619    }
620    break;
621  case DeclSpec::TST_char16:
622      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
623        "Unknown TSS value");
624      Result = Context.Char16Ty;
625    break;
626  case DeclSpec::TST_char32:
627      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
628        "Unknown TSS value");
629      Result = Context.Char32Ty;
630    break;
631  case DeclSpec::TST_unspecified:
632    // "<proto1,proto2>" is an objc qualified ID with a missing id.
633    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
634      Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
635                                         (ObjCProtocolDecl**)PQ,
636                                         DS.getNumProtocolQualifiers());
637      Result = Context.getObjCObjectPointerType(Result);
638      break;
639    }
640
641    // If this is a missing declspec in a block literal return context, then it
642    // is inferred from the return statements inside the block.
643    if (isOmittedBlockReturnType(declarator)) {
644      Result = Context.DependentTy;
645      break;
646    }
647
648    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
649    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
650    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
651    // Note that the one exception to this is function definitions, which are
652    // allowed to be completely missing a declspec.  This is handled in the
653    // parser already though by it pretending to have seen an 'int' in this
654    // case.
655    if (S.getLangOptions().ImplicitInt) {
656      // In C89 mode, we only warn if there is a completely missing declspec
657      // when one is not allowed.
658      if (DS.isEmpty()) {
659        S.Diag(DeclLoc, diag::ext_missing_declspec)
660          << DS.getSourceRange()
661        << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
662      }
663    } else if (!DS.hasTypeSpecifier()) {
664      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
665      // "At least one type specifier shall be given in the declaration
666      // specifiers in each declaration, and in the specifier-qualifier list in
667      // each struct declaration and type name."
668      // FIXME: Does Microsoft really have the implicit int extension in C++?
669      if (S.getLangOptions().CPlusPlus &&
670          !S.getLangOptions().Microsoft) {
671        S.Diag(DeclLoc, diag::err_missing_type_specifier)
672          << DS.getSourceRange();
673
674        // When this occurs in C++ code, often something is very broken with the
675        // value being declared, poison it as invalid so we don't get chains of
676        // errors.
677        declarator.setInvalidType(true);
678      } else {
679        S.Diag(DeclLoc, diag::ext_missing_type_specifier)
680          << DS.getSourceRange();
681      }
682    }
683
684    // FALL THROUGH.
685  case DeclSpec::TST_int: {
686    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
687      switch (DS.getTypeSpecWidth()) {
688      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
689      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
690      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
691      case DeclSpec::TSW_longlong:
692        Result = Context.LongLongTy;
693
694        // long long is a C99 feature.
695        if (!S.getLangOptions().C99 &&
696            !S.getLangOptions().CPlusPlus0x)
697          S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
698        break;
699      }
700    } else {
701      switch (DS.getTypeSpecWidth()) {
702      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
703      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
704      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
705      case DeclSpec::TSW_longlong:
706        Result = Context.UnsignedLongLongTy;
707
708        // long long is a C99 feature.
709        if (!S.getLangOptions().C99 &&
710            !S.getLangOptions().CPlusPlus0x)
711          S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
712        break;
713      }
714    }
715    break;
716  }
717  case DeclSpec::TST_float: Result = Context.FloatTy; break;
718  case DeclSpec::TST_double:
719    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
720      Result = Context.LongDoubleTy;
721    else
722      Result = Context.DoubleTy;
723
724    if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
725      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
726      declarator.setInvalidType(true);
727    }
728    break;
729  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
730  case DeclSpec::TST_decimal32:    // _Decimal32
731  case DeclSpec::TST_decimal64:    // _Decimal64
732  case DeclSpec::TST_decimal128:   // _Decimal128
733    S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
734    Result = Context.IntTy;
735    declarator.setInvalidType(true);
736    break;
737  case DeclSpec::TST_class:
738  case DeclSpec::TST_enum:
739  case DeclSpec::TST_union:
740  case DeclSpec::TST_struct: {
741    TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
742    if (!D) {
743      // This can happen in C++ with ambiguous lookups.
744      Result = Context.IntTy;
745      declarator.setInvalidType(true);
746      break;
747    }
748
749    // If the type is deprecated or unavailable, diagnose it.
750    S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
751
752    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
753           DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
754
755    // TypeQuals handled by caller.
756    Result = Context.getTypeDeclType(D);
757
758    // In both C and C++, make an ElaboratedType.
759    ElaboratedTypeKeyword Keyword
760      = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
761    Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
762
763    if (D->isInvalidDecl())
764      declarator.setInvalidType(true);
765    break;
766  }
767  case DeclSpec::TST_typename: {
768    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
769           DS.getTypeSpecSign() == 0 &&
770           "Can't handle qualifiers on typedef names yet!");
771    Result = S.GetTypeFromParser(DS.getRepAsType());
772    if (Result.isNull())
773      declarator.setInvalidType(true);
774    else if (DeclSpec::ProtocolQualifierListTy PQ
775               = DS.getProtocolQualifiers()) {
776      if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
777        // Silently drop any existing protocol qualifiers.
778        // TODO: determine whether that's the right thing to do.
779        if (ObjT->getNumProtocols())
780          Result = ObjT->getBaseType();
781
782        if (DS.getNumProtocolQualifiers())
783          Result = Context.getObjCObjectType(Result,
784                                             (ObjCProtocolDecl**) PQ,
785                                             DS.getNumProtocolQualifiers());
786      } else if (Result->isObjCIdType()) {
787        // id<protocol-list>
788        Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
789                                           (ObjCProtocolDecl**) PQ,
790                                           DS.getNumProtocolQualifiers());
791        Result = Context.getObjCObjectPointerType(Result);
792      } else if (Result->isObjCClassType()) {
793        // Class<protocol-list>
794        Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
795                                           (ObjCProtocolDecl**) PQ,
796                                           DS.getNumProtocolQualifiers());
797        Result = Context.getObjCObjectPointerType(Result);
798      } else {
799        S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
800          << DS.getSourceRange();
801        declarator.setInvalidType(true);
802      }
803    }
804
805    // TypeQuals handled by caller.
806    break;
807  }
808  case DeclSpec::TST_typeofType:
809    // FIXME: Preserve type source info.
810    Result = S.GetTypeFromParser(DS.getRepAsType());
811    assert(!Result.isNull() && "Didn't get a type for typeof?");
812    if (!Result->isDependentType())
813      if (const TagType *TT = Result->getAs<TagType>())
814        S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
815    // TypeQuals handled by caller.
816    Result = Context.getTypeOfType(Result);
817    break;
818  case DeclSpec::TST_typeofExpr: {
819    Expr *E = DS.getRepAsExpr();
820    assert(E && "Didn't get an expression for typeof?");
821    // TypeQuals handled by caller.
822    Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
823    if (Result.isNull()) {
824      Result = Context.IntTy;
825      declarator.setInvalidType(true);
826    }
827    break;
828  }
829  case DeclSpec::TST_decltype: {
830    Expr *E = DS.getRepAsExpr();
831    assert(E && "Didn't get an expression for decltype?");
832    // TypeQuals handled by caller.
833    Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
834    if (Result.isNull()) {
835      Result = Context.IntTy;
836      declarator.setInvalidType(true);
837    }
838    break;
839  }
840  case DeclSpec::TST_underlyingType:
841    Result = S.GetTypeFromParser(DS.getRepAsType());
842    assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
843    Result = S.BuildUnaryTransformType(Result,
844                                       UnaryTransformType::EnumUnderlyingType,
845                                       DS.getTypeSpecTypeLoc());
846    if (Result.isNull()) {
847      Result = Context.IntTy;
848      declarator.setInvalidType(true);
849    }
850    break;
851
852  case DeclSpec::TST_auto: {
853    // TypeQuals handled by caller.
854    Result = Context.getAutoType(QualType());
855    break;
856  }
857
858  case DeclSpec::TST_unknown_anytype:
859    Result = Context.UnknownAnyTy;
860    break;
861
862  case DeclSpec::TST_error:
863    Result = Context.IntTy;
864    declarator.setInvalidType(true);
865    break;
866  }
867
868  // Handle complex types.
869  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
870    if (S.getLangOptions().Freestanding)
871      S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
872    Result = Context.getComplexType(Result);
873  } else if (DS.isTypeAltiVecVector()) {
874    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
875    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
876    VectorType::VectorKind VecKind = VectorType::AltiVecVector;
877    if (DS.isTypeAltiVecPixel())
878      VecKind = VectorType::AltiVecPixel;
879    else if (DS.isTypeAltiVecBool())
880      VecKind = VectorType::AltiVecBool;
881    Result = Context.getVectorType(Result, 128/typeSize, VecKind);
882  }
883
884  // FIXME: Imaginary.
885  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
886    S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
887
888  // Before we process any type attributes, synthesize a block literal
889  // function declarator if necessary.
890  if (declarator.getContext() == Declarator::BlockLiteralContext)
891    maybeSynthesizeBlockSignature(state, Result);
892
893  // Apply any type attributes from the decl spec.  This may cause the
894  // list of type attributes to be temporarily saved while the type
895  // attributes are pushed around.
896  if (AttributeList *attrs = DS.getAttributes().getList())
897    processTypeAttrs(state, Result, true, attrs);
898
899  // Apply const/volatile/restrict qualifiers to T.
900  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
901
902    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
903    // or incomplete types shall not be restrict-qualified."  C++ also allows
904    // restrict-qualified references.
905    if (TypeQuals & DeclSpec::TQ_restrict) {
906      if (Result->isAnyPointerType() || Result->isReferenceType()) {
907        QualType EltTy;
908        if (Result->isObjCObjectPointerType())
909          EltTy = Result;
910        else
911          EltTy = Result->isPointerType() ?
912                    Result->getAs<PointerType>()->getPointeeType() :
913                    Result->getAs<ReferenceType>()->getPointeeType();
914
915        // If we have a pointer or reference, the pointee must have an object
916        // incomplete type.
917        if (!EltTy->isIncompleteOrObjectType()) {
918          S.Diag(DS.getRestrictSpecLoc(),
919               diag::err_typecheck_invalid_restrict_invalid_pointee)
920            << EltTy << DS.getSourceRange();
921          TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
922        }
923      } else {
924        S.Diag(DS.getRestrictSpecLoc(),
925               diag::err_typecheck_invalid_restrict_not_pointer)
926          << Result << DS.getSourceRange();
927        TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
928      }
929    }
930
931    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
932    // of a function type includes any type qualifiers, the behavior is
933    // undefined."
934    if (Result->isFunctionType() && TypeQuals) {
935      // Get some location to point at, either the C or V location.
936      SourceLocation Loc;
937      if (TypeQuals & DeclSpec::TQ_const)
938        Loc = DS.getConstSpecLoc();
939      else if (TypeQuals & DeclSpec::TQ_volatile)
940        Loc = DS.getVolatileSpecLoc();
941      else {
942        assert((TypeQuals & DeclSpec::TQ_restrict) &&
943               "Has CVR quals but not C, V, or R?");
944        Loc = DS.getRestrictSpecLoc();
945      }
946      S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
947        << Result << DS.getSourceRange();
948    }
949
950    // C++ [dcl.ref]p1:
951    //   Cv-qualified references are ill-formed except when the
952    //   cv-qualifiers are introduced through the use of a typedef
953    //   (7.1.3) or of a template type argument (14.3), in which
954    //   case the cv-qualifiers are ignored.
955    // FIXME: Shouldn't we be checking SCS_typedef here?
956    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
957        TypeQuals && Result->isReferenceType()) {
958      TypeQuals &= ~DeclSpec::TQ_const;
959      TypeQuals &= ~DeclSpec::TQ_volatile;
960    }
961
962    Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
963    Result = Context.getQualifiedType(Result, Quals);
964  }
965
966  return Result;
967}
968
969static std::string getPrintableNameForEntity(DeclarationName Entity) {
970  if (Entity)
971    return Entity.getAsString();
972
973  return "type name";
974}
975
976QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
977                                  Qualifiers Qs) {
978  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
979  // object or incomplete types shall not be restrict-qualified."
980  if (Qs.hasRestrict()) {
981    unsigned DiagID = 0;
982    QualType ProblemTy;
983
984    const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
985    if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
986      if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
987        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
988        ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
989      }
990    } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
991      if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
992        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
993        ProblemTy = T->getAs<PointerType>()->getPointeeType();
994      }
995    } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
996      if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
997        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
998        ProblemTy = T->getAs<PointerType>()->getPointeeType();
999      }
1000    } else if (!Ty->isDependentType()) {
1001      // FIXME: this deserves a proper diagnostic
1002      DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1003      ProblemTy = T;
1004    }
1005
1006    if (DiagID) {
1007      Diag(Loc, DiagID) << ProblemTy;
1008      Qs.removeRestrict();
1009    }
1010  }
1011
1012  return Context.getQualifiedType(T, Qs);
1013}
1014
1015/// \brief Build a paren type including \p T.
1016QualType Sema::BuildParenType(QualType T) {
1017  return Context.getParenType(T);
1018}
1019
1020/// \brief Build a pointer type.
1021///
1022/// \param T The type to which we'll be building a pointer.
1023///
1024/// \param Loc The location of the entity whose type involves this
1025/// pointer type or, if there is no such entity, the location of the
1026/// type that will have pointer type.
1027///
1028/// \param Entity The name of the entity that involves the pointer
1029/// type, if known.
1030///
1031/// \returns A suitable pointer type, if there are no
1032/// errors. Otherwise, returns a NULL type.
1033QualType Sema::BuildPointerType(QualType T,
1034                                SourceLocation Loc, DeclarationName Entity) {
1035  if (T->isReferenceType()) {
1036    // C++ 8.3.2p4: There shall be no ... pointers to references ...
1037    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1038      << getPrintableNameForEntity(Entity) << T;
1039    return QualType();
1040  }
1041
1042  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1043
1044  // Build the pointer type.
1045  return Context.getPointerType(T);
1046}
1047
1048/// \brief Build a reference type.
1049///
1050/// \param T The type to which we'll be building a reference.
1051///
1052/// \param Loc The location of the entity whose type involves this
1053/// reference type or, if there is no such entity, the location of the
1054/// type that will have reference type.
1055///
1056/// \param Entity The name of the entity that involves the reference
1057/// type, if known.
1058///
1059/// \returns A suitable reference type, if there are no
1060/// errors. Otherwise, returns a NULL type.
1061QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1062                                  SourceLocation Loc,
1063                                  DeclarationName Entity) {
1064  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1065         "Unresolved overloaded function type");
1066
1067  // C++0x [dcl.ref]p6:
1068  //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1069  //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1070  //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1071  //   the type "lvalue reference to T", while an attempt to create the type
1072  //   "rvalue reference to cv TR" creates the type TR.
1073  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1074
1075  // C++ [dcl.ref]p4: There shall be no references to references.
1076  //
1077  // According to C++ DR 106, references to references are only
1078  // diagnosed when they are written directly (e.g., "int & &"),
1079  // but not when they happen via a typedef:
1080  //
1081  //   typedef int& intref;
1082  //   typedef intref& intref2;
1083  //
1084  // Parser::ParseDeclaratorInternal diagnoses the case where
1085  // references are written directly; here, we handle the
1086  // collapsing of references-to-references as described in C++0x.
1087  // DR 106 and 540 introduce reference-collapsing into C++98/03.
1088
1089  // C++ [dcl.ref]p1:
1090  //   A declarator that specifies the type "reference to cv void"
1091  //   is ill-formed.
1092  if (T->isVoidType()) {
1093    Diag(Loc, diag::err_reference_to_void);
1094    return QualType();
1095  }
1096
1097  // Handle restrict on references.
1098  if (LValueRef)
1099    return Context.getLValueReferenceType(T, SpelledAsLValue);
1100  return Context.getRValueReferenceType(T);
1101}
1102
1103/// \brief Build an array type.
1104///
1105/// \param T The type of each element in the array.
1106///
1107/// \param ASM C99 array size modifier (e.g., '*', 'static').
1108///
1109/// \param ArraySize Expression describing the size of the array.
1110///
1111/// \param Loc The location of the entity whose type involves this
1112/// array type or, if there is no such entity, the location of the
1113/// type that will have array type.
1114///
1115/// \param Entity The name of the entity that involves the array
1116/// type, if known.
1117///
1118/// \returns A suitable array type, if there are no errors. Otherwise,
1119/// returns a NULL type.
1120QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1121                              Expr *ArraySize, unsigned Quals,
1122                              SourceRange Brackets, DeclarationName Entity) {
1123
1124  SourceLocation Loc = Brackets.getBegin();
1125  if (getLangOptions().CPlusPlus) {
1126    // C++ [dcl.array]p1:
1127    //   T is called the array element type; this type shall not be a reference
1128    //   type, the (possibly cv-qualified) type void, a function type or an
1129    //   abstract class type.
1130    //
1131    // Note: function types are handled in the common path with C.
1132    if (T->isReferenceType()) {
1133      Diag(Loc, diag::err_illegal_decl_array_of_references)
1134      << getPrintableNameForEntity(Entity) << T;
1135      return QualType();
1136    }
1137
1138    if (T->isVoidType()) {
1139      Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1140      return QualType();
1141    }
1142
1143    if (RequireNonAbstractType(Brackets.getBegin(), T,
1144                               diag::err_array_of_abstract_type))
1145      return QualType();
1146
1147  } else {
1148    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1149    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1150    if (RequireCompleteType(Loc, T,
1151                            diag::err_illegal_decl_array_incomplete_type))
1152      return QualType();
1153  }
1154
1155  if (T->isFunctionType()) {
1156    Diag(Loc, diag::err_illegal_decl_array_of_functions)
1157      << getPrintableNameForEntity(Entity) << T;
1158    return QualType();
1159  }
1160
1161  if (T->getContainedAutoType()) {
1162    Diag(Loc, diag::err_illegal_decl_array_of_auto)
1163      << getPrintableNameForEntity(Entity) << T;
1164    return QualType();
1165  }
1166
1167  if (const RecordType *EltTy = T->getAs<RecordType>()) {
1168    // If the element type is a struct or union that contains a variadic
1169    // array, accept it as a GNU extension: C99 6.7.2.1p2.
1170    if (EltTy->getDecl()->hasFlexibleArrayMember())
1171      Diag(Loc, diag::ext_flexible_array_in_array) << T;
1172  } else if (T->isObjCObjectType()) {
1173    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1174    return QualType();
1175  }
1176
1177  // Do lvalue-to-rvalue conversions on the array size expression.
1178  if (ArraySize && !ArraySize->isRValue()) {
1179    ExprResult Result = DefaultLvalueConversion(ArraySize);
1180    if (Result.isInvalid())
1181      return QualType();
1182
1183    ArraySize = Result.take();
1184  }
1185
1186  // C99 6.7.5.2p1: The size expression shall have integer type.
1187  // TODO: in theory, if we were insane, we could allow contextual
1188  // conversions to integer type here.
1189  if (ArraySize && !ArraySize->isTypeDependent() &&
1190      !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1191    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1192      << ArraySize->getType() << ArraySize->getSourceRange();
1193    return QualType();
1194  }
1195  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1196  if (!ArraySize) {
1197    if (ASM == ArrayType::Star)
1198      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1199    else
1200      T = Context.getIncompleteArrayType(T, ASM, Quals);
1201  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1202    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1203  } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
1204             (!T->isDependentType() && !T->isIncompleteType() &&
1205              !T->isConstantSizeType())) {
1206    // Per C99, a variable array is an array with either a non-constant
1207    // size or an element type that has a non-constant-size
1208    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1209  } else {
1210    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1211    // have a value greater than zero.
1212    if (ConstVal.isSigned() && ConstVal.isNegative()) {
1213      if (Entity)
1214        Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1215          << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1216      else
1217        Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1218          << ArraySize->getSourceRange();
1219      return QualType();
1220    }
1221    if (ConstVal == 0) {
1222      // GCC accepts zero sized static arrays. We allow them when
1223      // we're not in a SFINAE context.
1224      Diag(ArraySize->getLocStart(),
1225           isSFINAEContext()? diag::err_typecheck_zero_array_size
1226                            : diag::ext_typecheck_zero_array_size)
1227        << ArraySize->getSourceRange();
1228    } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1229               !T->isIncompleteType()) {
1230      // Is the array too large?
1231      unsigned ActiveSizeBits
1232        = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1233      if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1234        Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1235          << ConstVal.toString(10)
1236          << ArraySize->getSourceRange();
1237    }
1238
1239    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1240  }
1241  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1242  if (!getLangOptions().C99) {
1243    if (T->isVariableArrayType()) {
1244      // Prohibit the use of non-POD types in VLAs.
1245      if (!T->isDependentType() &&
1246          !Context.getBaseElementType(T)->isPODType()) {
1247        Diag(Loc, diag::err_vla_non_pod)
1248          << Context.getBaseElementType(T);
1249        return QualType();
1250      }
1251      // Prohibit the use of VLAs during template argument deduction.
1252      else if (isSFINAEContext()) {
1253        Diag(Loc, diag::err_vla_in_sfinae);
1254        return QualType();
1255      }
1256      // Just extwarn about VLAs.
1257      else
1258        Diag(Loc, diag::ext_vla);
1259    } else if (ASM != ArrayType::Normal || Quals != 0)
1260      Diag(Loc,
1261           getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1262                                     : diag::ext_c99_array_usage);
1263  }
1264
1265  return T;
1266}
1267
1268/// \brief Build an ext-vector type.
1269///
1270/// Run the required checks for the extended vector type.
1271QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1272                                  SourceLocation AttrLoc) {
1273  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1274  // in conjunction with complex types (pointers, arrays, functions, etc.).
1275  if (!T->isDependentType() &&
1276      !T->isIntegerType() && !T->isRealFloatingType()) {
1277    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1278    return QualType();
1279  }
1280
1281  if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1282    llvm::APSInt vecSize(32);
1283    if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1284      Diag(AttrLoc, diag::err_attribute_argument_not_int)
1285        << "ext_vector_type" << ArraySize->getSourceRange();
1286      return QualType();
1287    }
1288
1289    // unlike gcc's vector_size attribute, the size is specified as the
1290    // number of elements, not the number of bytes.
1291    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1292
1293    if (vectorSize == 0) {
1294      Diag(AttrLoc, diag::err_attribute_zero_size)
1295      << ArraySize->getSourceRange();
1296      return QualType();
1297    }
1298
1299    if (!T->isDependentType())
1300      return Context.getExtVectorType(T, vectorSize);
1301  }
1302
1303  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1304}
1305
1306/// \brief Build a function type.
1307///
1308/// This routine checks the function type according to C++ rules and
1309/// under the assumption that the result type and parameter types have
1310/// just been instantiated from a template. It therefore duplicates
1311/// some of the behavior of GetTypeForDeclarator, but in a much
1312/// simpler form that is only suitable for this narrow use case.
1313///
1314/// \param T The return type of the function.
1315///
1316/// \param ParamTypes The parameter types of the function. This array
1317/// will be modified to account for adjustments to the types of the
1318/// function parameters.
1319///
1320/// \param NumParamTypes The number of parameter types in ParamTypes.
1321///
1322/// \param Variadic Whether this is a variadic function type.
1323///
1324/// \param Quals The cvr-qualifiers to be applied to the function type.
1325///
1326/// \param Loc The location of the entity whose type involves this
1327/// function type or, if there is no such entity, the location of the
1328/// type that will have function type.
1329///
1330/// \param Entity The name of the entity that involves the function
1331/// type, if known.
1332///
1333/// \returns A suitable function type, if there are no
1334/// errors. Otherwise, returns a NULL type.
1335QualType Sema::BuildFunctionType(QualType T,
1336                                 QualType *ParamTypes,
1337                                 unsigned NumParamTypes,
1338                                 bool Variadic, unsigned Quals,
1339                                 RefQualifierKind RefQualifier,
1340                                 SourceLocation Loc, DeclarationName Entity,
1341                                 FunctionType::ExtInfo Info) {
1342  if (T->isArrayType() || T->isFunctionType()) {
1343    Diag(Loc, diag::err_func_returning_array_function)
1344      << T->isFunctionType() << T;
1345    return QualType();
1346  }
1347
1348  bool Invalid = false;
1349  for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
1350    QualType ParamType = adjustParameterType(ParamTypes[Idx]);
1351    if (ParamType->isVoidType()) {
1352      Diag(Loc, diag::err_param_with_void_type);
1353      Invalid = true;
1354    }
1355
1356    ParamTypes[Idx] = ParamType;
1357  }
1358
1359  if (Invalid)
1360    return QualType();
1361
1362  FunctionProtoType::ExtProtoInfo EPI;
1363  EPI.Variadic = Variadic;
1364  EPI.TypeQuals = Quals;
1365  EPI.RefQualifier = RefQualifier;
1366  EPI.ExtInfo = Info;
1367
1368  return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
1369}
1370
1371/// \brief Build a member pointer type \c T Class::*.
1372///
1373/// \param T the type to which the member pointer refers.
1374/// \param Class the class type into which the member pointer points.
1375/// \param CVR Qualifiers applied to the member pointer type
1376/// \param Loc the location where this type begins
1377/// \param Entity the name of the entity that will have this member pointer type
1378///
1379/// \returns a member pointer type, if successful, or a NULL type if there was
1380/// an error.
1381QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1382                                      SourceLocation Loc,
1383                                      DeclarationName Entity) {
1384  // Verify that we're not building a pointer to pointer to function with
1385  // exception specification.
1386  if (CheckDistantExceptionSpec(T)) {
1387    Diag(Loc, diag::err_distant_exception_spec);
1388
1389    // FIXME: If we're doing this as part of template instantiation,
1390    // we should return immediately.
1391
1392    // Build the type anyway, but use the canonical type so that the
1393    // exception specifiers are stripped off.
1394    T = Context.getCanonicalType(T);
1395  }
1396
1397  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1398  //   with reference type, or "cv void."
1399  if (T->isReferenceType()) {
1400    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1401      << (Entity? Entity.getAsString() : "type name") << T;
1402    return QualType();
1403  }
1404
1405  if (T->isVoidType()) {
1406    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1407      << (Entity? Entity.getAsString() : "type name");
1408    return QualType();
1409  }
1410
1411  if (!Class->isDependentType() && !Class->isRecordType()) {
1412    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1413    return QualType();
1414  }
1415
1416  // In the Microsoft ABI, the class is allowed to be an incomplete
1417  // type. In such cases, the compiler makes a worst-case assumption.
1418  // We make no such assumption right now, so emit an error if the
1419  // class isn't a complete type.
1420  if (Context.Target.getCXXABI() == CXXABI_Microsoft &&
1421      RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1422    return QualType();
1423
1424  return Context.getMemberPointerType(T, Class.getTypePtr());
1425}
1426
1427/// \brief Build a block pointer type.
1428///
1429/// \param T The type to which we'll be building a block pointer.
1430///
1431/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
1432///
1433/// \param Loc The location of the entity whose type involves this
1434/// block pointer type or, if there is no such entity, the location of the
1435/// type that will have block pointer type.
1436///
1437/// \param Entity The name of the entity that involves the block pointer
1438/// type, if known.
1439///
1440/// \returns A suitable block pointer type, if there are no
1441/// errors. Otherwise, returns a NULL type.
1442QualType Sema::BuildBlockPointerType(QualType T,
1443                                     SourceLocation Loc,
1444                                     DeclarationName Entity) {
1445  if (!T->isFunctionType()) {
1446    Diag(Loc, diag::err_nonfunction_block_type);
1447    return QualType();
1448  }
1449
1450  return Context.getBlockPointerType(T);
1451}
1452
1453QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1454  QualType QT = Ty.get();
1455  if (QT.isNull()) {
1456    if (TInfo) *TInfo = 0;
1457    return QualType();
1458  }
1459
1460  TypeSourceInfo *DI = 0;
1461  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1462    QT = LIT->getType();
1463    DI = LIT->getTypeSourceInfo();
1464  }
1465
1466  if (TInfo) *TInfo = DI;
1467  return QT;
1468}
1469
1470static void DiagnoseIgnoredQualifiers(unsigned Quals,
1471                                      SourceLocation ConstQualLoc,
1472                                      SourceLocation VolatileQualLoc,
1473                                      SourceLocation RestrictQualLoc,
1474                                      Sema& S) {
1475  std::string QualStr;
1476  unsigned NumQuals = 0;
1477  SourceLocation Loc;
1478
1479  FixItHint ConstFixIt;
1480  FixItHint VolatileFixIt;
1481  FixItHint RestrictFixIt;
1482
1483  const SourceManager &SM = S.getSourceManager();
1484
1485  // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1486  // find a range and grow it to encompass all the qualifiers, regardless of
1487  // the order in which they textually appear.
1488  if (Quals & Qualifiers::Const) {
1489    ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
1490    QualStr = "const";
1491    ++NumQuals;
1492    if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1493      Loc = ConstQualLoc;
1494  }
1495  if (Quals & Qualifiers::Volatile) {
1496    VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
1497    QualStr += (NumQuals == 0 ? "volatile" : " volatile");
1498    ++NumQuals;
1499    if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1500      Loc = VolatileQualLoc;
1501  }
1502  if (Quals & Qualifiers::Restrict) {
1503    RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
1504    QualStr += (NumQuals == 0 ? "restrict" : " restrict");
1505    ++NumQuals;
1506    if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1507      Loc = RestrictQualLoc;
1508  }
1509
1510  assert(NumQuals > 0 && "No known qualifiers?");
1511
1512  S.Diag(Loc, diag::warn_qual_return_type)
1513    << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
1514}
1515
1516/// GetTypeForDeclarator - Convert the type for the specified
1517/// declarator to Type instances.
1518///
1519/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
1520/// owns the declaration of a type (e.g., the definition of a struct
1521/// type), then *OwnedDecl will receive the owned declaration.
1522///
1523/// The result of this call will never be null, but the associated
1524/// type may be a null type if there's an unrecoverable error.
1525TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
1526                                           TagDecl **OwnedDecl,
1527                                           bool AutoAllowedInTypeName) {
1528  // Determine the type of the declarator. Not all forms of declarator
1529  // have a type.
1530  QualType T;
1531  TypeSourceInfo *ReturnTypeInfo = 0;
1532
1533  TypeProcessingState state(*this, D);
1534
1535  // In C++0x, deallocation functions (normal and array operator delete)
1536  // are implicitly noexcept.
1537  bool ImplicitlyNoexcept = false;
1538
1539  switch (D.getName().getKind()) {
1540  case UnqualifiedId::IK_OperatorFunctionId:
1541    if (getLangOptions().CPlusPlus0x) {
1542      OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1543      if (OO == OO_Delete || OO == OO_Array_Delete)
1544        ImplicitlyNoexcept = true;
1545    }
1546    // Intentional fall-through.
1547  case UnqualifiedId::IK_Identifier:
1548  case UnqualifiedId::IK_LiteralOperatorId:
1549  case UnqualifiedId::IK_TemplateId:
1550    T = ConvertDeclSpecToType(*this, state);
1551
1552    if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
1553      TagDecl* Owned = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1554      // Owned declaration is embedded in declarator.
1555      Owned->setEmbeddedInDeclarator(true);
1556      if (OwnedDecl) *OwnedDecl = Owned;
1557    }
1558    break;
1559
1560  case UnqualifiedId::IK_ConstructorName:
1561  case UnqualifiedId::IK_ConstructorTemplateId:
1562  case UnqualifiedId::IK_DestructorName:
1563    // Constructors and destructors don't have return types. Use
1564    // "void" instead.
1565    T = Context.VoidTy;
1566    break;
1567
1568  case UnqualifiedId::IK_ConversionFunctionId:
1569    // The result type of a conversion function is the type that it
1570    // converts to.
1571    T = GetTypeFromParser(D.getName().ConversionFunctionId,
1572                          &ReturnTypeInfo);
1573    break;
1574  }
1575
1576  if (D.getAttributes())
1577    distributeTypeAttrsFromDeclarator(state, T);
1578
1579  // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1580  // In C++0x, a function declarator using 'auto' must have a trailing return
1581  // type (this is checked later) and we can skip this. In other languages
1582  // using auto, we need to check regardless.
1583  if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1584      (!getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
1585    int Error = -1;
1586
1587    switch (D.getContext()) {
1588    case Declarator::KNRTypeListContext:
1589      assert(0 && "K&R type lists aren't allowed in C++");
1590      break;
1591    case Declarator::ObjCPrototypeContext:
1592    case Declarator::PrototypeContext:
1593      Error = 0; // Function prototype
1594      break;
1595    case Declarator::MemberContext:
1596      if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1597        break;
1598      switch (cast<TagDecl>(CurContext)->getTagKind()) {
1599      case TTK_Enum: assert(0 && "unhandled tag kind"); break;
1600      case TTK_Struct: Error = 1; /* Struct member */ break;
1601      case TTK_Union:  Error = 2; /* Union member */ break;
1602      case TTK_Class:  Error = 3; /* Class member */ break;
1603      }
1604      break;
1605    case Declarator::CXXCatchContext:
1606      Error = 4; // Exception declaration
1607      break;
1608    case Declarator::TemplateParamContext:
1609      Error = 5; // Template parameter
1610      break;
1611    case Declarator::BlockLiteralContext:
1612      Error = 6; // Block literal
1613      break;
1614    case Declarator::TemplateTypeArgContext:
1615      Error = 7; // Template type argument
1616      break;
1617    case Declarator::AliasDeclContext:
1618    case Declarator::AliasTemplateContext:
1619      Error = 9; // Type alias
1620      break;
1621    case Declarator::TypeNameContext:
1622      if (!AutoAllowedInTypeName)
1623        Error = 11; // Generic
1624      break;
1625    case Declarator::FileContext:
1626    case Declarator::BlockContext:
1627    case Declarator::ForContext:
1628    case Declarator::ConditionContext:
1629      break;
1630    }
1631
1632    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1633      Error = 8;
1634
1635    // In Objective-C it is an error to use 'auto' on a function declarator.
1636    if (D.isFunctionDeclarator())
1637      Error = 10;
1638
1639    // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1640    // contains a trailing return type. That is only legal at the outermost
1641    // level. Check all declarator chunks (outermost first) anyway, to give
1642    // better diagnostics.
1643    if (getLangOptions().CPlusPlus0x && Error != -1) {
1644      for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1645        unsigned chunkIndex = e - i - 1;
1646        state.setCurrentChunkIndex(chunkIndex);
1647        DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1648        if (DeclType.Kind == DeclaratorChunk::Function) {
1649          const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1650          if (FTI.TrailingReturnType) {
1651            Error = -1;
1652            break;
1653          }
1654        }
1655      }
1656    }
1657
1658    if (Error != -1) {
1659      Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1660        << Error;
1661      T = Context.IntTy;
1662      D.setInvalidType(true);
1663    }
1664  }
1665
1666  if (T.isNull())
1667    return Context.getNullTypeSourceInfo();
1668
1669  // The name we're declaring, if any.
1670  DeclarationName Name;
1671  if (D.getIdentifier())
1672    Name = D.getIdentifier();
1673
1674  // Does this declaration declare a typedef-name?
1675  bool IsTypedefName =
1676    D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
1677    D.getContext() == Declarator::AliasDeclContext ||
1678    D.getContext() == Declarator::AliasTemplateContext;
1679
1680  // Walk the DeclTypeInfo, building the recursive type as we go.
1681  // DeclTypeInfos are ordered from the identifier out, which is
1682  // opposite of what we want :).
1683  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1684    unsigned chunkIndex = e - i - 1;
1685    state.setCurrentChunkIndex(chunkIndex);
1686    DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1687    switch (DeclType.Kind) {
1688    default: assert(0 && "Unknown decltype!");
1689    case DeclaratorChunk::Paren:
1690      T = BuildParenType(T);
1691      break;
1692    case DeclaratorChunk::BlockPointer:
1693      // If blocks are disabled, emit an error.
1694      if (!LangOpts.Blocks)
1695        Diag(DeclType.Loc, diag::err_blocks_disable);
1696
1697      T = BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
1698      if (DeclType.Cls.TypeQuals)
1699        T = BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
1700      break;
1701    case DeclaratorChunk::Pointer:
1702      // Verify that we're not building a pointer to pointer to function with
1703      // exception specification.
1704      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1705        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1706        D.setInvalidType(true);
1707        // Build the type anyway.
1708      }
1709      if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) {
1710        T = Context.getObjCObjectPointerType(T);
1711        if (DeclType.Ptr.TypeQuals)
1712          T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1713        break;
1714      }
1715      T = BuildPointerType(T, DeclType.Loc, Name);
1716      if (DeclType.Ptr.TypeQuals)
1717        T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1718
1719      break;
1720    case DeclaratorChunk::Reference: {
1721      // Verify that we're not building a reference to pointer to function with
1722      // exception specification.
1723      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1724        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1725        D.setInvalidType(true);
1726        // Build the type anyway.
1727      }
1728      T = BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
1729
1730      Qualifiers Quals;
1731      if (DeclType.Ref.HasRestrict)
1732        T = BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
1733      break;
1734    }
1735    case DeclaratorChunk::Array: {
1736      // Verify that we're not building an array of pointers to function with
1737      // exception specification.
1738      if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1739        Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1740        D.setInvalidType(true);
1741        // Build the type anyway.
1742      }
1743      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1744      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1745      ArrayType::ArraySizeModifier ASM;
1746      if (ATI.isStar)
1747        ASM = ArrayType::Star;
1748      else if (ATI.hasStatic)
1749        ASM = ArrayType::Static;
1750      else
1751        ASM = ArrayType::Normal;
1752      if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
1753        // FIXME: This check isn't quite right: it allows star in prototypes
1754        // for function definitions, and disallows some edge cases detailed
1755        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1756        Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1757        ASM = ArrayType::Normal;
1758        D.setInvalidType(true);
1759      }
1760      T = BuildArrayType(T, ASM, ArraySize,
1761                         Qualifiers::fromCVRMask(ATI.TypeQuals),
1762                         SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1763      break;
1764    }
1765    case DeclaratorChunk::Function: {
1766      // If the function declarator has a prototype (i.e. it is not () and
1767      // does not have a K&R-style identifier list), then the arguments are part
1768      // of the type, otherwise the argument list is ().
1769      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1770
1771      // Check for auto functions and trailing return type and adjust the
1772      // return type accordingly.
1773      if (!D.isInvalidType()) {
1774        // trailing-return-type is only required if we're declaring a function,
1775        // and not, for instance, a pointer to a function.
1776        if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1777            !FTI.TrailingReturnType && chunkIndex == 0) {
1778          Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1779               diag::err_auto_missing_trailing_return);
1780          T = Context.IntTy;
1781          D.setInvalidType(true);
1782        } else if (FTI.TrailingReturnType) {
1783          // T must be exactly 'auto' at this point. See CWG issue 681.
1784          if (isa<ParenType>(T)) {
1785            Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1786                 diag::err_trailing_return_in_parens)
1787              << T << D.getDeclSpec().getSourceRange();
1788            D.setInvalidType(true);
1789          } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
1790            Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1791                 diag::err_trailing_return_without_auto)
1792              << T << D.getDeclSpec().getSourceRange();
1793            D.setInvalidType(true);
1794          }
1795
1796          T = GetTypeFromParser(
1797            ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
1798            &ReturnTypeInfo);
1799        }
1800      }
1801
1802      // C99 6.7.5.3p1: The return type may not be a function or array type.
1803      // For conversion functions, we'll diagnose this particular error later.
1804      if ((T->isArrayType() || T->isFunctionType()) &&
1805          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
1806        unsigned diagID = diag::err_func_returning_array_function;
1807        // Last processing chunk in block context means this function chunk
1808        // represents the block.
1809        if (chunkIndex == 0 &&
1810            D.getContext() == Declarator::BlockLiteralContext)
1811          diagID = diag::err_block_returning_array_function;
1812        Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
1813        T = Context.IntTy;
1814        D.setInvalidType(true);
1815      }
1816
1817      // cv-qualifiers on return types are pointless except when the type is a
1818      // class type in C++.
1819      if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
1820          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
1821          (!getLangOptions().CPlusPlus || !T->isDependentType())) {
1822        assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
1823        DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
1824        assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
1825
1826        DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
1827
1828        DiagnoseIgnoredQualifiers(PTI.TypeQuals,
1829            SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
1830            SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
1831            SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
1832            *this);
1833
1834      } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
1835          (!getLangOptions().CPlusPlus ||
1836           (!T->isDependentType() && !T->isRecordType()))) {
1837
1838        DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
1839                                  D.getDeclSpec().getConstSpecLoc(),
1840                                  D.getDeclSpec().getVolatileSpecLoc(),
1841                                  D.getDeclSpec().getRestrictSpecLoc(),
1842                                  *this);
1843      }
1844
1845      if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1846        // C++ [dcl.fct]p6:
1847        //   Types shall not be defined in return or parameter types.
1848        TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1849        if (Tag->isDefinition())
1850          Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1851            << Context.getTypeDeclType(Tag);
1852      }
1853
1854      // Exception specs are not allowed in typedefs. Complain, but add it
1855      // anyway.
1856      if (IsTypedefName && FTI.getExceptionSpecType())
1857        Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
1858          << (D.getContext() == Declarator::AliasDeclContext ||
1859              D.getContext() == Declarator::AliasTemplateContext);
1860
1861      if (!FTI.NumArgs && !FTI.isVariadic && !getLangOptions().CPlusPlus) {
1862        // Simple void foo(), where the incoming T is the result type.
1863        T = Context.getFunctionNoProtoType(T);
1864      } else {
1865        // We allow a zero-parameter variadic function in C if the
1866        // function is marked with the "overloadable" attribute. Scan
1867        // for this attribute now.
1868        if (!FTI.NumArgs && FTI.isVariadic && !getLangOptions().CPlusPlus) {
1869          bool Overloadable = false;
1870          for (const AttributeList *Attrs = D.getAttributes();
1871               Attrs; Attrs = Attrs->getNext()) {
1872            if (Attrs->getKind() == AttributeList::AT_overloadable) {
1873              Overloadable = true;
1874              break;
1875            }
1876          }
1877
1878          if (!Overloadable)
1879            Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1880        }
1881
1882        if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
1883          // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
1884          // definition.
1885          Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1886          D.setInvalidType(true);
1887          break;
1888        }
1889
1890        FunctionProtoType::ExtProtoInfo EPI;
1891        EPI.Variadic = FTI.isVariadic;
1892        EPI.TypeQuals = FTI.TypeQuals;
1893        EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
1894                    : FTI.RefQualifierIsLValueRef? RQ_LValue
1895                    : RQ_RValue;
1896
1897        // Otherwise, we have a function with an argument list that is
1898        // potentially variadic.
1899        llvm::SmallVector<QualType, 16> ArgTys;
1900        ArgTys.reserve(FTI.NumArgs);
1901
1902        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1903          ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
1904          QualType ArgTy = Param->getType();
1905          assert(!ArgTy.isNull() && "Couldn't parse type?");
1906
1907          // Adjust the parameter type.
1908          assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1909
1910          // Look for 'void'.  void is allowed only as a single argument to a
1911          // function with no other parameters (C99 6.7.5.3p10).  We record
1912          // int(void) as a FunctionProtoType with an empty argument list.
1913          if (ArgTy->isVoidType()) {
1914            // If this is something like 'float(int, void)', reject it.  'void'
1915            // is an incomplete type (C99 6.2.5p19) and function decls cannot
1916            // have arguments of incomplete type.
1917            if (FTI.NumArgs != 1 || FTI.isVariadic) {
1918              Diag(DeclType.Loc, diag::err_void_only_param);
1919              ArgTy = Context.IntTy;
1920              Param->setType(ArgTy);
1921            } else if (FTI.ArgInfo[i].Ident) {
1922              // Reject, but continue to parse 'int(void abc)'.
1923              Diag(FTI.ArgInfo[i].IdentLoc,
1924                   diag::err_param_with_void_type);
1925              ArgTy = Context.IntTy;
1926              Param->setType(ArgTy);
1927            } else {
1928              // Reject, but continue to parse 'float(const void)'.
1929              if (ArgTy.hasQualifiers())
1930                Diag(DeclType.Loc, diag::err_void_param_qualified);
1931
1932              // Do not add 'void' to the ArgTys list.
1933              break;
1934            }
1935          } else if (!FTI.hasPrototype) {
1936            if (ArgTy->isPromotableIntegerType()) {
1937              ArgTy = Context.getPromotedIntegerType(ArgTy);
1938              Param->setKNRPromoted(true);
1939            } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1940              if (BTy->getKind() == BuiltinType::Float) {
1941                ArgTy = Context.DoubleTy;
1942                Param->setKNRPromoted(true);
1943              }
1944            }
1945          }
1946
1947          ArgTys.push_back(ArgTy);
1948        }
1949
1950        llvm::SmallVector<QualType, 4> Exceptions;
1951        EPI.ExceptionSpecType = FTI.getExceptionSpecType();
1952        if (FTI.getExceptionSpecType() == EST_Dynamic) {
1953          Exceptions.reserve(FTI.NumExceptions);
1954          for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1955            // FIXME: Preserve type source info.
1956            QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1957            // Check that the type is valid for an exception spec, and
1958            // drop it if not.
1959            if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1960              Exceptions.push_back(ET);
1961          }
1962          EPI.NumExceptions = Exceptions.size();
1963          EPI.Exceptions = Exceptions.data();
1964        } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
1965          // If an error occurred, there's no expression here.
1966          if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
1967            assert((NoexceptExpr->isTypeDependent() ||
1968                    NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
1969                        Context.BoolTy) &&
1970                 "Parser should have made sure that the expression is boolean");
1971            SourceLocation ErrLoc;
1972            llvm::APSInt Dummy;
1973            if (!NoexceptExpr->isValueDependent() &&
1974                !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
1975                                                     /*evaluated*/false))
1976              Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
1977                  << NoexceptExpr->getSourceRange();
1978            else
1979              EPI.NoexceptExpr = NoexceptExpr;
1980          }
1981        } else if (FTI.getExceptionSpecType() == EST_None &&
1982                   ImplicitlyNoexcept && chunkIndex == 0) {
1983          // Only the outermost chunk is marked noexcept, of course.
1984          EPI.ExceptionSpecType = EST_BasicNoexcept;
1985        }
1986
1987        T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
1988      }
1989
1990      break;
1991    }
1992    case DeclaratorChunk::MemberPointer:
1993      // The scope spec must refer to a class, or be dependent.
1994      CXXScopeSpec &SS = DeclType.Mem.Scope();
1995      QualType ClsType;
1996      if (SS.isInvalid()) {
1997        // Avoid emitting extra errors if we already errored on the scope.
1998        D.setInvalidType(true);
1999      } else if (isDependentScopeSpecifier(SS) ||
2000                 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS))) {
2001        NestedNameSpecifier *NNS
2002          = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2003        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2004        switch (NNS->getKind()) {
2005        case NestedNameSpecifier::Identifier:
2006          ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
2007                                                 NNS->getAsIdentifier());
2008          break;
2009
2010        case NestedNameSpecifier::Namespace:
2011        case NestedNameSpecifier::NamespaceAlias:
2012        case NestedNameSpecifier::Global:
2013          llvm_unreachable("Nested-name-specifier must name a type");
2014          break;
2015
2016        case NestedNameSpecifier::TypeSpec:
2017        case NestedNameSpecifier::TypeSpecWithTemplate:
2018          ClsType = QualType(NNS->getAsType(), 0);
2019          // Note: if the NNS has a prefix and ClsType is a nondependent
2020          // TemplateSpecializationType, then the NNS prefix is NOT included
2021          // in ClsType; hence we wrap ClsType into an ElaboratedType.
2022          // NOTE: in particular, no wrap occurs if ClsType already is an
2023          // Elaborated, DependentName, or DependentTemplateSpecialization.
2024          if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2025            ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2026          break;
2027        }
2028      } else {
2029        Diag(DeclType.Mem.Scope().getBeginLoc(),
2030             diag::err_illegal_decl_mempointer_in_nonclass)
2031          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2032          << DeclType.Mem.Scope().getRange();
2033        D.setInvalidType(true);
2034      }
2035
2036      if (!ClsType.isNull())
2037        T = BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2038      if (T.isNull()) {
2039        T = Context.IntTy;
2040        D.setInvalidType(true);
2041      } else if (DeclType.Mem.TypeQuals) {
2042        T = BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2043      }
2044      break;
2045    }
2046
2047    if (T.isNull()) {
2048      D.setInvalidType(true);
2049      T = Context.IntTy;
2050    }
2051
2052    // See if there are any attributes on this declarator chunk.
2053    if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2054      processTypeAttrs(state, T, false, attrs);
2055  }
2056
2057  if (getLangOptions().CPlusPlus && T->isFunctionType()) {
2058    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
2059    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
2060
2061    // C++ 8.3.5p4:
2062    //   A cv-qualifier-seq shall only be part of the function type
2063    //   for a nonstatic member function, the function type to which a pointer
2064    //   to member refers, or the top-level function type of a function typedef
2065    //   declaration.
2066    //
2067    // Core issue 547 also allows cv-qualifiers on function types that are
2068    // top-level template type arguments.
2069    bool FreeFunction;
2070    if (!D.getCXXScopeSpec().isSet()) {
2071      FreeFunction = (D.getContext() != Declarator::MemberContext ||
2072                      D.getDeclSpec().isFriendSpecified());
2073    } else {
2074      DeclContext *DC = computeDeclContext(D.getCXXScopeSpec());
2075      FreeFunction = (DC && !DC->isRecord());
2076    }
2077
2078    // C++0x [dcl.fct]p6:
2079    //   A ref-qualifier shall only be part of the function type for a
2080    //   non-static member function, the function type to which a pointer to
2081    //   member refers, or the top-level function type of a function typedef
2082    //   declaration.
2083    if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
2084        !(D.getContext() == Declarator::TemplateTypeArgContext &&
2085          !D.isFunctionDeclarator()) && !IsTypedefName &&
2086        (FreeFunction ||
2087         D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
2088      if (D.getContext() == Declarator::TemplateTypeArgContext) {
2089        // Accept qualified function types as template type arguments as a GNU
2090        // extension. This is also the subject of C++ core issue 547.
2091        std::string Quals;
2092        if (FnTy->getTypeQuals() != 0)
2093          Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2094
2095        switch (FnTy->getRefQualifier()) {
2096        case RQ_None:
2097          break;
2098
2099        case RQ_LValue:
2100          if (!Quals.empty())
2101            Quals += ' ';
2102          Quals += '&';
2103          break;
2104
2105        case RQ_RValue:
2106          if (!Quals.empty())
2107            Quals += ' ';
2108          Quals += "&&";
2109          break;
2110        }
2111
2112        Diag(D.getIdentifierLoc(),
2113             diag::ext_qualified_function_type_template_arg)
2114          << Quals;
2115      } else {
2116        if (FnTy->getTypeQuals() != 0) {
2117          if (D.isFunctionDeclarator())
2118            Diag(D.getIdentifierLoc(),
2119                 diag::err_invalid_qualified_function_type);
2120          else
2121            Diag(D.getIdentifierLoc(),
2122                 diag::err_invalid_qualified_typedef_function_type_use)
2123              << FreeFunction;
2124        }
2125
2126        if (FnTy->getRefQualifier()) {
2127          if (D.isFunctionDeclarator()) {
2128            SourceLocation Loc = D.getIdentifierLoc();
2129            for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2130              const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2131              if (Chunk.Kind == DeclaratorChunk::Function &&
2132                  Chunk.Fun.hasRefQualifier()) {
2133                Loc = Chunk.Fun.getRefQualifierLoc();
2134                break;
2135              }
2136            }
2137
2138            Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
2139              << (FnTy->getRefQualifier() == RQ_LValue)
2140              << FixItHint::CreateRemoval(Loc);
2141          } else {
2142            Diag(D.getIdentifierLoc(),
2143                 diag::err_invalid_ref_qualifier_typedef_function_type_use)
2144              << FreeFunction
2145              << (FnTy->getRefQualifier() == RQ_LValue);
2146          }
2147        }
2148
2149        // Strip the cv-qualifiers and ref-qualifiers from the type.
2150        FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2151        EPI.TypeQuals = 0;
2152        EPI.RefQualifier = RQ_None;
2153
2154        T = Context.getFunctionType(FnTy->getResultType(),
2155                                    FnTy->arg_type_begin(),
2156                                    FnTy->getNumArgs(), EPI);
2157      }
2158    }
2159  }
2160
2161  // Apply any undistributed attributes from the declarator.
2162  if (!T.isNull())
2163    if (AttributeList *attrs = D.getAttributes())
2164      processTypeAttrs(state, T, false, attrs);
2165
2166  // Diagnose any ignored type attributes.
2167  if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2168
2169  // C++0x [dcl.constexpr]p9:
2170  //  A constexpr specifier used in an object declaration declares the object
2171  //  as const.
2172  if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
2173    T.addConst();
2174  }
2175
2176  // If there was an ellipsis in the declarator, the declaration declares a
2177  // parameter pack whose type may be a pack expansion type.
2178  if (D.hasEllipsis() && !T.isNull()) {
2179    // C++0x [dcl.fct]p13:
2180    //   A declarator-id or abstract-declarator containing an ellipsis shall
2181    //   only be used in a parameter-declaration. Such a parameter-declaration
2182    //   is a parameter pack (14.5.3). [...]
2183    switch (D.getContext()) {
2184    case Declarator::PrototypeContext:
2185      // C++0x [dcl.fct]p13:
2186      //   [...] When it is part of a parameter-declaration-clause, the
2187      //   parameter pack is a function parameter pack (14.5.3). The type T
2188      //   of the declarator-id of the function parameter pack shall contain
2189      //   a template parameter pack; each template parameter pack in T is
2190      //   expanded by the function parameter pack.
2191      //
2192      // We represent function parameter packs as function parameters whose
2193      // type is a pack expansion.
2194      if (!T->containsUnexpandedParameterPack()) {
2195        Diag(D.getEllipsisLoc(),
2196             diag::err_function_parameter_pack_without_parameter_packs)
2197          << T <<  D.getSourceRange();
2198        D.setEllipsisLoc(SourceLocation());
2199      } else {
2200        T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2201      }
2202      break;
2203
2204    case Declarator::TemplateParamContext:
2205      // C++0x [temp.param]p15:
2206      //   If a template-parameter is a [...] is a parameter-declaration that
2207      //   declares a parameter pack (8.3.5), then the template-parameter is a
2208      //   template parameter pack (14.5.3).
2209      //
2210      // Note: core issue 778 clarifies that, if there are any unexpanded
2211      // parameter packs in the type of the non-type template parameter, then
2212      // it expands those parameter packs.
2213      if (T->containsUnexpandedParameterPack())
2214        T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2215      else if (!getLangOptions().CPlusPlus0x)
2216        Diag(D.getEllipsisLoc(), diag::ext_variadic_templates);
2217      break;
2218
2219    case Declarator::FileContext:
2220    case Declarator::KNRTypeListContext:
2221    case Declarator::ObjCPrototypeContext: // FIXME: special diagnostic here?
2222    case Declarator::TypeNameContext:
2223    case Declarator::AliasDeclContext:
2224    case Declarator::AliasTemplateContext:
2225    case Declarator::MemberContext:
2226    case Declarator::BlockContext:
2227    case Declarator::ForContext:
2228    case Declarator::ConditionContext:
2229    case Declarator::CXXCatchContext:
2230    case Declarator::BlockLiteralContext:
2231    case Declarator::TemplateTypeArgContext:
2232      // FIXME: We may want to allow parameter packs in block-literal contexts
2233      // in the future.
2234      Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2235      D.setEllipsisLoc(SourceLocation());
2236      break;
2237    }
2238  }
2239
2240  if (T.isNull())
2241    return Context.getNullTypeSourceInfo();
2242  else if (D.isInvalidType())
2243    return Context.getTrivialTypeSourceInfo(T);
2244  return GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo);
2245}
2246
2247/// Map an AttributedType::Kind to an AttributeList::Kind.
2248static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2249  switch (kind) {
2250  case AttributedType::attr_address_space:
2251    return AttributeList::AT_address_space;
2252  case AttributedType::attr_regparm:
2253    return AttributeList::AT_regparm;
2254  case AttributedType::attr_vector_size:
2255    return AttributeList::AT_vector_size;
2256  case AttributedType::attr_neon_vector_type:
2257    return AttributeList::AT_neon_vector_type;
2258  case AttributedType::attr_neon_polyvector_type:
2259    return AttributeList::AT_neon_polyvector_type;
2260  case AttributedType::attr_objc_gc:
2261    return AttributeList::AT_objc_gc;
2262  case AttributedType::attr_noreturn:
2263    return AttributeList::AT_noreturn;
2264  case AttributedType::attr_cdecl:
2265    return AttributeList::AT_cdecl;
2266  case AttributedType::attr_fastcall:
2267    return AttributeList::AT_fastcall;
2268  case AttributedType::attr_stdcall:
2269    return AttributeList::AT_stdcall;
2270  case AttributedType::attr_thiscall:
2271    return AttributeList::AT_thiscall;
2272  case AttributedType::attr_pascal:
2273    return AttributeList::AT_pascal;
2274  case AttributedType::attr_pcs:
2275    return AttributeList::AT_pcs;
2276  }
2277  llvm_unreachable("unexpected attribute kind!");
2278  return AttributeList::Kind();
2279}
2280
2281static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2282                                  const AttributeList *attrs) {
2283  AttributedType::Kind kind = TL.getAttrKind();
2284
2285  assert(attrs && "no type attributes in the expected location!");
2286  AttributeList::Kind parsedKind = getAttrListKind(kind);
2287  while (attrs->getKind() != parsedKind) {
2288    attrs = attrs->getNext();
2289    assert(attrs && "no matching attribute in expected location!");
2290  }
2291
2292  TL.setAttrNameLoc(attrs->getLoc());
2293  if (TL.hasAttrExprOperand())
2294    TL.setAttrExprOperand(attrs->getArg(0));
2295  else if (TL.hasAttrEnumOperand())
2296    TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2297
2298  // FIXME: preserve this information to here.
2299  if (TL.hasAttrOperand())
2300    TL.setAttrOperandParensRange(SourceRange());
2301}
2302
2303namespace {
2304  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
2305    ASTContext &Context;
2306    const DeclSpec &DS;
2307
2308  public:
2309    TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2310      : Context(Context), DS(DS) {}
2311
2312    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2313      fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2314      Visit(TL.getModifiedLoc());
2315    }
2316    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2317      Visit(TL.getUnqualifiedLoc());
2318    }
2319    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2320      TL.setNameLoc(DS.getTypeSpecTypeLoc());
2321    }
2322    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2323      TL.setNameLoc(DS.getTypeSpecTypeLoc());
2324    }
2325    void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2326      // Handle the base type, which might not have been written explicitly.
2327      if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2328        TL.setHasBaseTypeAsWritten(false);
2329        TL.getBaseLoc().initialize(Context, SourceLocation());
2330      } else {
2331        TL.setHasBaseTypeAsWritten(true);
2332        Visit(TL.getBaseLoc());
2333      }
2334
2335      // Protocol qualifiers.
2336      if (DS.getProtocolQualifiers()) {
2337        assert(TL.getNumProtocols() > 0);
2338        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2339        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2340        TL.setRAngleLoc(DS.getSourceRange().getEnd());
2341        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2342          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2343      } else {
2344        assert(TL.getNumProtocols() == 0);
2345        TL.setLAngleLoc(SourceLocation());
2346        TL.setRAngleLoc(SourceLocation());
2347      }
2348    }
2349    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2350      TL.setStarLoc(SourceLocation());
2351      Visit(TL.getPointeeLoc());
2352    }
2353    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
2354      TypeSourceInfo *TInfo = 0;
2355      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2356
2357      // If we got no declarator info from previous Sema routines,
2358      // just fill with the typespec loc.
2359      if (!TInfo) {
2360        TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
2361        return;
2362      }
2363
2364      TypeLoc OldTL = TInfo->getTypeLoc();
2365      if (TInfo->getType()->getAs<ElaboratedType>()) {
2366        ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2367        TemplateSpecializationTypeLoc NamedTL =
2368          cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2369        TL.copy(NamedTL);
2370      }
2371      else
2372        TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
2373    }
2374    void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2375      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2376      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2377      TL.setParensRange(DS.getTypeofParensRange());
2378    }
2379    void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2380      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2381      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2382      TL.setParensRange(DS.getTypeofParensRange());
2383      assert(DS.getRepAsType());
2384      TypeSourceInfo *TInfo = 0;
2385      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2386      TL.setUnderlyingTInfo(TInfo);
2387    }
2388    void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2389      // FIXME: This holds only because we only have one unary transform.
2390      assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2391      TL.setKWLoc(DS.getTypeSpecTypeLoc());
2392      TL.setParensRange(DS.getTypeofParensRange());
2393      assert(DS.getRepAsType());
2394      TypeSourceInfo *TInfo = 0;
2395      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2396      TL.setUnderlyingTInfo(TInfo);
2397    }
2398    void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2399      // By default, use the source location of the type specifier.
2400      TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2401      if (TL.needsExtraLocalData()) {
2402        // Set info for the written builtin specifiers.
2403        TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2404        // Try to have a meaningful source location.
2405        if (TL.getWrittenSignSpec() != TSS_unspecified)
2406          // Sign spec loc overrides the others (e.g., 'unsigned long').
2407          TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2408        else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2409          // Width spec loc overrides type spec loc (e.g., 'short int').
2410          TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2411      }
2412    }
2413    void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2414      ElaboratedTypeKeyword Keyword
2415        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2416      if (DS.getTypeSpecType() == TST_typename) {
2417        TypeSourceInfo *TInfo = 0;
2418        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2419        if (TInfo) {
2420          TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2421          return;
2422        }
2423      }
2424      TL.setKeywordLoc(Keyword != ETK_None
2425                       ? DS.getTypeSpecTypeLoc()
2426                       : SourceLocation());
2427      const CXXScopeSpec& SS = DS.getTypeSpecScope();
2428      TL.setQualifierLoc(SS.getWithLocInContext(Context));
2429      Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2430    }
2431    void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2432      ElaboratedTypeKeyword Keyword
2433        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2434      if (DS.getTypeSpecType() == TST_typename) {
2435        TypeSourceInfo *TInfo = 0;
2436        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2437        if (TInfo) {
2438          TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2439          return;
2440        }
2441      }
2442      TL.setKeywordLoc(Keyword != ETK_None
2443                       ? DS.getTypeSpecTypeLoc()
2444                       : SourceLocation());
2445      const CXXScopeSpec& SS = DS.getTypeSpecScope();
2446      TL.setQualifierLoc(SS.getWithLocInContext(Context));
2447      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2448    }
2449    void VisitDependentTemplateSpecializationTypeLoc(
2450                                 DependentTemplateSpecializationTypeLoc TL) {
2451      ElaboratedTypeKeyword Keyword
2452        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2453      if (Keyword == ETK_Typename) {
2454        TypeSourceInfo *TInfo = 0;
2455        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2456        if (TInfo) {
2457          TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2458                    TInfo->getTypeLoc()));
2459          return;
2460        }
2461      }
2462      TL.initializeLocal(Context, SourceLocation());
2463      TL.setKeywordLoc(Keyword != ETK_None
2464                       ? DS.getTypeSpecTypeLoc()
2465                       : SourceLocation());
2466      const CXXScopeSpec& SS = DS.getTypeSpecScope();
2467      TL.setQualifierLoc(SS.getWithLocInContext(Context));
2468      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2469    }
2470    void VisitTagTypeLoc(TagTypeLoc TL) {
2471      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2472    }
2473
2474    void VisitTypeLoc(TypeLoc TL) {
2475      // FIXME: add other typespec types and change this to an assert.
2476      TL.initialize(Context, DS.getTypeSpecTypeLoc());
2477    }
2478  };
2479
2480  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
2481    ASTContext &Context;
2482    const DeclaratorChunk &Chunk;
2483
2484  public:
2485    DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2486      : Context(Context), Chunk(Chunk) {}
2487
2488    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2489      llvm_unreachable("qualified type locs not expected here!");
2490    }
2491
2492    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2493      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2494      TL.setCaretLoc(Chunk.Loc);
2495    }
2496    void VisitPointerTypeLoc(PointerTypeLoc TL) {
2497      assert(Chunk.Kind == DeclaratorChunk::Pointer);
2498      TL.setStarLoc(Chunk.Loc);
2499    }
2500    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2501      assert(Chunk.Kind == DeclaratorChunk::Pointer);
2502      TL.setStarLoc(Chunk.Loc);
2503    }
2504    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2505      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
2506      const CXXScopeSpec& SS = Chunk.Mem.Scope();
2507      NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
2508
2509      const Type* ClsTy = TL.getClass();
2510      QualType ClsQT = QualType(ClsTy, 0);
2511      TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
2512      // Now copy source location info into the type loc component.
2513      TypeLoc ClsTL = ClsTInfo->getTypeLoc();
2514      switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
2515      case NestedNameSpecifier::Identifier:
2516        assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
2517        {
2518          DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
2519          DNTLoc.setKeywordLoc(SourceLocation());
2520          DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
2521          DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
2522        }
2523        break;
2524
2525      case NestedNameSpecifier::TypeSpec:
2526      case NestedNameSpecifier::TypeSpecWithTemplate:
2527        if (isa<ElaboratedType>(ClsTy)) {
2528          ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
2529          ETLoc.setKeywordLoc(SourceLocation());
2530          ETLoc.setQualifierLoc(NNSLoc.getPrefix());
2531          TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
2532          NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
2533        } else {
2534          ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
2535        }
2536        break;
2537
2538      case NestedNameSpecifier::Namespace:
2539      case NestedNameSpecifier::NamespaceAlias:
2540      case NestedNameSpecifier::Global:
2541        llvm_unreachable("Nested-name-specifier must name a type");
2542        break;
2543      }
2544
2545      // Finally fill in MemberPointerLocInfo fields.
2546      TL.setStarLoc(Chunk.Loc);
2547      TL.setClassTInfo(ClsTInfo);
2548    }
2549    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2550      assert(Chunk.Kind == DeclaratorChunk::Reference);
2551      // 'Amp' is misleading: this might have been originally
2552      /// spelled with AmpAmp.
2553      TL.setAmpLoc(Chunk.Loc);
2554    }
2555    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2556      assert(Chunk.Kind == DeclaratorChunk::Reference);
2557      assert(!Chunk.Ref.LValueRef);
2558      TL.setAmpAmpLoc(Chunk.Loc);
2559    }
2560    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
2561      assert(Chunk.Kind == DeclaratorChunk::Array);
2562      TL.setLBracketLoc(Chunk.Loc);
2563      TL.setRBracketLoc(Chunk.EndLoc);
2564      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
2565    }
2566    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2567      assert(Chunk.Kind == DeclaratorChunk::Function);
2568      TL.setLocalRangeBegin(Chunk.Loc);
2569      TL.setLocalRangeEnd(Chunk.EndLoc);
2570      TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
2571
2572      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
2573      for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
2574        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2575        TL.setArg(tpi++, Param);
2576      }
2577      // FIXME: exception specs
2578    }
2579    void VisitParenTypeLoc(ParenTypeLoc TL) {
2580      assert(Chunk.Kind == DeclaratorChunk::Paren);
2581      TL.setLParenLoc(Chunk.Loc);
2582      TL.setRParenLoc(Chunk.EndLoc);
2583    }
2584
2585    void VisitTypeLoc(TypeLoc TL) {
2586      llvm_unreachable("unsupported TypeLoc kind in declarator!");
2587    }
2588  };
2589}
2590
2591/// \brief Create and instantiate a TypeSourceInfo with type source information.
2592///
2593/// \param T QualType referring to the type as written in source code.
2594///
2595/// \param ReturnTypeInfo For declarators whose return type does not show
2596/// up in the normal place in the declaration specifiers (such as a C++
2597/// conversion function), this pointer will refer to a type source information
2598/// for that return type.
2599TypeSourceInfo *
2600Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
2601                                     TypeSourceInfo *ReturnTypeInfo) {
2602  TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
2603  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
2604
2605  // Handle parameter packs whose type is a pack expansion.
2606  if (isa<PackExpansionType>(T)) {
2607    cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
2608    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2609  }
2610
2611  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2612    while (isa<AttributedTypeLoc>(CurrTL)) {
2613      AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
2614      fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
2615      CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
2616    }
2617
2618    DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
2619    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2620  }
2621
2622  // If we have different source information for the return type, use
2623  // that.  This really only applies to C++ conversion functions.
2624  if (ReturnTypeInfo) {
2625    TypeLoc TL = ReturnTypeInfo->getTypeLoc();
2626    assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
2627    memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
2628  } else {
2629    TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
2630  }
2631
2632  return TInfo;
2633}
2634
2635/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
2636ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
2637  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
2638  // and Sema during declaration parsing. Try deallocating/caching them when
2639  // it's appropriate, instead of allocating them and keeping them around.
2640  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
2641                                                       TypeAlignment);
2642  new (LocT) LocInfoType(T, TInfo);
2643  assert(LocT->getTypeClass() != T->getTypeClass() &&
2644         "LocInfoType's TypeClass conflicts with an existing Type class");
2645  return ParsedType::make(QualType(LocT, 0));
2646}
2647
2648void LocInfoType::getAsStringInternal(std::string &Str,
2649                                      const PrintingPolicy &Policy) const {
2650  assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
2651         " was used directly instead of getting the QualType through"
2652         " GetTypeFromParser");
2653}
2654
2655TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
2656  // C99 6.7.6: Type names have no identifier.  This is already validated by
2657  // the parser.
2658  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
2659
2660  TagDecl *OwnedTag = 0;
2661  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
2662  QualType T = TInfo->getType();
2663  if (D.isInvalidType())
2664    return true;
2665
2666  if (getLangOptions().CPlusPlus) {
2667    // Check that there are no default arguments (C++ only).
2668    CheckExtraCXXDefaultArguments(D);
2669
2670    // C++0x [dcl.type]p3:
2671    //   A type-specifier-seq shall not define a class or enumeration unless
2672    //   it appears in the type-id of an alias-declaration (7.1.3) that is not
2673    //   the declaration of a template-declaration.
2674    if (OwnedTag && OwnedTag->isDefinition()) {
2675      if (D.getContext() == Declarator::AliasTemplateContext)
2676        Diag(OwnedTag->getLocation(), diag::err_type_defined_in_alias_template)
2677          << Context.getTypeDeclType(OwnedTag);
2678      else if (D.getContext() != Declarator::AliasDeclContext)
2679        Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
2680          << Context.getTypeDeclType(OwnedTag);
2681    }
2682  }
2683
2684  return CreateParsedType(T, TInfo);
2685}
2686
2687
2688
2689//===----------------------------------------------------------------------===//
2690// Type Attribute Processing
2691//===----------------------------------------------------------------------===//
2692
2693/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
2694/// specified type.  The attribute contains 1 argument, the id of the address
2695/// space for the type.
2696static void HandleAddressSpaceTypeAttribute(QualType &Type,
2697                                            const AttributeList &Attr, Sema &S){
2698
2699  // If this type is already address space qualified, reject it.
2700  // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
2701  // for two or more different address spaces."
2702  if (Type.getAddressSpace()) {
2703    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
2704    Attr.setInvalid();
2705    return;
2706  }
2707
2708  // Check the attribute arguments.
2709  if (Attr.getNumArgs() != 1) {
2710    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2711    Attr.setInvalid();
2712    return;
2713  }
2714  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
2715  llvm::APSInt addrSpace(32);
2716  if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
2717      !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
2718    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
2719      << ASArgExpr->getSourceRange();
2720    Attr.setInvalid();
2721    return;
2722  }
2723
2724  // Bounds checking.
2725  if (addrSpace.isSigned()) {
2726    if (addrSpace.isNegative()) {
2727      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
2728        << ASArgExpr->getSourceRange();
2729      Attr.setInvalid();
2730      return;
2731    }
2732    addrSpace.setIsSigned(false);
2733  }
2734  llvm::APSInt max(addrSpace.getBitWidth());
2735  max = Qualifiers::MaxAddressSpace;
2736  if (addrSpace > max) {
2737    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
2738      << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
2739    Attr.setInvalid();
2740    return;
2741  }
2742
2743  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
2744  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
2745}
2746
2747/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
2748/// attribute on the specified type.  Returns true to indicate that
2749/// the attribute was handled, false to indicate that the type does
2750/// not permit the attribute.
2751static bool handleObjCGCTypeAttr(TypeProcessingState &state,
2752                                 AttributeList &attr,
2753                                 QualType &type) {
2754  Sema &S = state.getSema();
2755
2756  // Delay if this isn't some kind of pointer.
2757  if (!type->isPointerType() &&
2758      !type->isObjCObjectPointerType() &&
2759      !type->isBlockPointerType())
2760    return false;
2761
2762  if (type.getObjCGCAttr() != Qualifiers::GCNone) {
2763    S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
2764    attr.setInvalid();
2765    return true;
2766  }
2767
2768  // Check the attribute arguments.
2769  if (!attr.getParameterName()) {
2770    S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
2771      << "objc_gc" << 1;
2772    attr.setInvalid();
2773    return true;
2774  }
2775  Qualifiers::GC GCAttr;
2776  if (attr.getNumArgs() != 0) {
2777    S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2778    attr.setInvalid();
2779    return true;
2780  }
2781  if (attr.getParameterName()->isStr("weak"))
2782    GCAttr = Qualifiers::Weak;
2783  else if (attr.getParameterName()->isStr("strong"))
2784    GCAttr = Qualifiers::Strong;
2785  else {
2786    S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
2787      << "objc_gc" << attr.getParameterName();
2788    attr.setInvalid();
2789    return true;
2790  }
2791
2792  QualType origType = type;
2793  type = S.Context.getObjCGCQualType(origType, GCAttr);
2794
2795  // Make an attributed type to preserve the source information.
2796  if (attr.getLoc().isValid())
2797    type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
2798                                       origType, type);
2799
2800  return true;
2801}
2802
2803namespace {
2804  /// A helper class to unwrap a type down to a function for the
2805  /// purposes of applying attributes there.
2806  ///
2807  /// Use:
2808  ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
2809  ///   if (unwrapped.isFunctionType()) {
2810  ///     const FunctionType *fn = unwrapped.get();
2811  ///     // change fn somehow
2812  ///     T = unwrapped.wrap(fn);
2813  ///   }
2814  struct FunctionTypeUnwrapper {
2815    enum WrapKind {
2816      Desugar,
2817      Parens,
2818      Pointer,
2819      BlockPointer,
2820      Reference,
2821      MemberPointer
2822    };
2823
2824    QualType Original;
2825    const FunctionType *Fn;
2826    llvm::SmallVector<unsigned char /*WrapKind*/, 8> Stack;
2827
2828    FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
2829      while (true) {
2830        const Type *Ty = T.getTypePtr();
2831        if (isa<FunctionType>(Ty)) {
2832          Fn = cast<FunctionType>(Ty);
2833          return;
2834        } else if (isa<ParenType>(Ty)) {
2835          T = cast<ParenType>(Ty)->getInnerType();
2836          Stack.push_back(Parens);
2837        } else if (isa<PointerType>(Ty)) {
2838          T = cast<PointerType>(Ty)->getPointeeType();
2839          Stack.push_back(Pointer);
2840        } else if (isa<BlockPointerType>(Ty)) {
2841          T = cast<BlockPointerType>(Ty)->getPointeeType();
2842          Stack.push_back(BlockPointer);
2843        } else if (isa<MemberPointerType>(Ty)) {
2844          T = cast<MemberPointerType>(Ty)->getPointeeType();
2845          Stack.push_back(MemberPointer);
2846        } else if (isa<ReferenceType>(Ty)) {
2847          T = cast<ReferenceType>(Ty)->getPointeeType();
2848          Stack.push_back(Reference);
2849        } else {
2850          const Type *DTy = Ty->getUnqualifiedDesugaredType();
2851          if (Ty == DTy) {
2852            Fn = 0;
2853            return;
2854          }
2855
2856          T = QualType(DTy, 0);
2857          Stack.push_back(Desugar);
2858        }
2859      }
2860    }
2861
2862    bool isFunctionType() const { return (Fn != 0); }
2863    const FunctionType *get() const { return Fn; }
2864
2865    QualType wrap(Sema &S, const FunctionType *New) {
2866      // If T wasn't modified from the unwrapped type, do nothing.
2867      if (New == get()) return Original;
2868
2869      Fn = New;
2870      return wrap(S.Context, Original, 0);
2871    }
2872
2873  private:
2874    QualType wrap(ASTContext &C, QualType Old, unsigned I) {
2875      if (I == Stack.size())
2876        return C.getQualifiedType(Fn, Old.getQualifiers());
2877
2878      // Build up the inner type, applying the qualifiers from the old
2879      // type to the new type.
2880      SplitQualType SplitOld = Old.split();
2881
2882      // As a special case, tail-recurse if there are no qualifiers.
2883      if (SplitOld.second.empty())
2884        return wrap(C, SplitOld.first, I);
2885      return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
2886    }
2887
2888    QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
2889      if (I == Stack.size()) return QualType(Fn, 0);
2890
2891      switch (static_cast<WrapKind>(Stack[I++])) {
2892      case Desugar:
2893        // This is the point at which we potentially lose source
2894        // information.
2895        return wrap(C, Old->getUnqualifiedDesugaredType(), I);
2896
2897      case Parens: {
2898        QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
2899        return C.getParenType(New);
2900      }
2901
2902      case Pointer: {
2903        QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
2904        return C.getPointerType(New);
2905      }
2906
2907      case BlockPointer: {
2908        QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
2909        return C.getBlockPointerType(New);
2910      }
2911
2912      case MemberPointer: {
2913        const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
2914        QualType New = wrap(C, OldMPT->getPointeeType(), I);
2915        return C.getMemberPointerType(New, OldMPT->getClass());
2916      }
2917
2918      case Reference: {
2919        const ReferenceType *OldRef = cast<ReferenceType>(Old);
2920        QualType New = wrap(C, OldRef->getPointeeType(), I);
2921        if (isa<LValueReferenceType>(OldRef))
2922          return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
2923        else
2924          return C.getRValueReferenceType(New);
2925      }
2926      }
2927
2928      llvm_unreachable("unknown wrapping kind");
2929      return QualType();
2930    }
2931  };
2932}
2933
2934/// Process an individual function attribute.  Returns true to
2935/// indicate that the attribute was handled, false if it wasn't.
2936static bool handleFunctionTypeAttr(TypeProcessingState &state,
2937                                   AttributeList &attr,
2938                                   QualType &type) {
2939  Sema &S = state.getSema();
2940
2941  FunctionTypeUnwrapper unwrapped(S, type);
2942
2943  if (attr.getKind() == AttributeList::AT_noreturn) {
2944    if (S.CheckNoReturnAttr(attr))
2945      return true;
2946
2947    // Delay if this is not a function type.
2948    if (!unwrapped.isFunctionType())
2949      return false;
2950
2951    // Otherwise we can process right away.
2952    FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
2953    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2954    return true;
2955  }
2956
2957  if (attr.getKind() == AttributeList::AT_regparm) {
2958    unsigned value;
2959    if (S.CheckRegparmAttr(attr, value))
2960      return true;
2961
2962    // Delay if this is not a function type.
2963    if (!unwrapped.isFunctionType())
2964      return false;
2965
2966    // Diagnose regparm with fastcall.
2967    const FunctionType *fn = unwrapped.get();
2968    CallingConv CC = fn->getCallConv();
2969    if (CC == CC_X86FastCall) {
2970      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
2971        << FunctionType::getNameForCallConv(CC)
2972        << "regparm";
2973      attr.setInvalid();
2974      return true;
2975    }
2976
2977    FunctionType::ExtInfo EI =
2978      unwrapped.get()->getExtInfo().withRegParm(value);
2979    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2980    return true;
2981  }
2982
2983  // Otherwise, a calling convention.
2984  CallingConv CC;
2985  if (S.CheckCallingConvAttr(attr, CC))
2986    return true;
2987
2988  // Delay if the type didn't work out to a function.
2989  if (!unwrapped.isFunctionType()) return false;
2990
2991  const FunctionType *fn = unwrapped.get();
2992  CallingConv CCOld = fn->getCallConv();
2993  if (S.Context.getCanonicalCallConv(CC) ==
2994      S.Context.getCanonicalCallConv(CCOld)) {
2995    FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
2996    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2997    return true;
2998  }
2999
3000  if (CCOld != CC_Default) {
3001    // Should we diagnose reapplications of the same convention?
3002    S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3003      << FunctionType::getNameForCallConv(CC)
3004      << FunctionType::getNameForCallConv(CCOld);
3005    attr.setInvalid();
3006    return true;
3007  }
3008
3009  // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3010  if (CC == CC_X86FastCall) {
3011    if (isa<FunctionNoProtoType>(fn)) {
3012      S.Diag(attr.getLoc(), diag::err_cconv_knr)
3013        << FunctionType::getNameForCallConv(CC);
3014      attr.setInvalid();
3015      return true;
3016    }
3017
3018    const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
3019    if (FnP->isVariadic()) {
3020      S.Diag(attr.getLoc(), diag::err_cconv_varargs)
3021        << FunctionType::getNameForCallConv(CC);
3022      attr.setInvalid();
3023      return true;
3024    }
3025
3026    // Also diagnose fastcall with regparm.
3027    if (fn->getHasRegParm()) {
3028      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3029        << "regparm"
3030        << FunctionType::getNameForCallConv(CC);
3031      attr.setInvalid();
3032      return true;
3033    }
3034  }
3035
3036  FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3037  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3038  return true;
3039}
3040
3041/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3042static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3043                                             const AttributeList &Attr,
3044                                             Sema &S) {
3045  // Check the attribute arguments.
3046  if (Attr.getNumArgs() != 1) {
3047    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3048    Attr.setInvalid();
3049    return;
3050  }
3051  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3052  llvm::APSInt arg(32);
3053  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3054      !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3055    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3056      << "opencl_image_access" << sizeExpr->getSourceRange();
3057    Attr.setInvalid();
3058    return;
3059  }
3060  unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3061  switch (iarg) {
3062  case CLIA_read_only:
3063  case CLIA_write_only:
3064  case CLIA_read_write:
3065    // Implemented in a separate patch
3066    break;
3067  default:
3068    // Implemented in a separate patch
3069    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3070      << sizeExpr->getSourceRange();
3071    Attr.setInvalid();
3072    break;
3073  }
3074}
3075
3076/// HandleVectorSizeAttribute - this attribute is only applicable to integral
3077/// and float scalars, although arrays, pointers, and function return values are
3078/// allowed in conjunction with this construct. Aggregates with this attribute
3079/// are invalid, even if they are of the same size as a corresponding scalar.
3080/// The raw attribute should contain precisely 1 argument, the vector size for
3081/// the variable, measured in bytes. If curType and rawAttr are well formed,
3082/// this routine will return a new vector type.
3083static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3084                                 Sema &S) {
3085  // Check the attribute arguments.
3086  if (Attr.getNumArgs() != 1) {
3087    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3088    Attr.setInvalid();
3089    return;
3090  }
3091  Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3092  llvm::APSInt vecSize(32);
3093  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3094      !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
3095    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3096      << "vector_size" << sizeExpr->getSourceRange();
3097    Attr.setInvalid();
3098    return;
3099  }
3100  // the base type must be integer or float, and can't already be a vector.
3101  if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
3102    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
3103    Attr.setInvalid();
3104    return;
3105  }
3106  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3107  // vecSize is specified in bytes - convert to bits.
3108  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3109
3110  // the vector size needs to be an integral multiple of the type size.
3111  if (vectorSize % typeSize) {
3112    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3113      << sizeExpr->getSourceRange();
3114    Attr.setInvalid();
3115    return;
3116  }
3117  if (vectorSize == 0) {
3118    S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3119      << sizeExpr->getSourceRange();
3120    Attr.setInvalid();
3121    return;
3122  }
3123
3124  // Success! Instantiate the vector type, the number of elements is > 0, and
3125  // not required to be a power of 2, unlike GCC.
3126  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
3127                                    VectorType::GenericVector);
3128}
3129
3130/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3131/// "neon_polyvector_type" attributes are used to create vector types that
3132/// are mangled according to ARM's ABI.  Otherwise, these types are identical
3133/// to those created with the "vector_size" attribute.  Unlike "vector_size"
3134/// the argument to these Neon attributes is the number of vector elements,
3135/// not the vector size in bytes.  The vector width and element type must
3136/// match one of the standard Neon vector types.
3137static void HandleNeonVectorTypeAttr(QualType& CurType,
3138                                     const AttributeList &Attr, Sema &S,
3139                                     VectorType::VectorKind VecKind,
3140                                     const char *AttrName) {
3141  // Check the attribute arguments.
3142  if (Attr.getNumArgs() != 1) {
3143    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3144    Attr.setInvalid();
3145    return;
3146  }
3147  // The number of elements must be an ICE.
3148  Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3149  llvm::APSInt numEltsInt(32);
3150  if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3151      !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3152    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3153      << AttrName << numEltsExpr->getSourceRange();
3154    Attr.setInvalid();
3155    return;
3156  }
3157  // Only certain element types are supported for Neon vectors.
3158  const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3159  if (!BTy ||
3160      (VecKind == VectorType::NeonPolyVector &&
3161       BTy->getKind() != BuiltinType::SChar &&
3162       BTy->getKind() != BuiltinType::Short) ||
3163      (BTy->getKind() != BuiltinType::SChar &&
3164       BTy->getKind() != BuiltinType::UChar &&
3165       BTy->getKind() != BuiltinType::Short &&
3166       BTy->getKind() != BuiltinType::UShort &&
3167       BTy->getKind() != BuiltinType::Int &&
3168       BTy->getKind() != BuiltinType::UInt &&
3169       BTy->getKind() != BuiltinType::LongLong &&
3170       BTy->getKind() != BuiltinType::ULongLong &&
3171       BTy->getKind() != BuiltinType::Float)) {
3172    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3173    Attr.setInvalid();
3174    return;
3175  }
3176  // The total size of the vector must be 64 or 128 bits.
3177  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3178  unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3179  unsigned vecSize = typeSize * numElts;
3180  if (vecSize != 64 && vecSize != 128) {
3181    S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3182    Attr.setInvalid();
3183    return;
3184  }
3185
3186  CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3187}
3188
3189static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3190                             bool isDeclSpec, AttributeList *attrs) {
3191  // Scan through and apply attributes to this type where it makes sense.  Some
3192  // attributes (such as __address_space__, __vector_size__, etc) apply to the
3193  // type, but others can be present in the type specifiers even though they
3194  // apply to the decl.  Here we apply type attributes and ignore the rest.
3195
3196  AttributeList *next;
3197  do {
3198    AttributeList &attr = *attrs;
3199    next = attr.getNext();
3200
3201    // Skip attributes that were marked to be invalid.
3202    if (attr.isInvalid())
3203      continue;
3204
3205    // If this is an attribute we can handle, do so now,
3206    // otherwise, add it to the FnAttrs list for rechaining.
3207    switch (attr.getKind()) {
3208    default: break;
3209
3210    case AttributeList::AT_address_space:
3211      HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
3212      break;
3213    OBJC_POINTER_TYPE_ATTRS_CASELIST:
3214      if (!handleObjCPointerTypeAttr(state, attr, type))
3215        distributeObjCPointerTypeAttr(state, attr, type);
3216      break;
3217    case AttributeList::AT_vector_size:
3218      HandleVectorSizeAttr(type, attr, state.getSema());
3219      break;
3220    case AttributeList::AT_neon_vector_type:
3221      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3222                               VectorType::NeonVector, "neon_vector_type");
3223      break;
3224    case AttributeList::AT_neon_polyvector_type:
3225      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3226                               VectorType::NeonPolyVector,
3227                               "neon_polyvector_type");
3228      break;
3229
3230    case AttributeList::AT_opencl_image_access:
3231      HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
3232      break;
3233
3234    FUNCTION_TYPE_ATTRS_CASELIST:
3235      // Never process function type attributes as part of the
3236      // declaration-specifiers.
3237      if (isDeclSpec)
3238        distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3239
3240      // Otherwise, handle the possible delays.
3241      else if (!handleFunctionTypeAttr(state, attr, type))
3242        distributeFunctionTypeAttr(state, attr, type);
3243      break;
3244    }
3245  } while ((attrs = next));
3246}
3247
3248/// \brief Ensure that the type of the given expression is complete.
3249///
3250/// This routine checks whether the expression \p E has a complete type. If the
3251/// expression refers to an instantiable construct, that instantiation is
3252/// performed as needed to complete its type. Furthermore
3253/// Sema::RequireCompleteType is called for the expression's type (or in the
3254/// case of a reference type, the referred-to type).
3255///
3256/// \param E The expression whose type is required to be complete.
3257/// \param PD The partial diagnostic that will be printed out if the type cannot
3258/// be completed.
3259///
3260/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3261/// otherwise.
3262bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3263                                   std::pair<SourceLocation,
3264                                             PartialDiagnostic> Note) {
3265  QualType T = E->getType();
3266
3267  // Fast path the case where the type is already complete.
3268  if (!T->isIncompleteType())
3269    return false;
3270
3271  // Incomplete array types may be completed by the initializer attached to
3272  // their definitions. For static data members of class templates we need to
3273  // instantiate the definition to get this initializer and complete the type.
3274  if (T->isIncompleteArrayType()) {
3275    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3276      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3277        if (Var->isStaticDataMember() &&
3278            Var->getInstantiatedFromStaticDataMember()) {
3279
3280          MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3281          assert(MSInfo && "Missing member specialization information?");
3282          if (MSInfo->getTemplateSpecializationKind()
3283                != TSK_ExplicitSpecialization) {
3284            // If we don't already have a point of instantiation, this is it.
3285            if (MSInfo->getPointOfInstantiation().isInvalid()) {
3286              MSInfo->setPointOfInstantiation(E->getLocStart());
3287
3288              // This is a modification of an existing AST node. Notify
3289              // listeners.
3290              if (ASTMutationListener *L = getASTMutationListener())
3291                L->StaticDataMemberInstantiated(Var);
3292            }
3293
3294            InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
3295
3296            // Update the type to the newly instantiated definition's type both
3297            // here and within the expression.
3298            if (VarDecl *Def = Var->getDefinition()) {
3299              DRE->setDecl(Def);
3300              T = Def->getType();
3301              DRE->setType(T);
3302              E->setType(T);
3303            }
3304          }
3305
3306          // We still go on to try to complete the type independently, as it
3307          // may also require instantiations or diagnostics if it remains
3308          // incomplete.
3309        }
3310      }
3311    }
3312  }
3313
3314  // FIXME: Are there other cases which require instantiating something other
3315  // than the type to complete the type of an expression?
3316
3317  // Look through reference types and complete the referred type.
3318  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3319    T = Ref->getPointeeType();
3320
3321  return RequireCompleteType(E->getExprLoc(), T, PD, Note);
3322}
3323
3324/// @brief Ensure that the type T is a complete type.
3325///
3326/// This routine checks whether the type @p T is complete in any
3327/// context where a complete type is required. If @p T is a complete
3328/// type, returns false. If @p T is a class template specialization,
3329/// this routine then attempts to perform class template
3330/// instantiation. If instantiation fails, or if @p T is incomplete
3331/// and cannot be completed, issues the diagnostic @p diag (giving it
3332/// the type @p T) and returns true.
3333///
3334/// @param Loc  The location in the source that the incomplete type
3335/// diagnostic should refer to.
3336///
3337/// @param T  The type that this routine is examining for completeness.
3338///
3339/// @param PD The partial diagnostic that will be printed out if T is not a
3340/// complete type.
3341///
3342/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
3343/// @c false otherwise.
3344bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3345                               const PartialDiagnostic &PD,
3346                               std::pair<SourceLocation,
3347                                         PartialDiagnostic> Note) {
3348  unsigned diag = PD.getDiagID();
3349
3350  // FIXME: Add this assertion to make sure we always get instantiation points.
3351  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
3352  // FIXME: Add this assertion to help us flush out problems with
3353  // checking for dependent types and type-dependent expressions.
3354  //
3355  //  assert(!T->isDependentType() &&
3356  //         "Can't ask whether a dependent type is complete");
3357
3358  // If we have a complete type, we're done.
3359  if (!T->isIncompleteType())
3360    return false;
3361
3362  // If we have a class template specialization or a class member of a
3363  // class template specialization, or an array with known size of such,
3364  // try to instantiate it.
3365  QualType MaybeTemplate = T;
3366  if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
3367    MaybeTemplate = Array->getElementType();
3368  if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
3369    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
3370          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
3371      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
3372        return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
3373                                                      TSK_ImplicitInstantiation,
3374                                                      /*Complain=*/diag != 0);
3375    } else if (CXXRecordDecl *Rec
3376                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
3377      if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
3378        MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
3379        assert(MSInfo && "Missing member specialization information?");
3380        // This record was instantiated from a class within a template.
3381        if (MSInfo->getTemplateSpecializationKind()
3382                                               != TSK_ExplicitSpecialization)
3383          return InstantiateClass(Loc, Rec, Pattern,
3384                                  getTemplateInstantiationArgs(Rec),
3385                                  TSK_ImplicitInstantiation,
3386                                  /*Complain=*/diag != 0);
3387      }
3388    }
3389  }
3390
3391  if (diag == 0)
3392    return true;
3393
3394  const TagType *Tag = T->getAs<TagType>();
3395
3396  // Avoid diagnosing invalid decls as incomplete.
3397  if (Tag && Tag->getDecl()->isInvalidDecl())
3398    return true;
3399
3400  // Give the external AST source a chance to complete the type.
3401  if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
3402    Context.getExternalSource()->CompleteType(Tag->getDecl());
3403    if (!Tag->isIncompleteType())
3404      return false;
3405  }
3406
3407  // We have an incomplete type. Produce a diagnostic.
3408  Diag(Loc, PD) << T;
3409
3410  // If we have a note, produce it.
3411  if (!Note.first.isInvalid())
3412    Diag(Note.first, Note.second);
3413
3414  // If the type was a forward declaration of a class/struct/union
3415  // type, produce a note.
3416  if (Tag && !Tag->getDecl()->isInvalidDecl())
3417    Diag(Tag->getDecl()->getLocation(),
3418         Tag->isBeingDefined() ? diag::note_type_being_defined
3419                               : diag::note_forward_declaration)
3420        << QualType(Tag, 0);
3421
3422  return true;
3423}
3424
3425bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3426                               const PartialDiagnostic &PD) {
3427  return RequireCompleteType(Loc, T, PD,
3428                             std::make_pair(SourceLocation(), PDiag(0)));
3429}
3430
3431bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3432                               unsigned DiagID) {
3433  return RequireCompleteType(Loc, T, PDiag(DiagID),
3434                             std::make_pair(SourceLocation(), PDiag(0)));
3435}
3436
3437/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
3438/// and qualified by the nested-name-specifier contained in SS.
3439QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
3440                                 const CXXScopeSpec &SS, QualType T) {
3441  if (T.isNull())
3442    return T;
3443  NestedNameSpecifier *NNS;
3444  if (SS.isValid())
3445    NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3446  else {
3447    if (Keyword == ETK_None)
3448      return T;
3449    NNS = 0;
3450  }
3451  return Context.getElaboratedType(Keyword, NNS, T);
3452}
3453
3454QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
3455  ExprResult ER = CheckPlaceholderExpr(E);
3456  if (ER.isInvalid()) return QualType();
3457  E = ER.take();
3458
3459  if (!E->isTypeDependent()) {
3460    QualType T = E->getType();
3461    if (const TagType *TT = T->getAs<TagType>())
3462      DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
3463  }
3464  return Context.getTypeOfExprType(E);
3465}
3466
3467QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
3468  ExprResult ER = CheckPlaceholderExpr(E);
3469  if (ER.isInvalid()) return QualType();
3470  E = ER.take();
3471
3472  return Context.getDecltypeType(E);
3473}
3474
3475QualType Sema::BuildUnaryTransformType(QualType BaseType,
3476                                       UnaryTransformType::UTTKind UKind,
3477                                       SourceLocation Loc) {
3478  switch (UKind) {
3479  case UnaryTransformType::EnumUnderlyingType:
3480    if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
3481      Diag(Loc, diag::err_only_enums_have_underlying_types);
3482      return QualType();
3483    } else {
3484      QualType Underlying = BaseType;
3485      if (!BaseType->isDependentType()) {
3486        EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
3487        assert(ED && "EnumType has no EnumDecl");
3488        DiagnoseUseOfDecl(ED, Loc);
3489        Underlying = ED->getIntegerType();
3490      }
3491      assert(!Underlying.isNull());
3492      return Context.getUnaryTransformType(BaseType, Underlying,
3493                                        UnaryTransformType::EnumUnderlyingType);
3494    }
3495  }
3496  llvm_unreachable("unknown unary transform type");
3497}
3498