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