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