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