1193326Sed//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements type-related semantic analysis.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14212904Sdim#include "clang/Sema/SemaInternal.h"
15263508Sdim#include "clang/AST/ASTConsumer.h"
16193326Sed#include "clang/AST/ASTContext.h"
17223017Sdim#include "clang/AST/ASTMutationListener.h"
18198092Srdivacky#include "clang/AST/CXXInheritance.h"
19193326Sed#include "clang/AST/DeclObjC.h"
20193326Sed#include "clang/AST/DeclTemplate.h"
21249423Sdim#include "clang/AST/Expr.h"
22198092Srdivacky#include "clang/AST/TypeLoc.h"
23198398Srdivacky#include "clang/AST/TypeLocVisitor.h"
24249423Sdim#include "clang/Basic/OpenCL.h"
25198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
26212904Sdim#include "clang/Basic/TargetInfo.h"
27221345Sdim#include "clang/Lex/Preprocessor.h"
28234353Sdim#include "clang/Parse/ParseDiagnostic.h"
29212904Sdim#include "clang/Sema/DeclSpec.h"
30224145Sdim#include "clang/Sema/DelayedDiagnostic.h"
31234353Sdim#include "clang/Sema/Lookup.h"
32249423Sdim#include "clang/Sema/ScopeInfo.h"
33249423Sdim#include "clang/Sema/Template.h"
34195341Sed#include "llvm/ADT/SmallPtrSet.h"
35249423Sdim#include "llvm/ADT/SmallString.h"
36198954Srdivacky#include "llvm/Support/ErrorHandling.h"
37263508Sdim#include "TypeLocBuilder.h"
38263508Sdim
39193326Sedusing namespace clang;
40193326Sed
41263508Sdimenum TypeDiagSelector {
42263508Sdim  TDS_Function,
43263508Sdim  TDS_Pointer,
44263508Sdim  TDS_ObjCObjOrBlock
45263508Sdim};
46263508Sdim
47198893Srdivacky/// isOmittedBlockReturnType - Return true if this declarator is missing a
48239462Sdim/// return type because this is a omitted return type on a block literal.
49198893Srdivackystatic bool isOmittedBlockReturnType(const Declarator &D) {
50198893Srdivacky  if (D.getContext() != Declarator::BlockLiteralContext ||
51198893Srdivacky      D.getDeclSpec().hasTypeSpecifier())
52198893Srdivacky    return false;
53239462Sdim
54198893Srdivacky  if (D.getNumTypeObjects() == 0)
55198893Srdivacky    return true;   // ^{ ... }
56239462Sdim
57198893Srdivacky  if (D.getNumTypeObjects() == 1 &&
58198893Srdivacky      D.getTypeObject(0).Kind == DeclaratorChunk::Function)
59198893Srdivacky    return true;   // ^(int X, float Y) { ... }
60239462Sdim
61198893Srdivacky  return false;
62198893Srdivacky}
63198893Srdivacky
64221345Sdim/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
65221345Sdim/// doesn't apply to the given type.
66221345Sdimstatic void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
67221345Sdim                                     QualType type) {
68263508Sdim  TypeDiagSelector WhichType;
69263508Sdim  bool useExpansionLoc = true;
70221345Sdim  switch (attr.getKind()) {
71263508Sdim  case AttributeList::AT_ObjCGC:        WhichType = TDS_Pointer; break;
72263508Sdim  case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
73221345Sdim  default:
74221345Sdim    // Assume everything else was a function attribute.
75263508Sdim    WhichType = TDS_Function;
76263508Sdim    useExpansionLoc = false;
77221345Sdim    break;
78221345Sdim  }
79221345Sdim
80221345Sdim  SourceLocation loc = attr.getLoc();
81226633Sdim  StringRef name = attr.getName()->getName();
82221345Sdim
83221345Sdim  // The GC attributes are usually written with macros;  special-case them.
84263508Sdim  IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident : 0;
85263508Sdim  if (useExpansionLoc && loc.isMacroID() && II) {
86263508Sdim    if (II->isStr("strong")) {
87221345Sdim      if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
88263508Sdim    } else if (II->isStr("weak")) {
89221345Sdim      if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
90221345Sdim    }
91221345Sdim  }
92221345Sdim
93263508Sdim  S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
94263508Sdim    << type;
95221345Sdim}
96221345Sdim
97218893Sdim// objc_gc applies to Objective-C pointers or, otherwise, to the
98218893Sdim// smallest available pointer type (i.e. 'void*' in 'void**').
99218893Sdim#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
100239462Sdim    case AttributeList::AT_ObjCGC: \
101239462Sdim    case AttributeList::AT_ObjCOwnership
102203955Srdivacky
103218893Sdim// Function type attributes.
104218893Sdim#define FUNCTION_TYPE_ATTRS_CASELIST \
105239462Sdim    case AttributeList::AT_NoReturn: \
106239462Sdim    case AttributeList::AT_CDecl: \
107239462Sdim    case AttributeList::AT_FastCall: \
108239462Sdim    case AttributeList::AT_StdCall: \
109239462Sdim    case AttributeList::AT_ThisCall: \
110239462Sdim    case AttributeList::AT_Pascal: \
111256030Sdim    case AttributeList::AT_MSABI: \
112256030Sdim    case AttributeList::AT_SysVABI: \
113239462Sdim    case AttributeList::AT_Regparm: \
114243830Sdim    case AttributeList::AT_Pcs: \
115249423Sdim    case AttributeList::AT_PnaclCall: \
116263508Sdim    case AttributeList::AT_IntelOclBicc
117203955Srdivacky
118263508Sdim// Microsoft-specific type qualifiers.
119263508Sdim#define MS_TYPE_ATTRS_CASELIST  \
120263508Sdim    case AttributeList::AT_Ptr32: \
121263508Sdim    case AttributeList::AT_Ptr64: \
122263508Sdim    case AttributeList::AT_SPtr: \
123263508Sdim    case AttributeList::AT_UPtr
124263508Sdim
125218893Sdimnamespace {
126218893Sdim  /// An object which stores processing state for the entire
127218893Sdim  /// GetTypeForDeclarator process.
128218893Sdim  class TypeProcessingState {
129218893Sdim    Sema &sema;
130218893Sdim
131218893Sdim    /// The declarator being processed.
132218893Sdim    Declarator &declarator;
133218893Sdim
134218893Sdim    /// The index of the declarator chunk we're currently processing.
135218893Sdim    /// May be the total number of valid chunks, indicating the
136218893Sdim    /// DeclSpec.
137218893Sdim    unsigned chunkIndex;
138218893Sdim
139218893Sdim    /// Whether there are non-trivial modifications to the decl spec.
140218893Sdim    bool trivial;
141218893Sdim
142221345Sdim    /// Whether we saved the attributes in the decl spec.
143221345Sdim    bool hasSavedAttrs;
144221345Sdim
145218893Sdim    /// The original set of attributes on the DeclSpec.
146226633Sdim    SmallVector<AttributeList*, 2> savedAttrs;
147218893Sdim
148218893Sdim    /// A list of attributes to diagnose the uselessness of when the
149218893Sdim    /// processing is complete.
150226633Sdim    SmallVector<AttributeList*, 2> ignoredTypeAttrs;
151218893Sdim
152218893Sdim  public:
153218893Sdim    TypeProcessingState(Sema &sema, Declarator &declarator)
154218893Sdim      : sema(sema), declarator(declarator),
155218893Sdim        chunkIndex(declarator.getNumTypeObjects()),
156221345Sdim        trivial(true), hasSavedAttrs(false) {}
157218893Sdim
158218893Sdim    Sema &getSema() const {
159218893Sdim      return sema;
160207619Srdivacky    }
161218893Sdim
162218893Sdim    Declarator &getDeclarator() const {
163218893Sdim      return declarator;
164218893Sdim    }
165218893Sdim
166249423Sdim    bool isProcessingDeclSpec() const {
167249423Sdim      return chunkIndex == declarator.getNumTypeObjects();
168249423Sdim    }
169249423Sdim
170218893Sdim    unsigned getCurrentChunkIndex() const {
171218893Sdim      return chunkIndex;
172218893Sdim    }
173218893Sdim
174218893Sdim    void setCurrentChunkIndex(unsigned idx) {
175218893Sdim      assert(idx <= declarator.getNumTypeObjects());
176218893Sdim      chunkIndex = idx;
177218893Sdim    }
178218893Sdim
179218893Sdim    AttributeList *&getCurrentAttrListRef() const {
180249423Sdim      if (isProcessingDeclSpec())
181218893Sdim        return getMutableDeclSpec().getAttributes().getListRef();
182218893Sdim      return declarator.getTypeObject(chunkIndex).getAttrListRef();
183218893Sdim    }
184218893Sdim
185218893Sdim    /// Save the current set of attributes on the DeclSpec.
186218893Sdim    void saveDeclSpecAttrs() {
187218893Sdim      // Don't try to save them multiple times.
188221345Sdim      if (hasSavedAttrs) return;
189218893Sdim
190218893Sdim      DeclSpec &spec = getMutableDeclSpec();
191218893Sdim      for (AttributeList *attr = spec.getAttributes().getList(); attr;
192218893Sdim             attr = attr->getNext())
193218893Sdim        savedAttrs.push_back(attr);
194218893Sdim      trivial &= savedAttrs.empty();
195221345Sdim      hasSavedAttrs = true;
196218893Sdim    }
197218893Sdim
198218893Sdim    /// Record that we had nowhere to put the given type attribute.
199218893Sdim    /// We will diagnose such attributes later.
200218893Sdim    void addIgnoredTypeAttr(AttributeList &attr) {
201218893Sdim      ignoredTypeAttrs.push_back(&attr);
202218893Sdim    }
203218893Sdim
204218893Sdim    /// Diagnose all the ignored type attributes, given that the
205218893Sdim    /// declarator worked out to the given type.
206218893Sdim    void diagnoseIgnoredTypeAttrs(QualType type) const {
207226633Sdim      for (SmallVectorImpl<AttributeList*>::const_iterator
208218893Sdim             i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
209221345Sdim           i != e; ++i)
210221345Sdim        diagnoseBadTypeAttribute(getSema(), **i, type);
211218893Sdim    }
212218893Sdim
213218893Sdim    ~TypeProcessingState() {
214218893Sdim      if (trivial) return;
215218893Sdim
216218893Sdim      restoreDeclSpecAttrs();
217218893Sdim    }
218218893Sdim
219218893Sdim  private:
220218893Sdim    DeclSpec &getMutableDeclSpec() const {
221218893Sdim      return const_cast<DeclSpec&>(declarator.getDeclSpec());
222218893Sdim    }
223218893Sdim
224218893Sdim    void restoreDeclSpecAttrs() {
225221345Sdim      assert(hasSavedAttrs);
226221345Sdim
227221345Sdim      if (savedAttrs.empty()) {
228221345Sdim        getMutableDeclSpec().getAttributes().set(0);
229221345Sdim        return;
230221345Sdim      }
231221345Sdim
232218893Sdim      getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
233218893Sdim      for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
234218893Sdim        savedAttrs[i]->setNext(savedAttrs[i+1]);
235218893Sdim      savedAttrs.back()->setNext(0);
236218893Sdim    }
237218893Sdim  };
238203955Srdivacky}
239203955Srdivacky
240218893Sdimstatic void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
241218893Sdim  attr.setNext(head);
242218893Sdim  head = &attr;
243218893Sdim}
244218893Sdim
245218893Sdimstatic void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
246218893Sdim  if (head == &attr) {
247218893Sdim    head = attr.getNext();
248218893Sdim    return;
249203955Srdivacky  }
250218893Sdim
251218893Sdim  AttributeList *cur = head;
252218893Sdim  while (true) {
253218893Sdim    assert(cur && cur->getNext() && "ran out of attrs?");
254218893Sdim    if (cur->getNext() == &attr) {
255218893Sdim      cur->setNext(attr.getNext());
256218893Sdim      return;
257218893Sdim    }
258218893Sdim    cur = cur->getNext();
259218893Sdim  }
260203955Srdivacky}
261203955Srdivacky
262218893Sdimstatic void moveAttrFromListToList(AttributeList &attr,
263218893Sdim                                   AttributeList *&fromList,
264218893Sdim                                   AttributeList *&toList) {
265218893Sdim  spliceAttrOutOfList(attr, fromList);
266218893Sdim  spliceAttrIntoList(attr, toList);
267218893Sdim}
268218893Sdim
269249423Sdim/// The location of a type attribute.
270249423Sdimenum TypeAttrLocation {
271249423Sdim  /// The attribute is in the decl-specifier-seq.
272249423Sdim  TAL_DeclSpec,
273249423Sdim  /// The attribute is part of a DeclaratorChunk.
274249423Sdim  TAL_DeclChunk,
275249423Sdim  /// The attribute is immediately after the declaration's name.
276249423Sdim  TAL_DeclName
277249423Sdim};
278249423Sdim
279218893Sdimstatic void processTypeAttrs(TypeProcessingState &state,
280249423Sdim                             QualType &type, TypeAttrLocation TAL,
281218893Sdim                             AttributeList *attrs);
282218893Sdim
283218893Sdimstatic bool handleFunctionTypeAttr(TypeProcessingState &state,
284218893Sdim                                   AttributeList &attr,
285218893Sdim                                   QualType &type);
286218893Sdim
287263508Sdimstatic bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
288263508Sdim                                             AttributeList &attr,
289263508Sdim                                             QualType &type);
290263508Sdim
291218893Sdimstatic bool handleObjCGCTypeAttr(TypeProcessingState &state,
292218893Sdim                                 AttributeList &attr, QualType &type);
293218893Sdim
294224145Sdimstatic bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
295224145Sdim                                       AttributeList &attr, QualType &type);
296224145Sdim
297218893Sdimstatic bool handleObjCPointerTypeAttr(TypeProcessingState &state,
298218893Sdim                                      AttributeList &attr, QualType &type) {
299239462Sdim  if (attr.getKind() == AttributeList::AT_ObjCGC)
300224145Sdim    return handleObjCGCTypeAttr(state, attr, type);
301239462Sdim  assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
302224145Sdim  return handleObjCOwnershipTypeAttr(state, attr, type);
303218893Sdim}
304218893Sdim
305249423Sdim/// Given the index of a declarator chunk, check whether that chunk
306249423Sdim/// directly specifies the return type of a function and, if so, find
307249423Sdim/// an appropriate place for it.
308249423Sdim///
309249423Sdim/// \param i - a notional index which the search will start
310249423Sdim///   immediately inside
311249423Sdimstatic DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
312249423Sdim                                                unsigned i) {
313249423Sdim  assert(i <= declarator.getNumTypeObjects());
314249423Sdim
315249423Sdim  DeclaratorChunk *result = 0;
316249423Sdim
317249423Sdim  // First, look inwards past parens for a function declarator.
318249423Sdim  for (; i != 0; --i) {
319249423Sdim    DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
320249423Sdim    switch (fnChunk.Kind) {
321249423Sdim    case DeclaratorChunk::Paren:
322249423Sdim      continue;
323249423Sdim
324249423Sdim    // If we find anything except a function, bail out.
325249423Sdim    case DeclaratorChunk::Pointer:
326249423Sdim    case DeclaratorChunk::BlockPointer:
327249423Sdim    case DeclaratorChunk::Array:
328249423Sdim    case DeclaratorChunk::Reference:
329249423Sdim    case DeclaratorChunk::MemberPointer:
330249423Sdim      return result;
331249423Sdim
332249423Sdim    // If we do find a function declarator, scan inwards from that,
333249423Sdim    // looking for a block-pointer declarator.
334249423Sdim    case DeclaratorChunk::Function:
335249423Sdim      for (--i; i != 0; --i) {
336249423Sdim        DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1);
337249423Sdim        switch (blockChunk.Kind) {
338249423Sdim        case DeclaratorChunk::Paren:
339249423Sdim        case DeclaratorChunk::Pointer:
340249423Sdim        case DeclaratorChunk::Array:
341249423Sdim        case DeclaratorChunk::Function:
342249423Sdim        case DeclaratorChunk::Reference:
343249423Sdim        case DeclaratorChunk::MemberPointer:
344249423Sdim          continue;
345249423Sdim        case DeclaratorChunk::BlockPointer:
346249423Sdim          result = &blockChunk;
347249423Sdim          goto continue_outer;
348249423Sdim        }
349249423Sdim        llvm_unreachable("bad declarator chunk kind");
350249423Sdim      }
351249423Sdim
352249423Sdim      // If we run out of declarators doing that, we're done.
353249423Sdim      return result;
354249423Sdim    }
355249423Sdim    llvm_unreachable("bad declarator chunk kind");
356249423Sdim
357249423Sdim    // Okay, reconsider from our new point.
358249423Sdim  continue_outer: ;
359249423Sdim  }
360249423Sdim
361249423Sdim  // Ran out of chunks, bail out.
362249423Sdim  return result;
363249423Sdim}
364249423Sdim
365218893Sdim/// Given that an objc_gc attribute was written somewhere on a
366218893Sdim/// declaration *other* than on the declarator itself (for which, use
367218893Sdim/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
368218893Sdim/// didn't apply in whatever position it was written in, try to move
369218893Sdim/// it to a more appropriate position.
370218893Sdimstatic void distributeObjCPointerTypeAttr(TypeProcessingState &state,
371218893Sdim                                          AttributeList &attr,
372218893Sdim                                          QualType type) {
373218893Sdim  Declarator &declarator = state.getDeclarator();
374249423Sdim
375249423Sdim  // Move it to the outermost normal or block pointer declarator.
376218893Sdim  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
377218893Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
378218893Sdim    switch (chunk.Kind) {
379218893Sdim    case DeclaratorChunk::Pointer:
380249423Sdim    case DeclaratorChunk::BlockPointer: {
381249423Sdim      // But don't move an ARC ownership attribute to the return type
382249423Sdim      // of a block.
383249423Sdim      DeclaratorChunk *destChunk = 0;
384249423Sdim      if (state.isProcessingDeclSpec() &&
385249423Sdim          attr.getKind() == AttributeList::AT_ObjCOwnership)
386249423Sdim        destChunk = maybeMovePastReturnType(declarator, i - 1);
387249423Sdim      if (!destChunk) destChunk = &chunk;
388249423Sdim
389218893Sdim      moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
390249423Sdim                             destChunk->getAttrListRef());
391218893Sdim      return;
392249423Sdim    }
393218893Sdim
394218893Sdim    case DeclaratorChunk::Paren:
395218893Sdim    case DeclaratorChunk::Array:
396218893Sdim      continue;
397218893Sdim
398249423Sdim    // We may be starting at the return type of a block.
399249423Sdim    case DeclaratorChunk::Function:
400249423Sdim      if (state.isProcessingDeclSpec() &&
401249423Sdim          attr.getKind() == AttributeList::AT_ObjCOwnership) {
402249423Sdim        if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) {
403249423Sdim          moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
404249423Sdim                                 dest->getAttrListRef());
405249423Sdim          return;
406249423Sdim        }
407249423Sdim      }
408249423Sdim      goto error;
409249423Sdim
410218893Sdim    // Don't walk through these.
411218893Sdim    case DeclaratorChunk::Reference:
412218893Sdim    case DeclaratorChunk::MemberPointer:
413218893Sdim      goto error;
414218893Sdim    }
415218893Sdim  }
416218893Sdim error:
417221345Sdim
418221345Sdim  diagnoseBadTypeAttribute(state.getSema(), attr, type);
419218893Sdim}
420218893Sdim
421218893Sdim/// Distribute an objc_gc type attribute that was written on the
422218893Sdim/// declarator.
423218893Sdimstatic void
424218893SdimdistributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
425218893Sdim                                            AttributeList &attr,
426218893Sdim                                            QualType &declSpecType) {
427218893Sdim  Declarator &declarator = state.getDeclarator();
428218893Sdim
429218893Sdim  // objc_gc goes on the innermost pointer to something that's not a
430218893Sdim  // pointer.
431218893Sdim  unsigned innermost = -1U;
432218893Sdim  bool considerDeclSpec = true;
433218893Sdim  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
434218893Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(i);
435218893Sdim    switch (chunk.Kind) {
436218893Sdim    case DeclaratorChunk::Pointer:
437218893Sdim    case DeclaratorChunk::BlockPointer:
438218893Sdim      innermost = i;
439218893Sdim      continue;
440218893Sdim
441218893Sdim    case DeclaratorChunk::Reference:
442218893Sdim    case DeclaratorChunk::MemberPointer:
443218893Sdim    case DeclaratorChunk::Paren:
444218893Sdim    case DeclaratorChunk::Array:
445218893Sdim      continue;
446218893Sdim
447218893Sdim    case DeclaratorChunk::Function:
448218893Sdim      considerDeclSpec = false;
449218893Sdim      goto done;
450218893Sdim    }
451218893Sdim  }
452218893Sdim done:
453218893Sdim
454218893Sdim  // That might actually be the decl spec if we weren't blocked by
455218893Sdim  // anything in the declarator.
456218893Sdim  if (considerDeclSpec) {
457221345Sdim    if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
458221345Sdim      // Splice the attribute into the decl spec.  Prevents the
459221345Sdim      // attribute from being applied multiple times and gives
460221345Sdim      // the source-location-filler something to work with.
461221345Sdim      state.saveDeclSpecAttrs();
462221345Sdim      moveAttrFromListToList(attr, declarator.getAttrListRef(),
463221345Sdim               declarator.getMutableDeclSpec().getAttributes().getListRef());
464218893Sdim      return;
465221345Sdim    }
466218893Sdim  }
467218893Sdim
468218893Sdim  // Otherwise, if we found an appropriate chunk, splice the attribute
469218893Sdim  // into it.
470218893Sdim  if (innermost != -1U) {
471218893Sdim    moveAttrFromListToList(attr, declarator.getAttrListRef(),
472218893Sdim                       declarator.getTypeObject(innermost).getAttrListRef());
473218893Sdim    return;
474218893Sdim  }
475218893Sdim
476218893Sdim  // Otherwise, diagnose when we're done building the type.
477218893Sdim  spliceAttrOutOfList(attr, declarator.getAttrListRef());
478218893Sdim  state.addIgnoredTypeAttr(attr);
479218893Sdim}
480218893Sdim
481218893Sdim/// A function type attribute was written somewhere in a declaration
482218893Sdim/// *other* than on the declarator itself or in the decl spec.  Given
483218893Sdim/// that it didn't apply in whatever position it was written in, try
484218893Sdim/// to move it to a more appropriate position.
485218893Sdimstatic void distributeFunctionTypeAttr(TypeProcessingState &state,
486218893Sdim                                       AttributeList &attr,
487218893Sdim                                       QualType type) {
488218893Sdim  Declarator &declarator = state.getDeclarator();
489218893Sdim
490218893Sdim  // Try to push the attribute from the return type of a function to
491218893Sdim  // the function itself.
492218893Sdim  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
493218893Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
494218893Sdim    switch (chunk.Kind) {
495218893Sdim    case DeclaratorChunk::Function:
496218893Sdim      moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
497218893Sdim                             chunk.getAttrListRef());
498218893Sdim      return;
499218893Sdim
500218893Sdim    case DeclaratorChunk::Paren:
501218893Sdim    case DeclaratorChunk::Pointer:
502218893Sdim    case DeclaratorChunk::BlockPointer:
503218893Sdim    case DeclaratorChunk::Array:
504218893Sdim    case DeclaratorChunk::Reference:
505218893Sdim    case DeclaratorChunk::MemberPointer:
506218893Sdim      continue;
507218893Sdim    }
508218893Sdim  }
509239462Sdim
510221345Sdim  diagnoseBadTypeAttribute(state.getSema(), attr, type);
511218893Sdim}
512218893Sdim
513218893Sdim/// Try to distribute a function type attribute to the innermost
514218893Sdim/// function chunk or type.  Returns true if the attribute was
515218893Sdim/// distributed, false if no location was found.
516218893Sdimstatic bool
517218893SdimdistributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
518218893Sdim                                      AttributeList &attr,
519218893Sdim                                      AttributeList *&attrList,
520218893Sdim                                      QualType &declSpecType) {
521218893Sdim  Declarator &declarator = state.getDeclarator();
522218893Sdim
523218893Sdim  // Put it on the innermost function chunk, if there is one.
524218893Sdim  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
525218893Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(i);
526218893Sdim    if (chunk.Kind != DeclaratorChunk::Function) continue;
527218893Sdim
528218893Sdim    moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
529218893Sdim    return true;
530218893Sdim  }
531218893Sdim
532263508Sdim  return handleFunctionTypeAttr(state, attr, declSpecType);
533218893Sdim}
534218893Sdim
535218893Sdim/// A function type attribute was written in the decl spec.  Try to
536218893Sdim/// apply it somewhere.
537218893Sdimstatic void
538218893SdimdistributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
539218893Sdim                                       AttributeList &attr,
540218893Sdim                                       QualType &declSpecType) {
541218893Sdim  state.saveDeclSpecAttrs();
542218893Sdim
543249423Sdim  // C++11 attributes before the decl specifiers actually appertain to
544249423Sdim  // the declarators. Move them straight there. We don't support the
545249423Sdim  // 'put them wherever you like' semantics we allow for GNU attributes.
546249423Sdim  if (attr.isCXX11Attribute()) {
547249423Sdim    moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
548249423Sdim                           state.getDeclarator().getAttrListRef());
549249423Sdim    return;
550249423Sdim  }
551249423Sdim
552218893Sdim  // Try to distribute to the innermost.
553218893Sdim  if (distributeFunctionTypeAttrToInnermost(state, attr,
554218893Sdim                                            state.getCurrentAttrListRef(),
555218893Sdim                                            declSpecType))
556218893Sdim    return;
557218893Sdim
558218893Sdim  // If that failed, diagnose the bad attribute when the declarator is
559218893Sdim  // fully built.
560218893Sdim  state.addIgnoredTypeAttr(attr);
561218893Sdim}
562218893Sdim
563218893Sdim/// A function type attribute was written on the declarator.  Try to
564218893Sdim/// apply it somewhere.
565218893Sdimstatic void
566218893SdimdistributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
567218893Sdim                                         AttributeList &attr,
568218893Sdim                                         QualType &declSpecType) {
569218893Sdim  Declarator &declarator = state.getDeclarator();
570218893Sdim
571218893Sdim  // Try to distribute to the innermost.
572218893Sdim  if (distributeFunctionTypeAttrToInnermost(state, attr,
573218893Sdim                                            declarator.getAttrListRef(),
574218893Sdim                                            declSpecType))
575218893Sdim    return;
576218893Sdim
577218893Sdim  // If that failed, diagnose the bad attribute when the declarator is
578218893Sdim  // fully built.
579218893Sdim  spliceAttrOutOfList(attr, declarator.getAttrListRef());
580218893Sdim  state.addIgnoredTypeAttr(attr);
581218893Sdim}
582218893Sdim
583218893Sdim/// \brief Given that there are attributes written on the declarator
584218893Sdim/// itself, try to distribute any type attributes to the appropriate
585218893Sdim/// declarator chunk.
586218893Sdim///
587218893Sdim/// These are attributes like the following:
588218893Sdim///   int f ATTR;
589218893Sdim///   int (f ATTR)();
590218893Sdim/// but not necessarily this:
591218893Sdim///   int f() ATTR;
592218893Sdimstatic void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
593218893Sdim                                              QualType &declSpecType) {
594218893Sdim  // Collect all the type attributes from the declarator itself.
595218893Sdim  assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
596218893Sdim  AttributeList *attr = state.getDeclarator().getAttributes();
597218893Sdim  AttributeList *next;
598218893Sdim  do {
599218893Sdim    next = attr->getNext();
600218893Sdim
601249423Sdim    // Do not distribute C++11 attributes. They have strict rules for what
602249423Sdim    // they appertain to.
603249423Sdim    if (attr->isCXX11Attribute())
604249423Sdim      continue;
605249423Sdim
606218893Sdim    switch (attr->getKind()) {
607218893Sdim    OBJC_POINTER_TYPE_ATTRS_CASELIST:
608218893Sdim      distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
609218893Sdim      break;
610218893Sdim
611239462Sdim    case AttributeList::AT_NSReturnsRetained:
612234353Sdim      if (!state.getSema().getLangOpts().ObjCAutoRefCount)
613224145Sdim        break;
614224145Sdim      // fallthrough
615224145Sdim
616218893Sdim    FUNCTION_TYPE_ATTRS_CASELIST:
617218893Sdim      distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
618218893Sdim      break;
619218893Sdim
620263508Sdim    MS_TYPE_ATTRS_CASELIST:
621263508Sdim      // Microsoft type attributes cannot go after the declarator-id.
622263508Sdim      continue;
623263508Sdim
624218893Sdim    default:
625218893Sdim      break;
626218893Sdim    }
627218893Sdim  } while ((attr = next));
628218893Sdim}
629218893Sdim
630218893Sdim/// Add a synthetic '()' to a block-literal declarator if it is
631218893Sdim/// required, given the return type.
632218893Sdimstatic void maybeSynthesizeBlockSignature(TypeProcessingState &state,
633218893Sdim                                          QualType declSpecType) {
634218893Sdim  Declarator &declarator = state.getDeclarator();
635218893Sdim
636218893Sdim  // First, check whether the declarator would produce a function,
637218893Sdim  // i.e. whether the innermost semantic chunk is a function.
638218893Sdim  if (declarator.isFunctionDeclarator()) {
639218893Sdim    // If so, make that declarator a prototyped declarator.
640218893Sdim    declarator.getFunctionTypeInfo().hasPrototype = true;
641218893Sdim    return;
642218893Sdim  }
643218893Sdim
644218893Sdim  // If there are any type objects, the type as written won't name a
645218893Sdim  // function, regardless of the decl spec type.  This is because a
646218893Sdim  // block signature declarator is always an abstract-declarator, and
647218893Sdim  // abstract-declarators can't just be parentheses chunks.  Therefore
648218893Sdim  // we need to build a function chunk unless there are no type
649218893Sdim  // objects and the decl spec type is a function.
650218893Sdim  if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
651218893Sdim    return;
652218893Sdim
653218893Sdim  // Note that there *are* cases with invalid declarators where
654218893Sdim  // declarators consist solely of parentheses.  In general, these
655218893Sdim  // occur only in failed efforts to make function declarators, so
656218893Sdim  // faking up the function chunk is still the right thing to do.
657218893Sdim
658218893Sdim  // Otherwise, we need to fake up a function declarator.
659234353Sdim  SourceLocation loc = declarator.getLocStart();
660218893Sdim
661218893Sdim  // ...and *prepend* it to the declarator.
662243830Sdim  SourceLocation NoLoc;
663218893Sdim  declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
664243830Sdim                             /*HasProto=*/true,
665243830Sdim                             /*IsAmbiguous=*/false,
666243830Sdim                             /*LParenLoc=*/NoLoc,
667243830Sdim                             /*ArgInfo=*/0,
668243830Sdim                             /*NumArgs=*/0,
669243830Sdim                             /*EllipsisLoc=*/NoLoc,
670243830Sdim                             /*RParenLoc=*/NoLoc,
671243830Sdim                             /*TypeQuals=*/0,
672243830Sdim                             /*RefQualifierIsLvalueRef=*/true,
673243830Sdim                             /*RefQualifierLoc=*/NoLoc,
674243830Sdim                             /*ConstQualifierLoc=*/NoLoc,
675243830Sdim                             /*VolatileQualifierLoc=*/NoLoc,
676243830Sdim                             /*MutableLoc=*/NoLoc,
677243830Sdim                             EST_None,
678243830Sdim                             /*ESpecLoc=*/NoLoc,
679243830Sdim                             /*Exceptions=*/0,
680243830Sdim                             /*ExceptionRanges=*/0,
681243830Sdim                             /*NumExceptions=*/0,
682243830Sdim                             /*NoexceptExpr=*/0,
683243830Sdim                             loc, loc, declarator));
684218893Sdim
685218893Sdim  // For consistency, make sure the state still has us as processing
686218893Sdim  // the decl spec.
687218893Sdim  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
688218893Sdim  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
689218893Sdim}
690218893Sdim
691193326Sed/// \brief Convert the specified declspec to the appropriate type
692193326Sed/// object.
693239462Sdim/// \param state Specifies the declarator containing the declaration specifier
694239462Sdim/// to be converted, along with other associated processing state.
695193326Sed/// \returns The type described by the declaration specifiers.  This function
696193326Sed/// never returns null.
697224145Sdimstatic QualType ConvertDeclSpecToType(TypeProcessingState &state) {
698193326Sed  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
699193326Sed  // checking.
700218893Sdim
701224145Sdim  Sema &S = state.getSema();
702218893Sdim  Declarator &declarator = state.getDeclarator();
703218893Sdim  const DeclSpec &DS = declarator.getDeclSpec();
704218893Sdim  SourceLocation DeclLoc = declarator.getIdentifierLoc();
705198893Srdivacky  if (DeclLoc.isInvalid())
706234353Sdim    DeclLoc = DS.getLocStart();
707239462Sdim
708218893Sdim  ASTContext &Context = S.Context;
709198893Srdivacky
710193326Sed  QualType Result;
711193326Sed  switch (DS.getTypeSpecType()) {
712193326Sed  case DeclSpec::TST_void:
713193326Sed    Result = Context.VoidTy;
714193326Sed    break;
715193326Sed  case DeclSpec::TST_char:
716193326Sed    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
717193326Sed      Result = Context.CharTy;
718193326Sed    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
719193326Sed      Result = Context.SignedCharTy;
720193326Sed    else {
721193326Sed      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
722193326Sed             "Unknown TSS value");
723193326Sed      Result = Context.UnsignedCharTy;
724193326Sed    }
725193326Sed    break;
726193326Sed  case DeclSpec::TST_wchar:
727193326Sed    if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
728193326Sed      Result = Context.WCharTy;
729193326Sed    else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
730218893Sdim      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
731193326Sed        << DS.getSpecifierName(DS.getTypeSpecType());
732193326Sed      Result = Context.getSignedWCharType();
733193326Sed    } else {
734193326Sed      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
735193326Sed        "Unknown TSS value");
736218893Sdim      S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
737193326Sed        << DS.getSpecifierName(DS.getTypeSpecType());
738193326Sed      Result = Context.getUnsignedWCharType();
739193326Sed    }
740193326Sed    break;
741198092Srdivacky  case DeclSpec::TST_char16:
742198092Srdivacky      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
743198092Srdivacky        "Unknown TSS value");
744198092Srdivacky      Result = Context.Char16Ty;
745198092Srdivacky    break;
746198092Srdivacky  case DeclSpec::TST_char32:
747198092Srdivacky      assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
748198092Srdivacky        "Unknown TSS value");
749198092Srdivacky      Result = Context.Char32Ty;
750198092Srdivacky    break;
751193326Sed  case DeclSpec::TST_unspecified:
752193326Sed    // "<proto1,proto2>" is an objc qualified ID with a missing id.
753193326Sed    if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
754208600Srdivacky      Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
755243830Sdim                                         (ObjCProtocolDecl*const*)PQ,
756208600Srdivacky                                         DS.getNumProtocolQualifiers());
757208600Srdivacky      Result = Context.getObjCObjectPointerType(Result);
758193326Sed      break;
759193326Sed    }
760239462Sdim
761198893Srdivacky    // If this is a missing declspec in a block literal return context, then it
762198893Srdivacky    // is inferred from the return statements inside the block.
763234353Sdim    // The declspec is always missing in a lambda expr context; it is either
764234353Sdim    // specified with a trailing return type or inferred.
765263508Sdim    if (S.getLangOpts().CPlusPlus1y &&
766263508Sdim        declarator.getContext() == Declarator::LambdaExprContext) {
767263508Sdim      // In C++1y, a lambda's implicit return type is 'auto'.
768263508Sdim      Result = Context.getAutoDeductType();
769263508Sdim      break;
770263508Sdim    } else if (declarator.getContext() == Declarator::LambdaExprContext ||
771263508Sdim               isOmittedBlockReturnType(declarator)) {
772198893Srdivacky      Result = Context.DependentTy;
773198893Srdivacky      break;
774198893Srdivacky    }
775198092Srdivacky
776193326Sed    // Unspecified typespec defaults to int in C90.  However, the C90 grammar
777193326Sed    // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
778193326Sed    // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
779193326Sed    // Note that the one exception to this is function definitions, which are
780193326Sed    // allowed to be completely missing a declspec.  This is handled in the
781193326Sed    // parser already though by it pretending to have seen an 'int' in this
782193326Sed    // case.
783234353Sdim    if (S.getLangOpts().ImplicitInt) {
784193326Sed      // In C89 mode, we only warn if there is a completely missing declspec
785193326Sed      // when one is not allowed.
786193326Sed      if (DS.isEmpty()) {
787218893Sdim        S.Diag(DeclLoc, diag::ext_missing_declspec)
788193326Sed          << DS.getSourceRange()
789234353Sdim        << FixItHint::CreateInsertion(DS.getLocStart(), "int");
790193326Sed      }
791193326Sed    } else if (!DS.hasTypeSpecifier()) {
792193326Sed      // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
793193326Sed      // "At least one type specifier shall be given in the declaration
794193326Sed      // specifiers in each declaration, and in the specifier-qualifier list in
795193326Sed      // each struct declaration and type name."
796251662Sdim      if (S.getLangOpts().CPlusPlus) {
797218893Sdim        S.Diag(DeclLoc, diag::err_missing_type_specifier)
798193326Sed          << DS.getSourceRange();
799198092Srdivacky
800195099Sed        // When this occurs in C++ code, often something is very broken with the
801195099Sed        // value being declared, poison it as invalid so we don't get chains of
802195099Sed        // errors.
803218893Sdim        declarator.setInvalidType(true);
804195099Sed      } else {
805218893Sdim        S.Diag(DeclLoc, diag::ext_missing_type_specifier)
806193326Sed          << DS.getSourceRange();
807195099Sed      }
808193326Sed    }
809198092Srdivacky
810198092Srdivacky    // FALL THROUGH.
811193326Sed  case DeclSpec::TST_int: {
812193326Sed    if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
813193326Sed      switch (DS.getTypeSpecWidth()) {
814193326Sed      case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
815193326Sed      case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
816193326Sed      case DeclSpec::TSW_long:        Result = Context.LongTy; break;
817198893Srdivacky      case DeclSpec::TSW_longlong:
818198893Srdivacky        Result = Context.LongLongTy;
819239462Sdim
820243830Sdim        // 'long long' is a C99 or C++11 feature.
821243830Sdim        if (!S.getLangOpts().C99) {
822243830Sdim          if (S.getLangOpts().CPlusPlus)
823243830Sdim            S.Diag(DS.getTypeSpecWidthLoc(),
824249423Sdim                   S.getLangOpts().CPlusPlus11 ?
825243830Sdim                   diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
826243830Sdim          else
827243830Sdim            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
828243830Sdim        }
829198893Srdivacky        break;
830193326Sed      }
831193326Sed    } else {
832193326Sed      switch (DS.getTypeSpecWidth()) {
833193326Sed      case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
834193326Sed      case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
835193326Sed      case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
836198893Srdivacky      case DeclSpec::TSW_longlong:
837198893Srdivacky        Result = Context.UnsignedLongLongTy;
838239462Sdim
839243830Sdim        // 'long long' is a C99 or C++11 feature.
840243830Sdim        if (!S.getLangOpts().C99) {
841243830Sdim          if (S.getLangOpts().CPlusPlus)
842243830Sdim            S.Diag(DS.getTypeSpecWidthLoc(),
843249423Sdim                   S.getLangOpts().CPlusPlus11 ?
844243830Sdim                   diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
845243830Sdim          else
846243830Sdim            S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
847243830Sdim        }
848198893Srdivacky        break;
849193326Sed      }
850193326Sed    }
851193326Sed    break;
852193326Sed  }
853234353Sdim  case DeclSpec::TST_int128:
854249423Sdim    if (!S.PP.getTargetInfo().hasInt128Type())
855249423Sdim      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
856234353Sdim    if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
857234353Sdim      Result = Context.UnsignedInt128Ty;
858234353Sdim    else
859234353Sdim      Result = Context.Int128Ty;
860234353Sdim    break;
861226633Sdim  case DeclSpec::TST_half: Result = Context.HalfTy; break;
862193326Sed  case DeclSpec::TST_float: Result = Context.FloatTy; break;
863193326Sed  case DeclSpec::TST_double:
864193326Sed    if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
865193326Sed      Result = Context.LongDoubleTy;
866193326Sed    else
867193326Sed      Result = Context.DoubleTy;
868218893Sdim
869234353Sdim    if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
870218893Sdim      S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
871218893Sdim      declarator.setInvalidType(true);
872218893Sdim    }
873193326Sed    break;
874193326Sed  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
875193326Sed  case DeclSpec::TST_decimal32:    // _Decimal32
876193326Sed  case DeclSpec::TST_decimal64:    // _Decimal64
877193326Sed  case DeclSpec::TST_decimal128:   // _Decimal128
878218893Sdim    S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
879193326Sed    Result = Context.IntTy;
880218893Sdim    declarator.setInvalidType(true);
881193326Sed    break;
882193326Sed  case DeclSpec::TST_class:
883193326Sed  case DeclSpec::TST_enum:
884193326Sed  case DeclSpec::TST_union:
885243830Sdim  case DeclSpec::TST_struct:
886243830Sdim  case DeclSpec::TST_interface: {
887212904Sdim    TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
888198092Srdivacky    if (!D) {
889198092Srdivacky      // This can happen in C++ with ambiguous lookups.
890198092Srdivacky      Result = Context.IntTy;
891218893Sdim      declarator.setInvalidType(true);
892198092Srdivacky      break;
893198092Srdivacky    }
894198092Srdivacky
895198893Srdivacky    // If the type is deprecated or unavailable, diagnose it.
896221345Sdim    S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
897239462Sdim
898193326Sed    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
899198893Srdivacky           DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
900239462Sdim
901193326Sed    // TypeQuals handled by caller.
902198893Srdivacky    Result = Context.getTypeDeclType(D);
903198092Srdivacky
904221345Sdim    // In both C and C++, make an ElaboratedType.
905221345Sdim    ElaboratedTypeKeyword Keyword
906221345Sdim      = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
907221345Sdim    Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
908193326Sed    break;
909198092Srdivacky  }
910193326Sed  case DeclSpec::TST_typename: {
911193326Sed    assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
912193326Sed           DS.getTypeSpecSign() == 0 &&
913193326Sed           "Can't handle qualifiers on typedef names yet!");
914218893Sdim    Result = S.GetTypeFromParser(DS.getRepAsType());
915212904Sdim    if (Result.isNull())
916218893Sdim      declarator.setInvalidType(true);
917212904Sdim    else if (DeclSpec::ProtocolQualifierListTy PQ
918212904Sdim               = DS.getProtocolQualifiers()) {
919208600Srdivacky      if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
920208600Srdivacky        // Silently drop any existing protocol qualifiers.
921208600Srdivacky        // TODO: determine whether that's the right thing to do.
922208600Srdivacky        if (ObjT->getNumProtocols())
923208600Srdivacky          Result = ObjT->getBaseType();
924208600Srdivacky
925208600Srdivacky        if (DS.getNumProtocolQualifiers())
926208600Srdivacky          Result = Context.getObjCObjectType(Result,
927243830Sdim                                             (ObjCProtocolDecl*const*) PQ,
928208600Srdivacky                                             DS.getNumProtocolQualifiers());
929208600Srdivacky      } else if (Result->isObjCIdType()) {
930193326Sed        // id<protocol-list>
931208600Srdivacky        Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
932243830Sdim                                           (ObjCProtocolDecl*const*) PQ,
933208600Srdivacky                                           DS.getNumProtocolQualifiers());
934208600Srdivacky        Result = Context.getObjCObjectPointerType(Result);
935208600Srdivacky      } else if (Result->isObjCClassType()) {
936193326Sed        // Class<protocol-list>
937208600Srdivacky        Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
938243830Sdim                                           (ObjCProtocolDecl*const*) PQ,
939208600Srdivacky                                           DS.getNumProtocolQualifiers());
940208600Srdivacky        Result = Context.getObjCObjectPointerType(Result);
941193326Sed      } else {
942218893Sdim        S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
943193326Sed          << DS.getSourceRange();
944218893Sdim        declarator.setInvalidType(true);
945193326Sed      }
946193326Sed    }
947198092Srdivacky
948193326Sed    // TypeQuals handled by caller.
949193326Sed    break;
950193326Sed  }
951193326Sed  case DeclSpec::TST_typeofType:
952198092Srdivacky    // FIXME: Preserve type source info.
953218893Sdim    Result = S.GetTypeFromParser(DS.getRepAsType());
954193326Sed    assert(!Result.isNull() && "Didn't get a type for typeof?");
955218893Sdim    if (!Result->isDependentType())
956218893Sdim      if (const TagType *TT = Result->getAs<TagType>())
957218893Sdim        S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
958193326Sed    // TypeQuals handled by caller.
959193326Sed    Result = Context.getTypeOfType(Result);
960193326Sed    break;
961193326Sed  case DeclSpec::TST_typeofExpr: {
962212904Sdim    Expr *E = DS.getRepAsExpr();
963193326Sed    assert(E && "Didn't get an expression for typeof?");
964193326Sed    // TypeQuals handled by caller.
965218893Sdim    Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
966201361Srdivacky    if (Result.isNull()) {
967201361Srdivacky      Result = Context.IntTy;
968218893Sdim      declarator.setInvalidType(true);
969201361Srdivacky    }
970193326Sed    break;
971193326Sed  }
972195099Sed  case DeclSpec::TST_decltype: {
973212904Sdim    Expr *E = DS.getRepAsExpr();
974195099Sed    assert(E && "Didn't get an expression for decltype?");
975195099Sed    // TypeQuals handled by caller.
976218893Sdim    Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
977195341Sed    if (Result.isNull()) {
978195341Sed      Result = Context.IntTy;
979218893Sdim      declarator.setInvalidType(true);
980195341Sed    }
981195099Sed    break;
982195099Sed  }
983223017Sdim  case DeclSpec::TST_underlyingType:
984223017Sdim    Result = S.GetTypeFromParser(DS.getRepAsType());
985223017Sdim    assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
986223017Sdim    Result = S.BuildUnaryTransformType(Result,
987223017Sdim                                       UnaryTransformType::EnumUnderlyingType,
988223017Sdim                                       DS.getTypeSpecTypeLoc());
989223017Sdim    if (Result.isNull()) {
990223017Sdim      Result = Context.IntTy;
991223017Sdim      declarator.setInvalidType(true);
992223017Sdim    }
993239462Sdim    break;
994223017Sdim
995251662Sdim  case DeclSpec::TST_auto:
996195099Sed    // TypeQuals handled by caller.
997263508Sdim    // If auto is mentioned in a lambda parameter context, convert it to a
998263508Sdim    // template parameter type immediately, with the appropriate depth and
999263508Sdim    // index, and update sema's state (LambdaScopeInfo) for the current lambda
1000263508Sdim    // being analyzed (which tracks the invented type template parameter).
1001263508Sdim    if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1002263508Sdim      sema::LambdaScopeInfo *LSI = S.getCurLambda();
1003263508Sdim      assert(LSI && "No LambdaScopeInfo on the stack!");
1004263508Sdim      const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1005263508Sdim      const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1006263508Sdim      const bool IsParameterPack = declarator.hasEllipsis();
1007263508Sdim
1008263508Sdim      // Create a name for the invented template parameter type.
1009263508Sdim      std::string InventedTemplateParamName = "$auto-";
1010263508Sdim      llvm::raw_string_ostream ss(InventedTemplateParamName);
1011263508Sdim      ss << TemplateParameterDepth;
1012263508Sdim      ss << "-" << AutoParameterPosition;
1013263508Sdim      ss.flush();
1014263508Sdim
1015263508Sdim      IdentifierInfo& TemplateParamII = Context.Idents.get(
1016263508Sdim                                        InventedTemplateParamName.c_str());
1017263508Sdim      // Turns out we must create the TemplateTypeParmDecl here to
1018263508Sdim      // retrieve the corresponding template parameter type.
1019263508Sdim      TemplateTypeParmDecl *CorrespondingTemplateParam =
1020263508Sdim        TemplateTypeParmDecl::Create(Context,
1021263508Sdim        // Temporarily add to the TranslationUnit DeclContext.  When the
1022263508Sdim        // associated TemplateParameterList is attached to a template
1023263508Sdim        // declaration (such as FunctionTemplateDecl), the DeclContext
1024263508Sdim        // for each template parameter gets updated appropriately via
1025263508Sdim        // a call to AdoptTemplateParameterList.
1026263508Sdim        Context.getTranslationUnitDecl(),
1027263508Sdim        /*KeyLoc*/ SourceLocation(),
1028263508Sdim        /*NameLoc*/ declarator.getLocStart(),
1029263508Sdim        TemplateParameterDepth,
1030263508Sdim        AutoParameterPosition,  // our template param index
1031263508Sdim        /* Identifier*/ &TemplateParamII, false, IsParameterPack);
1032263508Sdim      LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1033263508Sdim      // Replace the 'auto' in the function parameter with this invented
1034263508Sdim      // template type parameter.
1035263508Sdim      Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1036263508Sdim    } else {
1037263508Sdim      Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false);
1038263508Sdim    }
1039195099Sed    break;
1040198092Srdivacky
1041251662Sdim  case DeclSpec::TST_decltype_auto:
1042263508Sdim    Result = Context.getAutoType(QualType(),
1043263508Sdim                                 /*decltype(auto)*/true,
1044263508Sdim                                 /*IsDependent*/   false);
1045251662Sdim    break;
1046251662Sdim
1047221345Sdim  case DeclSpec::TST_unknown_anytype:
1048221345Sdim    Result = Context.UnknownAnyTy;
1049221345Sdim    break;
1050221345Sdim
1051226633Sdim  case DeclSpec::TST_atomic:
1052226633Sdim    Result = S.GetTypeFromParser(DS.getRepAsType());
1053226633Sdim    assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1054226633Sdim    Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1055226633Sdim    if (Result.isNull()) {
1056226633Sdim      Result = Context.IntTy;
1057226633Sdim      declarator.setInvalidType(true);
1058226633Sdim    }
1059239462Sdim    break;
1060226633Sdim
1061249423Sdim  case DeclSpec::TST_image1d_t:
1062249423Sdim    Result = Context.OCLImage1dTy;
1063249423Sdim    break;
1064249423Sdim
1065249423Sdim  case DeclSpec::TST_image1d_array_t:
1066249423Sdim    Result = Context.OCLImage1dArrayTy;
1067249423Sdim    break;
1068249423Sdim
1069249423Sdim  case DeclSpec::TST_image1d_buffer_t:
1070249423Sdim    Result = Context.OCLImage1dBufferTy;
1071249423Sdim    break;
1072249423Sdim
1073249423Sdim  case DeclSpec::TST_image2d_t:
1074249423Sdim    Result = Context.OCLImage2dTy;
1075249423Sdim    break;
1076249423Sdim
1077249423Sdim  case DeclSpec::TST_image2d_array_t:
1078249423Sdim    Result = Context.OCLImage2dArrayTy;
1079249423Sdim    break;
1080249423Sdim
1081249423Sdim  case DeclSpec::TST_image3d_t:
1082249423Sdim    Result = Context.OCLImage3dTy;
1083249423Sdim    break;
1084249423Sdim
1085249423Sdim  case DeclSpec::TST_sampler_t:
1086249423Sdim    Result = Context.OCLSamplerTy;
1087249423Sdim    break;
1088249423Sdim
1089249423Sdim  case DeclSpec::TST_event_t:
1090249423Sdim    Result = Context.OCLEventTy;
1091249423Sdim    break;
1092249423Sdim
1093193326Sed  case DeclSpec::TST_error:
1094193326Sed    Result = Context.IntTy;
1095218893Sdim    declarator.setInvalidType(true);
1096193326Sed    break;
1097193326Sed  }
1098198092Srdivacky
1099193326Sed  // Handle complex types.
1100193326Sed  if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1101234353Sdim    if (S.getLangOpts().Freestanding)
1102218893Sdim      S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1103193326Sed    Result = Context.getComplexType(Result);
1104203955Srdivacky  } else if (DS.isTypeAltiVecVector()) {
1105203955Srdivacky    unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1106203955Srdivacky    assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1107218893Sdim    VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1108210299Sed    if (DS.isTypeAltiVecPixel())
1109218893Sdim      VecKind = VectorType::AltiVecPixel;
1110210299Sed    else if (DS.isTypeAltiVecBool())
1111218893Sdim      VecKind = VectorType::AltiVecBool;
1112218893Sdim    Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1113193326Sed  }
1114198092Srdivacky
1115218893Sdim  // FIXME: Imaginary.
1116218893Sdim  if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1117218893Sdim    S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1118198092Srdivacky
1119218893Sdim  // Before we process any type attributes, synthesize a block literal
1120218893Sdim  // function declarator if necessary.
1121218893Sdim  if (declarator.getContext() == Declarator::BlockLiteralContext)
1122218893Sdim    maybeSynthesizeBlockSignature(state, Result);
1123198092Srdivacky
1124218893Sdim  // Apply any type attributes from the decl spec.  This may cause the
1125218893Sdim  // list of type attributes to be temporarily saved while the type
1126218893Sdim  // attributes are pushed around.
1127218893Sdim  if (AttributeList *attrs = DS.getAttributes().getList())
1128249423Sdim    processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
1129218893Sdim
1130193326Sed  // Apply const/volatile/restrict qualifiers to T.
1131193326Sed  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1132193326Sed
1133193326Sed    // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
1134193326Sed    // of a function type includes any type qualifiers, the behavior is
1135193326Sed    // undefined."
1136193326Sed    if (Result->isFunctionType() && TypeQuals) {
1137198092Srdivacky      if (TypeQuals & DeclSpec::TQ_const)
1138249423Sdim        S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers)
1139249423Sdim          << Result << DS.getSourceRange();
1140198092Srdivacky      else if (TypeQuals & DeclSpec::TQ_volatile)
1141249423Sdim        S.Diag(DS.getVolatileSpecLoc(), diag::warn_typecheck_function_qualifiers)
1142249423Sdim          << Result << DS.getSourceRange();
1143193326Sed      else {
1144249423Sdim        assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) &&
1145249423Sdim               "Has CVRA quals but not C, V, R, or A?");
1146249423Sdim        // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a
1147249423Sdim        // function type later, in BuildQualifiedType.
1148193326Sed      }
1149193326Sed    }
1150198092Srdivacky
1151193326Sed    // C++ [dcl.ref]p1:
1152193326Sed    //   Cv-qualified references are ill-formed except when the
1153193326Sed    //   cv-qualifiers are introduced through the use of a typedef
1154193326Sed    //   (7.1.3) or of a template type argument (14.3), in which
1155193326Sed    //   case the cv-qualifiers are ignored.
1156193326Sed    // FIXME: Shouldn't we be checking SCS_typedef here?
1157193326Sed    if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
1158193326Sed        TypeQuals && Result->isReferenceType()) {
1159198092Srdivacky      TypeQuals &= ~DeclSpec::TQ_const;
1160198092Srdivacky      TypeQuals &= ~DeclSpec::TQ_volatile;
1161249423Sdim      TypeQuals &= ~DeclSpec::TQ_atomic;
1162198092Srdivacky    }
1163198092Srdivacky
1164234353Sdim    // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1165234353Sdim    // than once in the same specifier-list or qualifier-list, either directly
1166234353Sdim    // or via one or more typedefs."
1167239462Sdim    if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1168234353Sdim        && TypeQuals & Result.getCVRQualifiers()) {
1169234353Sdim      if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1170239462Sdim        S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1171234353Sdim          << "const";
1172234353Sdim      }
1173234353Sdim
1174234353Sdim      if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1175239462Sdim        S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1176234353Sdim          << "volatile";
1177234353Sdim      }
1178234353Sdim
1179249423Sdim      // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1180249423Sdim      // produce a warning in this case.
1181234353Sdim    }
1182234353Sdim
1183249423Sdim    QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1184249423Sdim
1185249423Sdim    // If adding qualifiers fails, just use the unqualified type.
1186249423Sdim    if (Qualified.isNull())
1187249423Sdim      declarator.setInvalidType(true);
1188249423Sdim    else
1189249423Sdim      Result = Qualified;
1190193326Sed  }
1191198092Srdivacky
1192193326Sed  return Result;
1193193326Sed}
1194193326Sed
1195193326Sedstatic std::string getPrintableNameForEntity(DeclarationName Entity) {
1196193326Sed  if (Entity)
1197193326Sed    return Entity.getAsString();
1198198092Srdivacky
1199193326Sed  return "type name";
1200193326Sed}
1201193326Sed
1202210299SedQualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1203249423Sdim                                  Qualifiers Qs, const DeclSpec *DS) {
1204210299Sed  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1205210299Sed  // object or incomplete types shall not be restrict-qualified."
1206210299Sed  if (Qs.hasRestrict()) {
1207210299Sed    unsigned DiagID = 0;
1208210299Sed    QualType ProblemTy;
1209210299Sed
1210249423Sdim    if (T->isAnyPointerType() || T->isReferenceType() ||
1211249423Sdim        T->isMemberPointerType()) {
1212249423Sdim      QualType EltTy;
1213249423Sdim      if (T->isObjCObjectPointerType())
1214249423Sdim        EltTy = T;
1215249423Sdim      else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1216249423Sdim        EltTy = PTy->getPointeeType();
1217249423Sdim      else
1218249423Sdim        EltTy = T->getPointeeType();
1219249423Sdim
1220249423Sdim      // If we have a pointer or reference, the pointee must have an object
1221249423Sdim      // incomplete type.
1222249423Sdim      if (!EltTy->isIncompleteOrObjectType()) {
1223210299Sed        DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1224249423Sdim        ProblemTy = EltTy;
1225210299Sed      }
1226249423Sdim    } else if (!T->isDependentType()) {
1227249423Sdim      DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1228210299Sed      ProblemTy = T;
1229210299Sed    }
1230210299Sed
1231210299Sed    if (DiagID) {
1232249423Sdim      Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1233210299Sed      Qs.removeRestrict();
1234210299Sed    }
1235210299Sed  }
1236210299Sed
1237210299Sed  return Context.getQualifiedType(T, Qs);
1238210299Sed}
1239210299Sed
1240249423SdimQualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1241249423Sdim                                  unsigned CVRA, const DeclSpec *DS) {
1242249423Sdim  // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1243249423Sdim  unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1244249423Sdim
1245249423Sdim  // C11 6.7.3/5:
1246249423Sdim  //   If the same qualifier appears more than once in the same
1247249423Sdim  //   specifier-qualifier-list, either directly or via one or more typedefs,
1248249423Sdim  //   the behavior is the same as if it appeared only once.
1249249423Sdim  //
1250249423Sdim  // It's not specified what happens when the _Atomic qualifier is applied to
1251249423Sdim  // a type specified with the _Atomic specifier, but we assume that this
1252249423Sdim  // should be treated as if the _Atomic qualifier appeared multiple times.
1253249423Sdim  if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1254249423Sdim    // C11 6.7.3/5:
1255249423Sdim    //   If other qualifiers appear along with the _Atomic qualifier in a
1256249423Sdim    //   specifier-qualifier-list, the resulting type is the so-qualified
1257249423Sdim    //   atomic type.
1258249423Sdim    //
1259249423Sdim    // Don't need to worry about array types here, since _Atomic can't be
1260249423Sdim    // applied to such types.
1261249423Sdim    SplitQualType Split = T.getSplitUnqualifiedType();
1262249423Sdim    T = BuildAtomicType(QualType(Split.Ty, 0),
1263249423Sdim                        DS ? DS->getAtomicSpecLoc() : Loc);
1264249423Sdim    if (T.isNull())
1265249423Sdim      return T;
1266249423Sdim    Split.Quals.addCVRQualifiers(CVR);
1267249423Sdim    return BuildQualifiedType(T, Loc, Split.Quals);
1268249423Sdim  }
1269249423Sdim
1270249423Sdim  return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1271249423Sdim}
1272249423Sdim
1273218893Sdim/// \brief Build a paren type including \p T.
1274218893SdimQualType Sema::BuildParenType(QualType T) {
1275218893Sdim  return Context.getParenType(T);
1276218893Sdim}
1277218893Sdim
1278224145Sdim/// Given that we're building a pointer or reference to the given
1279224145Sdimstatic QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1280224145Sdim                                           SourceLocation loc,
1281224145Sdim                                           bool isReference) {
1282224145Sdim  // Bail out if retention is unrequired or already specified.
1283224145Sdim  if (!type->isObjCLifetimeType() ||
1284224145Sdim      type.getObjCLifetime() != Qualifiers::OCL_None)
1285224145Sdim    return type;
1286224145Sdim
1287224145Sdim  Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1288224145Sdim
1289224145Sdim  // If the object type is const-qualified, we can safely use
1290224145Sdim  // __unsafe_unretained.  This is safe (because there are no read
1291224145Sdim  // barriers), and it'll be safe to coerce anything but __weak* to
1292224145Sdim  // the resulting type.
1293224145Sdim  if (type.isConstQualified()) {
1294224145Sdim    implicitLifetime = Qualifiers::OCL_ExplicitNone;
1295224145Sdim
1296224145Sdim  // Otherwise, check whether the static type does not require
1297224145Sdim  // retaining.  This currently only triggers for Class (possibly
1298224145Sdim  // protocol-qualifed, and arrays thereof).
1299224145Sdim  } else if (type->isObjCARCImplicitlyUnretainedType()) {
1300224145Sdim    implicitLifetime = Qualifiers::OCL_ExplicitNone;
1301224145Sdim
1302234353Sdim  // If we are in an unevaluated context, like sizeof, skip adding a
1303234353Sdim  // qualification.
1304239462Sdim  } else if (S.isUnevaluatedContext()) {
1305234353Sdim    return type;
1306226633Sdim
1307234353Sdim  // If that failed, give an error and recover using __strong.  __strong
1308234353Sdim  // is the option most likely to prevent spurious second-order diagnostics,
1309234353Sdim  // like when binding a reference to a field.
1310224145Sdim  } else {
1311224145Sdim    // These types can show up in private ivars in system headers, so
1312224145Sdim    // we need this to not be an error in those cases.  Instead we
1313224145Sdim    // want to delay.
1314224145Sdim    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1315224145Sdim      S.DelayedDiagnostics.add(
1316224145Sdim          sema::DelayedDiagnostic::makeForbiddenType(loc,
1317224145Sdim              diag::err_arc_indirect_no_ownership, type, isReference));
1318224145Sdim    } else {
1319224145Sdim      S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1320224145Sdim    }
1321234353Sdim    implicitLifetime = Qualifiers::OCL_Strong;
1322224145Sdim  }
1323224145Sdim  assert(implicitLifetime && "didn't infer any lifetime!");
1324224145Sdim
1325224145Sdim  Qualifiers qs;
1326224145Sdim  qs.addObjCLifetime(implicitLifetime);
1327224145Sdim  return S.Context.getQualifiedType(type, qs);
1328224145Sdim}
1329224145Sdim
1330193326Sed/// \brief Build a pointer type.
1331193326Sed///
1332193326Sed/// \param T The type to which we'll be building a pointer.
1333193326Sed///
1334193326Sed/// \param Loc The location of the entity whose type involves this
1335193326Sed/// pointer type or, if there is no such entity, the location of the
1336193326Sed/// type that will have pointer type.
1337193326Sed///
1338193326Sed/// \param Entity The name of the entity that involves the pointer
1339193326Sed/// type, if known.
1340193326Sed///
1341193326Sed/// \returns A suitable pointer type, if there are no
1342193326Sed/// errors. Otherwise, returns a NULL type.
1343210299SedQualType Sema::BuildPointerType(QualType T,
1344193326Sed                                SourceLocation Loc, DeclarationName Entity) {
1345193326Sed  if (T->isReferenceType()) {
1346193326Sed    // C++ 8.3.2p4: There shall be no ... pointers to references ...
1347193326Sed    Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1348198893Srdivacky      << getPrintableNameForEntity(Entity) << T;
1349193326Sed    return QualType();
1350193326Sed  }
1351193326Sed
1352208600Srdivacky  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1353207619Srdivacky
1354224145Sdim  // In ARC, it is forbidden to build pointers to unqualified pointers.
1355234353Sdim  if (getLangOpts().ObjCAutoRefCount)
1356224145Sdim    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1357224145Sdim
1358193326Sed  // Build the pointer type.
1359210299Sed  return Context.getPointerType(T);
1360193326Sed}
1361193326Sed
1362193326Sed/// \brief Build a reference type.
1363193326Sed///
1364193326Sed/// \param T The type to which we'll be building a reference.
1365193326Sed///
1366193326Sed/// \param Loc The location of the entity whose type involves this
1367193326Sed/// reference type or, if there is no such entity, the location of the
1368193326Sed/// type that will have reference type.
1369193326Sed///
1370193326Sed/// \param Entity The name of the entity that involves the reference
1371193326Sed/// type, if known.
1372193326Sed///
1373193326Sed/// \returns A suitable reference type, if there are no
1374193326Sed/// errors. Otherwise, returns a NULL type.
1375198398SrdivackyQualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1376210299Sed                                  SourceLocation Loc,
1377198398Srdivacky                                  DeclarationName Entity) {
1378239462Sdim  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1379223017Sdim         "Unresolved overloaded function type");
1380239462Sdim
1381218893Sdim  // C++0x [dcl.ref]p6:
1382239462Sdim  //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1383239462Sdim  //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1384239462Sdim  //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1385239462Sdim  //   the type "lvalue reference to T", while an attempt to create the type
1386218893Sdim  //   "rvalue reference to cv TR" creates the type TR.
1387198398Srdivacky  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1388198398Srdivacky
1389198398Srdivacky  // C++ [dcl.ref]p4: There shall be no references to references.
1390198398Srdivacky  //
1391198398Srdivacky  // According to C++ DR 106, references to references are only
1392198398Srdivacky  // diagnosed when they are written directly (e.g., "int & &"),
1393198398Srdivacky  // but not when they happen via a typedef:
1394198398Srdivacky  //
1395198398Srdivacky  //   typedef int& intref;
1396198398Srdivacky  //   typedef intref& intref2;
1397198398Srdivacky  //
1398198398Srdivacky  // Parser::ParseDeclaratorInternal diagnoses the case where
1399198398Srdivacky  // references are written directly; here, we handle the
1400218893Sdim  // collapsing of references-to-references as described in C++0x.
1401218893Sdim  // DR 106 and 540 introduce reference-collapsing into C++98/03.
1402198398Srdivacky
1403193326Sed  // C++ [dcl.ref]p1:
1404198092Srdivacky  //   A declarator that specifies the type "reference to cv void"
1405193326Sed  //   is ill-formed.
1406193326Sed  if (T->isVoidType()) {
1407193326Sed    Diag(Loc, diag::err_reference_to_void);
1408193326Sed    return QualType();
1409193326Sed  }
1410193326Sed
1411224145Sdim  // In ARC, it is forbidden to build references to unqualified pointers.
1412234353Sdim  if (getLangOpts().ObjCAutoRefCount)
1413224145Sdim    T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1414224145Sdim
1415193326Sed  // Handle restrict on references.
1416193326Sed  if (LValueRef)
1417210299Sed    return Context.getLValueReferenceType(T, SpelledAsLValue);
1418210299Sed  return Context.getRValueReferenceType(T);
1419193326Sed}
1420193326Sed
1421224145Sdim/// Check whether the specified array size makes the array type a VLA.  If so,
1422224145Sdim/// return true, if not, return the size of the array in SizeVal.
1423234353Sdimstatic bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1424234353Sdim  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1425234353Sdim  // (like gnu99, but not c99) accept any evaluatable value as an extension.
1426239462Sdim  class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1427239462Sdim  public:
1428239462Sdim    VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1429239462Sdim
1430239462Sdim    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1431239462Sdim    }
1432239462Sdim
1433239462Sdim    virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) {
1434239462Sdim      S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1435239462Sdim    }
1436239462Sdim  } Diagnoser;
1437239462Sdim
1438239462Sdim  return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1439239462Sdim                                           S.LangOpts.GNUMode).isInvalid();
1440224145Sdim}
1441224145Sdim
1442224145Sdim
1443193326Sed/// \brief Build an array type.
1444193326Sed///
1445193326Sed/// \param T The type of each element in the array.
1446193326Sed///
1447193326Sed/// \param ASM C99 array size modifier (e.g., '*', 'static').
1448193326Sed///
1449198092Srdivacky/// \param ArraySize Expression describing the size of the array.
1450198092Srdivacky///
1451239462Sdim/// \param Brackets The range from the opening '[' to the closing ']'.
1452193326Sed///
1453193326Sed/// \param Entity The name of the entity that involves the array
1454193326Sed/// type, if known.
1455193326Sed///
1456193326Sed/// \returns A suitable array type, if there are no errors. Otherwise,
1457193326Sed/// returns a NULL type.
1458193326SedQualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1459193326Sed                              Expr *ArraySize, unsigned Quals,
1460198092Srdivacky                              SourceRange Brackets, DeclarationName Entity) {
1461198092Srdivacky
1462198092Srdivacky  SourceLocation Loc = Brackets.getBegin();
1463234353Sdim  if (getLangOpts().CPlusPlus) {
1464207619Srdivacky    // C++ [dcl.array]p1:
1465207619Srdivacky    //   T is called the array element type; this type shall not be a reference
1466239462Sdim    //   type, the (possibly cv-qualified) type void, a function type or an
1467207619Srdivacky    //   abstract class type.
1468207619Srdivacky    //
1469239462Sdim    // C++ [dcl.array]p3:
1470239462Sdim    //   When several "array of" specifications are adjacent, [...] only the
1471239462Sdim    //   first of the constant expressions that specify the bounds of the arrays
1472239462Sdim    //   may be omitted.
1473239462Sdim    //
1474207619Srdivacky    // Note: function types are handled in the common path with C.
1475207619Srdivacky    if (T->isReferenceType()) {
1476207619Srdivacky      Diag(Loc, diag::err_illegal_decl_array_of_references)
1477207619Srdivacky      << getPrintableNameForEntity(Entity) << T;
1478207619Srdivacky      return QualType();
1479207619Srdivacky    }
1480239462Sdim
1481239462Sdim    if (T->isVoidType() || T->isIncompleteArrayType()) {
1482198954Srdivacky      Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1483198954Srdivacky      return QualType();
1484198954Srdivacky    }
1485239462Sdim
1486239462Sdim    if (RequireNonAbstractType(Brackets.getBegin(), T,
1487207619Srdivacky                               diag::err_array_of_abstract_type))
1488207619Srdivacky      return QualType();
1489239462Sdim
1490198954Srdivacky  } else {
1491207619Srdivacky    // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1492207619Srdivacky    // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1493198954Srdivacky    if (RequireCompleteType(Loc, T,
1494198954Srdivacky                            diag::err_illegal_decl_array_incomplete_type))
1495198954Srdivacky      return QualType();
1496198954Srdivacky  }
1497193326Sed
1498193326Sed  if (T->isFunctionType()) {
1499193326Sed    Diag(Loc, diag::err_illegal_decl_array_of_functions)
1500198893Srdivacky      << getPrintableNameForEntity(Entity) << T;
1501193326Sed    return QualType();
1502193326Sed  }
1503198092Srdivacky
1504198092Srdivacky  if (const RecordType *EltTy = T->getAs<RecordType>()) {
1505193326Sed    // If the element type is a struct or union that contains a variadic
1506193326Sed    // array, accept it as a GNU extension: C99 6.7.2.1p2.
1507193326Sed    if (EltTy->getDecl()->hasFlexibleArrayMember())
1508193326Sed      Diag(Loc, diag::ext_flexible_array_in_array) << T;
1509208600Srdivacky  } else if (T->isObjCObjectType()) {
1510193326Sed    Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1511193326Sed    return QualType();
1512193326Sed  }
1513198092Srdivacky
1514234353Sdim  // Do placeholder conversions on the array size expression.
1515234353Sdim  if (ArraySize && ArraySize->hasPlaceholderType()) {
1516234353Sdim    ExprResult Result = CheckPlaceholderExpr(ArraySize);
1517234353Sdim    if (Result.isInvalid()) return QualType();
1518234353Sdim    ArraySize = Result.take();
1519234353Sdim  }
1520234353Sdim
1521218893Sdim  // Do lvalue-to-rvalue conversions on the array size expression.
1522221345Sdim  if (ArraySize && !ArraySize->isRValue()) {
1523221345Sdim    ExprResult Result = DefaultLvalueConversion(ArraySize);
1524221345Sdim    if (Result.isInvalid())
1525221345Sdim      return QualType();
1526218893Sdim
1527221345Sdim    ArraySize = Result.take();
1528221345Sdim  }
1529221345Sdim
1530193326Sed  // C99 6.7.5.2p1: The size expression shall have integer type.
1531234353Sdim  // C++11 allows contextual conversions to such types.
1532249423Sdim  if (!getLangOpts().CPlusPlus11 &&
1533234353Sdim      ArraySize && !ArraySize->isTypeDependent() &&
1534218893Sdim      !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1535193326Sed    Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1536193326Sed      << ArraySize->getType() << ArraySize->getSourceRange();
1537193326Sed    return QualType();
1538193326Sed  }
1539234353Sdim
1540212904Sdim  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1541193326Sed  if (!ArraySize) {
1542193326Sed    if (ASM == ArrayType::Star)
1543198092Srdivacky      T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1544193326Sed    else
1545193326Sed      T = Context.getIncompleteArrayType(T, ASM, Quals);
1546208600Srdivacky  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1547198092Srdivacky    T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1548234353Sdim  } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1549234353Sdim              !T->isConstantSizeType()) ||
1550234353Sdim             isArraySizeVLA(*this, ArraySize, ConstVal)) {
1551234353Sdim    // Even in C++11, don't allow contextual conversions in the array bound
1552234353Sdim    // of a VLA.
1553249423Sdim    if (getLangOpts().CPlusPlus11 &&
1554234353Sdim        !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1555234353Sdim      Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1556234353Sdim        << ArraySize->getType() << ArraySize->getSourceRange();
1557234353Sdim      return QualType();
1558234353Sdim    }
1559234353Sdim
1560224145Sdim    // C99: an array with an element type that has a non-constant-size is a VLA.
1561224145Sdim    // C99: an array with a non-ICE size is a VLA.  We accept any expression
1562224145Sdim    // that we can fold to a non-zero positive value as an extension.
1563224145Sdim    T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1564193326Sed  } else {
1565193326Sed    // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1566193326Sed    // have a value greater than zero.
1567198954Srdivacky    if (ConstVal.isSigned() && ConstVal.isNegative()) {
1568218893Sdim      if (Entity)
1569218893Sdim        Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1570218893Sdim          << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1571218893Sdim      else
1572218893Sdim        Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1573218893Sdim          << ArraySize->getSourceRange();
1574198954Srdivacky      return QualType();
1575198092Srdivacky    }
1576198954Srdivacky    if (ConstVal == 0) {
1577206084Srdivacky      // GCC accepts zero sized static arrays. We allow them when
1578206084Srdivacky      // we're not in a SFINAE context.
1579239462Sdim      Diag(ArraySize->getLocStart(),
1580206084Srdivacky           isSFINAEContext()? diag::err_typecheck_zero_array_size
1581206084Srdivacky                            : diag::ext_typecheck_zero_array_size)
1582198954Srdivacky        << ArraySize->getSourceRange();
1583234353Sdim
1584234353Sdim      if (ASM == ArrayType::Static) {
1585234353Sdim        Diag(ArraySize->getLocStart(),
1586234353Sdim             diag::warn_typecheck_zero_static_array_size)
1587234353Sdim          << ArraySize->getSourceRange();
1588234353Sdim        ASM = ArrayType::Normal;
1589234353Sdim      }
1590239462Sdim    } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1591263508Sdim               !T->isIncompleteType() && !T->isUndeducedType()) {
1592239462Sdim      // Is the array too large?
1593212904Sdim      unsigned ActiveSizeBits
1594212904Sdim        = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1595263508Sdim      if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1596212904Sdim        Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1597212904Sdim          << ConstVal.toString(10)
1598212904Sdim          << ArraySize->getSourceRange();
1599263508Sdim        return QualType();
1600263508Sdim      }
1601198954Srdivacky    }
1602239462Sdim
1603198398Srdivacky    T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1604193326Sed  }
1605249423Sdim
1606249423Sdim  // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1607249423Sdim  if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1608249423Sdim    Diag(Loc, diag::err_opencl_vla);
1609249423Sdim    return QualType();
1610249423Sdim  }
1611193326Sed  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1612234353Sdim  if (!getLangOpts().C99) {
1613208600Srdivacky    if (T->isVariableArrayType()) {
1614208600Srdivacky      // Prohibit the use of non-POD types in VLAs.
1615224145Sdim      QualType BaseT = Context.getBaseElementType(T);
1616239462Sdim      if (!T->isDependentType() &&
1617224145Sdim          !BaseT.isPODType(Context) &&
1618224145Sdim          !BaseT->isObjCLifetimeType()) {
1619208600Srdivacky        Diag(Loc, diag::err_vla_non_pod)
1620224145Sdim          << BaseT;
1621208600Srdivacky        return QualType();
1622239462Sdim      }
1623208600Srdivacky      // Prohibit the use of VLAs during template argument deduction.
1624208600Srdivacky      else if (isSFINAEContext()) {
1625208600Srdivacky        Diag(Loc, diag::err_vla_in_sfinae);
1626208600Srdivacky        return QualType();
1627208600Srdivacky      }
1628208600Srdivacky      // Just extwarn about VLAs.
1629208600Srdivacky      else
1630263508Sdim        Diag(Loc, diag::ext_vla);
1631208600Srdivacky    } else if (ASM != ArrayType::Normal || Quals != 0)
1632234353Sdim      Diag(Loc,
1633234353Sdim           getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1634234353Sdim                                     : diag::ext_c99_array_usage) << ASM;
1635193326Sed  }
1636193326Sed
1637249423Sdim  if (T->isVariableArrayType()) {
1638249423Sdim    // Warn about VLAs for -Wvla.
1639249423Sdim    Diag(Loc, diag::warn_vla_used);
1640249423Sdim  }
1641249423Sdim
1642193326Sed  return T;
1643193326Sed}
1644194613Sed
1645194613Sed/// \brief Build an ext-vector type.
1646194613Sed///
1647194613Sed/// Run the required checks for the extended vector type.
1648212904SdimQualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1649194613Sed                                  SourceLocation AttrLoc) {
1650194613Sed  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1651194613Sed  // in conjunction with complex types (pointers, arrays, functions, etc.).
1652198092Srdivacky  if (!T->isDependentType() &&
1653194613Sed      !T->isIntegerType() && !T->isRealFloatingType()) {
1654194613Sed    Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1655194613Sed    return QualType();
1656194613Sed  }
1657194613Sed
1658212904Sdim  if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1659194613Sed    llvm::APSInt vecSize(32);
1660212904Sdim    if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1661263508Sdim      Diag(AttrLoc, diag::err_attribute_argument_type)
1662263508Sdim        << "ext_vector_type" << AANT_ArgumentIntegerConstant
1663263508Sdim        << ArraySize->getSourceRange();
1664194613Sed      return QualType();
1665194613Sed    }
1666198092Srdivacky
1667198092Srdivacky    // unlike gcc's vector_size attribute, the size is specified as the
1668194613Sed    // number of elements, not the number of bytes.
1669198092Srdivacky    unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1670198092Srdivacky
1671194613Sed    if (vectorSize == 0) {
1672194613Sed      Diag(AttrLoc, diag::err_attribute_zero_size)
1673212904Sdim      << ArraySize->getSourceRange();
1674194613Sed      return QualType();
1675194613Sed    }
1676198092Srdivacky
1677263508Sdim    if (VectorType::isVectorSizeTooLarge(vectorSize)) {
1678263508Sdim      Diag(AttrLoc, diag::err_attribute_size_too_large)
1679263508Sdim        << ArraySize->getSourceRange();
1680263508Sdim      return QualType();
1681263508Sdim    }
1682263508Sdim
1683224145Sdim    return Context.getExtVectorType(T, vectorSize);
1684198092Srdivacky  }
1685198092Srdivacky
1686212904Sdim  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1687194613Sed}
1688198092Srdivacky
1689263508Sdimbool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
1690193326Sed  if (T->isArrayType() || T->isFunctionType()) {
1691239462Sdim    Diag(Loc, diag::err_func_returning_array_function)
1692202379Srdivacky      << T->isFunctionType() << T;
1693263508Sdim    return true;
1694193326Sed  }
1695226633Sdim
1696226633Sdim  // Functions cannot return half FP.
1697226633Sdim  if (T->isHalfType()) {
1698226633Sdim    Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1699226633Sdim      FixItHint::CreateInsertion(Loc, "*");
1700263508Sdim    return true;
1701226633Sdim  }
1702226633Sdim
1703263508Sdim  // Methods cannot return interface types. All ObjC objects are
1704263508Sdim  // passed by reference.
1705263508Sdim  if (T->isObjCObjectType()) {
1706263508Sdim    Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
1707263508Sdim    return 0;
1708263508Sdim  }
1709263508Sdim
1710263508Sdim  return false;
1711263508Sdim}
1712263508Sdim
1713263508SdimQualType Sema::BuildFunctionType(QualType T,
1714263508Sdim                                 llvm::MutableArrayRef<QualType> ParamTypes,
1715263508Sdim                                 SourceLocation Loc, DeclarationName Entity,
1716263508Sdim                                 const FunctionProtoType::ExtProtoInfo &EPI) {
1717193326Sed  bool Invalid = false;
1718263508Sdim
1719263508Sdim  Invalid |= CheckFunctionReturnType(T, Loc);
1720263508Sdim
1721249423Sdim  for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
1722226633Sdim    // FIXME: Loc is too inprecise here, should use proper locations for args.
1723224145Sdim    QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1724193326Sed    if (ParamType->isVoidType()) {
1725193326Sed      Diag(Loc, diag::err_param_with_void_type);
1726193326Sed      Invalid = true;
1727226633Sdim    } else if (ParamType->isHalfType()) {
1728226633Sdim      // Disallow half FP arguments.
1729226633Sdim      Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1730226633Sdim        FixItHint::CreateInsertion(Loc, "*");
1731226633Sdim      Invalid = true;
1732193326Sed    }
1733193326Sed
1734198398Srdivacky    ParamTypes[Idx] = ParamType;
1735193326Sed  }
1736193326Sed
1737193326Sed  if (Invalid)
1738193326Sed    return QualType();
1739193326Sed
1740249423Sdim  return Context.getFunctionType(T, ParamTypes, EPI);
1741193326Sed}
1742198092Srdivacky
1743194179Sed/// \brief Build a member pointer type \c T Class::*.
1744194179Sed///
1745194179Sed/// \param T the type to which the member pointer refers.
1746194179Sed/// \param Class the class type into which the member pointer points.
1747194179Sed/// \param Loc the location where this type begins
1748194179Sed/// \param Entity the name of the entity that will have this member pointer type
1749194179Sed///
1750194179Sed/// \returns a member pointer type, if successful, or a NULL type if there was
1751194179Sed/// an error.
1752198092SrdivackyQualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1753210299Sed                                      SourceLocation Loc,
1754194179Sed                                      DeclarationName Entity) {
1755194179Sed  // Verify that we're not building a pointer to pointer to function with
1756194179Sed  // exception specification.
1757194179Sed  if (CheckDistantExceptionSpec(T)) {
1758194179Sed    Diag(Loc, diag::err_distant_exception_spec);
1759194179Sed
1760194179Sed    // FIXME: If we're doing this as part of template instantiation,
1761194179Sed    // we should return immediately.
1762194179Sed
1763194179Sed    // Build the type anyway, but use the canonical type so that the
1764194179Sed    // exception specifiers are stripped off.
1765194179Sed    T = Context.getCanonicalType(T);
1766194179Sed  }
1767194179Sed
1768210299Sed  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1769194179Sed  //   with reference type, or "cv void."
1770194179Sed  if (T->isReferenceType()) {
1771195341Sed    Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1772198893Srdivacky      << (Entity? Entity.getAsString() : "type name") << T;
1773194179Sed    return QualType();
1774194179Sed  }
1775194179Sed
1776194179Sed  if (T->isVoidType()) {
1777194179Sed    Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1778194179Sed      << (Entity? Entity.getAsString() : "type name");
1779194179Sed    return QualType();
1780194179Sed  }
1781194179Sed
1782194179Sed  if (!Class->isDependentType() && !Class->isRecordType()) {
1783194179Sed    Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1784194179Sed    return QualType();
1785194179Sed  }
1786194179Sed
1787249423Sdim  // C++ allows the class type in a member pointer to be an incomplete type.
1788249423Sdim  // In the Microsoft ABI, the size of the member pointer can vary
1789249423Sdim  // according to the class type, which means that we really need a
1790249423Sdim  // complete type if possible, which means we need to instantiate templates.
1791249423Sdim  //
1792249423Sdim  // If template instantiation fails or the type is just incomplete, we have to
1793249423Sdim  // add an extra slot to the member pointer.  Yes, this does cause problems
1794249423Sdim  // when passing pointers between TUs that disagree about the size.
1795249423Sdim  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1796249423Sdim    CXXRecordDecl *RD = Class->getAsCXXRecordDecl();
1797249423Sdim    if (RD && !RD->hasAttr<MSInheritanceAttr>()) {
1798249423Sdim      // Lock in the inheritance model on the first use of a member pointer.
1799249423Sdim      // Otherwise we may disagree about the size at different points in the TU.
1800249423Sdim      // FIXME: MSVC picks a model on the first use that needs to know the size,
1801249423Sdim      // rather than on the first mention of the type, e.g. typedefs.
1802249423Sdim      if (RequireCompleteType(Loc, Class, 0) && !RD->isBeingDefined()) {
1803249423Sdim        // We know it doesn't have an attribute and it's incomplete, so use the
1804249423Sdim        // unspecified inheritance model.  If we're in the record body, we can
1805249423Sdim        // figure out the inheritance model.
1806249423Sdim        for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
1807249423Sdim             E = RD->redecls_end(); I != E; ++I) {
1808249423Sdim          I->addAttr(::new (Context) UnspecifiedInheritanceAttr(
1809249423Sdim              RD->getSourceRange(), Context));
1810249423Sdim        }
1811249423Sdim      }
1812249423Sdim    }
1813249423Sdim  }
1814212904Sdim
1815263508Sdim  // FIXME: Adjust member function pointer calling conventions.
1816263508Sdim
1817210299Sed  return Context.getMemberPointerType(T, Class.getTypePtr());
1818194179Sed}
1819198092Srdivacky
1820194179Sed/// \brief Build a block pointer type.
1821194179Sed///
1822194179Sed/// \param T The type to which we'll be building a block pointer.
1823194179Sed///
1824239462Sdim/// \param Loc The source location, used for diagnostics.
1825194179Sed///
1826194179Sed/// \param Entity The name of the entity that involves the block pointer
1827194179Sed/// type, if known.
1828194179Sed///
1829194179Sed/// \returns A suitable block pointer type, if there are no
1830194179Sed/// errors. Otherwise, returns a NULL type.
1831239462SdimQualType Sema::BuildBlockPointerType(QualType T,
1832198092Srdivacky                                     SourceLocation Loc,
1833194179Sed                                     DeclarationName Entity) {
1834198092Srdivacky  if (!T->isFunctionType()) {
1835194179Sed    Diag(Loc, diag::err_nonfunction_block_type);
1836194179Sed    return QualType();
1837194179Sed  }
1838198092Srdivacky
1839210299Sed  return Context.getBlockPointerType(T);
1840194179Sed}
1841194179Sed
1842212904SdimQualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1843212904Sdim  QualType QT = Ty.get();
1844198893Srdivacky  if (QT.isNull()) {
1845200583Srdivacky    if (TInfo) *TInfo = 0;
1846198893Srdivacky    return QualType();
1847198893Srdivacky  }
1848198893Srdivacky
1849200583Srdivacky  TypeSourceInfo *DI = 0;
1850218893Sdim  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1851198092Srdivacky    QT = LIT->getType();
1852200583Srdivacky    DI = LIT->getTypeSourceInfo();
1853198092Srdivacky  }
1854198092Srdivacky
1855200583Srdivacky  if (TInfo) *TInfo = DI;
1856198092Srdivacky  return QT;
1857198092Srdivacky}
1858198092Srdivacky
1859224145Sdimstatic void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1860224145Sdim                                            Qualifiers::ObjCLifetime ownership,
1861224145Sdim                                            unsigned chunkIndex);
1862224145Sdim
1863224145Sdim/// Given that this is the declaration of a parameter under ARC,
1864224145Sdim/// attempt to infer attributes and such for pointer-to-whatever
1865224145Sdim/// types.
1866224145Sdimstatic void inferARCWriteback(TypeProcessingState &state,
1867224145Sdim                              QualType &declSpecType) {
1868224145Sdim  Sema &S = state.getSema();
1869224145Sdim  Declarator &declarator = state.getDeclarator();
1870224145Sdim
1871224145Sdim  // TODO: should we care about decl qualifiers?
1872224145Sdim
1873224145Sdim  // Check whether the declarator has the expected form.  We walk
1874224145Sdim  // from the inside out in order to make the block logic work.
1875224145Sdim  unsigned outermostPointerIndex = 0;
1876224145Sdim  bool isBlockPointer = false;
1877224145Sdim  unsigned numPointers = 0;
1878224145Sdim  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1879224145Sdim    unsigned chunkIndex = i;
1880224145Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1881224145Sdim    switch (chunk.Kind) {
1882224145Sdim    case DeclaratorChunk::Paren:
1883224145Sdim      // Ignore parens.
1884224145Sdim      break;
1885224145Sdim
1886224145Sdim    case DeclaratorChunk::Reference:
1887224145Sdim    case DeclaratorChunk::Pointer:
1888224145Sdim      // Count the number of pointers.  Treat references
1889224145Sdim      // interchangeably as pointers; if they're mis-ordered, normal
1890224145Sdim      // type building will discover that.
1891224145Sdim      outermostPointerIndex = chunkIndex;
1892224145Sdim      numPointers++;
1893224145Sdim      break;
1894224145Sdim
1895224145Sdim    case DeclaratorChunk::BlockPointer:
1896224145Sdim      // If we have a pointer to block pointer, that's an acceptable
1897224145Sdim      // indirect reference; anything else is not an application of
1898224145Sdim      // the rules.
1899224145Sdim      if (numPointers != 1) return;
1900224145Sdim      numPointers++;
1901224145Sdim      outermostPointerIndex = chunkIndex;
1902224145Sdim      isBlockPointer = true;
1903224145Sdim
1904224145Sdim      // We don't care about pointer structure in return values here.
1905224145Sdim      goto done;
1906224145Sdim
1907224145Sdim    case DeclaratorChunk::Array: // suppress if written (id[])?
1908224145Sdim    case DeclaratorChunk::Function:
1909224145Sdim    case DeclaratorChunk::MemberPointer:
1910224145Sdim      return;
1911224145Sdim    }
1912224145Sdim  }
1913224145Sdim done:
1914224145Sdim
1915224145Sdim  // If we have *one* pointer, then we want to throw the qualifier on
1916224145Sdim  // the declaration-specifiers, which means that it needs to be a
1917224145Sdim  // retainable object type.
1918224145Sdim  if (numPointers == 1) {
1919224145Sdim    // If it's not a retainable object type, the rule doesn't apply.
1920224145Sdim    if (!declSpecType->isObjCRetainableType()) return;
1921224145Sdim
1922224145Sdim    // If it already has lifetime, don't do anything.
1923224145Sdim    if (declSpecType.getObjCLifetime()) return;
1924224145Sdim
1925224145Sdim    // Otherwise, modify the type in-place.
1926224145Sdim    Qualifiers qs;
1927239462Sdim
1928224145Sdim    if (declSpecType->isObjCARCImplicitlyUnretainedType())
1929224145Sdim      qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1930224145Sdim    else
1931224145Sdim      qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1932224145Sdim    declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1933224145Sdim
1934224145Sdim  // If we have *two* pointers, then we want to throw the qualifier on
1935224145Sdim  // the outermost pointer.
1936224145Sdim  } else if (numPointers == 2) {
1937224145Sdim    // If we don't have a block pointer, we need to check whether the
1938224145Sdim    // declaration-specifiers gave us something that will turn into a
1939224145Sdim    // retainable object pointer after we slap the first pointer on it.
1940224145Sdim    if (!isBlockPointer && !declSpecType->isObjCObjectType())
1941224145Sdim      return;
1942224145Sdim
1943224145Sdim    // Look for an explicit lifetime attribute there.
1944224145Sdim    DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1945224145Sdim    if (chunk.Kind != DeclaratorChunk::Pointer &&
1946224145Sdim        chunk.Kind != DeclaratorChunk::BlockPointer)
1947224145Sdim      return;
1948224145Sdim    for (const AttributeList *attr = chunk.getAttrs(); attr;
1949224145Sdim           attr = attr->getNext())
1950239462Sdim      if (attr->getKind() == AttributeList::AT_ObjCOwnership)
1951224145Sdim        return;
1952224145Sdim
1953224145Sdim    transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1954224145Sdim                                          outermostPointerIndex);
1955224145Sdim
1956224145Sdim  // Any other number of pointers/references does not trigger the rule.
1957224145Sdim  } else return;
1958224145Sdim
1959224145Sdim  // TODO: mark whether we did this inference?
1960224145Sdim}
1961224145Sdim
1962249423Sdimstatic void diagnoseIgnoredQualifiers(
1963249423Sdim    Sema &S, unsigned Quals,
1964249423Sdim    SourceLocation FallbackLoc,
1965249423Sdim    SourceLocation ConstQualLoc = SourceLocation(),
1966249423Sdim    SourceLocation VolatileQualLoc = SourceLocation(),
1967249423Sdim    SourceLocation RestrictQualLoc = SourceLocation(),
1968249423Sdim    SourceLocation AtomicQualLoc = SourceLocation()) {
1969249423Sdim  if (!Quals)
1970249423Sdim    return;
1971249423Sdim
1972249423Sdim  const SourceManager &SM = S.getSourceManager();
1973249423Sdim
1974249423Sdim  struct Qual {
1975249423Sdim    unsigned Mask;
1976249423Sdim    const char *Name;
1977249423Sdim    SourceLocation Loc;
1978249423Sdim  } const QualKinds[4] = {
1979249423Sdim    { DeclSpec::TQ_const, "const", ConstQualLoc },
1980249423Sdim    { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc },
1981249423Sdim    { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc },
1982249423Sdim    { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc }
1983249423Sdim  };
1984249423Sdim
1985263508Sdim  SmallString<32> QualStr;
1986219077Sdim  unsigned NumQuals = 0;
1987219077Sdim  SourceLocation Loc;
1988249423Sdim  FixItHint FixIts[4];
1989219077Sdim
1990249423Sdim  // Build a string naming the redundant qualifiers.
1991249423Sdim  for (unsigned I = 0; I != 4; ++I) {
1992249423Sdim    if (Quals & QualKinds[I].Mask) {
1993249423Sdim      if (!QualStr.empty()) QualStr += ' ';
1994249423Sdim      QualStr += QualKinds[I].Name;
1995219077Sdim
1996249423Sdim      // If we have a location for the qualifier, offer a fixit.
1997249423Sdim      SourceLocation QualLoc = QualKinds[I].Loc;
1998249423Sdim      if (!QualLoc.isInvalid()) {
1999249423Sdim        FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2000249423Sdim        if (Loc.isInvalid() || SM.isBeforeInTranslationUnit(QualLoc, Loc))
2001249423Sdim          Loc = QualLoc;
2002249423Sdim      }
2003223017Sdim
2004249423Sdim      ++NumQuals;
2005249423Sdim    }
2006219077Sdim  }
2007249423Sdim
2008249423Sdim  S.Diag(Loc.isInvalid() ? FallbackLoc : Loc, diag::warn_qual_return_type)
2009249423Sdim    << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2010249423Sdim}
2011249423Sdim
2012249423Sdim// Diagnose pointless type qualifiers on the return type of a function.
2013249423Sdimstatic void diagnoseIgnoredFunctionQualifiers(Sema &S, QualType RetTy,
2014249423Sdim                                              Declarator &D,
2015249423Sdim                                              unsigned FunctionChunkIndex) {
2016249423Sdim  if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2017249423Sdim    // FIXME: TypeSourceInfo doesn't preserve location information for
2018249423Sdim    // qualifiers.
2019249423Sdim    diagnoseIgnoredQualifiers(S, RetTy.getLocalCVRQualifiers(),
2020249423Sdim                              D.getIdentifierLoc());
2021249423Sdim    return;
2022219077Sdim  }
2023249423Sdim
2024249423Sdim  for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2025249423Sdim                End = D.getNumTypeObjects();
2026249423Sdim       OuterChunkIndex != End; ++OuterChunkIndex) {
2027249423Sdim    DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2028249423Sdim    switch (OuterChunk.Kind) {
2029249423Sdim    case DeclaratorChunk::Paren:
2030249423Sdim      continue;
2031249423Sdim
2032249423Sdim    case DeclaratorChunk::Pointer: {
2033249423Sdim      DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2034249423Sdim      diagnoseIgnoredQualifiers(
2035249423Sdim          S, PTI.TypeQuals,
2036249423Sdim          SourceLocation(),
2037249423Sdim          SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2038249423Sdim          SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2039249423Sdim          SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2040249423Sdim          SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2041249423Sdim      return;
2042249423Sdim    }
2043249423Sdim
2044249423Sdim    case DeclaratorChunk::Function:
2045249423Sdim    case DeclaratorChunk::BlockPointer:
2046249423Sdim    case DeclaratorChunk::Reference:
2047249423Sdim    case DeclaratorChunk::Array:
2048249423Sdim    case DeclaratorChunk::MemberPointer:
2049249423Sdim      // FIXME: We can't currently provide an accurate source location and a
2050249423Sdim      // fix-it hint for these.
2051249423Sdim      unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2052249423Sdim      diagnoseIgnoredQualifiers(S, RetTy.getCVRQualifiers() | AtomicQual,
2053249423Sdim                                D.getIdentifierLoc());
2054249423Sdim      return;
2055249423Sdim    }
2056249423Sdim
2057249423Sdim    llvm_unreachable("unknown declarator chunk kind");
2058219077Sdim  }
2059219077Sdim
2060249423Sdim  // If the qualifiers come from a conversion function type, don't diagnose
2061249423Sdim  // them -- they're not necessarily redundant, since such a conversion
2062249423Sdim  // operator can be explicitly called as "x.operator const int()".
2063249423Sdim  if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2064249423Sdim    return;
2065219077Sdim
2066249423Sdim  // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2067249423Sdim  // which are present there.
2068249423Sdim  diagnoseIgnoredQualifiers(S, D.getDeclSpec().getTypeQualifiers(),
2069249423Sdim                            D.getIdentifierLoc(),
2070249423Sdim                            D.getDeclSpec().getConstSpecLoc(),
2071249423Sdim                            D.getDeclSpec().getVolatileSpecLoc(),
2072249423Sdim                            D.getDeclSpec().getRestrictSpecLoc(),
2073249423Sdim                            D.getDeclSpec().getAtomicSpecLoc());
2074219077Sdim}
2075219077Sdim
2076224145Sdimstatic QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2077224145Sdim                                             TypeSourceInfo *&ReturnTypeInfo) {
2078224145Sdim  Sema &SemaRef = state.getSema();
2079224145Sdim  Declarator &D = state.getDeclarator();
2080193326Sed  QualType T;
2081224145Sdim  ReturnTypeInfo = 0;
2082203955Srdivacky
2083224145Sdim  // The TagDecl owned by the DeclSpec.
2084224145Sdim  TagDecl *OwnedTagDecl = 0;
2085218893Sdim
2086251662Sdim  bool ContainsPlaceholderType = false;
2087251662Sdim
2088198893Srdivacky  switch (D.getName().getKind()) {
2089224145Sdim  case UnqualifiedId::IK_ImplicitSelfParam:
2090221345Sdim  case UnqualifiedId::IK_OperatorFunctionId:
2091198893Srdivacky  case UnqualifiedId::IK_Identifier:
2092199990Srdivacky  case UnqualifiedId::IK_LiteralOperatorId:
2093198893Srdivacky  case UnqualifiedId::IK_TemplateId:
2094224145Sdim    T = ConvertDeclSpecToType(state);
2095251662Sdim    ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType();
2096239462Sdim
2097203955Srdivacky    if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2098224145Sdim      OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2099221345Sdim      // Owned declaration is embedded in declarator.
2100224145Sdim      OwnedTagDecl->setEmbeddedInDeclarator(true);
2101203955Srdivacky    }
2102193326Sed    break;
2103193326Sed
2104198893Srdivacky  case UnqualifiedId::IK_ConstructorName:
2105202379Srdivacky  case UnqualifiedId::IK_ConstructorTemplateId:
2106198893Srdivacky  case UnqualifiedId::IK_DestructorName:
2107193326Sed    // Constructors and destructors don't have return types. Use
2108239462Sdim    // "void" instead.
2109224145Sdim    T = SemaRef.Context.VoidTy;
2110239462Sdim    if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
2111249423Sdim      processTypeAttrs(state, T, TAL_DeclSpec, attrs);
2112193326Sed    break;
2113202379Srdivacky
2114202379Srdivacky  case UnqualifiedId::IK_ConversionFunctionId:
2115202379Srdivacky    // The result type of a conversion function is the type that it
2116202379Srdivacky    // converts to.
2117239462Sdim    T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2118224145Sdim                                  &ReturnTypeInfo);
2119251662Sdim    ContainsPlaceholderType = T->getContainedAutoType();
2120202379Srdivacky    break;
2121193326Sed  }
2122200583Srdivacky
2123218893Sdim  if (D.getAttributes())
2124218893Sdim    distributeTypeAttrsFromDeclarator(state, T);
2125218893Sdim
2126234353Sdim  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2127234353Sdim  // In C++11, a function declarator using 'auto' must have a trailing return
2128219077Sdim  // type (this is checked later) and we can skip this. In other languages
2129219077Sdim  // using auto, we need to check regardless.
2130263508Sdim  // C++14 In generic lambdas allow 'auto' in their parameters.
2131251662Sdim  if (ContainsPlaceholderType &&
2132249423Sdim      (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
2133195099Sed    int Error = -1;
2134198092Srdivacky
2135195099Sed    switch (D.getContext()) {
2136195099Sed    case Declarator::KNRTypeListContext:
2137226633Sdim      llvm_unreachable("K&R type lists aren't allowed in C++");
2138234353Sdim    case Declarator::LambdaExprContext:
2139234353Sdim      llvm_unreachable("Can't specify a type specifier in lambda grammar");
2140226633Sdim    case Declarator::ObjCParameterContext:
2141226633Sdim    case Declarator::ObjCResultContext:
2142195099Sed    case Declarator::PrototypeContext:
2143263508Sdim      Error = 0;
2144195099Sed      break;
2145263508Sdim    case Declarator::LambdaExprParameterContext:
2146263508Sdim      if (!(SemaRef.getLangOpts().CPlusPlus1y
2147263508Sdim              && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2148263508Sdim        Error = 14;
2149263508Sdim      break;
2150195099Sed    case Declarator::MemberContext:
2151223017Sdim      if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2152223017Sdim        break;
2153224145Sdim      switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2154226633Sdim      case TTK_Enum: llvm_unreachable("unhandled tag kind");
2155208600Srdivacky      case TTK_Struct: Error = 1; /* Struct member */ break;
2156208600Srdivacky      case TTK_Union:  Error = 2; /* Union member */ break;
2157208600Srdivacky      case TTK_Class:  Error = 3; /* Class member */ break;
2158243830Sdim      case TTK_Interface: Error = 4; /* Interface member */ break;
2159198092Srdivacky      }
2160195099Sed      break;
2161195099Sed    case Declarator::CXXCatchContext:
2162224145Sdim    case Declarator::ObjCCatchContext:
2163243830Sdim      Error = 5; // Exception declaration
2164195099Sed      break;
2165195099Sed    case Declarator::TemplateParamContext:
2166243830Sdim      Error = 6; // Template parameter
2167195099Sed      break;
2168195099Sed    case Declarator::BlockLiteralContext:
2169243830Sdim      Error = 7; // Block literal
2170195099Sed      break;
2171218893Sdim    case Declarator::TemplateTypeArgContext:
2172243830Sdim      Error = 8; // Template type argument
2173218893Sdim      break;
2174221345Sdim    case Declarator::AliasDeclContext:
2175223017Sdim    case Declarator::AliasTemplateContext:
2176243830Sdim      Error = 10; // Type alias
2177221345Sdim      break;
2178234353Sdim    case Declarator::TrailingReturnContext:
2179251662Sdim      if (!SemaRef.getLangOpts().CPlusPlus1y)
2180251662Sdim        Error = 11; // Function return type
2181234353Sdim      break;
2182251662Sdim    case Declarator::ConversionIdContext:
2183251662Sdim      if (!SemaRef.getLangOpts().CPlusPlus1y)
2184251662Sdim        Error = 12; // conversion-type-id
2185251662Sdim      break;
2186218893Sdim    case Declarator::TypeNameContext:
2187251662Sdim      Error = 13; // Generic
2188218893Sdim      break;
2189195099Sed    case Declarator::FileContext:
2190195099Sed    case Declarator::BlockContext:
2191195099Sed    case Declarator::ForContext:
2192195099Sed    case Declarator::ConditionContext:
2193224145Sdim    case Declarator::CXXNewContext:
2194195099Sed      break;
2195195099Sed    }
2196195099Sed
2197219077Sdim    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2198243830Sdim      Error = 9;
2199219077Sdim
2200219077Sdim    // In Objective-C it is an error to use 'auto' on a function declarator.
2201219077Sdim    if (D.isFunctionDeclarator())
2202243830Sdim      Error = 11;
2203219077Sdim
2204234353Sdim    // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2205219077Sdim    // contains a trailing return type. That is only legal at the outermost
2206219077Sdim    // level. Check all declarator chunks (outermost first) anyway, to give
2207219077Sdim    // better diagnostics.
2208249423Sdim    if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
2209219077Sdim      for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2210219077Sdim        unsigned chunkIndex = e - i - 1;
2211219077Sdim        state.setCurrentChunkIndex(chunkIndex);
2212219077Sdim        DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2213219077Sdim        if (DeclType.Kind == DeclaratorChunk::Function) {
2214219077Sdim          const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2215239462Sdim          if (FTI.hasTrailingReturnType()) {
2216219077Sdim            Error = -1;
2217219077Sdim            break;
2218219077Sdim          }
2219219077Sdim        }
2220219077Sdim      }
2221219077Sdim    }
2222219077Sdim
2223251662Sdim    SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2224251662Sdim    if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2225251662Sdim      AutoRange = D.getName().getSourceRange();
2226251662Sdim
2227195099Sed    if (Error != -1) {
2228263508Sdim      const bool IsDeclTypeAuto =
2229263508Sdim          D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto;
2230251662Sdim      SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2231263508Sdim        << IsDeclTypeAuto << Error << AutoRange;
2232224145Sdim      T = SemaRef.Context.IntTy;
2233195099Sed      D.setInvalidType(true);
2234234353Sdim    } else
2235251662Sdim      SemaRef.Diag(AutoRange.getBegin(),
2236251662Sdim                   diag::warn_cxx98_compat_auto_type_specifier)
2237251662Sdim        << AutoRange;
2238195099Sed  }
2239218893Sdim
2240234353Sdim  if (SemaRef.getLangOpts().CPlusPlus &&
2241226633Sdim      OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2242224145Sdim    // Check the contexts where C++ forbids the declaration of a new class
2243224145Sdim    // or enumeration in a type-specifier-seq.
2244224145Sdim    switch (D.getContext()) {
2245234353Sdim    case Declarator::TrailingReturnContext:
2246234353Sdim      // Class and enumeration definitions are syntactically not allowed in
2247234353Sdim      // trailing return types.
2248234353Sdim      llvm_unreachable("parser should not have allowed this");
2249234353Sdim      break;
2250224145Sdim    case Declarator::FileContext:
2251224145Sdim    case Declarator::MemberContext:
2252224145Sdim    case Declarator::BlockContext:
2253224145Sdim    case Declarator::ForContext:
2254224145Sdim    case Declarator::BlockLiteralContext:
2255234353Sdim    case Declarator::LambdaExprContext:
2256234353Sdim      // C++11 [dcl.type]p3:
2257224145Sdim      //   A type-specifier-seq shall not define a class or enumeration unless
2258224145Sdim      //   it appears in the type-id of an alias-declaration (7.1.3) that is not
2259224145Sdim      //   the declaration of a template-declaration.
2260224145Sdim    case Declarator::AliasDeclContext:
2261224145Sdim      break;
2262224145Sdim    case Declarator::AliasTemplateContext:
2263224145Sdim      SemaRef.Diag(OwnedTagDecl->getLocation(),
2264224145Sdim             diag::err_type_defined_in_alias_template)
2265224145Sdim        << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2266249423Sdim      D.setInvalidType(true);
2267224145Sdim      break;
2268224145Sdim    case Declarator::TypeNameContext:
2269251662Sdim    case Declarator::ConversionIdContext:
2270224145Sdim    case Declarator::TemplateParamContext:
2271224145Sdim    case Declarator::CXXNewContext:
2272224145Sdim    case Declarator::CXXCatchContext:
2273224145Sdim    case Declarator::ObjCCatchContext:
2274224145Sdim    case Declarator::TemplateTypeArgContext:
2275224145Sdim      SemaRef.Diag(OwnedTagDecl->getLocation(),
2276224145Sdim             diag::err_type_defined_in_type_specifier)
2277224145Sdim        << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2278249423Sdim      D.setInvalidType(true);
2279224145Sdim      break;
2280224145Sdim    case Declarator::PrototypeContext:
2281263508Sdim    case Declarator::LambdaExprParameterContext:
2282226633Sdim    case Declarator::ObjCParameterContext:
2283226633Sdim    case Declarator::ObjCResultContext:
2284224145Sdim    case Declarator::KNRTypeListContext:
2285224145Sdim      // C++ [dcl.fct]p6:
2286224145Sdim      //   Types shall not be defined in return or parameter types.
2287224145Sdim      SemaRef.Diag(OwnedTagDecl->getLocation(),
2288224145Sdim                   diag::err_type_defined_in_param_type)
2289224145Sdim        << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2290249423Sdim      D.setInvalidType(true);
2291224145Sdim      break;
2292224145Sdim    case Declarator::ConditionContext:
2293224145Sdim      // C++ 6.4p2:
2294224145Sdim      // The type-specifier-seq shall not contain typedef and shall not declare
2295224145Sdim      // a new class or enumeration.
2296224145Sdim      SemaRef.Diag(OwnedTagDecl->getLocation(),
2297224145Sdim                   diag::err_type_defined_in_condition);
2298249423Sdim      D.setInvalidType(true);
2299224145Sdim      break;
2300224145Sdim    }
2301224145Sdim  }
2302224145Sdim
2303224145Sdim  return T;
2304224145Sdim}
2305224145Sdim
2306234353Sdimstatic std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2307234353Sdim  std::string Quals =
2308234353Sdim    Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2309234353Sdim
2310234353Sdim  switch (FnTy->getRefQualifier()) {
2311234353Sdim  case RQ_None:
2312234353Sdim    break;
2313234353Sdim
2314234353Sdim  case RQ_LValue:
2315234353Sdim    if (!Quals.empty())
2316234353Sdim      Quals += ' ';
2317234353Sdim    Quals += '&';
2318234353Sdim    break;
2319234353Sdim
2320234353Sdim  case RQ_RValue:
2321234353Sdim    if (!Quals.empty())
2322234353Sdim      Quals += ' ';
2323234353Sdim    Quals += "&&";
2324234353Sdim    break;
2325234353Sdim  }
2326234353Sdim
2327234353Sdim  return Quals;
2328234353Sdim}
2329234353Sdim
2330234353Sdim/// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
2331234353Sdim/// can be contained within the declarator chunk DeclType, and produce an
2332234353Sdim/// appropriate diagnostic if not.
2333234353Sdimstatic void checkQualifiedFunction(Sema &S, QualType T,
2334234353Sdim                                   DeclaratorChunk &DeclType) {
2335234353Sdim  // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
2336234353Sdim  // cv-qualifier or a ref-qualifier can only appear at the topmost level
2337234353Sdim  // of a type.
2338234353Sdim  int DiagKind = -1;
2339234353Sdim  switch (DeclType.Kind) {
2340234353Sdim  case DeclaratorChunk::Paren:
2341234353Sdim  case DeclaratorChunk::MemberPointer:
2342234353Sdim    // These cases are permitted.
2343234353Sdim    return;
2344234353Sdim  case DeclaratorChunk::Array:
2345234353Sdim  case DeclaratorChunk::Function:
2346234353Sdim    // These cases don't allow function types at all; no need to diagnose the
2347234353Sdim    // qualifiers separately.
2348234353Sdim    return;
2349234353Sdim  case DeclaratorChunk::BlockPointer:
2350234353Sdim    DiagKind = 0;
2351234353Sdim    break;
2352234353Sdim  case DeclaratorChunk::Pointer:
2353234353Sdim    DiagKind = 1;
2354234353Sdim    break;
2355234353Sdim  case DeclaratorChunk::Reference:
2356234353Sdim    DiagKind = 2;
2357234353Sdim    break;
2358234353Sdim  }
2359234353Sdim
2360234353Sdim  assert(DiagKind != -1);
2361234353Sdim  S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
2362234353Sdim    << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
2363234353Sdim    << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
2364234353Sdim}
2365234353Sdim
2366239462Sdim/// Produce an approprioate diagnostic for an ambiguity between a function
2367239462Sdim/// declarator and a C++ direct-initializer.
2368239462Sdimstatic void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2369239462Sdim                                       DeclaratorChunk &DeclType, QualType RT) {
2370239462Sdim  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2371239462Sdim  assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2372239462Sdim
2373239462Sdim  // If the return type is void there is no ambiguity.
2374239462Sdim  if (RT->isVoidType())
2375239462Sdim    return;
2376239462Sdim
2377239462Sdim  // An initializer for a non-class type can have at most one argument.
2378239462Sdim  if (!RT->isRecordType() && FTI.NumArgs > 1)
2379239462Sdim    return;
2380239462Sdim
2381239462Sdim  // An initializer for a reference must have exactly one argument.
2382239462Sdim  if (RT->isReferenceType() && FTI.NumArgs != 1)
2383239462Sdim    return;
2384239462Sdim
2385239462Sdim  // Only warn if this declarator is declaring a function at block scope, and
2386239462Sdim  // doesn't have a storage class (such as 'extern') specified.
2387239462Sdim  if (!D.isFunctionDeclarator() ||
2388239462Sdim      D.getFunctionDefinitionKind() != FDK_Declaration ||
2389239462Sdim      !S.CurContext->isFunctionOrMethod() ||
2390249423Sdim      D.getDeclSpec().getStorageClassSpec()
2391239462Sdim        != DeclSpec::SCS_unspecified)
2392239462Sdim    return;
2393239462Sdim
2394239462Sdim  // Inside a condition, a direct initializer is not permitted. We allow one to
2395239462Sdim  // be parsed in order to give better diagnostics in condition parsing.
2396239462Sdim  if (D.getContext() == Declarator::ConditionContext)
2397239462Sdim    return;
2398239462Sdim
2399239462Sdim  SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2400239462Sdim
2401239462Sdim  S.Diag(DeclType.Loc,
2402239462Sdim         FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration
2403239462Sdim                     : diag::warn_empty_parens_are_function_decl)
2404239462Sdim    << ParenRange;
2405239462Sdim
2406239462Sdim  // If the declaration looks like:
2407239462Sdim  //   T var1,
2408239462Sdim  //   f();
2409239462Sdim  // and name lookup finds a function named 'f', then the ',' was
2410239462Sdim  // probably intended to be a ';'.
2411239462Sdim  if (!D.isFirstDeclarator() && D.getIdentifier()) {
2412239462Sdim    FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2413239462Sdim    FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2414239462Sdim    if (Comma.getFileID() != Name.getFileID() ||
2415239462Sdim        Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2416239462Sdim      LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2417239462Sdim                          Sema::LookupOrdinaryName);
2418239462Sdim      if (S.LookupName(Result, S.getCurScope()))
2419239462Sdim        S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2420239462Sdim          << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2421239462Sdim          << D.getIdentifier();
2422239462Sdim    }
2423239462Sdim  }
2424239462Sdim
2425239462Sdim  if (FTI.NumArgs > 0) {
2426239462Sdim    // For a declaration with parameters, eg. "T var(T());", suggest adding parens
2427239462Sdim    // around the first parameter to turn the declaration into a variable
2428239462Sdim    // declaration.
2429239462Sdim    SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange();
2430239462Sdim    SourceLocation B = Range.getBegin();
2431239462Sdim    SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd());
2432239462Sdim    // FIXME: Maybe we should suggest adding braces instead of parens
2433239462Sdim    // in C++11 for classes that don't have an initializer_list constructor.
2434239462Sdim    S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2435239462Sdim      << FixItHint::CreateInsertion(B, "(")
2436239462Sdim      << FixItHint::CreateInsertion(E, ")");
2437239462Sdim  } else {
2438239462Sdim    // For a declaration without parameters, eg. "T var();", suggest replacing the
2439239462Sdim    // parens with an initializer to turn the declaration into a variable
2440239462Sdim    // declaration.
2441239462Sdim    const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2442239462Sdim
2443239462Sdim    // Empty parens mean value-initialization, and no parens mean
2444239462Sdim    // default initialization. These are equivalent if the default
2445239462Sdim    // constructor is user-provided or if zero-initialization is a
2446239462Sdim    // no-op.
2447239462Sdim    if (RD && RD->hasDefinition() &&
2448239462Sdim        (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2449239462Sdim      S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2450239462Sdim        << FixItHint::CreateRemoval(ParenRange);
2451239462Sdim    else {
2452263508Sdim      std::string Init =
2453263508Sdim          S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2454249423Sdim      if (Init.empty() && S.LangOpts.CPlusPlus11)
2455239462Sdim        Init = "{}";
2456239462Sdim      if (!Init.empty())
2457239462Sdim        S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2458239462Sdim          << FixItHint::CreateReplacement(ParenRange, Init);
2459239462Sdim    }
2460239462Sdim  }
2461239462Sdim}
2462239462Sdim
2463263508Sdim/// Helper for figuring out the default CC for a function declarator type.  If
2464263508Sdim/// this is the outermost chunk, then we can determine the CC from the
2465263508Sdim/// declarator context.  If not, then this could be either a member function
2466263508Sdim/// type or normal function type.
2467263508Sdimstatic CallingConv
2468263508SdimgetCCForDeclaratorChunk(Sema &S, Declarator &D,
2469263508Sdim                        const DeclaratorChunk::FunctionTypeInfo &FTI,
2470263508Sdim                        unsigned ChunkIndex) {
2471263508Sdim  assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2472263508Sdim
2473263508Sdim  bool IsCXXInstanceMethod = false;
2474263508Sdim
2475263508Sdim  if (S.getLangOpts().CPlusPlus) {
2476263508Sdim    // Look inwards through parentheses to see if this chunk will form a
2477263508Sdim    // member pointer type or if we're the declarator.  Any type attributes
2478263508Sdim    // between here and there will override the CC we choose here.
2479263508Sdim    unsigned I = ChunkIndex;
2480263508Sdim    bool FoundNonParen = false;
2481263508Sdim    while (I && !FoundNonParen) {
2482263508Sdim      --I;
2483263508Sdim      if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2484263508Sdim        FoundNonParen = true;
2485263508Sdim    }
2486263508Sdim
2487263508Sdim    if (FoundNonParen) {
2488263508Sdim      // If we're not the declarator, we're a regular function type unless we're
2489263508Sdim      // in a member pointer.
2490263508Sdim      IsCXXInstanceMethod =
2491263508Sdim          D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2492263508Sdim    } else {
2493263508Sdim      // We're the innermost decl chunk, so must be a function declarator.
2494263508Sdim      assert(D.isFunctionDeclarator());
2495263508Sdim
2496263508Sdim      // If we're inside a record, we're declaring a method, but it could be
2497263508Sdim      // explicitly or implicitly static.
2498263508Sdim      IsCXXInstanceMethod =
2499263508Sdim          D.isFirstDeclarationOfMember() &&
2500263508Sdim          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2501263508Sdim          !D.isStaticMember();
2502263508Sdim    }
2503263508Sdim  }
2504263508Sdim
2505263508Sdim  return S.Context.getDefaultCallingConvention(FTI.isVariadic,
2506263508Sdim                                               IsCXXInstanceMethod);
2507263508Sdim}
2508263508Sdim
2509224145Sdimstatic TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2510224145Sdim                                                QualType declSpecType,
2511224145Sdim                                                TypeSourceInfo *TInfo) {
2512224145Sdim
2513224145Sdim  QualType T = declSpecType;
2514224145Sdim  Declarator &D = state.getDeclarator();
2515224145Sdim  Sema &S = state.getSema();
2516224145Sdim  ASTContext &Context = S.Context;
2517234353Sdim  const LangOptions &LangOpts = S.getLangOpts();
2518224145Sdim
2519193326Sed  // The name we're declaring, if any.
2520193326Sed  DeclarationName Name;
2521193326Sed  if (D.getIdentifier())
2522193326Sed    Name = D.getIdentifier();
2523193326Sed
2524221345Sdim  // Does this declaration declare a typedef-name?
2525221345Sdim  bool IsTypedefName =
2526221345Sdim    D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2527223017Sdim    D.getContext() == Declarator::AliasDeclContext ||
2528223017Sdim    D.getContext() == Declarator::AliasTemplateContext;
2529221345Sdim
2530234353Sdim  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2531234353Sdim  bool IsQualifiedFunction = T->isFunctionProtoType() &&
2532234353Sdim      (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2533234353Sdim       T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2534234353Sdim
2535251662Sdim  // If T is 'decltype(auto)', the only declarators we can have are parens
2536251662Sdim  // and at most one function declarator if this is a function declaration.
2537251662Sdim  if (const AutoType *AT = T->getAs<AutoType>()) {
2538251662Sdim    if (AT->isDecltypeAuto()) {
2539251662Sdim      for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2540251662Sdim        unsigned Index = E - I - 1;
2541251662Sdim        DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
2542251662Sdim        unsigned DiagId = diag::err_decltype_auto_compound_type;
2543251662Sdim        unsigned DiagKind = 0;
2544251662Sdim        switch (DeclChunk.Kind) {
2545251662Sdim        case DeclaratorChunk::Paren:
2546251662Sdim          continue;
2547251662Sdim        case DeclaratorChunk::Function: {
2548251662Sdim          unsigned FnIndex;
2549251662Sdim          if (D.isFunctionDeclarationContext() &&
2550251662Sdim              D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
2551251662Sdim            continue;
2552251662Sdim          DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
2553251662Sdim          break;
2554251662Sdim        }
2555251662Sdim        case DeclaratorChunk::Pointer:
2556251662Sdim        case DeclaratorChunk::BlockPointer:
2557251662Sdim        case DeclaratorChunk::MemberPointer:
2558251662Sdim          DiagKind = 0;
2559251662Sdim          break;
2560251662Sdim        case DeclaratorChunk::Reference:
2561251662Sdim          DiagKind = 1;
2562251662Sdim          break;
2563251662Sdim        case DeclaratorChunk::Array:
2564251662Sdim          DiagKind = 2;
2565251662Sdim          break;
2566251662Sdim        }
2567251662Sdim
2568251662Sdim        S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
2569251662Sdim        D.setInvalidType(true);
2570251662Sdim        break;
2571251662Sdim      }
2572251662Sdim    }
2573251662Sdim  }
2574251662Sdim
2575193326Sed  // Walk the DeclTypeInfo, building the recursive type as we go.
2576193326Sed  // DeclTypeInfos are ordered from the identifier out, which is
2577193326Sed  // opposite of what we want :).
2578198893Srdivacky  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2579218893Sdim    unsigned chunkIndex = e - i - 1;
2580218893Sdim    state.setCurrentChunkIndex(chunkIndex);
2581218893Sdim    DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2582234353Sdim    if (IsQualifiedFunction) {
2583234353Sdim      checkQualifiedFunction(S, T, DeclType);
2584234353Sdim      IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
2585234353Sdim    }
2586193326Sed    switch (DeclType.Kind) {
2587218893Sdim    case DeclaratorChunk::Paren:
2588224145Sdim      T = S.BuildParenType(T);
2589218893Sdim      break;
2590193326Sed    case DeclaratorChunk::BlockPointer:
2591193326Sed      // If blocks are disabled, emit an error.
2592193326Sed      if (!LangOpts.Blocks)
2593224145Sdim        S.Diag(DeclType.Loc, diag::err_blocks_disable);
2594198092Srdivacky
2595224145Sdim      T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
2596210299Sed      if (DeclType.Cls.TypeQuals)
2597224145Sdim        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
2598193326Sed      break;
2599193326Sed    case DeclaratorChunk::Pointer:
2600193326Sed      // Verify that we're not building a pointer to pointer to function with
2601193326Sed      // exception specification.
2602224145Sdim      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2603224145Sdim        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2604193326Sed        D.setInvalidType(true);
2605193326Sed        // Build the type anyway.
2606193326Sed      }
2607224145Sdim      if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
2608208600Srdivacky        T = Context.getObjCObjectPointerType(T);
2609210299Sed        if (DeclType.Ptr.TypeQuals)
2610224145Sdim          T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2611198092Srdivacky        break;
2612198092Srdivacky      }
2613224145Sdim      T = S.BuildPointerType(T, DeclType.Loc, Name);
2614210299Sed      if (DeclType.Ptr.TypeQuals)
2615224145Sdim        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2616218893Sdim
2617193326Sed      break;
2618198092Srdivacky    case DeclaratorChunk::Reference: {
2619193326Sed      // Verify that we're not building a reference to pointer to function with
2620193326Sed      // exception specification.
2621224145Sdim      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2622224145Sdim        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2623193326Sed        D.setInvalidType(true);
2624193326Sed        // Build the type anyway.
2625193326Sed      }
2626224145Sdim      T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
2627210299Sed
2628210299Sed      Qualifiers Quals;
2629210299Sed      if (DeclType.Ref.HasRestrict)
2630224145Sdim        T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
2631193326Sed      break;
2632198092Srdivacky    }
2633193326Sed    case DeclaratorChunk::Array: {
2634193326Sed      // Verify that we're not building an array of pointers to function with
2635193326Sed      // exception specification.
2636224145Sdim      if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2637224145Sdim        S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2638193326Sed        D.setInvalidType(true);
2639193326Sed        // Build the type anyway.
2640193326Sed      }
2641193326Sed      DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2642193326Sed      Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2643193326Sed      ArrayType::ArraySizeModifier ASM;
2644193326Sed      if (ATI.isStar)
2645193326Sed        ASM = ArrayType::Star;
2646193326Sed      else if (ATI.hasStatic)
2647193326Sed        ASM = ArrayType::Static;
2648193326Sed      else
2649193326Sed        ASM = ArrayType::Normal;
2650221345Sdim      if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2651193326Sed        // FIXME: This check isn't quite right: it allows star in prototypes
2652193326Sed        // for function definitions, and disallows some edge cases detailed
2653193326Sed        // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2654224145Sdim        S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2655193326Sed        ASM = ArrayType::Normal;
2656193326Sed        D.setInvalidType(true);
2657193326Sed      }
2658239462Sdim
2659239462Sdim      // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2660239462Sdim      // shall appear only in a declaration of a function parameter with an
2661239462Sdim      // array type, ...
2662239462Sdim      if (ASM == ArrayType::Static || ATI.TypeQuals) {
2663239462Sdim        if (!(D.isPrototypeContext() ||
2664239462Sdim              D.getContext() == Declarator::KNRTypeListContext)) {
2665239462Sdim          S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2666239462Sdim              (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2667239462Sdim          // Remove the 'static' and the type qualifiers.
2668239462Sdim          if (ASM == ArrayType::Static)
2669239462Sdim            ASM = ArrayType::Normal;
2670239462Sdim          ATI.TypeQuals = 0;
2671239462Sdim          D.setInvalidType(true);
2672239462Sdim        }
2673239462Sdim
2674239462Sdim        // C99 6.7.5.2p1: ... and then only in the outermost array type
2675239462Sdim        // derivation.
2676239462Sdim        unsigned x = chunkIndex;
2677239462Sdim        while (x != 0) {
2678239462Sdim          // Walk outwards along the declarator chunks.
2679239462Sdim          x--;
2680239462Sdim          const DeclaratorChunk &DC = D.getTypeObject(x);
2681239462Sdim          switch (DC.Kind) {
2682239462Sdim          case DeclaratorChunk::Paren:
2683239462Sdim            continue;
2684239462Sdim          case DeclaratorChunk::Array:
2685239462Sdim          case DeclaratorChunk::Pointer:
2686239462Sdim          case DeclaratorChunk::Reference:
2687239462Sdim          case DeclaratorChunk::MemberPointer:
2688239462Sdim            S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2689239462Sdim              (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2690239462Sdim            if (ASM == ArrayType::Static)
2691239462Sdim              ASM = ArrayType::Normal;
2692239462Sdim            ATI.TypeQuals = 0;
2693239462Sdim            D.setInvalidType(true);
2694239462Sdim            break;
2695239462Sdim          case DeclaratorChunk::Function:
2696239462Sdim          case DeclaratorChunk::BlockPointer:
2697239462Sdim            // These are invalid anyway, so just ignore.
2698239462Sdim            break;
2699239462Sdim          }
2700239462Sdim        }
2701239462Sdim      }
2702263508Sdim      const AutoType *AT = T->getContainedAutoType();
2703263508Sdim      // Allow arrays of auto if we are a generic lambda parameter.
2704263508Sdim      // i.e. [](auto (&array)[5]) { return array[0]; }; OK
2705263508Sdim      if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
2706251662Sdim        // We've already diagnosed this for decltype(auto).
2707251662Sdim        if (!AT->isDecltypeAuto())
2708251662Sdim          S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
2709251662Sdim            << getPrintableNameForEntity(Name) << T;
2710251662Sdim        T = QualType();
2711251662Sdim        break;
2712251662Sdim      }
2713251662Sdim
2714234353Sdim      T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
2715224145Sdim                           SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2716193326Sed      break;
2717193326Sed    }
2718193326Sed    case DeclaratorChunk::Function: {
2719193326Sed      // If the function declarator has a prototype (i.e. it is not () and
2720193326Sed      // does not have a K&R-style identifier list), then the arguments are part
2721193326Sed      // of the type, otherwise the argument list is ().
2722193326Sed      const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2723234353Sdim      IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
2724193326Sed
2725218893Sdim      // Check for auto functions and trailing return type and adjust the
2726218893Sdim      // return type accordingly.
2727218893Sdim      if (!D.isInvalidType()) {
2728218893Sdim        // trailing-return-type is only required if we're declaring a function,
2729218893Sdim        // and not, for instance, a pointer to a function.
2730218893Sdim        if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2731251662Sdim            !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
2732251662Sdim            !S.getLangOpts().CPlusPlus1y) {
2733224145Sdim          S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2734218893Sdim               diag::err_auto_missing_trailing_return);
2735218893Sdim          T = Context.IntTy;
2736218893Sdim          D.setInvalidType(true);
2737239462Sdim        } else if (FTI.hasTrailingReturnType()) {
2738219077Sdim          // T must be exactly 'auto' at this point. See CWG issue 681.
2739219077Sdim          if (isa<ParenType>(T)) {
2740224145Sdim            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2741219077Sdim                 diag::err_trailing_return_in_parens)
2742219077Sdim              << T << D.getDeclSpec().getSourceRange();
2743219077Sdim            D.setInvalidType(true);
2744234353Sdim          } else if (D.getContext() != Declarator::LambdaExprContext &&
2745251662Sdim                     (T.hasQualifiers() || !isa<AutoType>(T) ||
2746251662Sdim                      cast<AutoType>(T)->isDecltypeAuto())) {
2747224145Sdim            S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2748218893Sdim                 diag::err_trailing_return_without_auto)
2749218893Sdim              << T << D.getDeclSpec().getSourceRange();
2750218893Sdim            D.setInvalidType(true);
2751218893Sdim          }
2752239462Sdim          T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2753239462Sdim          if (T.isNull()) {
2754239462Sdim            // An error occurred parsing the trailing return type.
2755239462Sdim            T = Context.IntTy;
2756239462Sdim            D.setInvalidType(true);
2757239462Sdim          }
2758218893Sdim        }
2759218893Sdim      }
2760218893Sdim
2761219077Sdim      // C99 6.7.5.3p1: The return type may not be a function or array type.
2762219077Sdim      // For conversion functions, we'll diagnose this particular error later.
2763219077Sdim      if ((T->isArrayType() || T->isFunctionType()) &&
2764219077Sdim          (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2765219077Sdim        unsigned diagID = diag::err_func_returning_array_function;
2766219077Sdim        // Last processing chunk in block context means this function chunk
2767219077Sdim        // represents the block.
2768219077Sdim        if (chunkIndex == 0 &&
2769219077Sdim            D.getContext() == Declarator::BlockLiteralContext)
2770219077Sdim          diagID = diag::err_block_returning_array_function;
2771224145Sdim        S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2772219077Sdim        T = Context.IntTy;
2773219077Sdim        D.setInvalidType(true);
2774219077Sdim      }
2775219077Sdim
2776226633Sdim      // Do not allow returning half FP value.
2777226633Sdim      // FIXME: This really should be in BuildFunctionType.
2778226633Sdim      if (T->isHalfType()) {
2779249423Sdim        if (S.getLangOpts().OpenCL) {
2780249423Sdim          if (!S.getOpenCLOptions().cl_khr_fp16) {
2781249423Sdim            S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
2782249423Sdim            D.setInvalidType(true);
2783249423Sdim          }
2784249423Sdim        } else {
2785249423Sdim          S.Diag(D.getIdentifierLoc(),
2786249423Sdim            diag::err_parameters_retval_cannot_have_fp16_type) << 1;
2787249423Sdim          D.setInvalidType(true);
2788249423Sdim        }
2789226633Sdim      }
2790226633Sdim
2791263508Sdim      // Methods cannot return interface types. All ObjC objects are
2792263508Sdim      // passed by reference.
2793263508Sdim      if (T->isObjCObjectType()) {
2794263508Sdim        SourceLocation DiagLoc, FixitLoc;
2795263508Sdim        if (TInfo) {
2796263508Sdim          DiagLoc = TInfo->getTypeLoc().getLocStart();
2797263508Sdim          FixitLoc = S.PP.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
2798263508Sdim        } else {
2799263508Sdim          DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
2800263508Sdim          FixitLoc = S.PP.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
2801263508Sdim        }
2802263508Sdim        S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
2803263508Sdim          << 0 << T
2804263508Sdim          << FixItHint::CreateInsertion(FixitLoc, "*");
2805263508Sdim
2806263508Sdim        T = Context.getObjCObjectPointerType(T);
2807263508Sdim        if (TInfo) {
2808263508Sdim          TypeLocBuilder TLB;
2809263508Sdim          TLB.pushFullCopy(TInfo->getTypeLoc());
2810263508Sdim          ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
2811263508Sdim          TLoc.setStarLoc(FixitLoc);
2812263508Sdim          TInfo = TLB.getTypeSourceInfo(Context, T);
2813263508Sdim        }
2814263508Sdim
2815263508Sdim        D.setInvalidType(true);
2816263508Sdim      }
2817263508Sdim
2818210299Sed      // cv-qualifiers on return types are pointless except when the type is a
2819210299Sed      // class type in C++.
2820249423Sdim      if ((T.getCVRQualifiers() || T->isAtomicType()) &&
2821249423Sdim          !(S.getLangOpts().CPlusPlus &&
2822249423Sdim            (T->isDependentType() || T->isRecordType())))
2823249423Sdim        diagnoseIgnoredFunctionQualifiers(S, T, D, chunkIndex);
2824219077Sdim
2825249423Sdim      // Objective-C ARC ownership qualifiers are ignored on the function
2826249423Sdim      // return type (by type canonicalization). Complain if this attribute
2827249423Sdim      // was written here.
2828249423Sdim      if (T.getQualifiers().hasObjCLifetime()) {
2829249423Sdim        SourceLocation AttrLoc;
2830249423Sdim        if (chunkIndex + 1 < D.getNumTypeObjects()) {
2831249423Sdim          DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2832249423Sdim          for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
2833249423Sdim               Attr; Attr = Attr->getNext()) {
2834249423Sdim            if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2835249423Sdim              AttrLoc = Attr->getLoc();
2836249423Sdim              break;
2837249423Sdim            }
2838249423Sdim          }
2839249423Sdim        }
2840249423Sdim        if (AttrLoc.isInvalid()) {
2841249423Sdim          for (const AttributeList *Attr
2842249423Sdim                 = D.getDeclSpec().getAttributes().getList();
2843249423Sdim               Attr; Attr = Attr->getNext()) {
2844249423Sdim            if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2845249423Sdim              AttrLoc = Attr->getLoc();
2846249423Sdim              break;
2847249423Sdim            }
2848249423Sdim          }
2849249423Sdim        }
2850219077Sdim
2851249423Sdim        if (AttrLoc.isValid()) {
2852249423Sdim          // The ownership attributes are almost always written via
2853249423Sdim          // the predefined
2854249423Sdim          // __strong/__weak/__autoreleasing/__unsafe_unretained.
2855249423Sdim          if (AttrLoc.isMacroID())
2856249423Sdim            AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
2857219077Sdim
2858249423Sdim          S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
2859249423Sdim            << T.getQualifiers().getObjCLifetime();
2860249423Sdim        }
2861210299Sed      }
2862219077Sdim
2863263508Sdim      if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
2864193326Sed        // C++ [dcl.fct]p6:
2865193326Sed        //   Types shall not be defined in return or parameter types.
2866212904Sdim        TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2867263508Sdim        S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2868263508Sdim          << Context.getTypeDeclType(Tag);
2869193326Sed      }
2870193326Sed
2871193326Sed      // Exception specs are not allowed in typedefs. Complain, but add it
2872193326Sed      // anyway.
2873221345Sdim      if (IsTypedefName && FTI.getExceptionSpecType())
2874224145Sdim        S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2875223017Sdim          << (D.getContext() == Declarator::AliasDeclContext ||
2876223017Sdim              D.getContext() == Declarator::AliasTemplateContext);
2877193326Sed
2878239462Sdim      // If we see "T var();" or "T var(T());" at block scope, it is probably
2879239462Sdim      // an attempt to initialize a variable, not a function declaration.
2880239462Sdim      if (FTI.isAmbiguous)
2881239462Sdim        warnAboutAmbiguousFunction(S, D, DeclType, T);
2882239462Sdim
2883263508Sdim      FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
2884263508Sdim
2885224145Sdim      if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2886210299Sed        // Simple void foo(), where the incoming T is the result type.
2887263508Sdim        T = Context.getFunctionNoProtoType(T, EI);
2888210299Sed      } else {
2889210299Sed        // We allow a zero-parameter variadic function in C if the
2890210299Sed        // function is marked with the "overloadable" attribute. Scan
2891210299Sed        // for this attribute now.
2892224145Sdim        if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
2893193326Sed          bool Overloadable = false;
2894193326Sed          for (const AttributeList *Attrs = D.getAttributes();
2895193326Sed               Attrs; Attrs = Attrs->getNext()) {
2896239462Sdim            if (Attrs->getKind() == AttributeList::AT_Overloadable) {
2897193326Sed              Overloadable = true;
2898193326Sed              break;
2899193326Sed            }
2900193326Sed          }
2901193326Sed
2902193326Sed          if (!Overloadable)
2903224145Sdim            S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
2904193326Sed        }
2905210299Sed
2906210299Sed        if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
2907210299Sed          // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2908210299Sed          // definition.
2909224145Sdim          S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
2910210299Sed          D.setInvalidType(true);
2911249423Sdim          // Recover by creating a K&R-style function type.
2912263508Sdim          T = Context.getFunctionNoProtoType(T, EI);
2913210299Sed          break;
2914210299Sed        }
2915210299Sed
2916218893Sdim        FunctionProtoType::ExtProtoInfo EPI;
2917263508Sdim        EPI.ExtInfo = EI;
2918218893Sdim        EPI.Variadic = FTI.isVariadic;
2919239462Sdim        EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
2920218893Sdim        EPI.TypeQuals = FTI.TypeQuals;
2921218893Sdim        EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2922218893Sdim                    : FTI.RefQualifierIsLValueRef? RQ_LValue
2923218893Sdim                    : RQ_RValue;
2924239462Sdim
2925193326Sed        // Otherwise, we have a function with an argument list that is
2926193326Sed        // potentially variadic.
2927226633Sdim        SmallVector<QualType, 16> ArgTys;
2928210299Sed        ArgTys.reserve(FTI.NumArgs);
2929198092Srdivacky
2930226633Sdim        SmallVector<bool, 16> ConsumedArguments;
2931224145Sdim        ConsumedArguments.reserve(FTI.NumArgs);
2932224145Sdim        bool HasAnyConsumedArguments = false;
2933224145Sdim
2934193326Sed        for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2935212904Sdim          ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2936193326Sed          QualType ArgTy = Param->getType();
2937193326Sed          assert(!ArgTy.isNull() && "Couldn't parse type?");
2938193326Sed
2939193326Sed          // Look for 'void'.  void is allowed only as a single argument to a
2940193326Sed          // function with no other parameters (C99 6.7.5.3p10).  We record
2941193326Sed          // int(void) as a FunctionProtoType with an empty argument list.
2942193326Sed          if (ArgTy->isVoidType()) {
2943193326Sed            // If this is something like 'float(int, void)', reject it.  'void'
2944193326Sed            // is an incomplete type (C99 6.2.5p19) and function decls cannot
2945193326Sed            // have arguments of incomplete type.
2946193326Sed            if (FTI.NumArgs != 1 || FTI.isVariadic) {
2947224145Sdim              S.Diag(DeclType.Loc, diag::err_void_only_param);
2948193326Sed              ArgTy = Context.IntTy;
2949193326Sed              Param->setType(ArgTy);
2950193326Sed            } else if (FTI.ArgInfo[i].Ident) {
2951193326Sed              // Reject, but continue to parse 'int(void abc)'.
2952224145Sdim              S.Diag(FTI.ArgInfo[i].IdentLoc,
2953193326Sed                   diag::err_param_with_void_type);
2954193326Sed              ArgTy = Context.IntTy;
2955193326Sed              Param->setType(ArgTy);
2956193326Sed            } else {
2957193326Sed              // Reject, but continue to parse 'float(const void)'.
2958198092Srdivacky              if (ArgTy.hasQualifiers())
2959224145Sdim                S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2960198092Srdivacky
2961193326Sed              // Do not add 'void' to the ArgTys list.
2962193326Sed              break;
2963193326Sed            }
2964226633Sdim          } else if (ArgTy->isHalfType()) {
2965226633Sdim            // Disallow half FP arguments.
2966226633Sdim            // FIXME: This really should be in BuildFunctionType.
2967249423Sdim            if (S.getLangOpts().OpenCL) {
2968249423Sdim              if (!S.getOpenCLOptions().cl_khr_fp16) {
2969249423Sdim                S.Diag(Param->getLocation(),
2970249423Sdim                  diag::err_opencl_half_argument) << ArgTy;
2971249423Sdim                D.setInvalidType();
2972249423Sdim                Param->setInvalidDecl();
2973249423Sdim              }
2974249423Sdim            } else {
2975249423Sdim              S.Diag(Param->getLocation(),
2976249423Sdim                diag::err_parameters_retval_cannot_have_fp16_type) << 0;
2977249423Sdim              D.setInvalidType();
2978249423Sdim            }
2979193326Sed          } else if (!FTI.hasPrototype) {
2980193326Sed            if (ArgTy->isPromotableIntegerType()) {
2981198092Srdivacky              ArgTy = Context.getPromotedIntegerType(ArgTy);
2982221345Sdim              Param->setKNRPromoted(true);
2983198092Srdivacky            } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
2984221345Sdim              if (BTy->getKind() == BuiltinType::Float) {
2985193326Sed                ArgTy = Context.DoubleTy;
2986221345Sdim                Param->setKNRPromoted(true);
2987221345Sdim              }
2988193326Sed            }
2989193326Sed          }
2990198092Srdivacky
2991224145Sdim          if (LangOpts.ObjCAutoRefCount) {
2992224145Sdim            bool Consumed = Param->hasAttr<NSConsumedAttr>();
2993224145Sdim            ConsumedArguments.push_back(Consumed);
2994224145Sdim            HasAnyConsumedArguments |= Consumed;
2995224145Sdim          }
2996224145Sdim
2997198398Srdivacky          ArgTys.push_back(ArgTy);
2998193326Sed        }
2999193326Sed
3000224145Sdim        if (HasAnyConsumedArguments)
3001224145Sdim          EPI.ConsumedArguments = ConsumedArguments.data();
3002224145Sdim
3003226633Sdim        SmallVector<QualType, 4> Exceptions;
3004234982Sdim        SmallVector<ParsedType, 2> DynamicExceptions;
3005234982Sdim        SmallVector<SourceRange, 2> DynamicExceptionRanges;
3006234982Sdim        Expr *NoexceptExpr = 0;
3007239462Sdim
3008221345Sdim        if (FTI.getExceptionSpecType() == EST_Dynamic) {
3009234982Sdim          // FIXME: It's rather inefficient to have to split into two vectors
3010234982Sdim          // here.
3011234982Sdim          unsigned N = FTI.NumExceptions;
3012234982Sdim          DynamicExceptions.reserve(N);
3013234982Sdim          DynamicExceptionRanges.reserve(N);
3014234982Sdim          for (unsigned I = 0; I != N; ++I) {
3015234982Sdim            DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
3016234982Sdim            DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
3017218893Sdim          }
3018221345Sdim        } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
3019234982Sdim          NoexceptExpr = FTI.NoexceptExpr;
3020234982Sdim        }
3021239462Sdim
3022234982Sdim        S.checkExceptionSpecification(FTI.getExceptionSpecType(),
3023234982Sdim                                      DynamicExceptions,
3024234982Sdim                                      DynamicExceptionRanges,
3025234982Sdim                                      NoexceptExpr,
3026234982Sdim                                      Exceptions,
3027234982Sdim                                      EPI);
3028239462Sdim
3029249423Sdim        T = Context.getFunctionType(T, ArgTys, EPI);
3030193326Sed      }
3031203955Srdivacky
3032193326Sed      break;
3033193326Sed    }
3034193326Sed    case DeclaratorChunk::MemberPointer:
3035193326Sed      // The scope spec must refer to a class, or be dependent.
3036212904Sdim      CXXScopeSpec &SS = DeclType.Mem.Scope();
3037193326Sed      QualType ClsType;
3038212904Sdim      if (SS.isInvalid()) {
3039207619Srdivacky        // Avoid emitting extra errors if we already errored on the scope.
3040207619Srdivacky        D.setInvalidType(true);
3041224145Sdim      } else if (S.isDependentScopeSpecifier(SS) ||
3042224145Sdim                 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
3043198092Srdivacky        NestedNameSpecifier *NNS
3044212904Sdim          = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3045198954Srdivacky        NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
3046198954Srdivacky        switch (NNS->getKind()) {
3047198954Srdivacky        case NestedNameSpecifier::Identifier:
3048212904Sdim          ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
3049206084Srdivacky                                                 NNS->getAsIdentifier());
3050198954Srdivacky          break;
3051198954Srdivacky
3052198954Srdivacky        case NestedNameSpecifier::Namespace:
3053219077Sdim        case NestedNameSpecifier::NamespaceAlias:
3054198954Srdivacky        case NestedNameSpecifier::Global:
3055200583Srdivacky          llvm_unreachable("Nested-name-specifier must name a type");
3056212904Sdim
3057198954Srdivacky        case NestedNameSpecifier::TypeSpec:
3058198954Srdivacky        case NestedNameSpecifier::TypeSpecWithTemplate:
3059198954Srdivacky          ClsType = QualType(NNS->getAsType(), 0);
3060221345Sdim          // Note: if the NNS has a prefix and ClsType is a nondependent
3061221345Sdim          // TemplateSpecializationType, then the NNS prefix is NOT included
3062221345Sdim          // in ClsType; hence we wrap ClsType into an ElaboratedType.
3063221345Sdim          // NOTE: in particular, no wrap occurs if ClsType already is an
3064221345Sdim          // Elaborated, DependentName, or DependentTemplateSpecialization.
3065221345Sdim          if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
3066208600Srdivacky            ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
3067198954Srdivacky          break;
3068198954Srdivacky        }
3069193326Sed      } else {
3070224145Sdim        S.Diag(DeclType.Mem.Scope().getBeginLoc(),
3071194179Sed             diag::err_illegal_decl_mempointer_in_nonclass)
3072194179Sed          << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
3073194179Sed          << DeclType.Mem.Scope().getRange();
3074193326Sed        D.setInvalidType(true);
3075193326Sed      }
3076193326Sed
3077194179Sed      if (!ClsType.isNull())
3078224145Sdim        T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
3079194179Sed      if (T.isNull()) {
3080194179Sed        T = Context.IntTy;
3081193326Sed        D.setInvalidType(true);
3082210299Sed      } else if (DeclType.Mem.TypeQuals) {
3083224145Sdim        T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
3084193326Sed      }
3085193326Sed      break;
3086193326Sed    }
3087193326Sed
3088193326Sed    if (T.isNull()) {
3089193326Sed      D.setInvalidType(true);
3090193326Sed      T = Context.IntTy;
3091193326Sed    }
3092193326Sed
3093193326Sed    // See if there are any attributes on this declarator chunk.
3094218893Sdim    if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
3095249423Sdim      processTypeAttrs(state, T, TAL_DeclChunk, attrs);
3096193326Sed  }
3097193326Sed
3098224145Sdim  if (LangOpts.CPlusPlus && T->isFunctionType()) {
3099198092Srdivacky    const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
3100198893Srdivacky    assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
3101193326Sed
3102239462Sdim    // C++ 8.3.5p4:
3103218893Sdim    //   A cv-qualifier-seq shall only be part of the function type
3104218893Sdim    //   for a nonstatic member function, the function type to which a pointer
3105218893Sdim    //   to member refers, or the top-level function type of a function typedef
3106218893Sdim    //   declaration.
3107218893Sdim    //
3108218893Sdim    // Core issue 547 also allows cv-qualifiers on function types that are
3109218893Sdim    // top-level template type arguments.
3110218893Sdim    bool FreeFunction;
3111218893Sdim    if (!D.getCXXScopeSpec().isSet()) {
3112234353Sdim      FreeFunction = ((D.getContext() != Declarator::MemberContext &&
3113234353Sdim                       D.getContext() != Declarator::LambdaExprContext) ||
3114218893Sdim                      D.getDeclSpec().isFriendSpecified());
3115218893Sdim    } else {
3116224145Sdim      DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
3117218893Sdim      FreeFunction = (DC && !DC->isRecord());
3118218893Sdim    }
3119218893Sdim
3120234353Sdim    // C++11 [dcl.fct]p6 (w/DR1417):
3121234353Sdim    // An attempt to specify a function type with a cv-qualifier-seq or a
3122234353Sdim    // ref-qualifier (including by typedef-name) is ill-formed unless it is:
3123234353Sdim    //  - the function type for a non-static member function,
3124234353Sdim    //  - the function type to which a pointer to member refers,
3125234353Sdim    //  - the top-level function type of a function typedef declaration or
3126234353Sdim    //    alias-declaration,
3127234353Sdim    //  - the type-id in the default argument of a type-parameter, or
3128234353Sdim    //  - the type-id of a template-argument for a type-parameter
3129234353Sdim    if (IsQualifiedFunction &&
3130234353Sdim        !(!FreeFunction &&
3131234353Sdim          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
3132234353Sdim        !IsTypedefName &&
3133234353Sdim        D.getContext() != Declarator::TemplateTypeArgContext) {
3134234353Sdim      SourceLocation Loc = D.getLocStart();
3135234353Sdim      SourceRange RemovalRange;
3136234353Sdim      unsigned I;
3137234353Sdim      if (D.isFunctionDeclarator(I)) {
3138234353Sdim        SmallVector<SourceLocation, 4> RemovalLocs;
3139234353Sdim        const DeclaratorChunk &Chunk = D.getTypeObject(I);
3140234353Sdim        assert(Chunk.Kind == DeclaratorChunk::Function);
3141234353Sdim        if (Chunk.Fun.hasRefQualifier())
3142234353Sdim          RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
3143234353Sdim        if (Chunk.Fun.TypeQuals & Qualifiers::Const)
3144234353Sdim          RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
3145234353Sdim        if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
3146234353Sdim          RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
3147234353Sdim        // FIXME: We do not track the location of the __restrict qualifier.
3148234353Sdim        //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
3149234353Sdim        //  RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
3150234353Sdim        if (!RemovalLocs.empty()) {
3151234353Sdim          std::sort(RemovalLocs.begin(), RemovalLocs.end(),
3152239462Sdim                    BeforeThanCompare<SourceLocation>(S.getSourceManager()));
3153234353Sdim          RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
3154234353Sdim          Loc = RemovalLocs.front();
3155218893Sdim        }
3156234353Sdim      }
3157193326Sed
3158234353Sdim      S.Diag(Loc, diag::err_invalid_qualified_function_type)
3159234353Sdim        << FreeFunction << D.isFunctionDeclarator() << T
3160234353Sdim        << getFunctionQualifiersAsString(FnTy)
3161234353Sdim        << FixItHint::CreateRemoval(RemovalRange);
3162234353Sdim
3163234353Sdim      // Strip the cv-qualifiers and ref-qualifiers from the type.
3164234353Sdim      FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
3165234353Sdim      EPI.TypeQuals = 0;
3166234353Sdim      EPI.RefQualifier = RQ_None;
3167234353Sdim
3168263508Sdim      T = Context.getFunctionType(FnTy->getResultType(), FnTy->getArgTypes(),
3169249423Sdim                                  EPI);
3170243830Sdim      // Rebuild any parens around the identifier in the function type.
3171243830Sdim      for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3172243830Sdim        if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
3173243830Sdim          break;
3174243830Sdim        T = S.BuildParenType(T);
3175243830Sdim      }
3176193326Sed    }
3177193326Sed  }
3178198092Srdivacky
3179218893Sdim  // Apply any undistributed attributes from the declarator.
3180218893Sdim  if (!T.isNull())
3181218893Sdim    if (AttributeList *attrs = D.getAttributes())
3182249423Sdim      processTypeAttrs(state, T, TAL_DeclName, attrs);
3183218893Sdim
3184218893Sdim  // Diagnose any ignored type attributes.
3185218893Sdim  if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
3186218893Sdim
3187221345Sdim  // C++0x [dcl.constexpr]p9:
3188221345Sdim  //  A constexpr specifier used in an object declaration declares the object
3189239462Sdim  //  as const.
3190221345Sdim  if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
3191210299Sed    T.addConst();
3192210299Sed  }
3193210299Sed
3194239462Sdim  // If there was an ellipsis in the declarator, the declaration declares a
3195218893Sdim  // parameter pack whose type may be a pack expansion type.
3196218893Sdim  if (D.hasEllipsis() && !T.isNull()) {
3197218893Sdim    // C++0x [dcl.fct]p13:
3198239462Sdim    //   A declarator-id or abstract-declarator containing an ellipsis shall
3199218893Sdim    //   only be used in a parameter-declaration. Such a parameter-declaration
3200218893Sdim    //   is a parameter pack (14.5.3). [...]
3201218893Sdim    switch (D.getContext()) {
3202218893Sdim    case Declarator::PrototypeContext:
3203263508Sdim    case Declarator::LambdaExprParameterContext:
3204218893Sdim      // C++0x [dcl.fct]p13:
3205239462Sdim      //   [...] When it is part of a parameter-declaration-clause, the
3206239462Sdim      //   parameter pack is a function parameter pack (14.5.3). The type T
3207218893Sdim      //   of the declarator-id of the function parameter pack shall contain
3208239462Sdim      //   a template parameter pack; each template parameter pack in T is
3209218893Sdim      //   expanded by the function parameter pack.
3210218893Sdim      //
3211218893Sdim      // We represent function parameter packs as function parameters whose
3212218893Sdim      // type is a pack expansion.
3213218893Sdim      if (!T->containsUnexpandedParameterPack()) {
3214239462Sdim        S.Diag(D.getEllipsisLoc(),
3215218893Sdim             diag::err_function_parameter_pack_without_parameter_packs)
3216218893Sdim          << T <<  D.getSourceRange();
3217218893Sdim        D.setEllipsisLoc(SourceLocation());
3218218893Sdim      } else {
3219249423Sdim        T = Context.getPackExpansionType(T, None);
3220218893Sdim      }
3221218893Sdim      break;
3222218893Sdim    case Declarator::TemplateParamContext:
3223218893Sdim      // C++0x [temp.param]p15:
3224239462Sdim      //   If a template-parameter is a [...] is a parameter-declaration that
3225218893Sdim      //   declares a parameter pack (8.3.5), then the template-parameter is a
3226218893Sdim      //   template parameter pack (14.5.3).
3227218893Sdim      //
3228218893Sdim      // Note: core issue 778 clarifies that, if there are any unexpanded
3229218893Sdim      // parameter packs in the type of the non-type template parameter, then
3230218893Sdim      // it expands those parameter packs.
3231218893Sdim      if (T->containsUnexpandedParameterPack())
3232249423Sdim        T = Context.getPackExpansionType(T, None);
3233226633Sdim      else
3234226633Sdim        S.Diag(D.getEllipsisLoc(),
3235249423Sdim               LangOpts.CPlusPlus11
3236226633Sdim                 ? diag::warn_cxx98_compat_variadic_templates
3237226633Sdim                 : diag::ext_variadic_templates);
3238218893Sdim      break;
3239239462Sdim
3240218893Sdim    case Declarator::FileContext:
3241218893Sdim    case Declarator::KNRTypeListContext:
3242226633Sdim    case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
3243226633Sdim    case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
3244218893Sdim    case Declarator::TypeNameContext:
3245224145Sdim    case Declarator::CXXNewContext:
3246221345Sdim    case Declarator::AliasDeclContext:
3247223017Sdim    case Declarator::AliasTemplateContext:
3248218893Sdim    case Declarator::MemberContext:
3249218893Sdim    case Declarator::BlockContext:
3250218893Sdim    case Declarator::ForContext:
3251218893Sdim    case Declarator::ConditionContext:
3252218893Sdim    case Declarator::CXXCatchContext:
3253224145Sdim    case Declarator::ObjCCatchContext:
3254218893Sdim    case Declarator::BlockLiteralContext:
3255234353Sdim    case Declarator::LambdaExprContext:
3256251662Sdim    case Declarator::ConversionIdContext:
3257234353Sdim    case Declarator::TrailingReturnContext:
3258218893Sdim    case Declarator::TemplateTypeArgContext:
3259218893Sdim      // FIXME: We may want to allow parameter packs in block-literal contexts
3260218893Sdim      // in the future.
3261224145Sdim      S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
3262218893Sdim      D.setEllipsisLoc(SourceLocation());
3263218893Sdim      break;
3264218893Sdim    }
3265218893Sdim  }
3266219077Sdim
3267210299Sed  if (T.isNull())
3268210299Sed    return Context.getNullTypeSourceInfo();
3269210299Sed  else if (D.isInvalidType())
3270210299Sed    return Context.getTrivialTypeSourceInfo(T);
3271224145Sdim
3272224145Sdim  return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3273193326Sed}
3274193326Sed
3275224145Sdim/// GetTypeForDeclarator - Convert the type for the specified
3276224145Sdim/// declarator to Type instances.
3277224145Sdim///
3278224145Sdim/// The result of this call will never be null, but the associated
3279224145Sdim/// type may be a null type if there's an unrecoverable error.
3280224145SdimTypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3281224145Sdim  // Determine the type of the declarator. Not all forms of declarator
3282224145Sdim  // have a type.
3283224145Sdim
3284224145Sdim  TypeProcessingState state(*this, D);
3285224145Sdim
3286224145Sdim  TypeSourceInfo *ReturnTypeInfo = 0;
3287224145Sdim  QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3288224145Sdim  if (T.isNull())
3289224145Sdim    return Context.getNullTypeSourceInfo();
3290224145Sdim
3291234353Sdim  if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
3292224145Sdim    inferARCWriteback(state, T);
3293239462Sdim
3294224145Sdim  return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
3295224145Sdim}
3296224145Sdim
3297224145Sdimstatic void transferARCOwnershipToDeclSpec(Sema &S,
3298224145Sdim                                           QualType &declSpecTy,
3299224145Sdim                                           Qualifiers::ObjCLifetime ownership) {
3300224145Sdim  if (declSpecTy->isObjCRetainableType() &&
3301224145Sdim      declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3302224145Sdim    Qualifiers qs;
3303224145Sdim    qs.addObjCLifetime(ownership);
3304224145Sdim    declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3305224145Sdim  }
3306224145Sdim}
3307224145Sdim
3308224145Sdimstatic void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3309224145Sdim                                            Qualifiers::ObjCLifetime ownership,
3310224145Sdim                                            unsigned chunkIndex) {
3311224145Sdim  Sema &S = state.getSema();
3312224145Sdim  Declarator &D = state.getDeclarator();
3313224145Sdim
3314224145Sdim  // Look for an explicit lifetime attribute.
3315224145Sdim  DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3316224145Sdim  for (const AttributeList *attr = chunk.getAttrs(); attr;
3317224145Sdim         attr = attr->getNext())
3318239462Sdim    if (attr->getKind() == AttributeList::AT_ObjCOwnership)
3319224145Sdim      return;
3320224145Sdim
3321224145Sdim  const char *attrStr = 0;
3322224145Sdim  switch (ownership) {
3323234353Sdim  case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
3324224145Sdim  case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3325224145Sdim  case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3326224145Sdim  case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3327224145Sdim  case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3328224145Sdim  }
3329224145Sdim
3330263508Sdim  IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
3331263508Sdim  Arg->Ident = &S.Context.Idents.get(attrStr);
3332263508Sdim  Arg->Loc = SourceLocation();
3333263508Sdim
3334263508Sdim  ArgsUnion Args(Arg);
3335263508Sdim
3336224145Sdim  // If there wasn't one, add one (with an invalid source location
3337224145Sdim  // so that we don't make an AttributedType for it).
3338224145Sdim  AttributeList *attr = D.getAttributePool()
3339224145Sdim    .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3340224145Sdim            /*scope*/ 0, SourceLocation(),
3341263508Sdim            /*args*/ &Args, 1, AttributeList::AS_GNU);
3342224145Sdim  spliceAttrIntoList(*attr, chunk.getAttrListRef());
3343224145Sdim
3344224145Sdim  // TODO: mark whether we did this inference?
3345224145Sdim}
3346224145Sdim
3347239462Sdim/// \brief Used for transferring ownership in casts resulting in l-values.
3348224145Sdimstatic void transferARCOwnership(TypeProcessingState &state,
3349224145Sdim                                 QualType &declSpecTy,
3350224145Sdim                                 Qualifiers::ObjCLifetime ownership) {
3351224145Sdim  Sema &S = state.getSema();
3352224145Sdim  Declarator &D = state.getDeclarator();
3353224145Sdim
3354224145Sdim  int inner = -1;
3355234353Sdim  bool hasIndirection = false;
3356224145Sdim  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3357224145Sdim    DeclaratorChunk &chunk = D.getTypeObject(i);
3358224145Sdim    switch (chunk.Kind) {
3359224145Sdim    case DeclaratorChunk::Paren:
3360224145Sdim      // Ignore parens.
3361224145Sdim      break;
3362224145Sdim
3363224145Sdim    case DeclaratorChunk::Array:
3364224145Sdim    case DeclaratorChunk::Reference:
3365224145Sdim    case DeclaratorChunk::Pointer:
3366234353Sdim      if (inner != -1)
3367234353Sdim        hasIndirection = true;
3368224145Sdim      inner = i;
3369224145Sdim      break;
3370224145Sdim
3371224145Sdim    case DeclaratorChunk::BlockPointer:
3372234353Sdim      if (inner != -1)
3373234353Sdim        transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3374234353Sdim      return;
3375224145Sdim
3376224145Sdim    case DeclaratorChunk::Function:
3377224145Sdim    case DeclaratorChunk::MemberPointer:
3378224145Sdim      return;
3379224145Sdim    }
3380224145Sdim  }
3381224145Sdim
3382224145Sdim  if (inner == -1)
3383234353Sdim    return;
3384224145Sdim
3385239462Sdim  DeclaratorChunk &chunk = D.getTypeObject(inner);
3386224145Sdim  if (chunk.Kind == DeclaratorChunk::Pointer) {
3387224145Sdim    if (declSpecTy->isObjCRetainableType())
3388224145Sdim      return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3389234353Sdim    if (declSpecTy->isObjCObjectType() && hasIndirection)
3390224145Sdim      return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3391224145Sdim  } else {
3392224145Sdim    assert(chunk.Kind == DeclaratorChunk::Array ||
3393224145Sdim           chunk.Kind == DeclaratorChunk::Reference);
3394224145Sdim    return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3395224145Sdim  }
3396224145Sdim}
3397224145Sdim
3398224145SdimTypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3399224145Sdim  TypeProcessingState state(*this, D);
3400224145Sdim
3401224145Sdim  TypeSourceInfo *ReturnTypeInfo = 0;
3402224145Sdim  QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3403224145Sdim  if (declSpecTy.isNull())
3404224145Sdim    return Context.getNullTypeSourceInfo();
3405224145Sdim
3406234353Sdim  if (getLangOpts().ObjCAutoRefCount) {
3407224145Sdim    Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3408224145Sdim    if (ownership != Qualifiers::OCL_None)
3409224145Sdim      transferARCOwnership(state, declSpecTy, ownership);
3410224145Sdim  }
3411224145Sdim
3412224145Sdim  return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3413224145Sdim}
3414224145Sdim
3415221345Sdim/// Map an AttributedType::Kind to an AttributeList::Kind.
3416221345Sdimstatic AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3417221345Sdim  switch (kind) {
3418221345Sdim  case AttributedType::attr_address_space:
3419239462Sdim    return AttributeList::AT_AddressSpace;
3420221345Sdim  case AttributedType::attr_regparm:
3421239462Sdim    return AttributeList::AT_Regparm;
3422221345Sdim  case AttributedType::attr_vector_size:
3423239462Sdim    return AttributeList::AT_VectorSize;
3424221345Sdim  case AttributedType::attr_neon_vector_type:
3425239462Sdim    return AttributeList::AT_NeonVectorType;
3426221345Sdim  case AttributedType::attr_neon_polyvector_type:
3427239462Sdim    return AttributeList::AT_NeonPolyVectorType;
3428221345Sdim  case AttributedType::attr_objc_gc:
3429239462Sdim    return AttributeList::AT_ObjCGC;
3430224145Sdim  case AttributedType::attr_objc_ownership:
3431239462Sdim    return AttributeList::AT_ObjCOwnership;
3432221345Sdim  case AttributedType::attr_noreturn:
3433239462Sdim    return AttributeList::AT_NoReturn;
3434221345Sdim  case AttributedType::attr_cdecl:
3435239462Sdim    return AttributeList::AT_CDecl;
3436221345Sdim  case AttributedType::attr_fastcall:
3437239462Sdim    return AttributeList::AT_FastCall;
3438221345Sdim  case AttributedType::attr_stdcall:
3439239462Sdim    return AttributeList::AT_StdCall;
3440221345Sdim  case AttributedType::attr_thiscall:
3441239462Sdim    return AttributeList::AT_ThisCall;
3442221345Sdim  case AttributedType::attr_pascal:
3443239462Sdim    return AttributeList::AT_Pascal;
3444221345Sdim  case AttributedType::attr_pcs:
3445263508Sdim  case AttributedType::attr_pcs_vfp:
3446239462Sdim    return AttributeList::AT_Pcs;
3447243830Sdim  case AttributedType::attr_pnaclcall:
3448243830Sdim    return AttributeList::AT_PnaclCall;
3449249423Sdim  case AttributedType::attr_inteloclbicc:
3450249423Sdim    return AttributeList::AT_IntelOclBicc;
3451256030Sdim  case AttributedType::attr_ms_abi:
3452256030Sdim    return AttributeList::AT_MSABI;
3453256030Sdim  case AttributedType::attr_sysv_abi:
3454256030Sdim    return AttributeList::AT_SysVABI;
3455263508Sdim  case AttributedType::attr_ptr32:
3456263508Sdim    return AttributeList::AT_Ptr32;
3457263508Sdim  case AttributedType::attr_ptr64:
3458263508Sdim    return AttributeList::AT_Ptr64;
3459263508Sdim  case AttributedType::attr_sptr:
3460263508Sdim    return AttributeList::AT_SPtr;
3461263508Sdim  case AttributedType::attr_uptr:
3462263508Sdim    return AttributeList::AT_UPtr;
3463221345Sdim  }
3464221345Sdim  llvm_unreachable("unexpected attribute kind!");
3465221345Sdim}
3466221345Sdim
3467221345Sdimstatic void fillAttributedTypeLoc(AttributedTypeLoc TL,
3468221345Sdim                                  const AttributeList *attrs) {
3469221345Sdim  AttributedType::Kind kind = TL.getAttrKind();
3470221345Sdim
3471221345Sdim  assert(attrs && "no type attributes in the expected location!");
3472221345Sdim  AttributeList::Kind parsedKind = getAttrListKind(kind);
3473221345Sdim  while (attrs->getKind() != parsedKind) {
3474221345Sdim    attrs = attrs->getNext();
3475221345Sdim    assert(attrs && "no matching attribute in expected location!");
3476221345Sdim  }
3477221345Sdim
3478221345Sdim  TL.setAttrNameLoc(attrs->getLoc());
3479263508Sdim  if (TL.hasAttrExprOperand() && attrs->isArgExpr(0))
3480263508Sdim    TL.setAttrExprOperand(attrs->getArgAsExpr(0));
3481263508Sdim  else if (TL.hasAttrEnumOperand() && attrs->isArgIdent(0))
3482263508Sdim    TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
3483221345Sdim
3484221345Sdim  // FIXME: preserve this information to here.
3485221345Sdim  if (TL.hasAttrOperand())
3486221345Sdim    TL.setAttrOperandParensRange(SourceRange());
3487221345Sdim}
3488221345Sdim
3489198398Srdivackynamespace {
3490198398Srdivacky  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
3491218893Sdim    ASTContext &Context;
3492198398Srdivacky    const DeclSpec &DS;
3493193326Sed
3494198398Srdivacky  public:
3495239462Sdim    TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
3496218893Sdim      : Context(Context), DS(DS) {}
3497193326Sed
3498221345Sdim    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3499221345Sdim      fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3500221345Sdim      Visit(TL.getModifiedLoc());
3501221345Sdim    }
3502198398Srdivacky    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3503198398Srdivacky      Visit(TL.getUnqualifiedLoc());
3504198398Srdivacky    }
3505198398Srdivacky    void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3506198398Srdivacky      TL.setNameLoc(DS.getTypeSpecTypeLoc());
3507198398Srdivacky    }
3508198398Srdivacky    void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3509198398Srdivacky      TL.setNameLoc(DS.getTypeSpecTypeLoc());
3510239462Sdim      // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3511239462Sdim      // addition field. What we have is good enough for dispay of location
3512239462Sdim      // of 'fixit' on interface name.
3513239462Sdim      TL.setNameEndLoc(DS.getLocEnd());
3514208600Srdivacky    }
3515208600Srdivacky    void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3516208600Srdivacky      // Handle the base type, which might not have been written explicitly.
3517208600Srdivacky      if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3518208600Srdivacky        TL.setHasBaseTypeAsWritten(false);
3519218893Sdim        TL.getBaseLoc().initialize(Context, SourceLocation());
3520208600Srdivacky      } else {
3521208600Srdivacky        TL.setHasBaseTypeAsWritten(true);
3522208600Srdivacky        Visit(TL.getBaseLoc());
3523208600Srdivacky      }
3524193326Sed
3525208600Srdivacky      // Protocol qualifiers.
3526198398Srdivacky      if (DS.getProtocolQualifiers()) {
3527198398Srdivacky        assert(TL.getNumProtocols() > 0);
3528198398Srdivacky        assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3529198398Srdivacky        TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3530198398Srdivacky        TL.setRAngleLoc(DS.getSourceRange().getEnd());
3531198398Srdivacky        for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3532198398Srdivacky          TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3533198398Srdivacky      } else {
3534198398Srdivacky        assert(TL.getNumProtocols() == 0);
3535198398Srdivacky        TL.setLAngleLoc(SourceLocation());
3536198398Srdivacky        TL.setRAngleLoc(SourceLocation());
3537198398Srdivacky      }
3538198398Srdivacky    }
3539198398Srdivacky    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3540198398Srdivacky      TL.setStarLoc(SourceLocation());
3541208600Srdivacky      Visit(TL.getPointeeLoc());
3542198092Srdivacky    }
3543198893Srdivacky    void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
3544200583Srdivacky      TypeSourceInfo *TInfo = 0;
3545212904Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3546198893Srdivacky
3547198893Srdivacky      // If we got no declarator info from previous Sema routines,
3548198893Srdivacky      // just fill with the typespec loc.
3549200583Srdivacky      if (!TInfo) {
3550221345Sdim        TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
3551198893Srdivacky        return;
3552198893Srdivacky      }
3553198893Srdivacky
3554208600Srdivacky      TypeLoc OldTL = TInfo->getTypeLoc();
3555208600Srdivacky      if (TInfo->getType()->getAs<ElaboratedType>()) {
3556249423Sdim        ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
3557249423Sdim        TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
3558249423Sdim            .castAs<TemplateSpecializationTypeLoc>();
3559208600Srdivacky        TL.copy(NamedTL);
3560263508Sdim      } else {
3561263508Sdim        TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
3562263508Sdim        assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
3563208600Srdivacky      }
3564263508Sdim
3565198893Srdivacky    }
3566202379Srdivacky    void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3567202379Srdivacky      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3568202379Srdivacky      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3569202379Srdivacky      TL.setParensRange(DS.getTypeofParensRange());
3570202379Srdivacky    }
3571202379Srdivacky    void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3572202379Srdivacky      assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3573202379Srdivacky      TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3574202379Srdivacky      TL.setParensRange(DS.getTypeofParensRange());
3575212904Sdim      assert(DS.getRepAsType());
3576202379Srdivacky      TypeSourceInfo *TInfo = 0;
3577212904Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3578202379Srdivacky      TL.setUnderlyingTInfo(TInfo);
3579202379Srdivacky    }
3580223017Sdim    void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3581223017Sdim      // FIXME: This holds only because we only have one unary transform.
3582223017Sdim      assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3583223017Sdim      TL.setKWLoc(DS.getTypeSpecTypeLoc());
3584223017Sdim      TL.setParensRange(DS.getTypeofParensRange());
3585223017Sdim      assert(DS.getRepAsType());
3586223017Sdim      TypeSourceInfo *TInfo = 0;
3587223017Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3588223017Sdim      TL.setUnderlyingTInfo(TInfo);
3589223017Sdim    }
3590202879Srdivacky    void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3591202879Srdivacky      // By default, use the source location of the type specifier.
3592202879Srdivacky      TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3593202879Srdivacky      if (TL.needsExtraLocalData()) {
3594202879Srdivacky        // Set info for the written builtin specifiers.
3595202879Srdivacky        TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3596202879Srdivacky        // Try to have a meaningful source location.
3597202879Srdivacky        if (TL.getWrittenSignSpec() != TSS_unspecified)
3598202879Srdivacky          // Sign spec loc overrides the others (e.g., 'unsigned long').
3599202879Srdivacky          TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3600202879Srdivacky        else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3601202879Srdivacky          // Width spec loc overrides type spec loc (e.g., 'short int').
3602202879Srdivacky          TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3603202879Srdivacky      }
3604202879Srdivacky    }
3605208600Srdivacky    void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3606208600Srdivacky      ElaboratedTypeKeyword Keyword
3607208600Srdivacky        = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
3608218893Sdim      if (DS.getTypeSpecType() == TST_typename) {
3609208600Srdivacky        TypeSourceInfo *TInfo = 0;
3610212904Sdim        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3611208600Srdivacky        if (TInfo) {
3612249423Sdim          TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
3613208600Srdivacky          return;
3614208600Srdivacky        }
3615208600Srdivacky      }
3616234353Sdim      TL.setElaboratedKeywordLoc(Keyword != ETK_None
3617234353Sdim                                 ? DS.getTypeSpecTypeLoc()
3618234353Sdim                                 : SourceLocation());
3619208600Srdivacky      const CXXScopeSpec& SS = DS.getTypeSpecScope();
3620221345Sdim      TL.setQualifierLoc(SS.getWithLocInContext(Context));
3621208600Srdivacky      Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3622208600Srdivacky    }
3623208600Srdivacky    void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3624234353Sdim      assert(DS.getTypeSpecType() == TST_typename);
3625234353Sdim      TypeSourceInfo *TInfo = 0;
3626234353Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3627234353Sdim      assert(TInfo);
3628249423Sdim      TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
3629208600Srdivacky    }
3630210299Sed    void VisitDependentTemplateSpecializationTypeLoc(
3631210299Sed                                 DependentTemplateSpecializationTypeLoc TL) {
3632234353Sdim      assert(DS.getTypeSpecType() == TST_typename);
3633234353Sdim      TypeSourceInfo *TInfo = 0;
3634234353Sdim      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3635234353Sdim      assert(TInfo);
3636249423Sdim      TL.copy(
3637249423Sdim          TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
3638210299Sed    }
3639221345Sdim    void VisitTagTypeLoc(TagTypeLoc TL) {
3640221345Sdim      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
3641221345Sdim    }
3642226633Sdim    void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3643249423Sdim      // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
3644249423Sdim      // or an _Atomic qualifier.
3645249423Sdim      if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
3646249423Sdim        TL.setKWLoc(DS.getTypeSpecTypeLoc());
3647249423Sdim        TL.setParensRange(DS.getTypeofParensRange());
3648239462Sdim
3649249423Sdim        TypeSourceInfo *TInfo = 0;
3650249423Sdim        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3651249423Sdim        assert(TInfo);
3652249423Sdim        TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
3653249423Sdim      } else {
3654249423Sdim        TL.setKWLoc(DS.getAtomicSpecLoc());
3655249423Sdim        // No parens, to indicate this was spelled as an _Atomic qualifier.
3656249423Sdim        TL.setParensRange(SourceRange());
3657249423Sdim        Visit(TL.getValueLoc());
3658249423Sdim      }
3659226633Sdim    }
3660208600Srdivacky
3661198398Srdivacky    void VisitTypeLoc(TypeLoc TL) {
3662198398Srdivacky      // FIXME: add other typespec types and change this to an assert.
3663218893Sdim      TL.initialize(Context, DS.getTypeSpecTypeLoc());
3664198092Srdivacky    }
3665198398Srdivacky  };
3666198398Srdivacky
3667198398Srdivacky  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
3668221345Sdim    ASTContext &Context;
3669198398Srdivacky    const DeclaratorChunk &Chunk;
3670198398Srdivacky
3671198398Srdivacky  public:
3672221345Sdim    DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3673221345Sdim      : Context(Context), Chunk(Chunk) {}
3674198398Srdivacky
3675198398Srdivacky    void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3676200583Srdivacky      llvm_unreachable("qualified type locs not expected here!");
3677198092Srdivacky    }
3678263508Sdim    void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
3679263508Sdim      llvm_unreachable("decayed type locs not expected here!");
3680263508Sdim    }
3681198398Srdivacky
3682224145Sdim    void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3683224145Sdim      fillAttributedTypeLoc(TL, Chunk.getAttrs());
3684224145Sdim    }
3685198398Srdivacky    void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3686198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3687198398Srdivacky      TL.setCaretLoc(Chunk.Loc);
3688198092Srdivacky    }
3689198398Srdivacky    void VisitPointerTypeLoc(PointerTypeLoc TL) {
3690198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Pointer);
3691198398Srdivacky      TL.setStarLoc(Chunk.Loc);
3692198398Srdivacky    }
3693198398Srdivacky    void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3694198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Pointer);
3695198398Srdivacky      TL.setStarLoc(Chunk.Loc);
3696198398Srdivacky    }
3697198398Srdivacky    void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3698198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3699221345Sdim      const CXXScopeSpec& SS = Chunk.Mem.Scope();
3700221345Sdim      NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3701221345Sdim
3702221345Sdim      const Type* ClsTy = TL.getClass();
3703221345Sdim      QualType ClsQT = QualType(ClsTy, 0);
3704221345Sdim      TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3705221345Sdim      // Now copy source location info into the type loc component.
3706221345Sdim      TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3707221345Sdim      switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3708221345Sdim      case NestedNameSpecifier::Identifier:
3709221345Sdim        assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3710221345Sdim        {
3711249423Sdim          DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
3712234353Sdim          DNTLoc.setElaboratedKeywordLoc(SourceLocation());
3713221345Sdim          DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3714221345Sdim          DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3715221345Sdim        }
3716221345Sdim        break;
3717221345Sdim
3718221345Sdim      case NestedNameSpecifier::TypeSpec:
3719221345Sdim      case NestedNameSpecifier::TypeSpecWithTemplate:
3720221345Sdim        if (isa<ElaboratedType>(ClsTy)) {
3721249423Sdim          ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
3722234353Sdim          ETLoc.setElaboratedKeywordLoc(SourceLocation());
3723221345Sdim          ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3724221345Sdim          TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3725221345Sdim          NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3726221345Sdim        } else {
3727221345Sdim          ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3728221345Sdim        }
3729221345Sdim        break;
3730221345Sdim
3731221345Sdim      case NestedNameSpecifier::Namespace:
3732221345Sdim      case NestedNameSpecifier::NamespaceAlias:
3733221345Sdim      case NestedNameSpecifier::Global:
3734221345Sdim        llvm_unreachable("Nested-name-specifier must name a type");
3735221345Sdim      }
3736221345Sdim
3737221345Sdim      // Finally fill in MemberPointerLocInfo fields.
3738198398Srdivacky      TL.setStarLoc(Chunk.Loc);
3739221345Sdim      TL.setClassTInfo(ClsTInfo);
3740198398Srdivacky    }
3741198398Srdivacky    void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3742198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Reference);
3743198398Srdivacky      // 'Amp' is misleading: this might have been originally
3744198398Srdivacky      /// spelled with AmpAmp.
3745198398Srdivacky      TL.setAmpLoc(Chunk.Loc);
3746198398Srdivacky    }
3747198398Srdivacky    void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3748198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Reference);
3749198398Srdivacky      assert(!Chunk.Ref.LValueRef);
3750198398Srdivacky      TL.setAmpAmpLoc(Chunk.Loc);
3751198398Srdivacky    }
3752198398Srdivacky    void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3753198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Array);
3754198398Srdivacky      TL.setLBracketLoc(Chunk.Loc);
3755198398Srdivacky      TL.setRBracketLoc(Chunk.EndLoc);
3756198398Srdivacky      TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3757198398Srdivacky    }
3758198398Srdivacky    void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3759198398Srdivacky      assert(Chunk.Kind == DeclaratorChunk::Function);
3760221345Sdim      TL.setLocalRangeBegin(Chunk.Loc);
3761221345Sdim      TL.setLocalRangeEnd(Chunk.EndLoc);
3762198398Srdivacky
3763198398Srdivacky      const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3764243830Sdim      TL.setLParenLoc(FTI.getLParenLoc());
3765243830Sdim      TL.setRParenLoc(FTI.getRParenLoc());
3766198398Srdivacky      for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
3767212904Sdim        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
3768198398Srdivacky        TL.setArg(tpi++, Param);
3769198092Srdivacky      }
3770198398Srdivacky      // FIXME: exception specs
3771198092Srdivacky    }
3772218893Sdim    void VisitParenTypeLoc(ParenTypeLoc TL) {
3773218893Sdim      assert(Chunk.Kind == DeclaratorChunk::Paren);
3774218893Sdim      TL.setLParenLoc(Chunk.Loc);
3775218893Sdim      TL.setRParenLoc(Chunk.EndLoc);
3776218893Sdim    }
3777193326Sed
3778198398Srdivacky    void VisitTypeLoc(TypeLoc TL) {
3779200583Srdivacky      llvm_unreachable("unsupported TypeLoc kind in declarator!");
3780198092Srdivacky    }
3781198398Srdivacky  };
3782198398Srdivacky}
3783198092Srdivacky
3784249423Sdimstatic void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
3785249423Sdim  SourceLocation Loc;
3786249423Sdim  switch (Chunk.Kind) {
3787249423Sdim  case DeclaratorChunk::Function:
3788249423Sdim  case DeclaratorChunk::Array:
3789249423Sdim  case DeclaratorChunk::Paren:
3790249423Sdim    llvm_unreachable("cannot be _Atomic qualified");
3791249423Sdim
3792249423Sdim  case DeclaratorChunk::Pointer:
3793249423Sdim    Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
3794249423Sdim    break;
3795249423Sdim
3796249423Sdim  case DeclaratorChunk::BlockPointer:
3797249423Sdim  case DeclaratorChunk::Reference:
3798249423Sdim  case DeclaratorChunk::MemberPointer:
3799249423Sdim    // FIXME: Provide a source location for the _Atomic keyword.
3800249423Sdim    break;
3801249423Sdim  }
3802249423Sdim
3803249423Sdim  ATL.setKWLoc(Loc);
3804249423Sdim  ATL.setParensRange(SourceRange());
3805249423Sdim}
3806249423Sdim
3807200583Srdivacky/// \brief Create and instantiate a TypeSourceInfo with type source information.
3808198398Srdivacky///
3809198398Srdivacky/// \param T QualType referring to the type as written in source code.
3810207619Srdivacky///
3811207619Srdivacky/// \param ReturnTypeInfo For declarators whose return type does not show
3812207619Srdivacky/// up in the normal place in the declaration specifiers (such as a C++
3813207619Srdivacky/// conversion function), this pointer will refer to a type source information
3814207619Srdivacky/// for that return type.
3815200583SrdivackyTypeSourceInfo *
3816207619SrdivackySema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3817207619Srdivacky                                     TypeSourceInfo *ReturnTypeInfo) {
3818200583Srdivacky  TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3819200583Srdivacky  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3820198398Srdivacky
3821218893Sdim  // Handle parameter packs whose type is a pack expansion.
3822218893Sdim  if (isa<PackExpansionType>(T)) {
3823249423Sdim    CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
3824239462Sdim    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3825218893Sdim  }
3826239462Sdim
3827198893Srdivacky  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3828249423Sdim    // An AtomicTypeLoc might be produced by an atomic qualifier in this
3829249423Sdim    // declarator chunk.
3830249423Sdim    if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
3831249423Sdim      fillAtomicQualLoc(ATL, D.getTypeObject(i));
3832249423Sdim      CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
3833249423Sdim    }
3834249423Sdim
3835249423Sdim    while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
3836221345Sdim      fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3837221345Sdim      CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3838221345Sdim    }
3839221345Sdim
3840221345Sdim    DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3841198398Srdivacky    CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3842195341Sed  }
3843239462Sdim
3844212904Sdim  // If we have different source information for the return type, use
3845212904Sdim  // that.  This really only applies to C++ conversion functions.
3846212904Sdim  if (ReturnTypeInfo) {
3847207619Srdivacky    TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3848207619Srdivacky    assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3849207619Srdivacky    memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3850212904Sdim  } else {
3851218893Sdim    TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3852207619Srdivacky  }
3853239462Sdim
3854200583Srdivacky  return TInfo;
3855198092Srdivacky}
3856195341Sed
3857200583Srdivacky/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3858212904SdimParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3859198092Srdivacky  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3860198092Srdivacky  // and Sema during declaration parsing. Try deallocating/caching them when
3861198092Srdivacky  // it's appropriate, instead of allocating them and keeping them around.
3862239462Sdim  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3863218893Sdim                                                       TypeAlignment);
3864200583Srdivacky  new (LocT) LocInfoType(T, TInfo);
3865198092Srdivacky  assert(LocT->getTypeClass() != T->getTypeClass() &&
3866198092Srdivacky         "LocInfoType's TypeClass conflicts with an existing Type class");
3867212904Sdim  return ParsedType::make(QualType(LocT, 0));
3868198092Srdivacky}
3869195341Sed
3870198092Srdivackyvoid LocInfoType::getAsStringInternal(std::string &Str,
3871198092Srdivacky                                      const PrintingPolicy &Policy) const {
3872226633Sdim  llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3873198092Srdivacky         " was used directly instead of getting the QualType through"
3874198092Srdivacky         " GetTypeFromParser");
3875195341Sed}
3876195341Sed
3877212904SdimTypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3878193326Sed  // C99 6.7.6: Type names have no identifier.  This is already validated by
3879193326Sed  // the parser.
3880193326Sed  assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
3881198092Srdivacky
3882224145Sdim  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3883210299Sed  QualType T = TInfo->getType();
3884193326Sed  if (D.isInvalidType())
3885193326Sed    return true;
3886193326Sed
3887226633Sdim  // Make sure there are no unused decl attributes on the declarator.
3888226633Sdim  // We don't want to do this for ObjC parameters because we're going
3889226633Sdim  // to apply them to the actual parameter declaration.
3890249423Sdim  // Likewise, we don't want to do this for alias declarations, because
3891249423Sdim  // we are actually going to build a declaration from this eventually.
3892249423Sdim  if (D.getContext() != Declarator::ObjCParameterContext &&
3893249423Sdim      D.getContext() != Declarator::AliasDeclContext &&
3894249423Sdim      D.getContext() != Declarator::AliasTemplateContext)
3895226633Sdim    checkUnusedDeclAttributes(D);
3896226633Sdim
3897234353Sdim  if (getLangOpts().CPlusPlus) {
3898193326Sed    // Check that there are no default arguments (C++ only).
3899193326Sed    CheckExtraCXXDefaultArguments(D);
3900193326Sed  }
3901193326Sed
3902212904Sdim  return CreateParsedType(T, TInfo);
3903193326Sed}
3904193326Sed
3905226633SdimParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3906226633Sdim  QualType T = Context.getObjCInstanceType();
3907226633Sdim  TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3908226633Sdim  return CreateParsedType(T, TInfo);
3909226633Sdim}
3910226633Sdim
3911226633Sdim
3912193326Sed//===----------------------------------------------------------------------===//
3913193326Sed// Type Attribute Processing
3914193326Sed//===----------------------------------------------------------------------===//
3915193326Sed
3916193326Sed/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3917193326Sed/// specified type.  The attribute contains 1 argument, the id of the address
3918193326Sed/// space for the type.
3919198092Srdivackystatic void HandleAddressSpaceTypeAttribute(QualType &Type,
3920193326Sed                                            const AttributeList &Attr, Sema &S){
3921198092Srdivacky
3922193326Sed  // If this type is already address space qualified, reject it.
3923226633Sdim  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3924226633Sdim  // qualifiers for two or more different address spaces."
3925193326Sed  if (Type.getAddressSpace()) {
3926193326Sed    S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3927207619Srdivacky    Attr.setInvalid();
3928193326Sed    return;
3929193326Sed  }
3930198092Srdivacky
3931226633Sdim  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3932226633Sdim  // qualified by an address-space qualifier."
3933226633Sdim  if (Type->isFunctionType()) {
3934226633Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3935226633Sdim    Attr.setInvalid();
3936226633Sdim    return;
3937226633Sdim  }
3938226633Sdim
3939193326Sed  // Check the attribute arguments.
3940193326Sed  if (Attr.getNumArgs() != 1) {
3941263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3942263508Sdim      << Attr.getName() << 1;
3943207619Srdivacky    Attr.setInvalid();
3944193326Sed    return;
3945193326Sed  }
3946263508Sdim  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
3947193326Sed  llvm::APSInt addrSpace(32);
3948208600Srdivacky  if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3949208600Srdivacky      !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3950263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3951263508Sdim      << Attr.getName() << AANT_ArgumentIntegerConstant
3952193326Sed      << ASArgExpr->getSourceRange();
3953207619Srdivacky    Attr.setInvalid();
3954193326Sed    return;
3955193326Sed  }
3956193326Sed
3957198092Srdivacky  // Bounds checking.
3958198092Srdivacky  if (addrSpace.isSigned()) {
3959198092Srdivacky    if (addrSpace.isNegative()) {
3960198092Srdivacky      S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3961198092Srdivacky        << ASArgExpr->getSourceRange();
3962207619Srdivacky      Attr.setInvalid();
3963198092Srdivacky      return;
3964198092Srdivacky    }
3965198092Srdivacky    addrSpace.setIsSigned(false);
3966198092Srdivacky  }
3967198092Srdivacky  llvm::APSInt max(addrSpace.getBitWidth());
3968198092Srdivacky  max = Qualifiers::MaxAddressSpace;
3969198092Srdivacky  if (addrSpace > max) {
3970198092Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3971263508Sdim      << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
3972207619Srdivacky    Attr.setInvalid();
3973198092Srdivacky    return;
3974198092Srdivacky  }
3975198092Srdivacky
3976198092Srdivacky  unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3977193326Sed  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3978193326Sed}
3979193326Sed
3980234353Sdim/// Does this type have a "direct" ownership qualifier?  That is,
3981234353Sdim/// is it written like "__strong id", as opposed to something like
3982234353Sdim/// "typeof(foo)", where that happens to be strong?
3983234353Sdimstatic bool hasDirectOwnershipQualifier(QualType type) {
3984234353Sdim  // Fast path: no qualifier at all.
3985234353Sdim  assert(type.getQualifiers().hasObjCLifetime());
3986234353Sdim
3987234353Sdim  while (true) {
3988234353Sdim    // __strong id
3989234353Sdim    if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3990234353Sdim      if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3991234353Sdim        return true;
3992234353Sdim
3993234353Sdim      type = attr->getModifiedType();
3994234353Sdim
3995234353Sdim    // X *__strong (...)
3996234353Sdim    } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3997234353Sdim      type = paren->getInnerType();
3998239462Sdim
3999234353Sdim    // That's it for things we want to complain about.  In particular,
4000234353Sdim    // we do not want to look through typedefs, typeof(expr),
4001234353Sdim    // typeof(type), or any other way that the type is somehow
4002234353Sdim    // abstracted.
4003234353Sdim    } else {
4004239462Sdim
4005234353Sdim      return false;
4006234353Sdim    }
4007234353Sdim  }
4008234353Sdim}
4009234353Sdim
4010224145Sdim/// handleObjCOwnershipTypeAttr - Process an objc_ownership
4011224145Sdim/// attribute on the specified type.
4012224145Sdim///
4013224145Sdim/// Returns 'true' if the attribute was handled.
4014224145Sdimstatic bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
4015224145Sdim                                       AttributeList &attr,
4016224145Sdim                                       QualType &type) {
4017234353Sdim  bool NonObjCPointer = false;
4018224145Sdim
4019251662Sdim  if (!type->isDependentType() && !type->isUndeducedType()) {
4020234353Sdim    if (const PointerType *ptr = type->getAs<PointerType>()) {
4021234353Sdim      QualType pointee = ptr->getPointeeType();
4022234353Sdim      if (pointee->isObjCRetainableType() || pointee->isPointerType())
4023234353Sdim        return false;
4024234353Sdim      // It is important not to lose the source info that there was an attribute
4025234353Sdim      // applied to non-objc pointer. We will create an attributed type but
4026234353Sdim      // its type will be the same as the original type.
4027234353Sdim      NonObjCPointer = true;
4028234353Sdim    } else if (!type->isObjCRetainableType()) {
4029234353Sdim      return false;
4030234353Sdim    }
4031249423Sdim
4032249423Sdim    // Don't accept an ownership attribute in the declspec if it would
4033249423Sdim    // just be the return type of a block pointer.
4034249423Sdim    if (state.isProcessingDeclSpec()) {
4035249423Sdim      Declarator &D = state.getDeclarator();
4036249423Sdim      if (maybeMovePastReturnType(D, D.getNumTypeObjects()))
4037249423Sdim        return false;
4038249423Sdim    }
4039234353Sdim  }
4040234353Sdim
4041224145Sdim  Sema &S = state.getSema();
4042226633Sdim  SourceLocation AttrLoc = attr.getLoc();
4043226633Sdim  if (AttrLoc.isMacroID())
4044226633Sdim    AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
4045224145Sdim
4046263508Sdim  if (!attr.isArgIdent(0)) {
4047263508Sdim    S.Diag(AttrLoc, diag::err_attribute_argument_type)
4048263508Sdim      << attr.getName() << AANT_ArgumentString;
4049224145Sdim    attr.setInvalid();
4050224145Sdim    return true;
4051224145Sdim  }
4052224145Sdim
4053234353Sdim  // Consume lifetime attributes without further comment outside of
4054234353Sdim  // ARC mode.
4055234353Sdim  if (!S.getLangOpts().ObjCAutoRefCount)
4056234353Sdim    return true;
4057234353Sdim
4058263508Sdim  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4059224145Sdim  Qualifiers::ObjCLifetime lifetime;
4060263508Sdim  if (II->isStr("none"))
4061224145Sdim    lifetime = Qualifiers::OCL_ExplicitNone;
4062263508Sdim  else if (II->isStr("strong"))
4063224145Sdim    lifetime = Qualifiers::OCL_Strong;
4064263508Sdim  else if (II->isStr("weak"))
4065224145Sdim    lifetime = Qualifiers::OCL_Weak;
4066263508Sdim  else if (II->isStr("autoreleasing"))
4067224145Sdim    lifetime = Qualifiers::OCL_Autoreleasing;
4068224145Sdim  else {
4069226633Sdim    S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
4070263508Sdim      << attr.getName() << II;
4071224145Sdim    attr.setInvalid();
4072224145Sdim    return true;
4073224145Sdim  }
4074224145Sdim
4075234353Sdim  SplitQualType underlyingType = type.split();
4076224145Sdim
4077234353Sdim  // Check for redundant/conflicting ownership qualifiers.
4078234353Sdim  if (Qualifiers::ObjCLifetime previousLifetime
4079234353Sdim        = type.getQualifiers().getObjCLifetime()) {
4080234353Sdim    // If it's written directly, that's an error.
4081234353Sdim    if (hasDirectOwnershipQualifier(type)) {
4082234353Sdim      S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
4083234353Sdim        << type;
4084234353Sdim      return true;
4085234353Sdim    }
4086234353Sdim
4087234353Sdim    // Otherwise, if the qualifiers actually conflict, pull sugar off
4088234353Sdim    // until we reach a type that is directly qualified.
4089234353Sdim    if (previousLifetime != lifetime) {
4090234353Sdim      // This should always terminate: the canonical type is
4091234353Sdim      // qualified, so some bit of sugar must be hiding it.
4092234353Sdim      while (!underlyingType.Quals.hasObjCLifetime()) {
4093234353Sdim        underlyingType = underlyingType.getSingleStepDesugaredType();
4094234353Sdim      }
4095234353Sdim      underlyingType.Quals.removeObjCLifetime();
4096234353Sdim    }
4097234353Sdim  }
4098234353Sdim
4099234353Sdim  underlyingType.Quals.addObjCLifetime(lifetime);
4100234353Sdim
4101234353Sdim  if (NonObjCPointer) {
4102234353Sdim    StringRef name = attr.getName()->getName();
4103234353Sdim    switch (lifetime) {
4104234353Sdim    case Qualifiers::OCL_None:
4105234353Sdim    case Qualifiers::OCL_ExplicitNone:
4106234353Sdim      break;
4107234353Sdim    case Qualifiers::OCL_Strong: name = "__strong"; break;
4108234353Sdim    case Qualifiers::OCL_Weak: name = "__weak"; break;
4109234353Sdim    case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
4110234353Sdim    }
4111263508Sdim    S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
4112263508Sdim      << TDS_ObjCObjOrBlock << type;
4113234353Sdim  }
4114234353Sdim
4115224145Sdim  QualType origType = type;
4116234353Sdim  if (!NonObjCPointer)
4117234353Sdim    type = S.Context.getQualifiedType(underlyingType);
4118224145Sdim
4119224145Sdim  // If we have a valid source location for the attribute, use an
4120224145Sdim  // AttributedType instead.
4121226633Sdim  if (AttrLoc.isValid())
4122224145Sdim    type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
4123224145Sdim                                       origType, type);
4124224145Sdim
4125224145Sdim  // Forbid __weak if the runtime doesn't support it.
4126224145Sdim  if (lifetime == Qualifiers::OCL_Weak &&
4127243830Sdim      !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
4128224145Sdim
4129224145Sdim    // Actually, delay this until we know what we're parsing.
4130224145Sdim    if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
4131224145Sdim      S.DelayedDiagnostics.add(
4132226633Sdim          sema::DelayedDiagnostic::makeForbiddenType(
4133226633Sdim              S.getSourceManager().getExpansionLoc(AttrLoc),
4134224145Sdim              diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
4135224145Sdim    } else {
4136226633Sdim      S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
4137224145Sdim    }
4138224145Sdim
4139224145Sdim    attr.setInvalid();
4140224145Sdim    return true;
4141224145Sdim  }
4142239462Sdim
4143239462Sdim  // Forbid __weak for class objects marked as
4144224145Sdim  // objc_arc_weak_reference_unavailable
4145224145Sdim  if (lifetime == Qualifiers::OCL_Weak) {
4146249423Sdim    if (const ObjCObjectPointerType *ObjT =
4147249423Sdim          type->getAs<ObjCObjectPointerType>()) {
4148243830Sdim      if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
4149243830Sdim        if (Class->isArcWeakrefUnavailable()) {
4150243830Sdim            S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
4151243830Sdim            S.Diag(ObjT->getInterfaceDecl()->getLocation(),
4152243830Sdim                   diag::note_class_declared);
4153243830Sdim        }
4154224145Sdim      }
4155224145Sdim    }
4156224145Sdim  }
4157239462Sdim
4158224145Sdim  return true;
4159224145Sdim}
4160224145Sdim
4161218893Sdim/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
4162218893Sdim/// attribute on the specified type.  Returns true to indicate that
4163218893Sdim/// the attribute was handled, false to indicate that the type does
4164218893Sdim/// not permit the attribute.
4165218893Sdimstatic bool handleObjCGCTypeAttr(TypeProcessingState &state,
4166218893Sdim                                 AttributeList &attr,
4167218893Sdim                                 QualType &type) {
4168218893Sdim  Sema &S = state.getSema();
4169218893Sdim
4170218893Sdim  // Delay if this isn't some kind of pointer.
4171218893Sdim  if (!type->isPointerType() &&
4172218893Sdim      !type->isObjCObjectPointerType() &&
4173218893Sdim      !type->isBlockPointerType())
4174218893Sdim    return false;
4175218893Sdim
4176218893Sdim  if (type.getObjCGCAttr() != Qualifiers::GCNone) {
4177218893Sdim    S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
4178218893Sdim    attr.setInvalid();
4179218893Sdim    return true;
4180193326Sed  }
4181263508Sdim
4182193326Sed  // Check the attribute arguments.
4183263508Sdim  if (!attr.isArgIdent(0)) {
4184263508Sdim    S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
4185263508Sdim      << attr.getName() << AANT_ArgumentString;
4186218893Sdim    attr.setInvalid();
4187218893Sdim    return true;
4188193326Sed  }
4189198092Srdivacky  Qualifiers::GC GCAttr;
4190263508Sdim  if (attr.getNumArgs() > 1) {
4191263508Sdim    S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4192263508Sdim      << attr.getName() << 1;
4193218893Sdim    attr.setInvalid();
4194218893Sdim    return true;
4195193326Sed  }
4196263508Sdim
4197263508Sdim  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4198263508Sdim  if (II->isStr("weak"))
4199198092Srdivacky    GCAttr = Qualifiers::Weak;
4200263508Sdim  else if (II->isStr("strong"))
4201198092Srdivacky    GCAttr = Qualifiers::Strong;
4202193326Sed  else {
4203218893Sdim    S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
4204263508Sdim      << attr.getName() << II;
4205218893Sdim    attr.setInvalid();
4206218893Sdim    return true;
4207193326Sed  }
4208198092Srdivacky
4209221345Sdim  QualType origType = type;
4210221345Sdim  type = S.Context.getObjCGCQualType(origType, GCAttr);
4211221345Sdim
4212221345Sdim  // Make an attributed type to preserve the source information.
4213221345Sdim  if (attr.getLoc().isValid())
4214221345Sdim    type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
4215221345Sdim                                       origType, type);
4216221345Sdim
4217218893Sdim  return true;
4218193326Sed}
4219193326Sed
4220218893Sdimnamespace {
4221218893Sdim  /// A helper class to unwrap a type down to a function for the
4222218893Sdim  /// purposes of applying attributes there.
4223218893Sdim  ///
4224218893Sdim  /// Use:
4225218893Sdim  ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
4226218893Sdim  ///   if (unwrapped.isFunctionType()) {
4227218893Sdim  ///     const FunctionType *fn = unwrapped.get();
4228218893Sdim  ///     // change fn somehow
4229218893Sdim  ///     T = unwrapped.wrap(fn);
4230218893Sdim  ///   }
4231218893Sdim  struct FunctionTypeUnwrapper {
4232218893Sdim    enum WrapKind {
4233218893Sdim      Desugar,
4234218893Sdim      Parens,
4235218893Sdim      Pointer,
4236218893Sdim      BlockPointer,
4237218893Sdim      Reference,
4238218893Sdim      MemberPointer
4239218893Sdim    };
4240218893Sdim
4241218893Sdim    QualType Original;
4242218893Sdim    const FunctionType *Fn;
4243226633Sdim    SmallVector<unsigned char /*WrapKind*/, 8> Stack;
4244218893Sdim
4245218893Sdim    FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
4246218893Sdim      while (true) {
4247218893Sdim        const Type *Ty = T.getTypePtr();
4248218893Sdim        if (isa<FunctionType>(Ty)) {
4249218893Sdim          Fn = cast<FunctionType>(Ty);
4250218893Sdim          return;
4251218893Sdim        } else if (isa<ParenType>(Ty)) {
4252218893Sdim          T = cast<ParenType>(Ty)->getInnerType();
4253218893Sdim          Stack.push_back(Parens);
4254218893Sdim        } else if (isa<PointerType>(Ty)) {
4255218893Sdim          T = cast<PointerType>(Ty)->getPointeeType();
4256218893Sdim          Stack.push_back(Pointer);
4257218893Sdim        } else if (isa<BlockPointerType>(Ty)) {
4258218893Sdim          T = cast<BlockPointerType>(Ty)->getPointeeType();
4259218893Sdim          Stack.push_back(BlockPointer);
4260218893Sdim        } else if (isa<MemberPointerType>(Ty)) {
4261218893Sdim          T = cast<MemberPointerType>(Ty)->getPointeeType();
4262218893Sdim          Stack.push_back(MemberPointer);
4263218893Sdim        } else if (isa<ReferenceType>(Ty)) {
4264218893Sdim          T = cast<ReferenceType>(Ty)->getPointeeType();
4265218893Sdim          Stack.push_back(Reference);
4266218893Sdim        } else {
4267218893Sdim          const Type *DTy = Ty->getUnqualifiedDesugaredType();
4268218893Sdim          if (Ty == DTy) {
4269218893Sdim            Fn = 0;
4270218893Sdim            return;
4271218893Sdim          }
4272218893Sdim
4273218893Sdim          T = QualType(DTy, 0);
4274218893Sdim          Stack.push_back(Desugar);
4275218893Sdim        }
4276218893Sdim      }
4277203955Srdivacky    }
4278198092Srdivacky
4279218893Sdim    bool isFunctionType() const { return (Fn != 0); }
4280218893Sdim    const FunctionType *get() const { return Fn; }
4281203955Srdivacky
4282218893Sdim    QualType wrap(Sema &S, const FunctionType *New) {
4283218893Sdim      // If T wasn't modified from the unwrapped type, do nothing.
4284218893Sdim      if (New == get()) return Original;
4285218893Sdim
4286218893Sdim      Fn = New;
4287218893Sdim      return wrap(S.Context, Original, 0);
4288206084Srdivacky    }
4289206084Srdivacky
4290218893Sdim  private:
4291218893Sdim    QualType wrap(ASTContext &C, QualType Old, unsigned I) {
4292218893Sdim      if (I == Stack.size())
4293218893Sdim        return C.getQualifiedType(Fn, Old.getQualifiers());
4294218893Sdim
4295218893Sdim      // Build up the inner type, applying the qualifiers from the old
4296218893Sdim      // type to the new type.
4297218893Sdim      SplitQualType SplitOld = Old.split();
4298218893Sdim
4299218893Sdim      // As a special case, tail-recurse if there are no qualifiers.
4300234353Sdim      if (SplitOld.Quals.empty())
4301234353Sdim        return wrap(C, SplitOld.Ty, I);
4302234353Sdim      return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
4303218893Sdim    }
4304218893Sdim
4305218893Sdim    QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
4306218893Sdim      if (I == Stack.size()) return QualType(Fn, 0);
4307218893Sdim
4308218893Sdim      switch (static_cast<WrapKind>(Stack[I++])) {
4309218893Sdim      case Desugar:
4310218893Sdim        // This is the point at which we potentially lose source
4311218893Sdim        // information.
4312218893Sdim        return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4313218893Sdim
4314218893Sdim      case Parens: {
4315218893Sdim        QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4316218893Sdim        return C.getParenType(New);
4317218893Sdim      }
4318218893Sdim
4319218893Sdim      case Pointer: {
4320218893Sdim        QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4321218893Sdim        return C.getPointerType(New);
4322218893Sdim      }
4323218893Sdim
4324218893Sdim      case BlockPointer: {
4325218893Sdim        QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4326218893Sdim        return C.getBlockPointerType(New);
4327218893Sdim      }
4328218893Sdim
4329218893Sdim      case MemberPointer: {
4330218893Sdim        const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4331218893Sdim        QualType New = wrap(C, OldMPT->getPointeeType(), I);
4332218893Sdim        return C.getMemberPointerType(New, OldMPT->getClass());
4333218893Sdim      }
4334218893Sdim
4335218893Sdim      case Reference: {
4336218893Sdim        const ReferenceType *OldRef = cast<ReferenceType>(Old);
4337218893Sdim        QualType New = wrap(C, OldRef->getPointeeType(), I);
4338218893Sdim        if (isa<LValueReferenceType>(OldRef))
4339218893Sdim          return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4340218893Sdim        else
4341218893Sdim          return C.getRValueReferenceType(New);
4342218893Sdim      }
4343218893Sdim      }
4344218893Sdim
4345218893Sdim      llvm_unreachable("unknown wrapping kind");
4346218893Sdim    }
4347218893Sdim  };
4348218893Sdim}
4349218893Sdim
4350263508Sdimstatic bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
4351263508Sdim                                             AttributeList &Attr,
4352263508Sdim                                             QualType &Type) {
4353263508Sdim  Sema &S = State.getSema();
4354263508Sdim
4355263508Sdim  AttributeList::Kind Kind = Attr.getKind();
4356263508Sdim  QualType Desugared = Type;
4357263508Sdim  const AttributedType *AT = dyn_cast<AttributedType>(Type);
4358263508Sdim  while (AT) {
4359263508Sdim    AttributedType::Kind CurAttrKind = AT->getAttrKind();
4360263508Sdim
4361263508Sdim    // You cannot specify duplicate type attributes, so if the attribute has
4362263508Sdim    // already been applied, flag it.
4363263508Sdim    if (getAttrListKind(CurAttrKind) == Kind) {
4364263508Sdim      S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
4365263508Sdim        << Attr.getName();
4366263508Sdim      return true;
4367263508Sdim    }
4368263508Sdim
4369263508Sdim    // You cannot have both __sptr and __uptr on the same type, nor can you
4370263508Sdim    // have __ptr32 and __ptr64.
4371263508Sdim    if ((CurAttrKind == AttributedType::attr_ptr32 &&
4372263508Sdim         Kind == AttributeList::AT_Ptr64) ||
4373263508Sdim        (CurAttrKind == AttributedType::attr_ptr64 &&
4374263508Sdim         Kind == AttributeList::AT_Ptr32)) {
4375263508Sdim      S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4376263508Sdim        << "'__ptr32'" << "'__ptr64'";
4377263508Sdim      return true;
4378263508Sdim    } else if ((CurAttrKind == AttributedType::attr_sptr &&
4379263508Sdim                Kind == AttributeList::AT_UPtr) ||
4380263508Sdim               (CurAttrKind == AttributedType::attr_uptr &&
4381263508Sdim                Kind == AttributeList::AT_SPtr)) {
4382263508Sdim      S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4383263508Sdim        << "'__sptr'" << "'__uptr'";
4384263508Sdim      return true;
4385263508Sdim    }
4386263508Sdim
4387263508Sdim    Desugared = AT->getEquivalentType();
4388263508Sdim    AT = dyn_cast<AttributedType>(Desugared);
4389263508Sdim  }
4390263508Sdim
4391263508Sdim  // Pointer type qualifiers can only operate on pointer types, but not
4392263508Sdim  // pointer-to-member types.
4393263508Sdim  if (!isa<PointerType>(Desugared)) {
4394263508Sdim    S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
4395263508Sdim                          diag::err_attribute_no_member_pointers :
4396263508Sdim                          diag::err_attribute_pointers_only) << Attr.getName();
4397263508Sdim    return true;
4398263508Sdim  }
4399263508Sdim
4400263508Sdim  AttributedType::Kind TAK;
4401263508Sdim  switch (Kind) {
4402263508Sdim  default: llvm_unreachable("Unknown attribute kind");
4403263508Sdim  case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
4404263508Sdim  case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
4405263508Sdim  case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
4406263508Sdim  case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
4407263508Sdim  }
4408263508Sdim
4409263508Sdim  Type = S.Context.getAttributedType(TAK, Type, Type);
4410263508Sdim  return false;
4411263508Sdim}
4412263508Sdim
4413263508Sdimstatic AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
4414263508Sdim  assert(!Attr.isInvalid());
4415263508Sdim  switch (Attr.getKind()) {
4416263508Sdim  default:
4417263508Sdim    llvm_unreachable("not a calling convention attribute");
4418263508Sdim  case AttributeList::AT_CDecl:
4419263508Sdim    return AttributedType::attr_cdecl;
4420263508Sdim  case AttributeList::AT_FastCall:
4421263508Sdim    return AttributedType::attr_fastcall;
4422263508Sdim  case AttributeList::AT_StdCall:
4423263508Sdim    return AttributedType::attr_stdcall;
4424263508Sdim  case AttributeList::AT_ThisCall:
4425263508Sdim    return AttributedType::attr_thiscall;
4426263508Sdim  case AttributeList::AT_Pascal:
4427263508Sdim    return AttributedType::attr_pascal;
4428263508Sdim  case AttributeList::AT_Pcs: {
4429263508Sdim    // The attribute may have had a fixit applied where we treated an
4430263508Sdim    // identifier as a string literal.  The contents of the string are valid,
4431263508Sdim    // but the form may not be.
4432263508Sdim    StringRef Str;
4433263508Sdim    if (Attr.isArgExpr(0))
4434263508Sdim      Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
4435263508Sdim    else
4436263508Sdim      Str = Attr.getArgAsIdent(0)->Ident->getName();
4437263508Sdim    return llvm::StringSwitch<AttributedType::Kind>(Str)
4438263508Sdim        .Case("aapcs", AttributedType::attr_pcs)
4439263508Sdim        .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
4440263508Sdim  }
4441263508Sdim  case AttributeList::AT_PnaclCall:
4442263508Sdim    return AttributedType::attr_pnaclcall;
4443263508Sdim  case AttributeList::AT_IntelOclBicc:
4444263508Sdim    return AttributedType::attr_inteloclbicc;
4445263508Sdim  case AttributeList::AT_MSABI:
4446263508Sdim    return AttributedType::attr_ms_abi;
4447263508Sdim  case AttributeList::AT_SysVABI:
4448263508Sdim    return AttributedType::attr_sysv_abi;
4449263508Sdim  }
4450263508Sdim  llvm_unreachable("unexpected attribute kind!");
4451263508Sdim}
4452263508Sdim
4453218893Sdim/// Process an individual function attribute.  Returns true to
4454218893Sdim/// indicate that the attribute was handled, false if it wasn't.
4455218893Sdimstatic bool handleFunctionTypeAttr(TypeProcessingState &state,
4456218893Sdim                                   AttributeList &attr,
4457218893Sdim                                   QualType &type) {
4458218893Sdim  Sema &S = state.getSema();
4459218893Sdim
4460218893Sdim  FunctionTypeUnwrapper unwrapped(S, type);
4461218893Sdim
4462239462Sdim  if (attr.getKind() == AttributeList::AT_NoReturn) {
4463218893Sdim    if (S.CheckNoReturnAttr(attr))
4464206084Srdivacky      return true;
4465206084Srdivacky
4466218893Sdim    // Delay if this is not a function type.
4467218893Sdim    if (!unwrapped.isFunctionType())
4468218893Sdim      return false;
4469218893Sdim
4470206084Srdivacky    // Otherwise we can process right away.
4471218893Sdim    FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
4472218893Sdim    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4473218893Sdim    return true;
4474218893Sdim  }
4475206084Srdivacky
4476224145Sdim  // ns_returns_retained is not always a type attribute, but if we got
4477224145Sdim  // here, we're treating it as one right now.
4478239462Sdim  if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
4479234353Sdim    assert(S.getLangOpts().ObjCAutoRefCount &&
4480224145Sdim           "ns_returns_retained treated as type attribute in non-ARC");
4481224145Sdim    if (attr.getNumArgs()) return true;
4482224145Sdim
4483224145Sdim    // Delay if this is not a function type.
4484224145Sdim    if (!unwrapped.isFunctionType())
4485224145Sdim      return false;
4486224145Sdim
4487224145Sdim    FunctionType::ExtInfo EI
4488224145Sdim      = unwrapped.get()->getExtInfo().withProducesResult(true);
4489224145Sdim    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4490224145Sdim    return true;
4491224145Sdim  }
4492224145Sdim
4493239462Sdim  if (attr.getKind() == AttributeList::AT_Regparm) {
4494218893Sdim    unsigned value;
4495218893Sdim    if (S.CheckRegparmAttr(attr, value))
4496218893Sdim      return true;
4497218893Sdim
4498218893Sdim    // Delay if this is not a function type.
4499218893Sdim    if (!unwrapped.isFunctionType())
4500206084Srdivacky      return false;
4501206084Srdivacky
4502218893Sdim    // Diagnose regparm with fastcall.
4503218893Sdim    const FunctionType *fn = unwrapped.get();
4504218893Sdim    CallingConv CC = fn->getCallConv();
4505218893Sdim    if (CC == CC_X86FastCall) {
4506218893Sdim      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4507218893Sdim        << FunctionType::getNameForCallConv(CC)
4508218893Sdim        << "regparm";
4509218893Sdim      attr.setInvalid();
4510218893Sdim      return true;
4511218893Sdim    }
4512218893Sdim
4513239462Sdim    FunctionType::ExtInfo EI =
4514218893Sdim      unwrapped.get()->getExtInfo().withRegParm(value);
4515218893Sdim    type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4516218893Sdim    return true;
4517206084Srdivacky  }
4518206084Srdivacky
4519243830Sdim  // Delay if the type didn't work out to a function.
4520243830Sdim  if (!unwrapped.isFunctionType()) return false;
4521243830Sdim
4522203955Srdivacky  // Otherwise, a calling convention.
4523218893Sdim  CallingConv CC;
4524218893Sdim  if (S.CheckCallingConvAttr(attr, CC))
4525218893Sdim    return true;
4526203955Srdivacky
4527218893Sdim  const FunctionType *fn = unwrapped.get();
4528218893Sdim  CallingConv CCOld = fn->getCallConv();
4529263508Sdim  AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
4530263508Sdim
4531263508Sdim  if (CCOld != CC) {
4532263508Sdim    // Error out on when there's already an attribute on the type
4533263508Sdim    // and the CCs don't match.
4534263508Sdim    const AttributedType *AT = S.getCallingConvAttributedType(type);
4535263508Sdim    if (AT && AT->getAttrKind() != CCAttrKind) {
4536263508Sdim      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4537263508Sdim        << FunctionType::getNameForCallConv(CC)
4538263508Sdim        << FunctionType::getNameForCallConv(CCOld);
4539263508Sdim      attr.setInvalid();
4540263508Sdim      return true;
4541263508Sdim    }
4542207619Srdivacky  }
4543203955Srdivacky
4544263508Sdim  // Diagnose use of callee-cleanup calling convention on variadic functions.
4545263508Sdim  if (isCalleeCleanup(CC)) {
4546263508Sdim    const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
4547263508Sdim    if (FnP && FnP->isVariadic()) {
4548263508Sdim      unsigned DiagID = diag::err_cconv_varargs;
4549263508Sdim      // stdcall and fastcall are ignored with a warning for GCC and MS
4550263508Sdim      // compatibility.
4551263508Sdim      if (CC == CC_X86StdCall || CC == CC_X86FastCall)
4552263508Sdim        DiagID = diag::warn_cconv_varargs;
4553263508Sdim
4554263508Sdim      S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
4555263508Sdim      attr.setInvalid();
4556263508Sdim      return true;
4557263508Sdim    }
4558203955Srdivacky  }
4559203955Srdivacky
4560263508Sdim  // Diagnose the use of X86 fastcall on unprototyped functions.
4561203955Srdivacky  if (CC == CC_X86FastCall) {
4562218893Sdim    if (isa<FunctionNoProtoType>(fn)) {
4563218893Sdim      S.Diag(attr.getLoc(), diag::err_cconv_knr)
4564203955Srdivacky        << FunctionType::getNameForCallConv(CC);
4565218893Sdim      attr.setInvalid();
4566218893Sdim      return true;
4567203955Srdivacky    }
4568203955Srdivacky
4569218893Sdim    // Also diagnose fastcall with regparm.
4570221345Sdim    if (fn->getHasRegParm()) {
4571218893Sdim      S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4572218893Sdim        << "regparm"
4573218893Sdim        << FunctionType::getNameForCallConv(CC);
4574218893Sdim      attr.setInvalid();
4575218893Sdim      return true;
4576218893Sdim    }
4577203955Srdivacky  }
4578203955Srdivacky
4579263508Sdim  // Modify the CC from the wrapped function type, wrap it all back, and then
4580263508Sdim  // wrap the whole thing in an AttributedType as written.  The modified type
4581263508Sdim  // might have a different CC if we ignored the attribute.
4582218893Sdim  FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
4583263508Sdim  QualType Equivalent =
4584263508Sdim      unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4585263508Sdim  type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
4586218893Sdim  return true;
4587198092Srdivacky}
4588198092Srdivacky
4589263508Sdimvoid Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) {
4590263508Sdim  const FunctionType *FT = T->castAs<FunctionType>();
4591263508Sdim  bool IsVariadic = (isa<FunctionProtoType>(FT) &&
4592263508Sdim                     cast<FunctionProtoType>(FT)->isVariadic());
4593263508Sdim  CallingConv CC = FT->getCallConv();
4594263508Sdim
4595263508Sdim  // Only adjust types with the default convention.  For example, on Windows we
4596263508Sdim  // should adjust a __cdecl type to __thiscall for instance methods, and a
4597263508Sdim  // __thiscall type to __cdecl for static methods.
4598263508Sdim  CallingConv DefaultCC =
4599263508Sdim      Context.getDefaultCallingConvention(IsVariadic, IsStatic);
4600263508Sdim  if (CC != DefaultCC)
4601263508Sdim    return;
4602263508Sdim
4603263508Sdim  // Check if there was an explicit attribute, but only look through parens.
4604263508Sdim  // The intent is to look for an attribute on the current declarator, but not
4605263508Sdim  // one that came from a typedef.
4606263508Sdim  QualType R = T.IgnoreParens();
4607263508Sdim  while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
4608263508Sdim    if (AT->isCallingConv())
4609263508Sdim      return;
4610263508Sdim    R = AT->getModifiedType().IgnoreParens();
4611263508Sdim  }
4612263508Sdim
4613263508Sdim  // FIXME: This loses sugar.  This should probably be fixed with an implicit
4614263508Sdim  // AttributedType node that adjusts the convention.
4615263508Sdim  CC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
4616263508Sdim  FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC));
4617263508Sdim  FunctionTypeUnwrapper Unwrapped(*this, T);
4618263508Sdim  T = Unwrapped.wrap(*this, FT);
4619263508Sdim}
4620263508Sdim
4621221345Sdim/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
4622221345Sdimstatic void HandleOpenCLImageAccessAttribute(QualType& CurType,
4623221345Sdim                                             const AttributeList &Attr,
4624221345Sdim                                             Sema &S) {
4625221345Sdim  // Check the attribute arguments.
4626221345Sdim  if (Attr.getNumArgs() != 1) {
4627263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4628263508Sdim      << Attr.getName() << 1;
4629221345Sdim    Attr.setInvalid();
4630221345Sdim    return;
4631221345Sdim  }
4632263508Sdim  Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4633221345Sdim  llvm::APSInt arg(32);
4634221345Sdim  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4635221345Sdim      !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
4636263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4637263508Sdim      << Attr.getName() << AANT_ArgumentIntegerConstant
4638263508Sdim      << sizeExpr->getSourceRange();
4639221345Sdim    Attr.setInvalid();
4640221345Sdim    return;
4641221345Sdim  }
4642221345Sdim  unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
4643221345Sdim  switch (iarg) {
4644221345Sdim  case CLIA_read_only:
4645221345Sdim  case CLIA_write_only:
4646221345Sdim  case CLIA_read_write:
4647221345Sdim    // Implemented in a separate patch
4648221345Sdim    break;
4649221345Sdim  default:
4650221345Sdim    // Implemented in a separate patch
4651221345Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4652221345Sdim      << sizeExpr->getSourceRange();
4653221345Sdim    Attr.setInvalid();
4654221345Sdim    break;
4655221345Sdim  }
4656221345Sdim}
4657221345Sdim
4658200583Srdivacky/// HandleVectorSizeAttribute - this attribute is only applicable to integral
4659200583Srdivacky/// and float scalars, although arrays, pointers, and function return values are
4660200583Srdivacky/// allowed in conjunction with this construct. Aggregates with this attribute
4661200583Srdivacky/// are invalid, even if they are of the same size as a corresponding scalar.
4662200583Srdivacky/// The raw attribute should contain precisely 1 argument, the vector size for
4663200583Srdivacky/// the variable, measured in bytes. If curType and rawAttr are well formed,
4664200583Srdivacky/// this routine will return a new vector type.
4665210299Sedstatic void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4666210299Sed                                 Sema &S) {
4667218893Sdim  // Check the attribute arguments.
4668200583Srdivacky  if (Attr.getNumArgs() != 1) {
4669263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4670263508Sdim      << Attr.getName() << 1;
4671207619Srdivacky    Attr.setInvalid();
4672200583Srdivacky    return;
4673200583Srdivacky  }
4674263508Sdim  Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4675200583Srdivacky  llvm::APSInt vecSize(32);
4676208600Srdivacky  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4677208600Srdivacky      !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
4678263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4679263508Sdim      << Attr.getName() << AANT_ArgumentIntegerConstant
4680263508Sdim      << sizeExpr->getSourceRange();
4681207619Srdivacky    Attr.setInvalid();
4682200583Srdivacky    return;
4683200583Srdivacky  }
4684263508Sdim  // The base type must be integer (not Boolean or enumeration) or float, and
4685263508Sdim  // can't already be a vector.
4686263508Sdim  if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
4687263508Sdim      (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
4688200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4689207619Srdivacky    Attr.setInvalid();
4690200583Srdivacky    return;
4691200583Srdivacky  }
4692200583Srdivacky  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4693200583Srdivacky  // vecSize is specified in bytes - convert to bits.
4694200583Srdivacky  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4695200583Srdivacky
4696200583Srdivacky  // the vector size needs to be an integral multiple of the type size.
4697200583Srdivacky  if (vectorSize % typeSize) {
4698200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4699200583Srdivacky      << sizeExpr->getSourceRange();
4700207619Srdivacky    Attr.setInvalid();
4701200583Srdivacky    return;
4702200583Srdivacky  }
4703263508Sdim  if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
4704263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
4705263508Sdim      << sizeExpr->getSourceRange();
4706263508Sdim    Attr.setInvalid();
4707263508Sdim    return;
4708263508Sdim  }
4709200583Srdivacky  if (vectorSize == 0) {
4710200583Srdivacky    S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4711200583Srdivacky      << sizeExpr->getSourceRange();
4712207619Srdivacky    Attr.setInvalid();
4713200583Srdivacky    return;
4714200583Srdivacky  }
4715200583Srdivacky
4716200583Srdivacky  // Success! Instantiate the vector type, the number of elements is > 0, and
4717200583Srdivacky  // not required to be a power of 2, unlike GCC.
4718210299Sed  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
4719218893Sdim                                    VectorType::GenericVector);
4720200583Srdivacky}
4721200583Srdivacky
4722224145Sdim/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4723224145Sdim/// a type.
4724239462Sdimstatic void HandleExtVectorTypeAttr(QualType &CurType,
4725239462Sdim                                    const AttributeList &Attr,
4726224145Sdim                                    Sema &S) {
4727263508Sdim  // check the attribute arguments.
4728263508Sdim  if (Attr.getNumArgs() != 1) {
4729263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4730263508Sdim      << Attr.getName() << 1;
4731263508Sdim    return;
4732263508Sdim  }
4733263508Sdim
4734224145Sdim  Expr *sizeExpr;
4735239462Sdim
4736224145Sdim  // Special case where the argument is a template id.
4737263508Sdim  if (Attr.isArgIdent(0)) {
4738224145Sdim    CXXScopeSpec SS;
4739234353Sdim    SourceLocation TemplateKWLoc;
4740224145Sdim    UnqualifiedId id;
4741263508Sdim    id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
4742234353Sdim
4743234353Sdim    ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4744234353Sdim                                          id, false, false);
4745224145Sdim    if (Size.isInvalid())
4746224145Sdim      return;
4747239462Sdim
4748224145Sdim    sizeExpr = Size.get();
4749224145Sdim  } else {
4750263508Sdim    sizeExpr = Attr.getArgAsExpr(0);
4751224145Sdim  }
4752239462Sdim
4753224145Sdim  // Create the vector type.
4754224145Sdim  QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4755224145Sdim  if (!T.isNull())
4756224145Sdim    CurType = T;
4757224145Sdim}
4758224145Sdim
4759263508Sdimstatic bool isPermittedNeonBaseType(QualType &Ty,
4760263508Sdim                                    VectorType::VectorKind VecKind,
4761263508Sdim                                    bool IsAArch64) {
4762263508Sdim  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
4763263508Sdim  if (!BTy)
4764263508Sdim    return false;
4765263508Sdim
4766263508Sdim  if (VecKind == VectorType::NeonPolyVector) {
4767263508Sdim    if (IsAArch64) {
4768263508Sdim      // AArch64 polynomial vectors are unsigned and support poly64.
4769263508Sdim      return BTy->getKind() == BuiltinType::UChar ||
4770263508Sdim             BTy->getKind() == BuiltinType::UShort ||
4771263508Sdim             BTy->getKind() == BuiltinType::ULongLong;
4772263508Sdim    } else {
4773263508Sdim      // AArch32 polynomial vector are signed.
4774263508Sdim      return BTy->getKind() == BuiltinType::SChar ||
4775263508Sdim             BTy->getKind() == BuiltinType::Short;
4776263508Sdim    }
4777263508Sdim  }
4778263508Sdim
4779263508Sdim  // Non-polynomial vector types: the usual suspects are allowed, as well as
4780263508Sdim  // float64_t on AArch64.
4781263508Sdim  if (IsAArch64 && BTy->getKind() == BuiltinType::Double)
4782263508Sdim    return true;
4783263508Sdim
4784263508Sdim  return BTy->getKind() == BuiltinType::SChar ||
4785263508Sdim         BTy->getKind() == BuiltinType::UChar ||
4786263508Sdim         BTy->getKind() == BuiltinType::Short ||
4787263508Sdim         BTy->getKind() == BuiltinType::UShort ||
4788263508Sdim         BTy->getKind() == BuiltinType::Int ||
4789263508Sdim         BTy->getKind() == BuiltinType::UInt ||
4790263508Sdim         BTy->getKind() == BuiltinType::LongLong ||
4791263508Sdim         BTy->getKind() == BuiltinType::ULongLong ||
4792263508Sdim         BTy->getKind() == BuiltinType::Float ||
4793263508Sdim         BTy->getKind() == BuiltinType::Half;
4794263508Sdim}
4795263508Sdim
4796218893Sdim/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4797218893Sdim/// "neon_polyvector_type" attributes are used to create vector types that
4798218893Sdim/// are mangled according to ARM's ABI.  Otherwise, these types are identical
4799218893Sdim/// to those created with the "vector_size" attribute.  Unlike "vector_size"
4800218893Sdim/// the argument to these Neon attributes is the number of vector elements,
4801218893Sdim/// not the vector size in bytes.  The vector width and element type must
4802218893Sdim/// match one of the standard Neon vector types.
4803218893Sdimstatic void HandleNeonVectorTypeAttr(QualType& CurType,
4804218893Sdim                                     const AttributeList &Attr, Sema &S,
4805263508Sdim                                     VectorType::VectorKind VecKind) {
4806263508Sdim  // Target must have NEON
4807263508Sdim  if (!S.Context.getTargetInfo().hasFeature("neon")) {
4808263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
4809263508Sdim    Attr.setInvalid();
4810263508Sdim    return;
4811263508Sdim  }
4812218893Sdim  // Check the attribute arguments.
4813218893Sdim  if (Attr.getNumArgs() != 1) {
4814263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4815263508Sdim      << Attr.getName() << 1;
4816218893Sdim    Attr.setInvalid();
4817218893Sdim    return;
4818218893Sdim  }
4819218893Sdim  // The number of elements must be an ICE.
4820263508Sdim  Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4821218893Sdim  llvm::APSInt numEltsInt(32);
4822218893Sdim  if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4823218893Sdim      !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4824263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4825263508Sdim      << Attr.getName() << AANT_ArgumentIntegerConstant
4826263508Sdim      << numEltsExpr->getSourceRange();
4827218893Sdim    Attr.setInvalid();
4828218893Sdim    return;
4829218893Sdim  }
4830218893Sdim  // Only certain element types are supported for Neon vectors.
4831263508Sdim  llvm::Triple::ArchType Arch =
4832263508Sdim        S.Context.getTargetInfo().getTriple().getArch();
4833263508Sdim  if (!isPermittedNeonBaseType(CurType, VecKind,
4834263508Sdim                               Arch == llvm::Triple::aarch64)) {
4835263508Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4836218893Sdim    Attr.setInvalid();
4837218893Sdim    return;
4838218893Sdim  }
4839263508Sdim
4840218893Sdim  // The total size of the vector must be 64 or 128 bits.
4841218893Sdim  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4842218893Sdim  unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4843218893Sdim  unsigned vecSize = typeSize * numElts;
4844218893Sdim  if (vecSize != 64 && vecSize != 128) {
4845218893Sdim    S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4846218893Sdim    Attr.setInvalid();
4847218893Sdim    return;
4848218893Sdim  }
4849218893Sdim
4850218893Sdim  CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4851218893Sdim}
4852218893Sdim
4853218893Sdimstatic void processTypeAttrs(TypeProcessingState &state, QualType &type,
4854249423Sdim                             TypeAttrLocation TAL, AttributeList *attrs) {
4855193326Sed  // Scan through and apply attributes to this type where it makes sense.  Some
4856193326Sed  // attributes (such as __address_space__, __vector_size__, etc) apply to the
4857193326Sed  // type, but others can be present in the type specifiers even though they
4858193326Sed  // apply to the decl.  Here we apply type attributes and ignore the rest.
4859218893Sdim
4860218893Sdim  AttributeList *next;
4861218893Sdim  do {
4862218893Sdim    AttributeList &attr = *attrs;
4863218893Sdim    next = attr.getNext();
4864218893Sdim
4865207619Srdivacky    // Skip attributes that were marked to be invalid.
4866218893Sdim    if (attr.isInvalid())
4867207619Srdivacky      continue;
4868207619Srdivacky
4869249423Sdim    if (attr.isCXX11Attribute()) {
4870249423Sdim      // [[gnu::...]] attributes are treated as declaration attributes, so may
4871249423Sdim      // not appertain to a DeclaratorChunk, even if we handle them as type
4872249423Sdim      // attributes.
4873249423Sdim      if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4874249423Sdim        if (TAL == TAL_DeclChunk) {
4875249423Sdim          state.getSema().Diag(attr.getLoc(),
4876249423Sdim                               diag::warn_cxx11_gnu_attribute_on_type)
4877249423Sdim              << attr.getName();
4878249423Sdim          continue;
4879249423Sdim        }
4880249423Sdim      } else if (TAL != TAL_DeclChunk) {
4881249423Sdim        // Otherwise, only consider type processing for a C++11 attribute if
4882249423Sdim        // it's actually been applied to a type.
4883249423Sdim        continue;
4884249423Sdim      }
4885249423Sdim    }
4886249423Sdim
4887207619Srdivacky    // If this is an attribute we can handle, do so now,
4888207619Srdivacky    // otherwise, add it to the FnAttrs list for rechaining.
4889218893Sdim    switch (attr.getKind()) {
4890249423Sdim    default:
4891249423Sdim      // A C++11 attribute on a declarator chunk must appertain to a type.
4892249423Sdim      if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
4893249423Sdim        state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
4894249423Sdim          << attr.getName();
4895249423Sdim        attr.setUsedAsTypeAttr();
4896249423Sdim      }
4897249423Sdim      break;
4898203955Srdivacky
4899249423Sdim    case AttributeList::UnknownAttribute:
4900249423Sdim      if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4901249423Sdim        state.getSema().Diag(attr.getLoc(),
4902249423Sdim                             diag::warn_unknown_attribute_ignored)
4903249423Sdim          << attr.getName();
4904249423Sdim      break;
4905249423Sdim
4906249423Sdim    case AttributeList::IgnoredAttribute:
4907249423Sdim      break;
4908249423Sdim
4909239462Sdim    case AttributeList::AT_MayAlias:
4910226633Sdim      // FIXME: This attribute needs to actually be handled, but if we ignore
4911226633Sdim      // it it breaks large amounts of Linux software.
4912226633Sdim      attr.setUsedAsTypeAttr();
4913226633Sdim      break;
4914239462Sdim    case AttributeList::AT_AddressSpace:
4915218893Sdim      HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
4916226633Sdim      attr.setUsedAsTypeAttr();
4917193326Sed      break;
4918218893Sdim    OBJC_POINTER_TYPE_ATTRS_CASELIST:
4919218893Sdim      if (!handleObjCPointerTypeAttr(state, attr, type))
4920218893Sdim        distributeObjCPointerTypeAttr(state, attr, type);
4921226633Sdim      attr.setUsedAsTypeAttr();
4922193326Sed      break;
4923239462Sdim    case AttributeList::AT_VectorSize:
4924218893Sdim      HandleVectorSizeAttr(type, attr, state.getSema());
4925226633Sdim      attr.setUsedAsTypeAttr();
4926203955Srdivacky      break;
4927239462Sdim    case AttributeList::AT_ExtVectorType:
4928249423Sdim      HandleExtVectorTypeAttr(type, attr, state.getSema());
4929226633Sdim      attr.setUsedAsTypeAttr();
4930224145Sdim      break;
4931239462Sdim    case AttributeList::AT_NeonVectorType:
4932218893Sdim      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4933263508Sdim                               VectorType::NeonVector);
4934226633Sdim      attr.setUsedAsTypeAttr();
4935218893Sdim      break;
4936239462Sdim    case AttributeList::AT_NeonPolyVectorType:
4937218893Sdim      HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4938263508Sdim                               VectorType::NeonPolyVector);
4939226633Sdim      attr.setUsedAsTypeAttr();
4940218893Sdim      break;
4941239462Sdim    case AttributeList::AT_OpenCLImageAccess:
4942221345Sdim      HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
4943226633Sdim      attr.setUsedAsTypeAttr();
4944221345Sdim      break;
4945221345Sdim
4946239462Sdim    case AttributeList::AT_Win64:
4947239462Sdim      attr.setUsedAsTypeAttr();
4948239462Sdim      break;
4949263508Sdim    MS_TYPE_ATTRS_CASELIST:
4950263508Sdim      if (!handleMSPointerTypeQualifierAttr(state, attr, type))
4951263508Sdim        attr.setUsedAsTypeAttr();
4952263508Sdim      break;
4953239462Sdim
4954239462Sdim    case AttributeList::AT_NSReturnsRetained:
4955234353Sdim      if (!state.getSema().getLangOpts().ObjCAutoRefCount)
4956249423Sdim        break;
4957224145Sdim      // fallthrough into the function attrs
4958224145Sdim
4959218893Sdim    FUNCTION_TYPE_ATTRS_CASELIST:
4960226633Sdim      attr.setUsedAsTypeAttr();
4961226633Sdim
4962218893Sdim      // Never process function type attributes as part of the
4963218893Sdim      // declaration-specifiers.
4964249423Sdim      if (TAL == TAL_DeclSpec)
4965218893Sdim        distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4966218893Sdim
4967218893Sdim      // Otherwise, handle the possible delays.
4968218893Sdim      else if (!handleFunctionTypeAttr(state, attr, type))
4969218893Sdim        distributeFunctionTypeAttr(state, attr, type);
4970198092Srdivacky      break;
4971193326Sed    }
4972218893Sdim  } while ((attrs = next));
4973193326Sed}
4974193326Sed
4975223017Sdim/// \brief Ensure that the type of the given expression is complete.
4976223017Sdim///
4977223017Sdim/// This routine checks whether the expression \p E has a complete type. If the
4978223017Sdim/// expression refers to an instantiable construct, that instantiation is
4979223017Sdim/// performed as needed to complete its type. Furthermore
4980223017Sdim/// Sema::RequireCompleteType is called for the expression's type (or in the
4981223017Sdim/// case of a reference type, the referred-to type).
4982223017Sdim///
4983223017Sdim/// \param E The expression whose type is required to be complete.
4984239462Sdim/// \param Diagnoser The object that will emit a diagnostic if the type is
4985239462Sdim/// incomplete.
4986223017Sdim///
4987223017Sdim/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4988223017Sdim/// otherwise.
4989239462Sdimbool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
4990223017Sdim  QualType T = E->getType();
4991223017Sdim
4992223017Sdim  // Fast path the case where the type is already complete.
4993223017Sdim  if (!T->isIncompleteType())
4994263508Sdim    // FIXME: The definition might not be visible.
4995223017Sdim    return false;
4996223017Sdim
4997223017Sdim  // Incomplete array types may be completed by the initializer attached to
4998263508Sdim  // their definitions. For static data members of class templates and for
4999263508Sdim  // variable templates, we need to instantiate the definition to get this
5000263508Sdim  // initializer and complete the type.
5001223017Sdim  if (T->isIncompleteArrayType()) {
5002223017Sdim    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5003223017Sdim      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5004263508Sdim        if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
5005263508Sdim          SourceLocation PointOfInstantiation = E->getExprLoc();
5006239462Sdim
5007263508Sdim          if (MemberSpecializationInfo *MSInfo =
5008263508Sdim                  Var->getMemberSpecializationInfo()) {
5009223017Sdim            // If we don't already have a point of instantiation, this is it.
5010223017Sdim            if (MSInfo->getPointOfInstantiation().isInvalid()) {
5011263508Sdim              MSInfo->setPointOfInstantiation(PointOfInstantiation);
5012239462Sdim
5013239462Sdim              // This is a modification of an existing AST node. Notify
5014223017Sdim              // listeners.
5015223017Sdim              if (ASTMutationListener *L = getASTMutationListener())
5016223017Sdim                L->StaticDataMemberInstantiated(Var);
5017223017Sdim            }
5018263508Sdim          } else {
5019263508Sdim            VarTemplateSpecializationDecl *VarSpec =
5020263508Sdim                cast<VarTemplateSpecializationDecl>(Var);
5021263508Sdim            if (VarSpec->getPointOfInstantiation().isInvalid())
5022263508Sdim              VarSpec->setPointOfInstantiation(PointOfInstantiation);
5023263508Sdim          }
5024239462Sdim
5025263508Sdim          InstantiateVariableDefinition(PointOfInstantiation, Var);
5026239462Sdim
5027263508Sdim          // Update the type to the newly instantiated definition's type both
5028263508Sdim          // here and within the expression.
5029263508Sdim          if (VarDecl *Def = Var->getDefinition()) {
5030263508Sdim            DRE->setDecl(Def);
5031263508Sdim            T = Def->getType();
5032263508Sdim            DRE->setType(T);
5033263508Sdim            E->setType(T);
5034223017Sdim          }
5035239462Sdim
5036223017Sdim          // We still go on to try to complete the type independently, as it
5037223017Sdim          // may also require instantiations or diagnostics if it remains
5038223017Sdim          // incomplete.
5039223017Sdim        }
5040223017Sdim      }
5041223017Sdim    }
5042223017Sdim  }
5043223017Sdim
5044223017Sdim  // FIXME: Are there other cases which require instantiating something other
5045223017Sdim  // than the type to complete the type of an expression?
5046223017Sdim
5047223017Sdim  // Look through reference types and complete the referred type.
5048223017Sdim  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5049223017Sdim    T = Ref->getPointeeType();
5050223017Sdim
5051239462Sdim  return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
5052223017Sdim}
5053223017Sdim
5054239462Sdimnamespace {
5055239462Sdim  struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
5056239462Sdim    unsigned DiagID;
5057239462Sdim
5058239462Sdim    TypeDiagnoserDiag(unsigned DiagID)
5059239462Sdim      : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
5060239462Sdim
5061239462Sdim    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5062239462Sdim      if (Suppressed) return;
5063239462Sdim      S.Diag(Loc, DiagID) << T;
5064239462Sdim    }
5065239462Sdim  };
5066239462Sdim}
5067239462Sdim
5068239462Sdimbool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
5069239462Sdim  TypeDiagnoserDiag Diagnoser(DiagID);
5070239462Sdim  return RequireCompleteExprType(E, Diagnoser);
5071239462Sdim}
5072239462Sdim
5073198092Srdivacky/// @brief Ensure that the type T is a complete type.
5074193326Sed///
5075193326Sed/// This routine checks whether the type @p T is complete in any
5076193326Sed/// context where a complete type is required. If @p T is a complete
5077193326Sed/// type, returns false. If @p T is a class template specialization,
5078193326Sed/// this routine then attempts to perform class template
5079193326Sed/// instantiation. If instantiation fails, or if @p T is incomplete
5080193326Sed/// and cannot be completed, issues the diagnostic @p diag (giving it
5081193326Sed/// the type @p T) and returns true.
5082193326Sed///
5083193326Sed/// @param Loc  The location in the source that the incomplete type
5084193326Sed/// diagnostic should refer to.
5085193326Sed///
5086193326Sed/// @param T  The type that this routine is examining for completeness.
5087193326Sed///
5088193326Sed/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
5089193326Sed/// @c false otherwise.
5090198092Srdivackybool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5091239462Sdim                               TypeDiagnoser &Diagnoser) {
5092263508Sdim  if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
5093263508Sdim    return true;
5094263508Sdim  if (const TagType *Tag = T->getAs<TagType>()) {
5095263508Sdim    if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
5096263508Sdim      Tag->getDecl()->setCompleteDefinitionRequired();
5097263508Sdim      Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
5098263508Sdim    }
5099263508Sdim  }
5100263508Sdim  return false;
5101263508Sdim}
5102263508Sdim
5103263508Sdim/// \brief The implementation of RequireCompleteType
5104263508Sdimbool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
5105263508Sdim                                   TypeDiagnoser &Diagnoser) {
5106198398Srdivacky  // FIXME: Add this assertion to make sure we always get instantiation points.
5107198398Srdivacky  //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
5108193326Sed  // FIXME: Add this assertion to help us flush out problems with
5109193326Sed  // checking for dependent types and type-dependent expressions.
5110193326Sed  //
5111198092Srdivacky  //  assert(!T->isDependentType() &&
5112193326Sed  //         "Can't ask whether a dependent type is complete");
5113193326Sed
5114193326Sed  // If we have a complete type, we're done.
5115234353Sdim  NamedDecl *Def = 0;
5116234353Sdim  if (!T->isIncompleteType(&Def)) {
5117234353Sdim    // If we know about the definition but it is not visible, complain.
5118263508Sdim    if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(*this, Def)) {
5119234353Sdim      // Suppress this error outside of a SFINAE context if we've already
5120239462Sdim      // emitted the error once for this type. There's no usefulness in
5121234353Sdim      // repeating the diagnostic.
5122234353Sdim      // FIXME: Add a Fix-It that imports the corresponding module or includes
5123234353Sdim      // the header.
5124249423Sdim      Module *Owner = Def->getOwningModule();
5125249423Sdim      Diag(Loc, diag::err_module_private_definition)
5126249423Sdim        << T << Owner->getFullModuleName();
5127249423Sdim      Diag(Def->getLocation(), diag::note_previous_definition);
5128249423Sdim
5129249423Sdim      if (!isSFINAEContext()) {
5130249423Sdim        // Recover by implicitly importing this module.
5131249423Sdim        createImplicitModuleImport(Loc, Owner);
5132234353Sdim      }
5133234353Sdim    }
5134239462Sdim
5135193326Sed    return false;
5136234353Sdim  }
5137193326Sed
5138263508Sdim  // FIXME: If there's an unimported definition of this type in a module (for
5139263508Sdim  // instance, because we forward declared it, then imported the definition),
5140263508Sdim  // import that definition now.
5141263508Sdim  // FIXME: What about other cases where an import extends a redeclaration
5142263508Sdim  // chain for a declaration that can be accessed through a mechanism other
5143263508Sdim  // than name lookup (eg, referenced in a template, or a variable whose type
5144263508Sdim  // could be completed by the module)?
5145263508Sdim
5146234353Sdim  const TagType *Tag = T->getAs<TagType>();
5147234353Sdim  const ObjCInterfaceType *IFace = 0;
5148239462Sdim
5149234353Sdim  if (Tag) {
5150234353Sdim    // Avoid diagnosing invalid decls as incomplete.
5151234353Sdim    if (Tag->getDecl()->isInvalidDecl())
5152234353Sdim      return true;
5153234353Sdim
5154234353Sdim    // Give the external AST source a chance to complete the type.
5155234353Sdim    if (Tag->getDecl()->hasExternalLexicalStorage()) {
5156234353Sdim      Context.getExternalSource()->CompleteType(Tag->getDecl());
5157234353Sdim      if (!Tag->isIncompleteType())
5158234353Sdim        return false;
5159234353Sdim    }
5160234353Sdim  }
5161234353Sdim  else if ((IFace = T->getAs<ObjCInterfaceType>())) {
5162234353Sdim    // Avoid diagnosing invalid decls as incomplete.
5163234353Sdim    if (IFace->getDecl()->isInvalidDecl())
5164234353Sdim      return true;
5165239462Sdim
5166234353Sdim    // Give the external AST source a chance to complete the type.
5167234353Sdim    if (IFace->getDecl()->hasExternalLexicalStorage()) {
5168234353Sdim      Context.getExternalSource()->CompleteType(IFace->getDecl());
5169234353Sdim      if (!IFace->isIncompleteType())
5170234353Sdim        return false;
5171234353Sdim    }
5172234353Sdim  }
5173239462Sdim
5174193326Sed  // If we have a class template specialization or a class member of a
5175198954Srdivacky  // class template specialization, or an array with known size of such,
5176198954Srdivacky  // try to instantiate it.
5177198954Srdivacky  QualType MaybeTemplate = T;
5178235864Sdim  while (const ConstantArrayType *Array
5179235864Sdim           = Context.getAsConstantArrayType(MaybeTemplate))
5180198954Srdivacky    MaybeTemplate = Array->getElementType();
5181198954Srdivacky  if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
5182193326Sed    if (ClassTemplateSpecializationDecl *ClassTemplateSpec
5183193326Sed          = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
5184198893Srdivacky      if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
5185198893Srdivacky        return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
5186198092Srdivacky                                                      TSK_ImplicitInstantiation,
5187239462Sdim                                            /*Complain=*/!Diagnoser.Suppressed);
5188198092Srdivacky    } else if (CXXRecordDecl *Rec
5189193326Sed                 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
5190234353Sdim      CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
5191234353Sdim      if (!Rec->isBeingDefined() && Pattern) {
5192234353Sdim        MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
5193234353Sdim        assert(MSI && "Missing member specialization information?");
5194198092Srdivacky        // This record was instantiated from a class within a template.
5195234353Sdim        if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5196198092Srdivacky          return InstantiateClass(Loc, Rec, Pattern,
5197198092Srdivacky                                  getTemplateInstantiationArgs(Rec),
5198198092Srdivacky                                  TSK_ImplicitInstantiation,
5199239462Sdim                                  /*Complain=*/!Diagnoser.Suppressed);
5200193326Sed      }
5201193326Sed    }
5202193326Sed  }
5203193326Sed
5204239462Sdim  if (Diagnoser.Suppressed)
5205198092Srdivacky    return true;
5206239462Sdim
5207193326Sed  // We have an incomplete type. Produce a diagnostic.
5208263508Sdim  if (Ident___float128 &&
5209263508Sdim      T == Context.getTypeDeclType(Context.getFloat128StubType())) {
5210263508Sdim    Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
5211263508Sdim    return true;
5212263508Sdim  }
5213263508Sdim
5214239462Sdim  Diagnoser.diagnose(*this, Loc, T);
5215239462Sdim
5216193326Sed  // If the type was a forward declaration of a class/struct/union
5217206084Srdivacky  // type, produce a note.
5218193326Sed  if (Tag && !Tag->getDecl()->isInvalidDecl())
5219198092Srdivacky    Diag(Tag->getDecl()->getLocation(),
5220193326Sed         Tag->isBeingDefined() ? diag::note_type_being_defined
5221193326Sed                               : diag::note_forward_declaration)
5222234353Sdim      << QualType(Tag, 0);
5223239462Sdim
5224234353Sdim  // If the Objective-C class was a forward declaration, produce a note.
5225234353Sdim  if (IFace && !IFace->getDecl()->isInvalidDecl())
5226234353Sdim    Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
5227193326Sed
5228263508Sdim  // If we have external information that we can use to suggest a fix,
5229263508Sdim  // produce a note.
5230263508Sdim  if (ExternalSource)
5231263508Sdim    ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
5232263508Sdim
5233193326Sed  return true;
5234193326Sed}
5235193326Sed
5236206084Srdivackybool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5237206084Srdivacky                               unsigned DiagID) {
5238239462Sdim  TypeDiagnoserDiag Diagnoser(DiagID);
5239239462Sdim  return RequireCompleteType(Loc, T, Diagnoser);
5240206084Srdivacky}
5241206084Srdivacky
5242243830Sdim/// \brief Get diagnostic %select index for tag kind for
5243243830Sdim/// literal type diagnostic message.
5244243830Sdim/// WARNING: Indexes apply to particular diagnostics only!
5245243830Sdim///
5246243830Sdim/// \returns diagnostic %select index.
5247243830Sdimstatic unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
5248243830Sdim  switch (Tag) {
5249243830Sdim  case TTK_Struct: return 0;
5250243830Sdim  case TTK_Interface: return 1;
5251243830Sdim  case TTK_Class:  return 2;
5252243830Sdim  default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
5253243830Sdim  }
5254243830Sdim}
5255243830Sdim
5256226633Sdim/// @brief Ensure that the type T is a literal type.
5257226633Sdim///
5258226633Sdim/// This routine checks whether the type @p T is a literal type. If @p T is an
5259226633Sdim/// incomplete type, an attempt is made to complete it. If @p T is a literal
5260226633Sdim/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
5261226633Sdim/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
5262226633Sdim/// it the type @p T), along with notes explaining why the type is not a
5263226633Sdim/// literal type, and returns true.
5264226633Sdim///
5265226633Sdim/// @param Loc  The location in the source that the non-literal type
5266226633Sdim/// diagnostic should refer to.
5267226633Sdim///
5268226633Sdim/// @param T  The type that this routine is examining for literalness.
5269226633Sdim///
5270239462Sdim/// @param Diagnoser Emits a diagnostic if T is not a literal type.
5271226633Sdim///
5272226633Sdim/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
5273226633Sdim/// @c false otherwise.
5274226633Sdimbool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
5275239462Sdim                              TypeDiagnoser &Diagnoser) {
5276226633Sdim  assert(!T->isDependentType() && "type should not be dependent");
5277226633Sdim
5278234353Sdim  QualType ElemType = Context.getBaseElementType(T);
5279234353Sdim  RequireCompleteType(Loc, ElemType, 0);
5280234353Sdim
5281251662Sdim  if (T->isLiteralType(Context))
5282226633Sdim    return false;
5283226633Sdim
5284239462Sdim  if (Diagnoser.Suppressed)
5285226633Sdim    return true;
5286226633Sdim
5287239462Sdim  Diagnoser.diagnose(*this, Loc, T);
5288226633Sdim
5289226633Sdim  if (T->isVariableArrayType())
5290226633Sdim    return true;
5291226633Sdim
5292234353Sdim  const RecordType *RT = ElemType->getAs<RecordType>();
5293226633Sdim  if (!RT)
5294226633Sdim    return true;
5295226633Sdim
5296226633Sdim  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5297226633Sdim
5298239462Sdim  // A partially-defined class type can't be a literal type, because a literal
5299239462Sdim  // class type must have a trivial destructor (which can't be checked until
5300239462Sdim  // the class definition is complete).
5301239462Sdim  if (!RD->isCompleteDefinition()) {
5302239462Sdim    RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
5303234353Sdim    return true;
5304239462Sdim  }
5305234353Sdim
5306226633Sdim  // If the class has virtual base classes, then it's not an aggregate, and
5307234353Sdim  // cannot have any constexpr constructors or a trivial default constructor,
5308234353Sdim  // so is non-literal. This is better to diagnose than the resulting absence
5309234353Sdim  // of constexpr constructors.
5310226633Sdim  if (RD->getNumVBases()) {
5311226633Sdim    Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
5312243830Sdim      << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
5313226633Sdim    for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
5314226633Sdim           E = RD->vbases_end(); I != E; ++I)
5315234353Sdim      Diag(I->getLocStart(),
5316226633Sdim           diag::note_constexpr_virtual_base_here) << I->getSourceRange();
5317234353Sdim  } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
5318234353Sdim             !RD->hasTrivialDefaultConstructor()) {
5319226633Sdim    Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
5320226633Sdim  } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
5321226633Sdim    for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5322226633Sdim         E = RD->bases_end(); I != E; ++I) {
5323251662Sdim      if (!I->getType()->isLiteralType(Context)) {
5324234353Sdim        Diag(I->getLocStart(),
5325226633Sdim             diag::note_non_literal_base_class)
5326226633Sdim          << RD << I->getType() << I->getSourceRange();
5327226633Sdim        return true;
5328226633Sdim      }
5329226633Sdim    }
5330226633Sdim    for (CXXRecordDecl::field_iterator I = RD->field_begin(),
5331226633Sdim         E = RD->field_end(); I != E; ++I) {
5332251662Sdim      if (!I->getType()->isLiteralType(Context) ||
5333239462Sdim          I->getType().isVolatileQualified()) {
5334239462Sdim        Diag(I->getLocation(), diag::note_non_literal_field)
5335239462Sdim          << RD << *I << I->getType()
5336239462Sdim          << I->getType().isVolatileQualified();
5337226633Sdim        return true;
5338226633Sdim      }
5339226633Sdim    }
5340226633Sdim  } else if (!RD->hasTrivialDestructor()) {
5341226633Sdim    // All fields and bases are of literal types, so have trivial destructors.
5342226633Sdim    // If this class's destructor is non-trivial it must be user-declared.
5343226633Sdim    CXXDestructorDecl *Dtor = RD->getDestructor();
5344226633Sdim    assert(Dtor && "class has literal fields and bases but no dtor?");
5345226633Sdim    if (!Dtor)
5346226633Sdim      return true;
5347226633Sdim
5348226633Sdim    Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
5349226633Sdim         diag::note_non_literal_user_provided_dtor :
5350226633Sdim         diag::note_non_literal_nontrivial_dtor) << RD;
5351249423Sdim    if (!Dtor->isUserProvided())
5352249423Sdim      SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
5353226633Sdim  }
5354226633Sdim
5355226633Sdim  return true;
5356226633Sdim}
5357226633Sdim
5358239462Sdimbool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
5359239462Sdim  TypeDiagnoserDiag Diagnoser(DiagID);
5360239462Sdim  return RequireLiteralType(Loc, T, Diagnoser);
5361239462Sdim}
5362239462Sdim
5363208600Srdivacky/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
5364208600Srdivacky/// and qualified by the nested-name-specifier contained in SS.
5365208600SrdivackyQualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
5366208600Srdivacky                                 const CXXScopeSpec &SS, QualType T) {
5367208600Srdivacky  if (T.isNull())
5368193326Sed    return T;
5369208600Srdivacky  NestedNameSpecifier *NNS;
5370208600Srdivacky  if (SS.isValid())
5371208600Srdivacky    NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5372208600Srdivacky  else {
5373208600Srdivacky    if (Keyword == ETK_None)
5374208600Srdivacky      return T;
5375208600Srdivacky    NNS = 0;
5376208600Srdivacky  }
5377208600Srdivacky  return Context.getElaboratedType(Keyword, NNS, T);
5378193326Sed}
5379195341Sed
5380218893SdimQualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
5381221345Sdim  ExprResult ER = CheckPlaceholderExpr(E);
5382218893Sdim  if (ER.isInvalid()) return QualType();
5383218893Sdim  E = ER.take();
5384218893Sdim
5385218893Sdim  if (!E->isTypeDependent()) {
5386218893Sdim    QualType T = E->getType();
5387218893Sdim    if (const TagType *TT = T->getAs<TagType>())
5388218893Sdim      DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
5389201361Srdivacky  }
5390195341Sed  return Context.getTypeOfExprType(E);
5391195341Sed}
5392195341Sed
5393234353Sdim/// getDecltypeForExpr - Given an expr, will return the decltype for
5394234353Sdim/// that expression, according to the rules in C++11
5395234353Sdim/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
5396234353Sdimstatic QualType getDecltypeForExpr(Sema &S, Expr *E) {
5397234353Sdim  if (E->isTypeDependent())
5398234353Sdim    return S.Context.DependentTy;
5399234353Sdim
5400234353Sdim  // C++11 [dcl.type.simple]p4:
5401234353Sdim  //   The type denoted by decltype(e) is defined as follows:
5402234353Sdim  //
5403234353Sdim  //     - if e is an unparenthesized id-expression or an unparenthesized class
5404239462Sdim  //       member access (5.2.5), decltype(e) is the type of the entity named
5405239462Sdim  //       by e. If there is no such entity, or if e names a set of overloaded
5406234353Sdim  //       functions, the program is ill-formed;
5407243830Sdim  //
5408243830Sdim  // We apply the same rules for Objective-C ivar and property references.
5409234353Sdim  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5410234353Sdim    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
5411234353Sdim      return VD->getType();
5412243830Sdim  } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5413234353Sdim    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
5414234353Sdim      return FD->getType();
5415243830Sdim  } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
5416243830Sdim    return IR->getDecl()->getType();
5417243830Sdim  } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
5418243830Sdim    if (PR->isExplicitProperty())
5419243830Sdim      return PR->getExplicitProperty()->getType();
5420234353Sdim  }
5421243830Sdim
5422234353Sdim  // C++11 [expr.lambda.prim]p18:
5423234353Sdim  //   Every occurrence of decltype((x)) where x is a possibly
5424234353Sdim  //   parenthesized id-expression that names an entity of automatic
5425234353Sdim  //   storage duration is treated as if x were transformed into an
5426234353Sdim  //   access to a corresponding data member of the closure type that
5427234353Sdim  //   would have been declared if x were an odr-use of the denoted
5428234353Sdim  //   entity.
5429234353Sdim  using namespace sema;
5430234353Sdim  if (S.getCurLambda()) {
5431234353Sdim    if (isa<ParenExpr>(E)) {
5432234353Sdim      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5433234353Sdim        if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5434234353Sdim          QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
5435234353Sdim          if (!T.isNull())
5436234353Sdim            return S.Context.getLValueReferenceType(T);
5437234353Sdim        }
5438234353Sdim      }
5439234353Sdim    }
5440234353Sdim  }
5441234353Sdim
5442234353Sdim
5443234353Sdim  // C++11 [dcl.type.simple]p4:
5444234353Sdim  //   [...]
5445234353Sdim  QualType T = E->getType();
5446234353Sdim  switch (E->getValueKind()) {
5447239462Sdim  //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5448234353Sdim  //       type of e;
5449234353Sdim  case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
5450239462Sdim  //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5451234353Sdim  //       type of e;
5452234353Sdim  case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
5453234353Sdim  //  - otherwise, decltype(e) is the type of e.
5454234353Sdim  case VK_RValue: break;
5455234353Sdim  }
5456239462Sdim
5457234353Sdim  return T;
5458234353Sdim}
5459234353Sdim
5460218893SdimQualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
5461221345Sdim  ExprResult ER = CheckPlaceholderExpr(E);
5462218893Sdim  if (ER.isInvalid()) return QualType();
5463218893Sdim  E = ER.take();
5464239462Sdim
5465234353Sdim  return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
5466195341Sed}
5467223017Sdim
5468223017SdimQualType Sema::BuildUnaryTransformType(QualType BaseType,
5469223017Sdim                                       UnaryTransformType::UTTKind UKind,
5470223017Sdim                                       SourceLocation Loc) {
5471223017Sdim  switch (UKind) {
5472223017Sdim  case UnaryTransformType::EnumUnderlyingType:
5473223017Sdim    if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
5474223017Sdim      Diag(Loc, diag::err_only_enums_have_underlying_types);
5475223017Sdim      return QualType();
5476223017Sdim    } else {
5477223017Sdim      QualType Underlying = BaseType;
5478223017Sdim      if (!BaseType->isDependentType()) {
5479223017Sdim        EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
5480223017Sdim        assert(ED && "EnumType has no EnumDecl");
5481223017Sdim        DiagnoseUseOfDecl(ED, Loc);
5482223017Sdim        Underlying = ED->getIntegerType();
5483223017Sdim      }
5484223017Sdim      assert(!Underlying.isNull());
5485223017Sdim      return Context.getUnaryTransformType(BaseType, Underlying,
5486223017Sdim                                        UnaryTransformType::EnumUnderlyingType);
5487223017Sdim    }
5488223017Sdim  }
5489223017Sdim  llvm_unreachable("unknown unary transform type");
5490223017Sdim}
5491226633Sdim
5492226633SdimQualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
5493226633Sdim  if (!T->isDependentType()) {
5494234353Sdim    // FIXME: It isn't entirely clear whether incomplete atomic types
5495234353Sdim    // are allowed or not; for simplicity, ban them for the moment.
5496239462Sdim    if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
5497234353Sdim      return QualType();
5498234353Sdim
5499226633Sdim    int DisallowedKind = -1;
5500234353Sdim    if (T->isArrayType())
5501226633Sdim      DisallowedKind = 1;
5502226633Sdim    else if (T->isFunctionType())
5503226633Sdim      DisallowedKind = 2;
5504226633Sdim    else if (T->isReferenceType())
5505226633Sdim      DisallowedKind = 3;
5506226633Sdim    else if (T->isAtomicType())
5507226633Sdim      DisallowedKind = 4;
5508226633Sdim    else if (T.hasQualifiers())
5509226633Sdim      DisallowedKind = 5;
5510226633Sdim    else if (!T.isTriviallyCopyableType(Context))
5511226633Sdim      // Some other non-trivially-copyable type (probably a C++ class)
5512226633Sdim      DisallowedKind = 6;
5513226633Sdim
5514226633Sdim    if (DisallowedKind != -1) {
5515226633Sdim      Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
5516226633Sdim      return QualType();
5517226633Sdim    }
5518226633Sdim
5519226633Sdim    // FIXME: Do we need any handling for ARC here?
5520226633Sdim  }
5521226633Sdim
5522226633Sdim  // Build the pointer type.
5523226633Sdim  return Context.getAtomicType(T);
5524226633Sdim}
5525