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