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