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