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