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