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