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