1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements type-related semantic analysis.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/Basic/OpenCL.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/AST/TypeLocVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/DeclSpec.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/Support/ErrorHandling.h"
30 using namespace clang;
31 
32 /// \brief Perform adjustment on the parameter type of a function.
33 ///
34 /// This routine adjusts the given parameter type @p T to the actual
35 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
36 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
37 QualType Sema::adjustParameterType(QualType T) {
38   // C99 6.7.5.3p7:
39   //   A declaration of a parameter as "array of type" shall be
40   //   adjusted to "qualified pointer to type", where the type
41   //   qualifiers (if any) are those specified within the [ and ] of
42   //   the array type derivation.
43   if (T->isArrayType())
44     return Context.getArrayDecayedType(T);
45 
46   // C99 6.7.5.3p8:
47   //   A declaration of a parameter as "function returning type"
48   //   shall be adjusted to "pointer to function returning type", as
49   //   in 6.3.2.1.
50   if (T->isFunctionType())
51     return Context.getPointerType(T);
52 
53   return T;
54 }
55 
56 
57 
58 /// isOmittedBlockReturnType - Return true if this declarator is missing a
59 /// return type because this is a omitted return type on a block literal.
60 static bool isOmittedBlockReturnType(const Declarator &D) {
61   if (D.getContext() != Declarator::BlockLiteralContext ||
62       D.getDeclSpec().hasTypeSpecifier())
63     return false;
64 
65   if (D.getNumTypeObjects() == 0)
66     return true;   // ^{ ... }
67 
68   if (D.getNumTypeObjects() == 1 &&
69       D.getTypeObject(0).Kind == DeclaratorChunk::Function)
70     return true;   // ^(int X, float Y) { ... }
71 
72   return false;
73 }
74 
75 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
76 /// doesn't apply to the given type.
77 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
78                                      QualType type) {
79   bool useInstantiationLoc = false;
80 
81   unsigned diagID = 0;
82   switch (attr.getKind()) {
83   case AttributeList::AT_objc_gc:
84     diagID = diag::warn_pointer_attribute_wrong_type;
85     useInstantiationLoc = true;
86     break;
87 
88   default:
89     // Assume everything else was a function attribute.
90     diagID = diag::warn_function_attribute_wrong_type;
91     break;
92   }
93 
94   SourceLocation loc = attr.getLoc();
95   llvm::StringRef name = attr.getName()->getName();
96 
97   // The GC attributes are usually written with macros;  special-case them.
98   if (useInstantiationLoc && loc.isMacroID() && attr.getParameterName()) {
99     if (attr.getParameterName()->isStr("strong")) {
100       if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
101     } else if (attr.getParameterName()->isStr("weak")) {
102       if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
103     }
104   }
105 
106   S.Diag(loc, diagID) << name << type;
107 }
108 
109 // objc_gc applies to Objective-C pointers or, otherwise, to the
110 // smallest available pointer type (i.e. 'void*' in 'void**').
111 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
112     case AttributeList::AT_objc_gc
113 
114 // Function type attributes.
115 #define FUNCTION_TYPE_ATTRS_CASELIST \
116     case AttributeList::AT_noreturn: \
117     case AttributeList::AT_cdecl: \
118     case AttributeList::AT_fastcall: \
119     case AttributeList::AT_stdcall: \
120     case AttributeList::AT_thiscall: \
121     case AttributeList::AT_pascal: \
122     case AttributeList::AT_regparm: \
123     case AttributeList::AT_pcs \
124 
125 namespace {
126   /// An object which stores processing state for the entire
127   /// GetTypeForDeclarator process.
128   class TypeProcessingState {
129     Sema &sema;
130 
131     /// The declarator being processed.
132     Declarator &declarator;
133 
134     /// The index of the declarator chunk we're currently processing.
135     /// May be the total number of valid chunks, indicating the
136     /// DeclSpec.
137     unsigned chunkIndex;
138 
139     /// Whether there are non-trivial modifications to the decl spec.
140     bool trivial;
141 
142     /// Whether we saved the attributes in the decl spec.
143     bool hasSavedAttrs;
144 
145     /// The original set of attributes on the DeclSpec.
146     llvm::SmallVector<AttributeList*, 2> savedAttrs;
147 
148     /// A list of attributes to diagnose the uselessness of when the
149     /// processing is complete.
150     llvm::SmallVector<AttributeList*, 2> ignoredTypeAttrs;
151 
152   public:
153     TypeProcessingState(Sema &sema, Declarator &declarator)
154       : sema(sema), declarator(declarator),
155         chunkIndex(declarator.getNumTypeObjects()),
156         trivial(true), hasSavedAttrs(false) {}
157 
158     Sema &getSema() const {
159       return sema;
160     }
161 
162     Declarator &getDeclarator() const {
163       return declarator;
164     }
165 
166     unsigned getCurrentChunkIndex() const {
167       return chunkIndex;
168     }
169 
170     void setCurrentChunkIndex(unsigned idx) {
171       assert(idx <= declarator.getNumTypeObjects());
172       chunkIndex = idx;
173     }
174 
175     AttributeList *&getCurrentAttrListRef() const {
176       assert(chunkIndex <= declarator.getNumTypeObjects());
177       if (chunkIndex == declarator.getNumTypeObjects())
178         return getMutableDeclSpec().getAttributes().getListRef();
179       return declarator.getTypeObject(chunkIndex).getAttrListRef();
180     }
181 
182     /// Save the current set of attributes on the DeclSpec.
183     void saveDeclSpecAttrs() {
184       // Don't try to save them multiple times.
185       if (hasSavedAttrs) return;
186 
187       DeclSpec &spec = getMutableDeclSpec();
188       for (AttributeList *attr = spec.getAttributes().getList(); attr;
189              attr = attr->getNext())
190         savedAttrs.push_back(attr);
191       trivial &= savedAttrs.empty();
192       hasSavedAttrs = true;
193     }
194 
195     /// Record that we had nowhere to put the given type attribute.
196     /// We will diagnose such attributes later.
197     void addIgnoredTypeAttr(AttributeList &attr) {
198       ignoredTypeAttrs.push_back(&attr);
199     }
200 
201     /// Diagnose all the ignored type attributes, given that the
202     /// declarator worked out to the given type.
203     void diagnoseIgnoredTypeAttrs(QualType type) const {
204       for (llvm::SmallVectorImpl<AttributeList*>::const_iterator
205              i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
206            i != e; ++i)
207         diagnoseBadTypeAttribute(getSema(), **i, type);
208     }
209 
210     ~TypeProcessingState() {
211       if (trivial) return;
212 
213       restoreDeclSpecAttrs();
214     }
215 
216   private:
217     DeclSpec &getMutableDeclSpec() const {
218       return const_cast<DeclSpec&>(declarator.getDeclSpec());
219     }
220 
221     void restoreDeclSpecAttrs() {
222       assert(hasSavedAttrs);
223 
224       if (savedAttrs.empty()) {
225         getMutableDeclSpec().getAttributes().set(0);
226         return;
227       }
228 
229       getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
230       for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
231         savedAttrs[i]->setNext(savedAttrs[i+1]);
232       savedAttrs.back()->setNext(0);
233     }
234   };
235 
236   /// Basically std::pair except that we really want to avoid an
237   /// implicit operator= for safety concerns.  It's also a minor
238   /// link-time optimization for this to be a private type.
239   struct AttrAndList {
240     /// The attribute.
241     AttributeList &first;
242 
243     /// The head of the list the attribute is currently in.
244     AttributeList *&second;
245 
246     AttrAndList(AttributeList &attr, AttributeList *&head)
247       : first(attr), second(head) {}
248   };
249 }
250 
251 namespace llvm {
252   template <> struct isPodLike<AttrAndList> {
253     static const bool value = true;
254   };
255 }
256 
257 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
258   attr.setNext(head);
259   head = &attr;
260 }
261 
262 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
263   if (head == &attr) {
264     head = attr.getNext();
265     return;
266   }
267 
268   AttributeList *cur = head;
269   while (true) {
270     assert(cur && cur->getNext() && "ran out of attrs?");
271     if (cur->getNext() == &attr) {
272       cur->setNext(attr.getNext());
273       return;
274     }
275     cur = cur->getNext();
276   }
277 }
278 
279 static void moveAttrFromListToList(AttributeList &attr,
280                                    AttributeList *&fromList,
281                                    AttributeList *&toList) {
282   spliceAttrOutOfList(attr, fromList);
283   spliceAttrIntoList(attr, toList);
284 }
285 
286 static void processTypeAttrs(TypeProcessingState &state,
287                              QualType &type, bool isDeclSpec,
288                              AttributeList *attrs);
289 
290 static bool handleFunctionTypeAttr(TypeProcessingState &state,
291                                    AttributeList &attr,
292                                    QualType &type);
293 
294 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
295                                  AttributeList &attr, QualType &type);
296 
297 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
298                                       AttributeList &attr, QualType &type) {
299   // Right now, we have exactly one of these attributes: objc_gc.
300   assert(attr.getKind() == AttributeList::AT_objc_gc);
301   return handleObjCGCTypeAttr(state, attr, type);
302 }
303 
304 /// Given that an objc_gc attribute was written somewhere on a
305 /// declaration *other* than on the declarator itself (for which, use
306 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
307 /// didn't apply in whatever position it was written in, try to move
308 /// it to a more appropriate position.
309 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
310                                           AttributeList &attr,
311                                           QualType type) {
312   Declarator &declarator = state.getDeclarator();
313   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
314     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
315     switch (chunk.Kind) {
316     case DeclaratorChunk::Pointer:
317     case DeclaratorChunk::BlockPointer:
318       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
319                              chunk.getAttrListRef());
320       return;
321 
322     case DeclaratorChunk::Paren:
323     case DeclaratorChunk::Array:
324       continue;
325 
326     // Don't walk through these.
327     case DeclaratorChunk::Reference:
328     case DeclaratorChunk::Function:
329     case DeclaratorChunk::MemberPointer:
330       goto error;
331     }
332   }
333  error:
334 
335   diagnoseBadTypeAttribute(state.getSema(), attr, type);
336 }
337 
338 /// Distribute an objc_gc type attribute that was written on the
339 /// declarator.
340 static void
341 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
342                                             AttributeList &attr,
343                                             QualType &declSpecType) {
344   Declarator &declarator = state.getDeclarator();
345 
346   // objc_gc goes on the innermost pointer to something that's not a
347   // pointer.
348   unsigned innermost = -1U;
349   bool considerDeclSpec = true;
350   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
351     DeclaratorChunk &chunk = declarator.getTypeObject(i);
352     switch (chunk.Kind) {
353     case DeclaratorChunk::Pointer:
354     case DeclaratorChunk::BlockPointer:
355       innermost = i;
356       continue;
357 
358     case DeclaratorChunk::Reference:
359     case DeclaratorChunk::MemberPointer:
360     case DeclaratorChunk::Paren:
361     case DeclaratorChunk::Array:
362       continue;
363 
364     case DeclaratorChunk::Function:
365       considerDeclSpec = false;
366       goto done;
367     }
368   }
369  done:
370 
371   // That might actually be the decl spec if we weren't blocked by
372   // anything in the declarator.
373   if (considerDeclSpec) {
374     if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
375       // Splice the attribute into the decl spec.  Prevents the
376       // attribute from being applied multiple times and gives
377       // the source-location-filler something to work with.
378       state.saveDeclSpecAttrs();
379       moveAttrFromListToList(attr, declarator.getAttrListRef(),
380                declarator.getMutableDeclSpec().getAttributes().getListRef());
381       return;
382     }
383   }
384 
385   // Otherwise, if we found an appropriate chunk, splice the attribute
386   // into it.
387   if (innermost != -1U) {
388     moveAttrFromListToList(attr, declarator.getAttrListRef(),
389                        declarator.getTypeObject(innermost).getAttrListRef());
390     return;
391   }
392 
393   // Otherwise, diagnose when we're done building the type.
394   spliceAttrOutOfList(attr, declarator.getAttrListRef());
395   state.addIgnoredTypeAttr(attr);
396 }
397 
398 /// A function type attribute was written somewhere in a declaration
399 /// *other* than on the declarator itself or in the decl spec.  Given
400 /// that it didn't apply in whatever position it was written in, try
401 /// to move it to a more appropriate position.
402 static void distributeFunctionTypeAttr(TypeProcessingState &state,
403                                        AttributeList &attr,
404                                        QualType type) {
405   Declarator &declarator = state.getDeclarator();
406 
407   // Try to push the attribute from the return type of a function to
408   // the function itself.
409   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
410     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
411     switch (chunk.Kind) {
412     case DeclaratorChunk::Function:
413       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
414                              chunk.getAttrListRef());
415       return;
416 
417     case DeclaratorChunk::Paren:
418     case DeclaratorChunk::Pointer:
419     case DeclaratorChunk::BlockPointer:
420     case DeclaratorChunk::Array:
421     case DeclaratorChunk::Reference:
422     case DeclaratorChunk::MemberPointer:
423       continue;
424     }
425   }
426 
427   diagnoseBadTypeAttribute(state.getSema(), attr, type);
428 }
429 
430 /// Try to distribute a function type attribute to the innermost
431 /// function chunk or type.  Returns true if the attribute was
432 /// distributed, false if no location was found.
433 static bool
434 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
435                                       AttributeList &attr,
436                                       AttributeList *&attrList,
437                                       QualType &declSpecType) {
438   Declarator &declarator = state.getDeclarator();
439 
440   // Put it on the innermost function chunk, if there is one.
441   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
442     DeclaratorChunk &chunk = declarator.getTypeObject(i);
443     if (chunk.Kind != DeclaratorChunk::Function) continue;
444 
445     moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
446     return true;
447   }
448 
449   return handleFunctionTypeAttr(state, attr, declSpecType);
450 }
451 
452 /// A function type attribute was written in the decl spec.  Try to
453 /// apply it somewhere.
454 static void
455 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
456                                        AttributeList &attr,
457                                        QualType &declSpecType) {
458   state.saveDeclSpecAttrs();
459 
460   // Try to distribute to the innermost.
461   if (distributeFunctionTypeAttrToInnermost(state, attr,
462                                             state.getCurrentAttrListRef(),
463                                             declSpecType))
464     return;
465 
466   // If that failed, diagnose the bad attribute when the declarator is
467   // fully built.
468   state.addIgnoredTypeAttr(attr);
469 }
470 
471 /// A function type attribute was written on the declarator.  Try to
472 /// apply it somewhere.
473 static void
474 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
475                                          AttributeList &attr,
476                                          QualType &declSpecType) {
477   Declarator &declarator = state.getDeclarator();
478 
479   // Try to distribute to the innermost.
480   if (distributeFunctionTypeAttrToInnermost(state, attr,
481                                             declarator.getAttrListRef(),
482                                             declSpecType))
483     return;
484 
485   // If that failed, diagnose the bad attribute when the declarator is
486   // fully built.
487   spliceAttrOutOfList(attr, declarator.getAttrListRef());
488   state.addIgnoredTypeAttr(attr);
489 }
490 
491 /// \brief Given that there are attributes written on the declarator
492 /// itself, try to distribute any type attributes to the appropriate
493 /// declarator chunk.
494 ///
495 /// These are attributes like the following:
496 ///   int f ATTR;
497 ///   int (f ATTR)();
498 /// but not necessarily this:
499 ///   int f() ATTR;
500 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
501                                               QualType &declSpecType) {
502   // Collect all the type attributes from the declarator itself.
503   assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
504   AttributeList *attr = state.getDeclarator().getAttributes();
505   AttributeList *next;
506   do {
507     next = attr->getNext();
508 
509     switch (attr->getKind()) {
510     OBJC_POINTER_TYPE_ATTRS_CASELIST:
511       distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
512       break;
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.getSourceRange().getBegin();
554 
555   // ...and *prepend* it to the declarator.
556   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
557                              /*proto*/ true,
558                              /*variadic*/ false, SourceLocation(),
559                              /*args*/ 0, 0,
560                              /*type quals*/ 0,
561                              /*ref-qualifier*/true, SourceLocation(),
562                              /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
563                              /*parens*/ loc, loc,
564                              declarator));
565 
566   // For consistency, make sure the state still has us as processing
567   // the decl spec.
568   assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
569   state.setCurrentChunkIndex(declarator.getNumTypeObjects());
570 }
571 
572 /// \brief Convert the specified declspec to the appropriate type
573 /// object.
574 /// \param D  the declarator containing the declaration specifier.
575 /// \returns The type described by the declaration specifiers.  This function
576 /// never returns null.
577 static QualType ConvertDeclSpecToType(Sema &S, TypeProcessingState &state) {
578   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
579   // checking.
580 
581   Declarator &declarator = state.getDeclarator();
582   const DeclSpec &DS = declarator.getDeclSpec();
583   SourceLocation DeclLoc = declarator.getIdentifierLoc();
584   if (DeclLoc.isInvalid())
585     DeclLoc = DS.getSourceRange().getBegin();
586 
587   ASTContext &Context = S.Context;
588 
589   QualType Result;
590   switch (DS.getTypeSpecType()) {
591   case DeclSpec::TST_void:
592     Result = Context.VoidTy;
593     break;
594   case DeclSpec::TST_char:
595     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
596       Result = Context.CharTy;
597     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
598       Result = Context.SignedCharTy;
599     else {
600       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
601              "Unknown TSS value");
602       Result = Context.UnsignedCharTy;
603     }
604     break;
605   case DeclSpec::TST_wchar:
606     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
607       Result = Context.WCharTy;
608     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
609       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
610         << DS.getSpecifierName(DS.getTypeSpecType());
611       Result = Context.getSignedWCharType();
612     } else {
613       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
614         "Unknown TSS value");
615       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
616         << DS.getSpecifierName(DS.getTypeSpecType());
617       Result = Context.getUnsignedWCharType();
618     }
619     break;
620   case DeclSpec::TST_char16:
621       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
622         "Unknown TSS value");
623       Result = Context.Char16Ty;
624     break;
625   case DeclSpec::TST_char32:
626       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
627         "Unknown TSS value");
628       Result = Context.Char32Ty;
629     break;
630   case DeclSpec::TST_unspecified:
631     // "<proto1,proto2>" is an objc qualified ID with a missing id.
632     if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
633       Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
634                                          (ObjCProtocolDecl**)PQ,
635                                          DS.getNumProtocolQualifiers());
636       Result = Context.getObjCObjectPointerType(Result);
637       break;
638     }
639 
640     // If this is a missing declspec in a block literal return context, then it
641     // is inferred from the return statements inside the block.
642     if (isOmittedBlockReturnType(declarator)) {
643       Result = Context.DependentTy;
644       break;
645     }
646 
647     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
648     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
649     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
650     // Note that the one exception to this is function definitions, which are
651     // allowed to be completely missing a declspec.  This is handled in the
652     // parser already though by it pretending to have seen an 'int' in this
653     // case.
654     if (S.getLangOptions().ImplicitInt) {
655       // In C89 mode, we only warn if there is a completely missing declspec
656       // when one is not allowed.
657       if (DS.isEmpty()) {
658         S.Diag(DeclLoc, diag::ext_missing_declspec)
659           << DS.getSourceRange()
660         << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
661       }
662     } else if (!DS.hasTypeSpecifier()) {
663       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
664       // "At least one type specifier shall be given in the declaration
665       // specifiers in each declaration, and in the specifier-qualifier list in
666       // each struct declaration and type name."
667       // FIXME: Does Microsoft really have the implicit int extension in C++?
668       if (S.getLangOptions().CPlusPlus &&
669           !S.getLangOptions().Microsoft) {
670         S.Diag(DeclLoc, diag::err_missing_type_specifier)
671           << DS.getSourceRange();
672 
673         // When this occurs in C++ code, often something is very broken with the
674         // value being declared, poison it as invalid so we don't get chains of
675         // errors.
676         declarator.setInvalidType(true);
677       } else {
678         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
679           << DS.getSourceRange();
680       }
681     }
682 
683     // FALL THROUGH.
684   case DeclSpec::TST_int: {
685     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
686       switch (DS.getTypeSpecWidth()) {
687       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
688       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
689       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
690       case DeclSpec::TSW_longlong:
691         Result = Context.LongLongTy;
692 
693         // long long is a C99 feature.
694         if (!S.getLangOptions().C99 &&
695             !S.getLangOptions().CPlusPlus0x)
696           S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
697         break;
698       }
699     } else {
700       switch (DS.getTypeSpecWidth()) {
701       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
702       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
703       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
704       case DeclSpec::TSW_longlong:
705         Result = Context.UnsignedLongLongTy;
706 
707         // long long is a C99 feature.
708         if (!S.getLangOptions().C99 &&
709             !S.getLangOptions().CPlusPlus0x)
710           S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
711         break;
712       }
713     }
714     break;
715   }
716   case DeclSpec::TST_float: Result = Context.FloatTy; break;
717   case DeclSpec::TST_double:
718     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
719       Result = Context.LongDoubleTy;
720     else
721       Result = Context.DoubleTy;
722 
723     if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
724       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
725       declarator.setInvalidType(true);
726     }
727     break;
728   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
729   case DeclSpec::TST_decimal32:    // _Decimal32
730   case DeclSpec::TST_decimal64:    // _Decimal64
731   case DeclSpec::TST_decimal128:   // _Decimal128
732     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
733     Result = Context.IntTy;
734     declarator.setInvalidType(true);
735     break;
736   case DeclSpec::TST_class:
737   case DeclSpec::TST_enum:
738   case DeclSpec::TST_union:
739   case DeclSpec::TST_struct: {
740     TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
741     if (!D) {
742       // This can happen in C++ with ambiguous lookups.
743       Result = Context.IntTy;
744       declarator.setInvalidType(true);
745       break;
746     }
747 
748     // If the type is deprecated or unavailable, diagnose it.
749     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
750 
751     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
752            DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
753 
754     // TypeQuals handled by caller.
755     Result = Context.getTypeDeclType(D);
756 
757     // In both C and C++, make an ElaboratedType.
758     ElaboratedTypeKeyword Keyword
759       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
760     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
761 
762     if (D->isInvalidDecl())
763       declarator.setInvalidType(true);
764     break;
765   }
766   case DeclSpec::TST_typename: {
767     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
768            DS.getTypeSpecSign() == 0 &&
769            "Can't handle qualifiers on typedef names yet!");
770     Result = S.GetTypeFromParser(DS.getRepAsType());
771     if (Result.isNull())
772       declarator.setInvalidType(true);
773     else if (DeclSpec::ProtocolQualifierListTy PQ
774                = DS.getProtocolQualifiers()) {
775       if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
776         // Silently drop any existing protocol qualifiers.
777         // TODO: determine whether that's the right thing to do.
778         if (ObjT->getNumProtocols())
779           Result = ObjT->getBaseType();
780 
781         if (DS.getNumProtocolQualifiers())
782           Result = Context.getObjCObjectType(Result,
783                                              (ObjCProtocolDecl**) PQ,
784                                              DS.getNumProtocolQualifiers());
785       } else if (Result->isObjCIdType()) {
786         // id<protocol-list>
787         Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
788                                            (ObjCProtocolDecl**) PQ,
789                                            DS.getNumProtocolQualifiers());
790         Result = Context.getObjCObjectPointerType(Result);
791       } else if (Result->isObjCClassType()) {
792         // Class<protocol-list>
793         Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
794                                            (ObjCProtocolDecl**) PQ,
795                                            DS.getNumProtocolQualifiers());
796         Result = Context.getObjCObjectPointerType(Result);
797       } else {
798         S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
799           << DS.getSourceRange();
800         declarator.setInvalidType(true);
801       }
802     }
803 
804     // TypeQuals handled by caller.
805     break;
806   }
807   case DeclSpec::TST_typeofType:
808     // FIXME: Preserve type source info.
809     Result = S.GetTypeFromParser(DS.getRepAsType());
810     assert(!Result.isNull() && "Didn't get a type for typeof?");
811     if (!Result->isDependentType())
812       if (const TagType *TT = Result->getAs<TagType>())
813         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
814     // TypeQuals handled by caller.
815     Result = Context.getTypeOfType(Result);
816     break;
817   case DeclSpec::TST_typeofExpr: {
818     Expr *E = DS.getRepAsExpr();
819     assert(E && "Didn't get an expression for typeof?");
820     // TypeQuals handled by caller.
821     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
822     if (Result.isNull()) {
823       Result = Context.IntTy;
824       declarator.setInvalidType(true);
825     }
826     break;
827   }
828   case DeclSpec::TST_decltype: {
829     Expr *E = DS.getRepAsExpr();
830     assert(E && "Didn't get an expression for decltype?");
831     // TypeQuals handled by caller.
832     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
833     if (Result.isNull()) {
834       Result = Context.IntTy;
835       declarator.setInvalidType(true);
836     }
837     break;
838   }
839   case DeclSpec::TST_auto: {
840     // TypeQuals handled by caller.
841     Result = Context.getAutoType(QualType());
842     break;
843   }
844 
845   case DeclSpec::TST_unknown_anytype:
846     Result = Context.UnknownAnyTy;
847     break;
848 
849   case DeclSpec::TST_error:
850     Result = Context.IntTy;
851     declarator.setInvalidType(true);
852     break;
853   }
854 
855   // Handle complex types.
856   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
857     if (S.getLangOptions().Freestanding)
858       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
859     Result = Context.getComplexType(Result);
860   } else if (DS.isTypeAltiVecVector()) {
861     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
862     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
863     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
864     if (DS.isTypeAltiVecPixel())
865       VecKind = VectorType::AltiVecPixel;
866     else if (DS.isTypeAltiVecBool())
867       VecKind = VectorType::AltiVecBool;
868     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
869   }
870 
871   // FIXME: Imaginary.
872   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
873     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
874 
875   // Before we process any type attributes, synthesize a block literal
876   // function declarator if necessary.
877   if (declarator.getContext() == Declarator::BlockLiteralContext)
878     maybeSynthesizeBlockSignature(state, Result);
879 
880   // Apply any type attributes from the decl spec.  This may cause the
881   // list of type attributes to be temporarily saved while the type
882   // attributes are pushed around.
883   if (AttributeList *attrs = DS.getAttributes().getList())
884     processTypeAttrs(state, Result, true, attrs);
885 
886   // Apply const/volatile/restrict qualifiers to T.
887   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
888 
889     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
890     // or incomplete types shall not be restrict-qualified."  C++ also allows
891     // restrict-qualified references.
892     if (TypeQuals & DeclSpec::TQ_restrict) {
893       if (Result->isAnyPointerType() || Result->isReferenceType()) {
894         QualType EltTy;
895         if (Result->isObjCObjectPointerType())
896           EltTy = Result;
897         else
898           EltTy = Result->isPointerType() ?
899                     Result->getAs<PointerType>()->getPointeeType() :
900                     Result->getAs<ReferenceType>()->getPointeeType();
901 
902         // If we have a pointer or reference, the pointee must have an object
903         // incomplete type.
904         if (!EltTy->isIncompleteOrObjectType()) {
905           S.Diag(DS.getRestrictSpecLoc(),
906                diag::err_typecheck_invalid_restrict_invalid_pointee)
907             << EltTy << DS.getSourceRange();
908           TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
909         }
910       } else {
911         S.Diag(DS.getRestrictSpecLoc(),
912                diag::err_typecheck_invalid_restrict_not_pointer)
913           << Result << DS.getSourceRange();
914         TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
915       }
916     }
917 
918     // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
919     // of a function type includes any type qualifiers, the behavior is
920     // undefined."
921     if (Result->isFunctionType() && TypeQuals) {
922       // Get some location to point at, either the C or V location.
923       SourceLocation Loc;
924       if (TypeQuals & DeclSpec::TQ_const)
925         Loc = DS.getConstSpecLoc();
926       else if (TypeQuals & DeclSpec::TQ_volatile)
927         Loc = DS.getVolatileSpecLoc();
928       else {
929         assert((TypeQuals & DeclSpec::TQ_restrict) &&
930                "Has CVR quals but not C, V, or R?");
931         Loc = DS.getRestrictSpecLoc();
932       }
933       S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
934         << Result << DS.getSourceRange();
935     }
936 
937     // C++ [dcl.ref]p1:
938     //   Cv-qualified references are ill-formed except when the
939     //   cv-qualifiers are introduced through the use of a typedef
940     //   (7.1.3) or of a template type argument (14.3), in which
941     //   case the cv-qualifiers are ignored.
942     // FIXME: Shouldn't we be checking SCS_typedef here?
943     if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
944         TypeQuals && Result->isReferenceType()) {
945       TypeQuals &= ~DeclSpec::TQ_const;
946       TypeQuals &= ~DeclSpec::TQ_volatile;
947     }
948 
949     Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
950     Result = Context.getQualifiedType(Result, Quals);
951   }
952 
953   return Result;
954 }
955 
956 static std::string getPrintableNameForEntity(DeclarationName Entity) {
957   if (Entity)
958     return Entity.getAsString();
959 
960   return "type name";
961 }
962 
963 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
964                                   Qualifiers Qs) {
965   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
966   // object or incomplete types shall not be restrict-qualified."
967   if (Qs.hasRestrict()) {
968     unsigned DiagID = 0;
969     QualType ProblemTy;
970 
971     const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
972     if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
973       if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
974         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
975         ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
976       }
977     } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
978       if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
979         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
980         ProblemTy = T->getAs<PointerType>()->getPointeeType();
981       }
982     } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
983       if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
984         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
985         ProblemTy = T->getAs<PointerType>()->getPointeeType();
986       }
987     } else if (!Ty->isDependentType()) {
988       // FIXME: this deserves a proper diagnostic
989       DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
990       ProblemTy = T;
991     }
992 
993     if (DiagID) {
994       Diag(Loc, DiagID) << ProblemTy;
995       Qs.removeRestrict();
996     }
997   }
998 
999   return Context.getQualifiedType(T, Qs);
1000 }
1001 
1002 /// \brief Build a paren type including \p T.
1003 QualType Sema::BuildParenType(QualType T) {
1004   return Context.getParenType(T);
1005 }
1006 
1007 /// \brief Build a pointer type.
1008 ///
1009 /// \param T The type to which we'll be building a pointer.
1010 ///
1011 /// \param Loc The location of the entity whose type involves this
1012 /// pointer type or, if there is no such entity, the location of the
1013 /// type that will have pointer type.
1014 ///
1015 /// \param Entity The name of the entity that involves the pointer
1016 /// type, if known.
1017 ///
1018 /// \returns A suitable pointer type, if there are no
1019 /// errors. Otherwise, returns a NULL type.
1020 QualType Sema::BuildPointerType(QualType T,
1021                                 SourceLocation Loc, DeclarationName Entity) {
1022   if (T->isReferenceType()) {
1023     // C++ 8.3.2p4: There shall be no ... pointers to references ...
1024     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1025       << getPrintableNameForEntity(Entity) << T;
1026     return QualType();
1027   }
1028 
1029   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1030 
1031   // Build the pointer type.
1032   return Context.getPointerType(T);
1033 }
1034 
1035 /// \brief Build a reference type.
1036 ///
1037 /// \param T The type to which we'll be building a reference.
1038 ///
1039 /// \param Loc The location of the entity whose type involves this
1040 /// reference type or, if there is no such entity, the location of the
1041 /// type that will have reference type.
1042 ///
1043 /// \param Entity The name of the entity that involves the reference
1044 /// type, if known.
1045 ///
1046 /// \returns A suitable reference type, if there are no
1047 /// errors. Otherwise, returns a NULL type.
1048 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1049                                   SourceLocation Loc,
1050                                   DeclarationName Entity) {
1051   // C++0x [dcl.ref]p6:
1052   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1053   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1054   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1055   //   the type "lvalue reference to T", while an attempt to create the type
1056   //   "rvalue reference to cv TR" creates the type TR.
1057   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1058 
1059   // C++ [dcl.ref]p4: There shall be no references to references.
1060   //
1061   // According to C++ DR 106, references to references are only
1062   // diagnosed when they are written directly (e.g., "int & &"),
1063   // but not when they happen via a typedef:
1064   //
1065   //   typedef int& intref;
1066   //   typedef intref& intref2;
1067   //
1068   // Parser::ParseDeclaratorInternal diagnoses the case where
1069   // references are written directly; here, we handle the
1070   // collapsing of references-to-references as described in C++0x.
1071   // DR 106 and 540 introduce reference-collapsing into C++98/03.
1072 
1073   // C++ [dcl.ref]p1:
1074   //   A declarator that specifies the type "reference to cv void"
1075   //   is ill-formed.
1076   if (T->isVoidType()) {
1077     Diag(Loc, diag::err_reference_to_void);
1078     return QualType();
1079   }
1080 
1081   // Handle restrict on references.
1082   if (LValueRef)
1083     return Context.getLValueReferenceType(T, SpelledAsLValue);
1084   return Context.getRValueReferenceType(T);
1085 }
1086 
1087 /// \brief Build an array type.
1088 ///
1089 /// \param T The type of each element in the array.
1090 ///
1091 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1092 ///
1093 /// \param ArraySize Expression describing the size of the array.
1094 ///
1095 /// \param Loc The location of the entity whose type involves this
1096 /// array type or, if there is no such entity, the location of the
1097 /// type that will have array type.
1098 ///
1099 /// \param Entity The name of the entity that involves the array
1100 /// type, if known.
1101 ///
1102 /// \returns A suitable array type, if there are no errors. Otherwise,
1103 /// returns a NULL type.
1104 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1105                               Expr *ArraySize, unsigned Quals,
1106                               SourceRange Brackets, DeclarationName Entity) {
1107 
1108   SourceLocation Loc = Brackets.getBegin();
1109   if (getLangOptions().CPlusPlus) {
1110     // C++ [dcl.array]p1:
1111     //   T is called the array element type; this type shall not be a reference
1112     //   type, the (possibly cv-qualified) type void, a function type or an
1113     //   abstract class type.
1114     //
1115     // Note: function types are handled in the common path with C.
1116     if (T->isReferenceType()) {
1117       Diag(Loc, diag::err_illegal_decl_array_of_references)
1118       << getPrintableNameForEntity(Entity) << T;
1119       return QualType();
1120     }
1121 
1122     if (T->isVoidType()) {
1123       Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1124       return QualType();
1125     }
1126 
1127     if (RequireNonAbstractType(Brackets.getBegin(), T,
1128                                diag::err_array_of_abstract_type))
1129       return QualType();
1130 
1131   } else {
1132     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1133     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1134     if (RequireCompleteType(Loc, T,
1135                             diag::err_illegal_decl_array_incomplete_type))
1136       return QualType();
1137   }
1138 
1139   if (T->isFunctionType()) {
1140     Diag(Loc, diag::err_illegal_decl_array_of_functions)
1141       << getPrintableNameForEntity(Entity) << T;
1142     return QualType();
1143   }
1144 
1145   if (T->getContainedAutoType()) {
1146     Diag(Loc, diag::err_illegal_decl_array_of_auto)
1147       << getPrintableNameForEntity(Entity) << T;
1148     return QualType();
1149   }
1150 
1151   if (const RecordType *EltTy = T->getAs<RecordType>()) {
1152     // If the element type is a struct or union that contains a variadic
1153     // array, accept it as a GNU extension: C99 6.7.2.1p2.
1154     if (EltTy->getDecl()->hasFlexibleArrayMember())
1155       Diag(Loc, diag::ext_flexible_array_in_array) << T;
1156   } else if (T->isObjCObjectType()) {
1157     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1158     return QualType();
1159   }
1160 
1161   // Do lvalue-to-rvalue conversions on the array size expression.
1162   if (ArraySize && !ArraySize->isRValue()) {
1163     ExprResult Result = DefaultLvalueConversion(ArraySize);
1164     if (Result.isInvalid())
1165       return QualType();
1166 
1167     ArraySize = Result.take();
1168   }
1169 
1170   // C99 6.7.5.2p1: The size expression shall have integer type.
1171   // TODO: in theory, if we were insane, we could allow contextual
1172   // conversions to integer type here.
1173   if (ArraySize && !ArraySize->isTypeDependent() &&
1174       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1175     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1176       << ArraySize->getType() << ArraySize->getSourceRange();
1177     return QualType();
1178   }
1179   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1180   if (!ArraySize) {
1181     if (ASM == ArrayType::Star)
1182       T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1183     else
1184       T = Context.getIncompleteArrayType(T, ASM, Quals);
1185   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1186     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1187   } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
1188              (!T->isDependentType() && !T->isIncompleteType() &&
1189               !T->isConstantSizeType())) {
1190     // Per C99, a variable array is an array with either a non-constant
1191     // size or an element type that has a non-constant-size
1192     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1193   } else {
1194     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1195     // have a value greater than zero.
1196     if (ConstVal.isSigned() && ConstVal.isNegative()) {
1197       if (Entity)
1198         Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1199           << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1200       else
1201         Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1202           << ArraySize->getSourceRange();
1203       return QualType();
1204     }
1205     if (ConstVal == 0) {
1206       // GCC accepts zero sized static arrays. We allow them when
1207       // we're not in a SFINAE context.
1208       Diag(ArraySize->getLocStart(),
1209            isSFINAEContext()? diag::err_typecheck_zero_array_size
1210                             : diag::ext_typecheck_zero_array_size)
1211         << ArraySize->getSourceRange();
1212     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1213                !T->isIncompleteType()) {
1214       // Is the array too large?
1215       unsigned ActiveSizeBits
1216         = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1217       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1218         Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1219           << ConstVal.toString(10)
1220           << ArraySize->getSourceRange();
1221     }
1222 
1223     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1224   }
1225   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1226   if (!getLangOptions().C99) {
1227     if (T->isVariableArrayType()) {
1228       // Prohibit the use of non-POD types in VLAs.
1229       if (!T->isDependentType() &&
1230           !Context.getBaseElementType(T)->isPODType()) {
1231         Diag(Loc, diag::err_vla_non_pod)
1232           << Context.getBaseElementType(T);
1233         return QualType();
1234       }
1235       // Prohibit the use of VLAs during template argument deduction.
1236       else if (isSFINAEContext()) {
1237         Diag(Loc, diag::err_vla_in_sfinae);
1238         return QualType();
1239       }
1240       // Just extwarn about VLAs.
1241       else
1242         Diag(Loc, diag::ext_vla);
1243     } else if (ASM != ArrayType::Normal || Quals != 0)
1244       Diag(Loc,
1245            getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1246                                      : diag::ext_c99_array_usage);
1247   }
1248 
1249   return T;
1250 }
1251 
1252 /// \brief Build an ext-vector type.
1253 ///
1254 /// Run the required checks for the extended vector type.
1255 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1256                                   SourceLocation AttrLoc) {
1257   // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1258   // in conjunction with complex types (pointers, arrays, functions, etc.).
1259   if (!T->isDependentType() &&
1260       !T->isIntegerType() && !T->isRealFloatingType()) {
1261     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1262     return QualType();
1263   }
1264 
1265   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1266     llvm::APSInt vecSize(32);
1267     if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1268       Diag(AttrLoc, diag::err_attribute_argument_not_int)
1269         << "ext_vector_type" << ArraySize->getSourceRange();
1270       return QualType();
1271     }
1272 
1273     // unlike gcc's vector_size attribute, the size is specified as the
1274     // number of elements, not the number of bytes.
1275     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1276 
1277     if (vectorSize == 0) {
1278       Diag(AttrLoc, diag::err_attribute_zero_size)
1279       << ArraySize->getSourceRange();
1280       return QualType();
1281     }
1282 
1283     if (!T->isDependentType())
1284       return Context.getExtVectorType(T, vectorSize);
1285   }
1286 
1287   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1288 }
1289 
1290 /// \brief Build a function type.
1291 ///
1292 /// This routine checks the function type according to C++ rules and
1293 /// under the assumption that the result type and parameter types have
1294 /// just been instantiated from a template. It therefore duplicates
1295 /// some of the behavior of GetTypeForDeclarator, but in a much
1296 /// simpler form that is only suitable for this narrow use case.
1297 ///
1298 /// \param T The return type of the function.
1299 ///
1300 /// \param ParamTypes The parameter types of the function. This array
1301 /// will be modified to account for adjustments to the types of the
1302 /// function parameters.
1303 ///
1304 /// \param NumParamTypes The number of parameter types in ParamTypes.
1305 ///
1306 /// \param Variadic Whether this is a variadic function type.
1307 ///
1308 /// \param Quals The cvr-qualifiers to be applied to the function type.
1309 ///
1310 /// \param Loc The location of the entity whose type involves this
1311 /// function type or, if there is no such entity, the location of the
1312 /// type that will have function type.
1313 ///
1314 /// \param Entity The name of the entity that involves the function
1315 /// type, if known.
1316 ///
1317 /// \returns A suitable function type, if there are no
1318 /// errors. Otherwise, returns a NULL type.
1319 QualType Sema::BuildFunctionType(QualType T,
1320                                  QualType *ParamTypes,
1321                                  unsigned NumParamTypes,
1322                                  bool Variadic, unsigned Quals,
1323                                  RefQualifierKind RefQualifier,
1324                                  SourceLocation Loc, DeclarationName Entity,
1325                                  FunctionType::ExtInfo Info) {
1326   if (T->isArrayType() || T->isFunctionType()) {
1327     Diag(Loc, diag::err_func_returning_array_function)
1328       << T->isFunctionType() << T;
1329     return QualType();
1330   }
1331 
1332   bool Invalid = false;
1333   for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
1334     QualType ParamType = adjustParameterType(ParamTypes[Idx]);
1335     if (ParamType->isVoidType()) {
1336       Diag(Loc, diag::err_param_with_void_type);
1337       Invalid = true;
1338     }
1339 
1340     ParamTypes[Idx] = ParamType;
1341   }
1342 
1343   if (Invalid)
1344     return QualType();
1345 
1346   FunctionProtoType::ExtProtoInfo EPI;
1347   EPI.Variadic = Variadic;
1348   EPI.TypeQuals = Quals;
1349   EPI.RefQualifier = RefQualifier;
1350   EPI.ExtInfo = Info;
1351 
1352   return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
1353 }
1354 
1355 /// \brief Build a member pointer type \c T Class::*.
1356 ///
1357 /// \param T the type to which the member pointer refers.
1358 /// \param Class the class type into which the member pointer points.
1359 /// \param CVR Qualifiers applied to the member pointer type
1360 /// \param Loc the location where this type begins
1361 /// \param Entity the name of the entity that will have this member pointer type
1362 ///
1363 /// \returns a member pointer type, if successful, or a NULL type if there was
1364 /// an error.
1365 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1366                                       SourceLocation Loc,
1367                                       DeclarationName Entity) {
1368   // Verify that we're not building a pointer to pointer to function with
1369   // exception specification.
1370   if (CheckDistantExceptionSpec(T)) {
1371     Diag(Loc, diag::err_distant_exception_spec);
1372 
1373     // FIXME: If we're doing this as part of template instantiation,
1374     // we should return immediately.
1375 
1376     // Build the type anyway, but use the canonical type so that the
1377     // exception specifiers are stripped off.
1378     T = Context.getCanonicalType(T);
1379   }
1380 
1381   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1382   //   with reference type, or "cv void."
1383   if (T->isReferenceType()) {
1384     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1385       << (Entity? Entity.getAsString() : "type name") << T;
1386     return QualType();
1387   }
1388 
1389   if (T->isVoidType()) {
1390     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1391       << (Entity? Entity.getAsString() : "type name");
1392     return QualType();
1393   }
1394 
1395   if (!Class->isDependentType() && !Class->isRecordType()) {
1396     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1397     return QualType();
1398   }
1399 
1400   // In the Microsoft ABI, the class is allowed to be an incomplete
1401   // type. In such cases, the compiler makes a worst-case assumption.
1402   // We make no such assumption right now, so emit an error if the
1403   // class isn't a complete type.
1404   if (Context.Target.getCXXABI() == CXXABI_Microsoft &&
1405       RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1406     return QualType();
1407 
1408   return Context.getMemberPointerType(T, Class.getTypePtr());
1409 }
1410 
1411 /// \brief Build a block pointer type.
1412 ///
1413 /// \param T The type to which we'll be building a block pointer.
1414 ///
1415 /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
1416 ///
1417 /// \param Loc The location of the entity whose type involves this
1418 /// block pointer type or, if there is no such entity, the location of the
1419 /// type that will have block pointer type.
1420 ///
1421 /// \param Entity The name of the entity that involves the block pointer
1422 /// type, if known.
1423 ///
1424 /// \returns A suitable block pointer type, if there are no
1425 /// errors. Otherwise, returns a NULL type.
1426 QualType Sema::BuildBlockPointerType(QualType T,
1427                                      SourceLocation Loc,
1428                                      DeclarationName Entity) {
1429   if (!T->isFunctionType()) {
1430     Diag(Loc, diag::err_nonfunction_block_type);
1431     return QualType();
1432   }
1433 
1434   return Context.getBlockPointerType(T);
1435 }
1436 
1437 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1438   QualType QT = Ty.get();
1439   if (QT.isNull()) {
1440     if (TInfo) *TInfo = 0;
1441     return QualType();
1442   }
1443 
1444   TypeSourceInfo *DI = 0;
1445   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1446     QT = LIT->getType();
1447     DI = LIT->getTypeSourceInfo();
1448   }
1449 
1450   if (TInfo) *TInfo = DI;
1451   return QT;
1452 }
1453 
1454 static void DiagnoseIgnoredQualifiers(unsigned Quals,
1455                                       SourceLocation ConstQualLoc,
1456                                       SourceLocation VolatileQualLoc,
1457                                       SourceLocation RestrictQualLoc,
1458                                       Sema& S) {
1459   std::string QualStr;
1460   unsigned NumQuals = 0;
1461   SourceLocation Loc;
1462 
1463   FixItHint ConstFixIt;
1464   FixItHint VolatileFixIt;
1465   FixItHint RestrictFixIt;
1466 
1467   // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1468   // find a range and grow it to encompass all the qualifiers, regardless of
1469   // the order in which they textually appear.
1470   if (Quals & Qualifiers::Const) {
1471     ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
1472     Loc = ConstQualLoc;
1473     ++NumQuals;
1474     QualStr = "const";
1475   }
1476   if (Quals & Qualifiers::Volatile) {
1477     VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
1478     if (NumQuals == 0) {
1479       Loc = VolatileQualLoc;
1480       QualStr = "volatile";
1481     } else {
1482       QualStr += " volatile";
1483     }
1484     ++NumQuals;
1485   }
1486   if (Quals & Qualifiers::Restrict) {
1487     RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
1488     if (NumQuals == 0) {
1489       Loc = RestrictQualLoc;
1490       QualStr = "restrict";
1491     } else {
1492       QualStr += " restrict";
1493     }
1494     ++NumQuals;
1495   }
1496 
1497   assert(NumQuals > 0 && "No known qualifiers?");
1498 
1499   S.Diag(Loc, diag::warn_qual_return_type)
1500     << QualStr << NumQuals
1501     << ConstFixIt << VolatileFixIt << RestrictFixIt;
1502 }
1503 
1504 /// GetTypeForDeclarator - Convert the type for the specified
1505 /// declarator to Type instances.
1506 ///
1507 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
1508 /// owns the declaration of a type (e.g., the definition of a struct
1509 /// type), then *OwnedDecl will receive the owned declaration.
1510 ///
1511 /// The result of this call will never be null, but the associated
1512 /// type may be a null type if there's an unrecoverable error.
1513 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
1514                                            TagDecl **OwnedDecl,
1515                                            bool AutoAllowedInTypeName) {
1516   // Determine the type of the declarator. Not all forms of declarator
1517   // have a type.
1518   QualType T;
1519   TypeSourceInfo *ReturnTypeInfo = 0;
1520 
1521   TypeProcessingState state(*this, D);
1522 
1523   // In C++0x, deallocation functions (normal and array operator delete)
1524   // are implicitly noexcept.
1525   bool ImplicitlyNoexcept = false;
1526 
1527   switch (D.getName().getKind()) {
1528   case UnqualifiedId::IK_OperatorFunctionId:
1529     if (getLangOptions().CPlusPlus0x) {
1530       OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1531       if (OO == OO_Delete || OO == OO_Array_Delete)
1532         ImplicitlyNoexcept = true;
1533     }
1534     // Intentional fall-through.
1535   case UnqualifiedId::IK_Identifier:
1536   case UnqualifiedId::IK_LiteralOperatorId:
1537   case UnqualifiedId::IK_TemplateId:
1538     T = ConvertDeclSpecToType(*this, state);
1539 
1540     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
1541       TagDecl* Owned = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1542       // Owned declaration is embedded in declarator.
1543       Owned->setEmbeddedInDeclarator(true);
1544       if (OwnedDecl) *OwnedDecl = Owned;
1545     }
1546     break;
1547 
1548   case UnqualifiedId::IK_ConstructorName:
1549   case UnqualifiedId::IK_ConstructorTemplateId:
1550   case UnqualifiedId::IK_DestructorName:
1551     // Constructors and destructors don't have return types. Use
1552     // "void" instead.
1553     T = Context.VoidTy;
1554     break;
1555 
1556   case UnqualifiedId::IK_ConversionFunctionId:
1557     // The result type of a conversion function is the type that it
1558     // converts to.
1559     T = GetTypeFromParser(D.getName().ConversionFunctionId,
1560                           &ReturnTypeInfo);
1561     break;
1562   }
1563 
1564   if (D.getAttributes())
1565     distributeTypeAttrsFromDeclarator(state, T);
1566 
1567   // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1568   // In C++0x, a function declarator using 'auto' must have a trailing return
1569   // type (this is checked later) and we can skip this. In other languages
1570   // using auto, we need to check regardless.
1571   if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1572       (!getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
1573     int Error = -1;
1574 
1575     switch (D.getContext()) {
1576     case Declarator::KNRTypeListContext:
1577       assert(0 && "K&R type lists aren't allowed in C++");
1578       break;
1579     case Declarator::ObjCPrototypeContext:
1580     case Declarator::PrototypeContext:
1581       Error = 0; // Function prototype
1582       break;
1583     case Declarator::MemberContext:
1584       switch (cast<TagDecl>(CurContext)->getTagKind()) {
1585       case TTK_Enum: assert(0 && "unhandled tag kind"); break;
1586       case TTK_Struct: Error = 1; /* Struct member */ break;
1587       case TTK_Union:  Error = 2; /* Union member */ break;
1588       case TTK_Class:  Error = 3; /* Class member */ break;
1589       }
1590       break;
1591     case Declarator::CXXCatchContext:
1592       Error = 4; // Exception declaration
1593       break;
1594     case Declarator::TemplateParamContext:
1595       Error = 5; // Template parameter
1596       break;
1597     case Declarator::BlockLiteralContext:
1598       Error = 6; // Block literal
1599       break;
1600     case Declarator::TemplateTypeArgContext:
1601       Error = 7; // Template type argument
1602       break;
1603     case Declarator::TypeNameContext:
1604       if (!AutoAllowedInTypeName)
1605         Error = 10; // Generic
1606       break;
1607     case Declarator::FileContext:
1608     case Declarator::BlockContext:
1609     case Declarator::ForContext:
1610     case Declarator::ConditionContext:
1611       break;
1612     }
1613 
1614     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1615       Error = 8;
1616 
1617     // In Objective-C it is an error to use 'auto' on a function declarator.
1618     if (D.isFunctionDeclarator())
1619       Error = 9;
1620 
1621     // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1622     // contains a trailing return type. That is only legal at the outermost
1623     // level. Check all declarator chunks (outermost first) anyway, to give
1624     // better diagnostics.
1625     if (getLangOptions().CPlusPlus0x && Error != -1) {
1626       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1627         unsigned chunkIndex = e - i - 1;
1628         state.setCurrentChunkIndex(chunkIndex);
1629         DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1630         if (DeclType.Kind == DeclaratorChunk::Function) {
1631           const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1632           if (FTI.TrailingReturnType) {
1633             Error = -1;
1634             break;
1635           }
1636         }
1637       }
1638     }
1639 
1640     if (Error != -1) {
1641       Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1642         << Error;
1643       T = Context.IntTy;
1644       D.setInvalidType(true);
1645     }
1646   }
1647 
1648   if (T.isNull())
1649     return Context.getNullTypeSourceInfo();
1650 
1651   // The name we're declaring, if any.
1652   DeclarationName Name;
1653   if (D.getIdentifier())
1654     Name = D.getIdentifier();
1655 
1656   // Walk the DeclTypeInfo, building the recursive type as we go.
1657   // DeclTypeInfos are ordered from the identifier out, which is
1658   // opposite of what we want :).
1659   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1660     unsigned chunkIndex = e - i - 1;
1661     state.setCurrentChunkIndex(chunkIndex);
1662     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1663     switch (DeclType.Kind) {
1664     default: assert(0 && "Unknown decltype!");
1665     case DeclaratorChunk::Paren:
1666       T = BuildParenType(T);
1667       break;
1668     case DeclaratorChunk::BlockPointer:
1669       // If blocks are disabled, emit an error.
1670       if (!LangOpts.Blocks)
1671         Diag(DeclType.Loc, diag::err_blocks_disable);
1672 
1673       T = BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
1674       if (DeclType.Cls.TypeQuals)
1675         T = BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
1676       break;
1677     case DeclaratorChunk::Pointer:
1678       // Verify that we're not building a pointer to pointer to function with
1679       // exception specification.
1680       if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1681         Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1682         D.setInvalidType(true);
1683         // Build the type anyway.
1684       }
1685       if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) {
1686         T = Context.getObjCObjectPointerType(T);
1687         if (DeclType.Ptr.TypeQuals)
1688           T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1689         break;
1690       }
1691       T = BuildPointerType(T, DeclType.Loc, Name);
1692       if (DeclType.Ptr.TypeQuals)
1693         T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1694 
1695       break;
1696     case DeclaratorChunk::Reference: {
1697       // Verify that we're not building a reference to pointer to function with
1698       // exception specification.
1699       if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1700         Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1701         D.setInvalidType(true);
1702         // Build the type anyway.
1703       }
1704       T = BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
1705 
1706       Qualifiers Quals;
1707       if (DeclType.Ref.HasRestrict)
1708         T = BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
1709       break;
1710     }
1711     case DeclaratorChunk::Array: {
1712       // Verify that we're not building an array of pointers to function with
1713       // exception specification.
1714       if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1715         Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1716         D.setInvalidType(true);
1717         // Build the type anyway.
1718       }
1719       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1720       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1721       ArrayType::ArraySizeModifier ASM;
1722       if (ATI.isStar)
1723         ASM = ArrayType::Star;
1724       else if (ATI.hasStatic)
1725         ASM = ArrayType::Static;
1726       else
1727         ASM = ArrayType::Normal;
1728       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
1729         // FIXME: This check isn't quite right: it allows star in prototypes
1730         // for function definitions, and disallows some edge cases detailed
1731         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1732         Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1733         ASM = ArrayType::Normal;
1734         D.setInvalidType(true);
1735       }
1736       T = BuildArrayType(T, ASM, ArraySize,
1737                          Qualifiers::fromCVRMask(ATI.TypeQuals),
1738                          SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1739       break;
1740     }
1741     case DeclaratorChunk::Function: {
1742       // If the function declarator has a prototype (i.e. it is not () and
1743       // does not have a K&R-style identifier list), then the arguments are part
1744       // of the type, otherwise the argument list is ().
1745       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1746 
1747       // Check for auto functions and trailing return type and adjust the
1748       // return type accordingly.
1749       if (!D.isInvalidType()) {
1750         // trailing-return-type is only required if we're declaring a function,
1751         // and not, for instance, a pointer to a function.
1752         if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1753             !FTI.TrailingReturnType && chunkIndex == 0) {
1754           Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1755                diag::err_auto_missing_trailing_return);
1756           T = Context.IntTy;
1757           D.setInvalidType(true);
1758         } else if (FTI.TrailingReturnType) {
1759           // T must be exactly 'auto' at this point. See CWG issue 681.
1760           if (isa<ParenType>(T)) {
1761             Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1762                  diag::err_trailing_return_in_parens)
1763               << T << D.getDeclSpec().getSourceRange();
1764             D.setInvalidType(true);
1765           } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
1766             Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1767                  diag::err_trailing_return_without_auto)
1768               << T << D.getDeclSpec().getSourceRange();
1769             D.setInvalidType(true);
1770           }
1771 
1772           T = GetTypeFromParser(
1773             ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
1774             &ReturnTypeInfo);
1775         }
1776       }
1777 
1778       // C99 6.7.5.3p1: The return type may not be a function or array type.
1779       // For conversion functions, we'll diagnose this particular error later.
1780       if ((T->isArrayType() || T->isFunctionType()) &&
1781           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
1782         unsigned diagID = diag::err_func_returning_array_function;
1783         // Last processing chunk in block context means this function chunk
1784         // represents the block.
1785         if (chunkIndex == 0 &&
1786             D.getContext() == Declarator::BlockLiteralContext)
1787           diagID = diag::err_block_returning_array_function;
1788         Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
1789         T = Context.IntTy;
1790         D.setInvalidType(true);
1791       }
1792 
1793       // cv-qualifiers on return types are pointless except when the type is a
1794       // class type in C++.
1795       if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
1796           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
1797           (!getLangOptions().CPlusPlus || !T->isDependentType())) {
1798         assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
1799         DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
1800         assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
1801 
1802         DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
1803 
1804         DiagnoseIgnoredQualifiers(PTI.TypeQuals,
1805             SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
1806             SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
1807             SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
1808             *this);
1809 
1810       } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
1811           (!getLangOptions().CPlusPlus ||
1812            (!T->isDependentType() && !T->isRecordType()))) {
1813 
1814         DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
1815                                   D.getDeclSpec().getConstSpecLoc(),
1816                                   D.getDeclSpec().getVolatileSpecLoc(),
1817                                   D.getDeclSpec().getRestrictSpecLoc(),
1818                                   *this);
1819       }
1820 
1821       if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1822         // C++ [dcl.fct]p6:
1823         //   Types shall not be defined in return or parameter types.
1824         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1825         if (Tag->isDefinition())
1826           Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1827             << Context.getTypeDeclType(Tag);
1828       }
1829 
1830       // Exception specs are not allowed in typedefs. Complain, but add it
1831       // anyway.
1832       if (FTI.getExceptionSpecType() != EST_None &&
1833           D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1834         Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef);
1835 
1836       if (!FTI.NumArgs && !FTI.isVariadic && !getLangOptions().CPlusPlus) {
1837         // Simple void foo(), where the incoming T is the result type.
1838         T = Context.getFunctionNoProtoType(T);
1839       } else {
1840         // We allow a zero-parameter variadic function in C if the
1841         // function is marked with the "overloadable" attribute. Scan
1842         // for this attribute now.
1843         if (!FTI.NumArgs && FTI.isVariadic && !getLangOptions().CPlusPlus) {
1844           bool Overloadable = false;
1845           for (const AttributeList *Attrs = D.getAttributes();
1846                Attrs; Attrs = Attrs->getNext()) {
1847             if (Attrs->getKind() == AttributeList::AT_overloadable) {
1848               Overloadable = true;
1849               break;
1850             }
1851           }
1852 
1853           if (!Overloadable)
1854             Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1855         }
1856 
1857         if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
1858           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
1859           // definition.
1860           Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1861           D.setInvalidType(true);
1862           break;
1863         }
1864 
1865         FunctionProtoType::ExtProtoInfo EPI;
1866         EPI.Variadic = FTI.isVariadic;
1867         EPI.TypeQuals = FTI.TypeQuals;
1868         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
1869                     : FTI.RefQualifierIsLValueRef? RQ_LValue
1870                     : RQ_RValue;
1871 
1872         // Otherwise, we have a function with an argument list that is
1873         // potentially variadic.
1874         llvm::SmallVector<QualType, 16> ArgTys;
1875         ArgTys.reserve(FTI.NumArgs);
1876 
1877         for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1878           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
1879           QualType ArgTy = Param->getType();
1880           assert(!ArgTy.isNull() && "Couldn't parse type?");
1881 
1882           // Adjust the parameter type.
1883           assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1884 
1885           // Look for 'void'.  void is allowed only as a single argument to a
1886           // function with no other parameters (C99 6.7.5.3p10).  We record
1887           // int(void) as a FunctionProtoType with an empty argument list.
1888           if (ArgTy->isVoidType()) {
1889             // If this is something like 'float(int, void)', reject it.  'void'
1890             // is an incomplete type (C99 6.2.5p19) and function decls cannot
1891             // have arguments of incomplete type.
1892             if (FTI.NumArgs != 1 || FTI.isVariadic) {
1893               Diag(DeclType.Loc, diag::err_void_only_param);
1894               ArgTy = Context.IntTy;
1895               Param->setType(ArgTy);
1896             } else if (FTI.ArgInfo[i].Ident) {
1897               // Reject, but continue to parse 'int(void abc)'.
1898               Diag(FTI.ArgInfo[i].IdentLoc,
1899                    diag::err_param_with_void_type);
1900               ArgTy = Context.IntTy;
1901               Param->setType(ArgTy);
1902             } else {
1903               // Reject, but continue to parse 'float(const void)'.
1904               if (ArgTy.hasQualifiers())
1905                 Diag(DeclType.Loc, diag::err_void_param_qualified);
1906 
1907               // Do not add 'void' to the ArgTys list.
1908               break;
1909             }
1910           } else if (!FTI.hasPrototype) {
1911             if (ArgTy->isPromotableIntegerType()) {
1912               ArgTy = Context.getPromotedIntegerType(ArgTy);
1913               Param->setKNRPromoted(true);
1914             } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1915               if (BTy->getKind() == BuiltinType::Float) {
1916                 ArgTy = Context.DoubleTy;
1917                 Param->setKNRPromoted(true);
1918               }
1919             }
1920           }
1921 
1922           ArgTys.push_back(ArgTy);
1923         }
1924 
1925         llvm::SmallVector<QualType, 4> Exceptions;
1926         EPI.ExceptionSpecType = FTI.getExceptionSpecType();
1927         if (FTI.getExceptionSpecType() == EST_Dynamic) {
1928           Exceptions.reserve(FTI.NumExceptions);
1929           for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1930             // FIXME: Preserve type source info.
1931             QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1932             // Check that the type is valid for an exception spec, and
1933             // drop it if not.
1934             if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1935               Exceptions.push_back(ET);
1936           }
1937           EPI.NumExceptions = Exceptions.size();
1938           EPI.Exceptions = Exceptions.data();
1939         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
1940           // If an error occurred, there's no expression here.
1941           if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
1942             assert((NoexceptExpr->isTypeDependent() ||
1943                     NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
1944                         Context.BoolTy) &&
1945                  "Parser should have made sure that the expression is boolean");
1946             SourceLocation ErrLoc;
1947             llvm::APSInt Dummy;
1948             if (!NoexceptExpr->isValueDependent() &&
1949                 !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
1950                                                      /*evaluated*/false))
1951               Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
1952                   << NoexceptExpr->getSourceRange();
1953             else
1954               EPI.NoexceptExpr = NoexceptExpr;
1955           }
1956         } else if (FTI.getExceptionSpecType() == EST_None &&
1957                    ImplicitlyNoexcept && chunkIndex == 0) {
1958           // Only the outermost chunk is marked noexcept, of course.
1959           EPI.ExceptionSpecType = EST_BasicNoexcept;
1960         }
1961 
1962         T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
1963       }
1964 
1965       break;
1966     }
1967     case DeclaratorChunk::MemberPointer:
1968       // The scope spec must refer to a class, or be dependent.
1969       CXXScopeSpec &SS = DeclType.Mem.Scope();
1970       QualType ClsType;
1971       if (SS.isInvalid()) {
1972         // Avoid emitting extra errors if we already errored on the scope.
1973         D.setInvalidType(true);
1974       } else if (isDependentScopeSpecifier(SS) ||
1975                  dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS))) {
1976         NestedNameSpecifier *NNS
1977           = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1978         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1979         switch (NNS->getKind()) {
1980         case NestedNameSpecifier::Identifier:
1981           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
1982                                                  NNS->getAsIdentifier());
1983           break;
1984 
1985         case NestedNameSpecifier::Namespace:
1986         case NestedNameSpecifier::NamespaceAlias:
1987         case NestedNameSpecifier::Global:
1988           llvm_unreachable("Nested-name-specifier must name a type");
1989           break;
1990 
1991         case NestedNameSpecifier::TypeSpec:
1992         case NestedNameSpecifier::TypeSpecWithTemplate:
1993           ClsType = QualType(NNS->getAsType(), 0);
1994           // Note: if the NNS has a prefix and ClsType is a nondependent
1995           // TemplateSpecializationType, then the NNS prefix is NOT included
1996           // in ClsType; hence we wrap ClsType into an ElaboratedType.
1997           // NOTE: in particular, no wrap occurs if ClsType already is an
1998           // Elaborated, DependentName, or DependentTemplateSpecialization.
1999           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2000             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2001           break;
2002         }
2003       } else {
2004         Diag(DeclType.Mem.Scope().getBeginLoc(),
2005              diag::err_illegal_decl_mempointer_in_nonclass)
2006           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2007           << DeclType.Mem.Scope().getRange();
2008         D.setInvalidType(true);
2009       }
2010 
2011       if (!ClsType.isNull())
2012         T = BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2013       if (T.isNull()) {
2014         T = Context.IntTy;
2015         D.setInvalidType(true);
2016       } else if (DeclType.Mem.TypeQuals) {
2017         T = BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2018       }
2019       break;
2020     }
2021 
2022     if (T.isNull()) {
2023       D.setInvalidType(true);
2024       T = Context.IntTy;
2025     }
2026 
2027     // See if there are any attributes on this declarator chunk.
2028     if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2029       processTypeAttrs(state, T, false, attrs);
2030   }
2031 
2032   if (getLangOptions().CPlusPlus && T->isFunctionType()) {
2033     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
2034     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
2035 
2036     // C++ 8.3.5p4:
2037     //   A cv-qualifier-seq shall only be part of the function type
2038     //   for a nonstatic member function, the function type to which a pointer
2039     //   to member refers, or the top-level function type of a function typedef
2040     //   declaration.
2041     //
2042     // Core issue 547 also allows cv-qualifiers on function types that are
2043     // top-level template type arguments.
2044     bool FreeFunction;
2045     if (!D.getCXXScopeSpec().isSet()) {
2046       FreeFunction = (D.getContext() != Declarator::MemberContext ||
2047                       D.getDeclSpec().isFriendSpecified());
2048     } else {
2049       DeclContext *DC = computeDeclContext(D.getCXXScopeSpec());
2050       FreeFunction = (DC && !DC->isRecord());
2051     }
2052 
2053     // C++0x [dcl.fct]p6:
2054     //   A ref-qualifier shall only be part of the function type for a
2055     //   non-static member function, the function type to which a pointer to
2056     //   member refers, or the top-level function type of a function typedef
2057     //   declaration.
2058     if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
2059         !(D.getContext() == Declarator::TemplateTypeArgContext &&
2060           !D.isFunctionDeclarator()) &&
2061         D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2062         (FreeFunction ||
2063          D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
2064       if (D.getContext() == Declarator::TemplateTypeArgContext) {
2065         // Accept qualified function types as template type arguments as a GNU
2066         // extension. This is also the subject of C++ core issue 547.
2067         std::string Quals;
2068         if (FnTy->getTypeQuals() != 0)
2069           Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2070 
2071         switch (FnTy->getRefQualifier()) {
2072         case RQ_None:
2073           break;
2074 
2075         case RQ_LValue:
2076           if (!Quals.empty())
2077             Quals += ' ';
2078           Quals += '&';
2079           break;
2080 
2081         case RQ_RValue:
2082           if (!Quals.empty())
2083             Quals += ' ';
2084           Quals += "&&";
2085           break;
2086         }
2087 
2088         Diag(D.getIdentifierLoc(),
2089              diag::ext_qualified_function_type_template_arg)
2090           << Quals;
2091       } else {
2092         if (FnTy->getTypeQuals() != 0) {
2093           if (D.isFunctionDeclarator())
2094             Diag(D.getIdentifierLoc(),
2095                  diag::err_invalid_qualified_function_type);
2096           else
2097             Diag(D.getIdentifierLoc(),
2098                  diag::err_invalid_qualified_typedef_function_type_use)
2099               << FreeFunction;
2100         }
2101 
2102         if (FnTy->getRefQualifier()) {
2103           if (D.isFunctionDeclarator()) {
2104             SourceLocation Loc = D.getIdentifierLoc();
2105             for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2106               const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2107               if (Chunk.Kind == DeclaratorChunk::Function &&
2108                   Chunk.Fun.hasRefQualifier()) {
2109                 Loc = Chunk.Fun.getRefQualifierLoc();
2110                 break;
2111               }
2112             }
2113 
2114             Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
2115               << (FnTy->getRefQualifier() == RQ_LValue)
2116               << FixItHint::CreateRemoval(Loc);
2117           } else {
2118             Diag(D.getIdentifierLoc(),
2119                  diag::err_invalid_ref_qualifier_typedef_function_type_use)
2120               << FreeFunction
2121               << (FnTy->getRefQualifier() == RQ_LValue);
2122           }
2123         }
2124 
2125         // Strip the cv-qualifiers and ref-qualifiers from the type.
2126         FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2127         EPI.TypeQuals = 0;
2128         EPI.RefQualifier = RQ_None;
2129 
2130         T = Context.getFunctionType(FnTy->getResultType(),
2131                                     FnTy->arg_type_begin(),
2132                                     FnTy->getNumArgs(), EPI);
2133       }
2134     }
2135   }
2136 
2137   // Apply any undistributed attributes from the declarator.
2138   if (!T.isNull())
2139     if (AttributeList *attrs = D.getAttributes())
2140       processTypeAttrs(state, T, false, attrs);
2141 
2142   // Diagnose any ignored type attributes.
2143   if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2144 
2145   // C++0x [dcl.constexpr]p9:
2146   //  A constexpr specifier used in an object declaration declares the object
2147   //  as const.
2148   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
2149     T.addConst();
2150   }
2151 
2152   // If there was an ellipsis in the declarator, the declaration declares a
2153   // parameter pack whose type may be a pack expansion type.
2154   if (D.hasEllipsis() && !T.isNull()) {
2155     // C++0x [dcl.fct]p13:
2156     //   A declarator-id or abstract-declarator containing an ellipsis shall
2157     //   only be used in a parameter-declaration. Such a parameter-declaration
2158     //   is a parameter pack (14.5.3). [...]
2159     switch (D.getContext()) {
2160     case Declarator::PrototypeContext:
2161       // C++0x [dcl.fct]p13:
2162       //   [...] When it is part of a parameter-declaration-clause, the
2163       //   parameter pack is a function parameter pack (14.5.3). The type T
2164       //   of the declarator-id of the function parameter pack shall contain
2165       //   a template parameter pack; each template parameter pack in T is
2166       //   expanded by the function parameter pack.
2167       //
2168       // We represent function parameter packs as function parameters whose
2169       // type is a pack expansion.
2170       if (!T->containsUnexpandedParameterPack()) {
2171         Diag(D.getEllipsisLoc(),
2172              diag::err_function_parameter_pack_without_parameter_packs)
2173           << T <<  D.getSourceRange();
2174         D.setEllipsisLoc(SourceLocation());
2175       } else {
2176         T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2177       }
2178       break;
2179 
2180     case Declarator::TemplateParamContext:
2181       // C++0x [temp.param]p15:
2182       //   If a template-parameter is a [...] is a parameter-declaration that
2183       //   declares a parameter pack (8.3.5), then the template-parameter is a
2184       //   template parameter pack (14.5.3).
2185       //
2186       // Note: core issue 778 clarifies that, if there are any unexpanded
2187       // parameter packs in the type of the non-type template parameter, then
2188       // it expands those parameter packs.
2189       if (T->containsUnexpandedParameterPack())
2190         T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2191       else if (!getLangOptions().CPlusPlus0x)
2192         Diag(D.getEllipsisLoc(), diag::ext_variadic_templates);
2193       break;
2194 
2195     case Declarator::FileContext:
2196     case Declarator::KNRTypeListContext:
2197     case Declarator::ObjCPrototypeContext: // FIXME: special diagnostic here?
2198     case Declarator::TypeNameContext:
2199     case Declarator::MemberContext:
2200     case Declarator::BlockContext:
2201     case Declarator::ForContext:
2202     case Declarator::ConditionContext:
2203     case Declarator::CXXCatchContext:
2204     case Declarator::BlockLiteralContext:
2205     case Declarator::TemplateTypeArgContext:
2206       // FIXME: We may want to allow parameter packs in block-literal contexts
2207       // in the future.
2208       Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2209       D.setEllipsisLoc(SourceLocation());
2210       break;
2211     }
2212   }
2213 
2214   if (T.isNull())
2215     return Context.getNullTypeSourceInfo();
2216   else if (D.isInvalidType())
2217     return Context.getTrivialTypeSourceInfo(T);
2218   return GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo);
2219 }
2220 
2221 /// Map an AttributedType::Kind to an AttributeList::Kind.
2222 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2223   switch (kind) {
2224   case AttributedType::attr_address_space:
2225     return AttributeList::AT_address_space;
2226   case AttributedType::attr_regparm:
2227     return AttributeList::AT_regparm;
2228   case AttributedType::attr_vector_size:
2229     return AttributeList::AT_vector_size;
2230   case AttributedType::attr_neon_vector_type:
2231     return AttributeList::AT_neon_vector_type;
2232   case AttributedType::attr_neon_polyvector_type:
2233     return AttributeList::AT_neon_polyvector_type;
2234   case AttributedType::attr_objc_gc:
2235     return AttributeList::AT_objc_gc;
2236   case AttributedType::attr_noreturn:
2237     return AttributeList::AT_noreturn;
2238   case AttributedType::attr_cdecl:
2239     return AttributeList::AT_cdecl;
2240   case AttributedType::attr_fastcall:
2241     return AttributeList::AT_fastcall;
2242   case AttributedType::attr_stdcall:
2243     return AttributeList::AT_stdcall;
2244   case AttributedType::attr_thiscall:
2245     return AttributeList::AT_thiscall;
2246   case AttributedType::attr_pascal:
2247     return AttributeList::AT_pascal;
2248   case AttributedType::attr_pcs:
2249     return AttributeList::AT_pcs;
2250   }
2251   llvm_unreachable("unexpected attribute kind!");
2252   return AttributeList::Kind();
2253 }
2254 
2255 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2256                                   const AttributeList *attrs) {
2257   AttributedType::Kind kind = TL.getAttrKind();
2258 
2259   assert(attrs && "no type attributes in the expected location!");
2260   AttributeList::Kind parsedKind = getAttrListKind(kind);
2261   while (attrs->getKind() != parsedKind) {
2262     attrs = attrs->getNext();
2263     assert(attrs && "no matching attribute in expected location!");
2264   }
2265 
2266   TL.setAttrNameLoc(attrs->getLoc());
2267   if (TL.hasAttrExprOperand())
2268     TL.setAttrExprOperand(attrs->getArg(0));
2269   else if (TL.hasAttrEnumOperand())
2270     TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2271 
2272   // FIXME: preserve this information to here.
2273   if (TL.hasAttrOperand())
2274     TL.setAttrOperandParensRange(SourceRange());
2275 }
2276 
2277 namespace {
2278   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
2279     ASTContext &Context;
2280     const DeclSpec &DS;
2281 
2282   public:
2283     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2284       : Context(Context), DS(DS) {}
2285 
2286     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2287       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2288       Visit(TL.getModifiedLoc());
2289     }
2290     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2291       Visit(TL.getUnqualifiedLoc());
2292     }
2293     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2294       TL.setNameLoc(DS.getTypeSpecTypeLoc());
2295     }
2296     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2297       TL.setNameLoc(DS.getTypeSpecTypeLoc());
2298     }
2299     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2300       // Handle the base type, which might not have been written explicitly.
2301       if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2302         TL.setHasBaseTypeAsWritten(false);
2303         TL.getBaseLoc().initialize(Context, SourceLocation());
2304       } else {
2305         TL.setHasBaseTypeAsWritten(true);
2306         Visit(TL.getBaseLoc());
2307       }
2308 
2309       // Protocol qualifiers.
2310       if (DS.getProtocolQualifiers()) {
2311         assert(TL.getNumProtocols() > 0);
2312         assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2313         TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2314         TL.setRAngleLoc(DS.getSourceRange().getEnd());
2315         for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2316           TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2317       } else {
2318         assert(TL.getNumProtocols() == 0);
2319         TL.setLAngleLoc(SourceLocation());
2320         TL.setRAngleLoc(SourceLocation());
2321       }
2322     }
2323     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2324       TL.setStarLoc(SourceLocation());
2325       Visit(TL.getPointeeLoc());
2326     }
2327     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
2328       TypeSourceInfo *TInfo = 0;
2329       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2330 
2331       // If we got no declarator info from previous Sema routines,
2332       // just fill with the typespec loc.
2333       if (!TInfo) {
2334         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
2335         return;
2336       }
2337 
2338       TypeLoc OldTL = TInfo->getTypeLoc();
2339       if (TInfo->getType()->getAs<ElaboratedType>()) {
2340         ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2341         TemplateSpecializationTypeLoc NamedTL =
2342           cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2343         TL.copy(NamedTL);
2344       }
2345       else
2346         TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
2347     }
2348     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2349       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2350       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2351       TL.setParensRange(DS.getTypeofParensRange());
2352     }
2353     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2354       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2355       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2356       TL.setParensRange(DS.getTypeofParensRange());
2357       assert(DS.getRepAsType());
2358       TypeSourceInfo *TInfo = 0;
2359       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2360       TL.setUnderlyingTInfo(TInfo);
2361     }
2362     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2363       // By default, use the source location of the type specifier.
2364       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2365       if (TL.needsExtraLocalData()) {
2366         // Set info for the written builtin specifiers.
2367         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2368         // Try to have a meaningful source location.
2369         if (TL.getWrittenSignSpec() != TSS_unspecified)
2370           // Sign spec loc overrides the others (e.g., 'unsigned long').
2371           TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2372         else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2373           // Width spec loc overrides type spec loc (e.g., 'short int').
2374           TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2375       }
2376     }
2377     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2378       ElaboratedTypeKeyword Keyword
2379         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2380       if (DS.getTypeSpecType() == TST_typename) {
2381         TypeSourceInfo *TInfo = 0;
2382         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2383         if (TInfo) {
2384           TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2385           return;
2386         }
2387       }
2388       TL.setKeywordLoc(Keyword != ETK_None
2389                        ? DS.getTypeSpecTypeLoc()
2390                        : SourceLocation());
2391       const CXXScopeSpec& SS = DS.getTypeSpecScope();
2392       TL.setQualifierLoc(SS.getWithLocInContext(Context));
2393       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2394     }
2395     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2396       ElaboratedTypeKeyword Keyword
2397         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2398       if (DS.getTypeSpecType() == TST_typename) {
2399         TypeSourceInfo *TInfo = 0;
2400         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2401         if (TInfo) {
2402           TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2403           return;
2404         }
2405       }
2406       TL.setKeywordLoc(Keyword != ETK_None
2407                        ? DS.getTypeSpecTypeLoc()
2408                        : SourceLocation());
2409       const CXXScopeSpec& SS = DS.getTypeSpecScope();
2410       TL.setQualifierLoc(SS.getWithLocInContext(Context));
2411       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2412     }
2413     void VisitDependentTemplateSpecializationTypeLoc(
2414                                  DependentTemplateSpecializationTypeLoc TL) {
2415       ElaboratedTypeKeyword Keyword
2416         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2417       if (Keyword == ETK_Typename) {
2418         TypeSourceInfo *TInfo = 0;
2419         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2420         if (TInfo) {
2421           TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2422                     TInfo->getTypeLoc()));
2423           return;
2424         }
2425       }
2426       TL.initializeLocal(Context, SourceLocation());
2427       TL.setKeywordLoc(Keyword != ETK_None
2428                        ? DS.getTypeSpecTypeLoc()
2429                        : SourceLocation());
2430       const CXXScopeSpec& SS = DS.getTypeSpecScope();
2431       TL.setQualifierLoc(SS.getWithLocInContext(Context));
2432       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2433     }
2434     void VisitTagTypeLoc(TagTypeLoc TL) {
2435       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2436     }
2437 
2438     void VisitTypeLoc(TypeLoc TL) {
2439       // FIXME: add other typespec types and change this to an assert.
2440       TL.initialize(Context, DS.getTypeSpecTypeLoc());
2441     }
2442   };
2443 
2444   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
2445     ASTContext &Context;
2446     const DeclaratorChunk &Chunk;
2447 
2448   public:
2449     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2450       : Context(Context), Chunk(Chunk) {}
2451 
2452     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2453       llvm_unreachable("qualified type locs not expected here!");
2454     }
2455 
2456     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2457       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2458       TL.setCaretLoc(Chunk.Loc);
2459     }
2460     void VisitPointerTypeLoc(PointerTypeLoc TL) {
2461       assert(Chunk.Kind == DeclaratorChunk::Pointer);
2462       TL.setStarLoc(Chunk.Loc);
2463     }
2464     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2465       assert(Chunk.Kind == DeclaratorChunk::Pointer);
2466       TL.setStarLoc(Chunk.Loc);
2467     }
2468     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2469       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
2470       const CXXScopeSpec& SS = Chunk.Mem.Scope();
2471       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
2472 
2473       const Type* ClsTy = TL.getClass();
2474       QualType ClsQT = QualType(ClsTy, 0);
2475       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
2476       // Now copy source location info into the type loc component.
2477       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
2478       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
2479       case NestedNameSpecifier::Identifier:
2480         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
2481         {
2482           DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
2483           DNTLoc.setKeywordLoc(SourceLocation());
2484           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
2485           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
2486         }
2487         break;
2488 
2489       case NestedNameSpecifier::TypeSpec:
2490       case NestedNameSpecifier::TypeSpecWithTemplate:
2491         if (isa<ElaboratedType>(ClsTy)) {
2492           ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
2493           ETLoc.setKeywordLoc(SourceLocation());
2494           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
2495           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
2496           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
2497         } else {
2498           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
2499         }
2500         break;
2501 
2502       case NestedNameSpecifier::Namespace:
2503       case NestedNameSpecifier::NamespaceAlias:
2504       case NestedNameSpecifier::Global:
2505         llvm_unreachable("Nested-name-specifier must name a type");
2506         break;
2507       }
2508 
2509       // Finally fill in MemberPointerLocInfo fields.
2510       TL.setStarLoc(Chunk.Loc);
2511       TL.setClassTInfo(ClsTInfo);
2512     }
2513     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2514       assert(Chunk.Kind == DeclaratorChunk::Reference);
2515       // 'Amp' is misleading: this might have been originally
2516       /// spelled with AmpAmp.
2517       TL.setAmpLoc(Chunk.Loc);
2518     }
2519     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2520       assert(Chunk.Kind == DeclaratorChunk::Reference);
2521       assert(!Chunk.Ref.LValueRef);
2522       TL.setAmpAmpLoc(Chunk.Loc);
2523     }
2524     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
2525       assert(Chunk.Kind == DeclaratorChunk::Array);
2526       TL.setLBracketLoc(Chunk.Loc);
2527       TL.setRBracketLoc(Chunk.EndLoc);
2528       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
2529     }
2530     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2531       assert(Chunk.Kind == DeclaratorChunk::Function);
2532       TL.setLocalRangeBegin(Chunk.Loc);
2533       TL.setLocalRangeEnd(Chunk.EndLoc);
2534       TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
2535 
2536       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
2537       for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
2538         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2539         TL.setArg(tpi++, Param);
2540       }
2541       // FIXME: exception specs
2542     }
2543     void VisitParenTypeLoc(ParenTypeLoc TL) {
2544       assert(Chunk.Kind == DeclaratorChunk::Paren);
2545       TL.setLParenLoc(Chunk.Loc);
2546       TL.setRParenLoc(Chunk.EndLoc);
2547     }
2548 
2549     void VisitTypeLoc(TypeLoc TL) {
2550       llvm_unreachable("unsupported TypeLoc kind in declarator!");
2551     }
2552   };
2553 }
2554 
2555 /// \brief Create and instantiate a TypeSourceInfo with type source information.
2556 ///
2557 /// \param T QualType referring to the type as written in source code.
2558 ///
2559 /// \param ReturnTypeInfo For declarators whose return type does not show
2560 /// up in the normal place in the declaration specifiers (such as a C++
2561 /// conversion function), this pointer will refer to a type source information
2562 /// for that return type.
2563 TypeSourceInfo *
2564 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
2565                                      TypeSourceInfo *ReturnTypeInfo) {
2566   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
2567   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
2568 
2569   // Handle parameter packs whose type is a pack expansion.
2570   if (isa<PackExpansionType>(T)) {
2571     cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
2572     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2573   }
2574 
2575   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2576     while (isa<AttributedTypeLoc>(CurrTL)) {
2577       AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
2578       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
2579       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
2580     }
2581 
2582     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
2583     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2584   }
2585 
2586   // If we have different source information for the return type, use
2587   // that.  This really only applies to C++ conversion functions.
2588   if (ReturnTypeInfo) {
2589     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
2590     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
2591     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
2592   } else {
2593     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
2594   }
2595 
2596   return TInfo;
2597 }
2598 
2599 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
2600 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
2601   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
2602   // and Sema during declaration parsing. Try deallocating/caching them when
2603   // it's appropriate, instead of allocating them and keeping them around.
2604   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
2605                                                        TypeAlignment);
2606   new (LocT) LocInfoType(T, TInfo);
2607   assert(LocT->getTypeClass() != T->getTypeClass() &&
2608          "LocInfoType's TypeClass conflicts with an existing Type class");
2609   return ParsedType::make(QualType(LocT, 0));
2610 }
2611 
2612 void LocInfoType::getAsStringInternal(std::string &Str,
2613                                       const PrintingPolicy &Policy) const {
2614   assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
2615          " was used directly instead of getting the QualType through"
2616          " GetTypeFromParser");
2617 }
2618 
2619 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
2620   // C99 6.7.6: Type names have no identifier.  This is already validated by
2621   // the parser.
2622   assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
2623 
2624   TagDecl *OwnedTag = 0;
2625   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
2626   QualType T = TInfo->getType();
2627   if (D.isInvalidType())
2628     return true;
2629 
2630   if (getLangOptions().CPlusPlus) {
2631     // Check that there are no default arguments (C++ only).
2632     CheckExtraCXXDefaultArguments(D);
2633 
2634     // C++0x [dcl.type]p3:
2635     //   A type-specifier-seq shall not define a class or enumeration
2636     //   unless it appears in the type-id of an alias-declaration
2637     //   (7.1.3).
2638     if (OwnedTag && OwnedTag->isDefinition())
2639       Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
2640         << Context.getTypeDeclType(OwnedTag);
2641   }
2642 
2643   return CreateParsedType(T, TInfo);
2644 }
2645 
2646 
2647 
2648 //===----------------------------------------------------------------------===//
2649 // Type Attribute Processing
2650 //===----------------------------------------------------------------------===//
2651 
2652 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
2653 /// specified type.  The attribute contains 1 argument, the id of the address
2654 /// space for the type.
2655 static void HandleAddressSpaceTypeAttribute(QualType &Type,
2656                                             const AttributeList &Attr, Sema &S){
2657 
2658   // If this type is already address space qualified, reject it.
2659   // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
2660   // for two or more different address spaces."
2661   if (Type.getAddressSpace()) {
2662     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
2663     Attr.setInvalid();
2664     return;
2665   }
2666 
2667   // Check the attribute arguments.
2668   if (Attr.getNumArgs() != 1) {
2669     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2670     Attr.setInvalid();
2671     return;
2672   }
2673   Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
2674   llvm::APSInt addrSpace(32);
2675   if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
2676       !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
2677     S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
2678       << ASArgExpr->getSourceRange();
2679     Attr.setInvalid();
2680     return;
2681   }
2682 
2683   // Bounds checking.
2684   if (addrSpace.isSigned()) {
2685     if (addrSpace.isNegative()) {
2686       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
2687         << ASArgExpr->getSourceRange();
2688       Attr.setInvalid();
2689       return;
2690     }
2691     addrSpace.setIsSigned(false);
2692   }
2693   llvm::APSInt max(addrSpace.getBitWidth());
2694   max = Qualifiers::MaxAddressSpace;
2695   if (addrSpace > max) {
2696     S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
2697       << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
2698     Attr.setInvalid();
2699     return;
2700   }
2701 
2702   unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
2703   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
2704 }
2705 
2706 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
2707 /// attribute on the specified type.  Returns true to indicate that
2708 /// the attribute was handled, false to indicate that the type does
2709 /// not permit the attribute.
2710 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
2711                                  AttributeList &attr,
2712                                  QualType &type) {
2713   Sema &S = state.getSema();
2714 
2715   // Delay if this isn't some kind of pointer.
2716   if (!type->isPointerType() &&
2717       !type->isObjCObjectPointerType() &&
2718       !type->isBlockPointerType())
2719     return false;
2720 
2721   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
2722     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
2723     attr.setInvalid();
2724     return true;
2725   }
2726 
2727   // Check the attribute arguments.
2728   if (!attr.getParameterName()) {
2729     S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
2730       << "objc_gc" << 1;
2731     attr.setInvalid();
2732     return true;
2733   }
2734   Qualifiers::GC GCAttr;
2735   if (attr.getNumArgs() != 0) {
2736     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2737     attr.setInvalid();
2738     return true;
2739   }
2740   if (attr.getParameterName()->isStr("weak"))
2741     GCAttr = Qualifiers::Weak;
2742   else if (attr.getParameterName()->isStr("strong"))
2743     GCAttr = Qualifiers::Strong;
2744   else {
2745     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
2746       << "objc_gc" << attr.getParameterName();
2747     attr.setInvalid();
2748     return true;
2749   }
2750 
2751   QualType origType = type;
2752   type = S.Context.getObjCGCQualType(origType, GCAttr);
2753 
2754   // Make an attributed type to preserve the source information.
2755   if (attr.getLoc().isValid())
2756     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
2757                                        origType, type);
2758 
2759   return true;
2760 }
2761 
2762 namespace {
2763   /// A helper class to unwrap a type down to a function for the
2764   /// purposes of applying attributes there.
2765   ///
2766   /// Use:
2767   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
2768   ///   if (unwrapped.isFunctionType()) {
2769   ///     const FunctionType *fn = unwrapped.get();
2770   ///     // change fn somehow
2771   ///     T = unwrapped.wrap(fn);
2772   ///   }
2773   struct FunctionTypeUnwrapper {
2774     enum WrapKind {
2775       Desugar,
2776       Parens,
2777       Pointer,
2778       BlockPointer,
2779       Reference,
2780       MemberPointer
2781     };
2782 
2783     QualType Original;
2784     const FunctionType *Fn;
2785     llvm::SmallVector<unsigned char /*WrapKind*/, 8> Stack;
2786 
2787     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
2788       while (true) {
2789         const Type *Ty = T.getTypePtr();
2790         if (isa<FunctionType>(Ty)) {
2791           Fn = cast<FunctionType>(Ty);
2792           return;
2793         } else if (isa<ParenType>(Ty)) {
2794           T = cast<ParenType>(Ty)->getInnerType();
2795           Stack.push_back(Parens);
2796         } else if (isa<PointerType>(Ty)) {
2797           T = cast<PointerType>(Ty)->getPointeeType();
2798           Stack.push_back(Pointer);
2799         } else if (isa<BlockPointerType>(Ty)) {
2800           T = cast<BlockPointerType>(Ty)->getPointeeType();
2801           Stack.push_back(BlockPointer);
2802         } else if (isa<MemberPointerType>(Ty)) {
2803           T = cast<MemberPointerType>(Ty)->getPointeeType();
2804           Stack.push_back(MemberPointer);
2805         } else if (isa<ReferenceType>(Ty)) {
2806           T = cast<ReferenceType>(Ty)->getPointeeType();
2807           Stack.push_back(Reference);
2808         } else {
2809           const Type *DTy = Ty->getUnqualifiedDesugaredType();
2810           if (Ty == DTy) {
2811             Fn = 0;
2812             return;
2813           }
2814 
2815           T = QualType(DTy, 0);
2816           Stack.push_back(Desugar);
2817         }
2818       }
2819     }
2820 
2821     bool isFunctionType() const { return (Fn != 0); }
2822     const FunctionType *get() const { return Fn; }
2823 
2824     QualType wrap(Sema &S, const FunctionType *New) {
2825       // If T wasn't modified from the unwrapped type, do nothing.
2826       if (New == get()) return Original;
2827 
2828       Fn = New;
2829       return wrap(S.Context, Original, 0);
2830     }
2831 
2832   private:
2833     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
2834       if (I == Stack.size())
2835         return C.getQualifiedType(Fn, Old.getQualifiers());
2836 
2837       // Build up the inner type, applying the qualifiers from the old
2838       // type to the new type.
2839       SplitQualType SplitOld = Old.split();
2840 
2841       // As a special case, tail-recurse if there are no qualifiers.
2842       if (SplitOld.second.empty())
2843         return wrap(C, SplitOld.first, I);
2844       return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
2845     }
2846 
2847     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
2848       if (I == Stack.size()) return QualType(Fn, 0);
2849 
2850       switch (static_cast<WrapKind>(Stack[I++])) {
2851       case Desugar:
2852         // This is the point at which we potentially lose source
2853         // information.
2854         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
2855 
2856       case Parens: {
2857         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
2858         return C.getParenType(New);
2859       }
2860 
2861       case Pointer: {
2862         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
2863         return C.getPointerType(New);
2864       }
2865 
2866       case BlockPointer: {
2867         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
2868         return C.getBlockPointerType(New);
2869       }
2870 
2871       case MemberPointer: {
2872         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
2873         QualType New = wrap(C, OldMPT->getPointeeType(), I);
2874         return C.getMemberPointerType(New, OldMPT->getClass());
2875       }
2876 
2877       case Reference: {
2878         const ReferenceType *OldRef = cast<ReferenceType>(Old);
2879         QualType New = wrap(C, OldRef->getPointeeType(), I);
2880         if (isa<LValueReferenceType>(OldRef))
2881           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
2882         else
2883           return C.getRValueReferenceType(New);
2884       }
2885       }
2886 
2887       llvm_unreachable("unknown wrapping kind");
2888       return QualType();
2889     }
2890   };
2891 }
2892 
2893 /// Process an individual function attribute.  Returns true to
2894 /// indicate that the attribute was handled, false if it wasn't.
2895 static bool handleFunctionTypeAttr(TypeProcessingState &state,
2896                                    AttributeList &attr,
2897                                    QualType &type) {
2898   Sema &S = state.getSema();
2899 
2900   FunctionTypeUnwrapper unwrapped(S, type);
2901 
2902   if (attr.getKind() == AttributeList::AT_noreturn) {
2903     if (S.CheckNoReturnAttr(attr))
2904       return true;
2905 
2906     // Delay if this is not a function type.
2907     if (!unwrapped.isFunctionType())
2908       return false;
2909 
2910     // Otherwise we can process right away.
2911     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
2912     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2913     return true;
2914   }
2915 
2916   if (attr.getKind() == AttributeList::AT_regparm) {
2917     unsigned value;
2918     if (S.CheckRegparmAttr(attr, value))
2919       return true;
2920 
2921     // Delay if this is not a function type.
2922     if (!unwrapped.isFunctionType())
2923       return false;
2924 
2925     // Diagnose regparm with fastcall.
2926     const FunctionType *fn = unwrapped.get();
2927     CallingConv CC = fn->getCallConv();
2928     if (CC == CC_X86FastCall) {
2929       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
2930         << FunctionType::getNameForCallConv(CC)
2931         << "regparm";
2932       attr.setInvalid();
2933       return true;
2934     }
2935 
2936     FunctionType::ExtInfo EI =
2937       unwrapped.get()->getExtInfo().withRegParm(value);
2938     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2939     return true;
2940   }
2941 
2942   // Otherwise, a calling convention.
2943   CallingConv CC;
2944   if (S.CheckCallingConvAttr(attr, CC))
2945     return true;
2946 
2947   // Delay if the type didn't work out to a function.
2948   if (!unwrapped.isFunctionType()) return false;
2949 
2950   const FunctionType *fn = unwrapped.get();
2951   CallingConv CCOld = fn->getCallConv();
2952   if (S.Context.getCanonicalCallConv(CC) ==
2953       S.Context.getCanonicalCallConv(CCOld)) {
2954     FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
2955     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2956     return true;
2957   }
2958 
2959   if (CCOld != CC_Default) {
2960     // Should we diagnose reapplications of the same convention?
2961     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
2962       << FunctionType::getNameForCallConv(CC)
2963       << FunctionType::getNameForCallConv(CCOld);
2964     attr.setInvalid();
2965     return true;
2966   }
2967 
2968   // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
2969   if (CC == CC_X86FastCall) {
2970     if (isa<FunctionNoProtoType>(fn)) {
2971       S.Diag(attr.getLoc(), diag::err_cconv_knr)
2972         << FunctionType::getNameForCallConv(CC);
2973       attr.setInvalid();
2974       return true;
2975     }
2976 
2977     const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
2978     if (FnP->isVariadic()) {
2979       S.Diag(attr.getLoc(), diag::err_cconv_varargs)
2980         << FunctionType::getNameForCallConv(CC);
2981       attr.setInvalid();
2982       return true;
2983     }
2984 
2985     // Also diagnose fastcall with regparm.
2986     if (fn->getHasRegParm()) {
2987       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
2988         << "regparm"
2989         << FunctionType::getNameForCallConv(CC);
2990       attr.setInvalid();
2991       return true;
2992     }
2993   }
2994 
2995   FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
2996   type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2997   return true;
2998 }
2999 
3000 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3001 static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3002                                              const AttributeList &Attr,
3003                                              Sema &S) {
3004   // Check the attribute arguments.
3005   if (Attr.getNumArgs() != 1) {
3006     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3007     Attr.setInvalid();
3008     return;
3009   }
3010   Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3011   llvm::APSInt arg(32);
3012   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3013       !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3014     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3015       << "opencl_image_access" << sizeExpr->getSourceRange();
3016     Attr.setInvalid();
3017     return;
3018   }
3019   unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3020   switch (iarg) {
3021   case CLIA_read_only:
3022   case CLIA_write_only:
3023   case CLIA_read_write:
3024     // Implemented in a separate patch
3025     break;
3026   default:
3027     // Implemented in a separate patch
3028     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3029       << sizeExpr->getSourceRange();
3030     Attr.setInvalid();
3031     break;
3032   }
3033 }
3034 
3035 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
3036 /// and float scalars, although arrays, pointers, and function return values are
3037 /// allowed in conjunction with this construct. Aggregates with this attribute
3038 /// are invalid, even if they are of the same size as a corresponding scalar.
3039 /// The raw attribute should contain precisely 1 argument, the vector size for
3040 /// the variable, measured in bytes. If curType and rawAttr are well formed,
3041 /// this routine will return a new vector type.
3042 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3043                                  Sema &S) {
3044   // Check the attribute arguments.
3045   if (Attr.getNumArgs() != 1) {
3046     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3047     Attr.setInvalid();
3048     return;
3049   }
3050   Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3051   llvm::APSInt vecSize(32);
3052   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3053       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
3054     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3055       << "vector_size" << sizeExpr->getSourceRange();
3056     Attr.setInvalid();
3057     return;
3058   }
3059   // the base type must be integer or float, and can't already be a vector.
3060   if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
3061     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
3062     Attr.setInvalid();
3063     return;
3064   }
3065   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3066   // vecSize is specified in bytes - convert to bits.
3067   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3068 
3069   // the vector size needs to be an integral multiple of the type size.
3070   if (vectorSize % typeSize) {
3071     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3072       << sizeExpr->getSourceRange();
3073     Attr.setInvalid();
3074     return;
3075   }
3076   if (vectorSize == 0) {
3077     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3078       << sizeExpr->getSourceRange();
3079     Attr.setInvalid();
3080     return;
3081   }
3082 
3083   // Success! Instantiate the vector type, the number of elements is > 0, and
3084   // not required to be a power of 2, unlike GCC.
3085   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
3086                                     VectorType::GenericVector);
3087 }
3088 
3089 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3090 /// "neon_polyvector_type" attributes are used to create vector types that
3091 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
3092 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
3093 /// the argument to these Neon attributes is the number of vector elements,
3094 /// not the vector size in bytes.  The vector width and element type must
3095 /// match one of the standard Neon vector types.
3096 static void HandleNeonVectorTypeAttr(QualType& CurType,
3097                                      const AttributeList &Attr, Sema &S,
3098                                      VectorType::VectorKind VecKind,
3099                                      const char *AttrName) {
3100   // Check the attribute arguments.
3101   if (Attr.getNumArgs() != 1) {
3102     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3103     Attr.setInvalid();
3104     return;
3105   }
3106   // The number of elements must be an ICE.
3107   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3108   llvm::APSInt numEltsInt(32);
3109   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3110       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3111     S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3112       << AttrName << numEltsExpr->getSourceRange();
3113     Attr.setInvalid();
3114     return;
3115   }
3116   // Only certain element types are supported for Neon vectors.
3117   const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3118   if (!BTy ||
3119       (VecKind == VectorType::NeonPolyVector &&
3120        BTy->getKind() != BuiltinType::SChar &&
3121        BTy->getKind() != BuiltinType::Short) ||
3122       (BTy->getKind() != BuiltinType::SChar &&
3123        BTy->getKind() != BuiltinType::UChar &&
3124        BTy->getKind() != BuiltinType::Short &&
3125        BTy->getKind() != BuiltinType::UShort &&
3126        BTy->getKind() != BuiltinType::Int &&
3127        BTy->getKind() != BuiltinType::UInt &&
3128        BTy->getKind() != BuiltinType::LongLong &&
3129        BTy->getKind() != BuiltinType::ULongLong &&
3130        BTy->getKind() != BuiltinType::Float)) {
3131     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3132     Attr.setInvalid();
3133     return;
3134   }
3135   // The total size of the vector must be 64 or 128 bits.
3136   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3137   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3138   unsigned vecSize = typeSize * numElts;
3139   if (vecSize != 64 && vecSize != 128) {
3140     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3141     Attr.setInvalid();
3142     return;
3143   }
3144 
3145   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3146 }
3147 
3148 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3149                              bool isDeclSpec, AttributeList *attrs) {
3150   // Scan through and apply attributes to this type where it makes sense.  Some
3151   // attributes (such as __address_space__, __vector_size__, etc) apply to the
3152   // type, but others can be present in the type specifiers even though they
3153   // apply to the decl.  Here we apply type attributes and ignore the rest.
3154 
3155   AttributeList *next;
3156   do {
3157     AttributeList &attr = *attrs;
3158     next = attr.getNext();
3159 
3160     // Skip attributes that were marked to be invalid.
3161     if (attr.isInvalid())
3162       continue;
3163 
3164     // If this is an attribute we can handle, do so now,
3165     // otherwise, add it to the FnAttrs list for rechaining.
3166     switch (attr.getKind()) {
3167     default: break;
3168 
3169     case AttributeList::AT_address_space:
3170       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
3171       break;
3172     OBJC_POINTER_TYPE_ATTRS_CASELIST:
3173       if (!handleObjCPointerTypeAttr(state, attr, type))
3174         distributeObjCPointerTypeAttr(state, attr, type);
3175       break;
3176     case AttributeList::AT_vector_size:
3177       HandleVectorSizeAttr(type, attr, state.getSema());
3178       break;
3179     case AttributeList::AT_neon_vector_type:
3180       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3181                                VectorType::NeonVector, "neon_vector_type");
3182       break;
3183     case AttributeList::AT_neon_polyvector_type:
3184       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3185                                VectorType::NeonPolyVector,
3186                                "neon_polyvector_type");
3187       break;
3188 
3189     case AttributeList::AT_opencl_image_access:
3190       HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
3191       break;
3192 
3193     FUNCTION_TYPE_ATTRS_CASELIST:
3194       // Never process function type attributes as part of the
3195       // declaration-specifiers.
3196       if (isDeclSpec)
3197         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3198 
3199       // Otherwise, handle the possible delays.
3200       else if (!handleFunctionTypeAttr(state, attr, type))
3201         distributeFunctionTypeAttr(state, attr, type);
3202       break;
3203     }
3204   } while ((attrs = next));
3205 }
3206 
3207 /// @brief Ensure that the type T is a complete type.
3208 ///
3209 /// This routine checks whether the type @p T is complete in any
3210 /// context where a complete type is required. If @p T is a complete
3211 /// type, returns false. If @p T is a class template specialization,
3212 /// this routine then attempts to perform class template
3213 /// instantiation. If instantiation fails, or if @p T is incomplete
3214 /// and cannot be completed, issues the diagnostic @p diag (giving it
3215 /// the type @p T) and returns true.
3216 ///
3217 /// @param Loc  The location in the source that the incomplete type
3218 /// diagnostic should refer to.
3219 ///
3220 /// @param T  The type that this routine is examining for completeness.
3221 ///
3222 /// @param PD The partial diagnostic that will be printed out if T is not a
3223 /// complete type.
3224 ///
3225 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
3226 /// @c false otherwise.
3227 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3228                                const PartialDiagnostic &PD,
3229                                std::pair<SourceLocation,
3230                                          PartialDiagnostic> Note) {
3231   unsigned diag = PD.getDiagID();
3232 
3233   // FIXME: Add this assertion to make sure we always get instantiation points.
3234   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
3235   // FIXME: Add this assertion to help us flush out problems with
3236   // checking for dependent types and type-dependent expressions.
3237   //
3238   //  assert(!T->isDependentType() &&
3239   //         "Can't ask whether a dependent type is complete");
3240 
3241   // If we have a complete type, we're done.
3242   if (!T->isIncompleteType())
3243     return false;
3244 
3245   // If we have a class template specialization or a class member of a
3246   // class template specialization, or an array with known size of such,
3247   // try to instantiate it.
3248   QualType MaybeTemplate = T;
3249   if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
3250     MaybeTemplate = Array->getElementType();
3251   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
3252     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
3253           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
3254       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
3255         return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
3256                                                       TSK_ImplicitInstantiation,
3257                                                       /*Complain=*/diag != 0);
3258     } else if (CXXRecordDecl *Rec
3259                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
3260       if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
3261         MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
3262         assert(MSInfo && "Missing member specialization information?");
3263         // This record was instantiated from a class within a template.
3264         if (MSInfo->getTemplateSpecializationKind()
3265                                                != TSK_ExplicitSpecialization)
3266           return InstantiateClass(Loc, Rec, Pattern,
3267                                   getTemplateInstantiationArgs(Rec),
3268                                   TSK_ImplicitInstantiation,
3269                                   /*Complain=*/diag != 0);
3270       }
3271     }
3272   }
3273 
3274   if (diag == 0)
3275     return true;
3276 
3277   const TagType *Tag = T->getAs<TagType>();
3278 
3279   // Avoid diagnosing invalid decls as incomplete.
3280   if (Tag && Tag->getDecl()->isInvalidDecl())
3281     return true;
3282 
3283   // Give the external AST source a chance to complete the type.
3284   if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
3285     Context.getExternalSource()->CompleteType(Tag->getDecl());
3286     if (!Tag->isIncompleteType())
3287       return false;
3288   }
3289 
3290   // We have an incomplete type. Produce a diagnostic.
3291   Diag(Loc, PD) << T;
3292 
3293   // If we have a note, produce it.
3294   if (!Note.first.isInvalid())
3295     Diag(Note.first, Note.second);
3296 
3297   // If the type was a forward declaration of a class/struct/union
3298   // type, produce a note.
3299   if (Tag && !Tag->getDecl()->isInvalidDecl())
3300     Diag(Tag->getDecl()->getLocation(),
3301          Tag->isBeingDefined() ? diag::note_type_being_defined
3302                                : diag::note_forward_declaration)
3303         << QualType(Tag, 0);
3304 
3305   return true;
3306 }
3307 
3308 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3309                                const PartialDiagnostic &PD) {
3310   return RequireCompleteType(Loc, T, PD,
3311                              std::make_pair(SourceLocation(), PDiag(0)));
3312 }
3313 
3314 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3315                                unsigned DiagID) {
3316   return RequireCompleteType(Loc, T, PDiag(DiagID),
3317                              std::make_pair(SourceLocation(), PDiag(0)));
3318 }
3319 
3320 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
3321 /// and qualified by the nested-name-specifier contained in SS.
3322 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
3323                                  const CXXScopeSpec &SS, QualType T) {
3324   if (T.isNull())
3325     return T;
3326   NestedNameSpecifier *NNS;
3327   if (SS.isValid())
3328     NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3329   else {
3330     if (Keyword == ETK_None)
3331       return T;
3332     NNS = 0;
3333   }
3334   return Context.getElaboratedType(Keyword, NNS, T);
3335 }
3336 
3337 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
3338   ExprResult ER = CheckPlaceholderExpr(E);
3339   if (ER.isInvalid()) return QualType();
3340   E = ER.take();
3341 
3342   if (!E->isTypeDependent()) {
3343     QualType T = E->getType();
3344     if (const TagType *TT = T->getAs<TagType>())
3345       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
3346   }
3347   return Context.getTypeOfExprType(E);
3348 }
3349 
3350 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
3351   ExprResult ER = CheckPlaceholderExpr(E);
3352   if (ER.isInvalid()) return QualType();
3353   E = ER.take();
3354 
3355   return Context.getDecltypeType(E);
3356 }
3357