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