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