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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/AST/TypeLocVisitor.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/DeclSpec.h"
28 #include "clang/Sema/DelayedDiagnostic.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "clang/Sema/SemaInternal.h"
32 #include "clang/Sema/Template.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/StringSwitch.h"
36 #include "llvm/Support/ErrorHandling.h"
37 
38 using namespace clang;
39 
40 enum TypeDiagSelector {
41   TDS_Function,
42   TDS_Pointer,
43   TDS_ObjCObjOrBlock
44 };
45 
46 /// isOmittedBlockReturnType - Return true if this declarator is missing a
47 /// return type because this is a omitted return type on a block literal.
48 static bool isOmittedBlockReturnType(const Declarator &D) {
49   if (D.getContext() != Declarator::BlockLiteralContext ||
50       D.getDeclSpec().hasTypeSpecifier())
51     return false;
52 
53   if (D.getNumTypeObjects() == 0)
54     return true;   // ^{ ... }
55 
56   if (D.getNumTypeObjects() == 1 &&
57       D.getTypeObject(0).Kind == DeclaratorChunk::Function)
58     return true;   // ^(int X, float Y) { ... }
59 
60   return false;
61 }
62 
63 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
64 /// doesn't apply to the given type.
65 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
66                                      QualType type) {
67   TypeDiagSelector WhichType;
68   bool useExpansionLoc = true;
69   switch (attr.getKind()) {
70   case AttributeList::AT_ObjCGC:        WhichType = TDS_Pointer; break;
71   case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
72   default:
73     // Assume everything else was a function attribute.
74     WhichType = TDS_Function;
75     useExpansionLoc = false;
76     break;
77   }
78 
79   SourceLocation loc = attr.getLoc();
80   StringRef name = attr.getName()->getName();
81 
82   // The GC attributes are usually written with macros;  special-case them.
83   IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
84                                           : nullptr;
85   if (useExpansionLoc && loc.isMacroID() && II) {
86     if (II->isStr("strong")) {
87       if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
88     } else if (II->isStr("weak")) {
89       if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
90     }
91   }
92 
93   S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
94     << type;
95 }
96 
97 // objc_gc applies to Objective-C pointers or, otherwise, to the
98 // smallest available pointer type (i.e. 'void*' in 'void**').
99 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
100     case AttributeList::AT_ObjCGC: \
101     case AttributeList::AT_ObjCOwnership
102 
103 // Calling convention attributes.
104 #define CALLING_CONV_ATTRS_CASELIST \
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_SwiftCall: \
111     case AttributeList::AT_VectorCall: \
112     case AttributeList::AT_MSABI: \
113     case AttributeList::AT_SysVABI: \
114     case AttributeList::AT_Pcs: \
115     case AttributeList::AT_IntelOclBicc: \
116     case AttributeList::AT_PreserveMost: \
117     case AttributeList::AT_PreserveAll
118 
119 // Function type attributes.
120 #define FUNCTION_TYPE_ATTRS_CASELIST \
121     case AttributeList::AT_NoReturn: \
122     case AttributeList::AT_Regparm: \
123     CALLING_CONV_ATTRS_CASELIST
124 
125 // Microsoft-specific type qualifiers.
126 #define MS_TYPE_ATTRS_CASELIST  \
127     case AttributeList::AT_Ptr32: \
128     case AttributeList::AT_Ptr64: \
129     case AttributeList::AT_SPtr: \
130     case AttributeList::AT_UPtr
131 
132 // Nullability qualifiers.
133 #define NULLABILITY_TYPE_ATTRS_CASELIST         \
134     case AttributeList::AT_TypeNonNull:         \
135     case AttributeList::AT_TypeNullable:        \
136     case AttributeList::AT_TypeNullUnspecified
137 
138 namespace {
139   /// An object which stores processing state for the entire
140   /// GetTypeForDeclarator process.
141   class TypeProcessingState {
142     Sema &sema;
143 
144     /// The declarator being processed.
145     Declarator &declarator;
146 
147     /// The index of the declarator chunk we're currently processing.
148     /// May be the total number of valid chunks, indicating the
149     /// DeclSpec.
150     unsigned chunkIndex;
151 
152     /// Whether there are non-trivial modifications to the decl spec.
153     bool trivial;
154 
155     /// Whether we saved the attributes in the decl spec.
156     bool hasSavedAttrs;
157 
158     /// The original set of attributes on the DeclSpec.
159     SmallVector<AttributeList*, 2> savedAttrs;
160 
161     /// A list of attributes to diagnose the uselessness of when the
162     /// processing is complete.
163     SmallVector<AttributeList*, 2> ignoredTypeAttrs;
164 
165   public:
166     TypeProcessingState(Sema &sema, Declarator &declarator)
167       : sema(sema), declarator(declarator),
168         chunkIndex(declarator.getNumTypeObjects()),
169         trivial(true), hasSavedAttrs(false) {}
170 
171     Sema &getSema() const {
172       return sema;
173     }
174 
175     Declarator &getDeclarator() const {
176       return declarator;
177     }
178 
179     bool isProcessingDeclSpec() const {
180       return chunkIndex == declarator.getNumTypeObjects();
181     }
182 
183     unsigned getCurrentChunkIndex() const {
184       return chunkIndex;
185     }
186 
187     void setCurrentChunkIndex(unsigned idx) {
188       assert(idx <= declarator.getNumTypeObjects());
189       chunkIndex = idx;
190     }
191 
192     AttributeList *&getCurrentAttrListRef() const {
193       if (isProcessingDeclSpec())
194         return getMutableDeclSpec().getAttributes().getListRef();
195       return declarator.getTypeObject(chunkIndex).getAttrListRef();
196     }
197 
198     /// Save the current set of attributes on the DeclSpec.
199     void saveDeclSpecAttrs() {
200       // Don't try to save them multiple times.
201       if (hasSavedAttrs) return;
202 
203       DeclSpec &spec = getMutableDeclSpec();
204       for (AttributeList *attr = spec.getAttributes().getList(); attr;
205              attr = attr->getNext())
206         savedAttrs.push_back(attr);
207       trivial &= savedAttrs.empty();
208       hasSavedAttrs = true;
209     }
210 
211     /// Record that we had nowhere to put the given type attribute.
212     /// We will diagnose such attributes later.
213     void addIgnoredTypeAttr(AttributeList &attr) {
214       ignoredTypeAttrs.push_back(&attr);
215     }
216 
217     /// Diagnose all the ignored type attributes, given that the
218     /// declarator worked out to the given type.
219     void diagnoseIgnoredTypeAttrs(QualType type) const {
220       for (auto *Attr : ignoredTypeAttrs)
221         diagnoseBadTypeAttribute(getSema(), *Attr, type);
222     }
223 
224     ~TypeProcessingState() {
225       if (trivial) return;
226 
227       restoreDeclSpecAttrs();
228     }
229 
230   private:
231     DeclSpec &getMutableDeclSpec() const {
232       return const_cast<DeclSpec&>(declarator.getDeclSpec());
233     }
234 
235     void restoreDeclSpecAttrs() {
236       assert(hasSavedAttrs);
237 
238       if (savedAttrs.empty()) {
239         getMutableDeclSpec().getAttributes().set(nullptr);
240         return;
241       }
242 
243       getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
244       for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
245         savedAttrs[i]->setNext(savedAttrs[i+1]);
246       savedAttrs.back()->setNext(nullptr);
247     }
248   };
249 } // end anonymous namespace
250 
251 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
252   attr.setNext(head);
253   head = &attr;
254 }
255 
256 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
257   if (head == &attr) {
258     head = attr.getNext();
259     return;
260   }
261 
262   AttributeList *cur = head;
263   while (true) {
264     assert(cur && cur->getNext() && "ran out of attrs?");
265     if (cur->getNext() == &attr) {
266       cur->setNext(attr.getNext());
267       return;
268     }
269     cur = cur->getNext();
270   }
271 }
272 
273 static void moveAttrFromListToList(AttributeList &attr,
274                                    AttributeList *&fromList,
275                                    AttributeList *&toList) {
276   spliceAttrOutOfList(attr, fromList);
277   spliceAttrIntoList(attr, toList);
278 }
279 
280 /// The location of a type attribute.
281 enum TypeAttrLocation {
282   /// The attribute is in the decl-specifier-seq.
283   TAL_DeclSpec,
284   /// The attribute is part of a DeclaratorChunk.
285   TAL_DeclChunk,
286   /// The attribute is immediately after the declaration's name.
287   TAL_DeclName
288 };
289 
290 static void processTypeAttrs(TypeProcessingState &state,
291                              QualType &type, TypeAttrLocation TAL,
292                              AttributeList *attrs);
293 
294 static bool handleFunctionTypeAttr(TypeProcessingState &state,
295                                    AttributeList &attr,
296                                    QualType &type);
297 
298 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
299                                              AttributeList &attr,
300                                              QualType &type);
301 
302 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
303                                  AttributeList &attr, QualType &type);
304 
305 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
306                                        AttributeList &attr, QualType &type);
307 
308 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
309                                       AttributeList &attr, QualType &type) {
310   if (attr.getKind() == AttributeList::AT_ObjCGC)
311     return handleObjCGCTypeAttr(state, attr, type);
312   assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
313   return handleObjCOwnershipTypeAttr(state, attr, type);
314 }
315 
316 /// Given the index of a declarator chunk, check whether that chunk
317 /// directly specifies the return type of a function and, if so, find
318 /// an appropriate place for it.
319 ///
320 /// \param i - a notional index which the search will start
321 ///   immediately inside
322 ///
323 /// \param onlyBlockPointers Whether we should only look into block
324 /// pointer types (vs. all pointer types).
325 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
326                                                 unsigned i,
327                                                 bool onlyBlockPointers) {
328   assert(i <= declarator.getNumTypeObjects());
329 
330   DeclaratorChunk *result = nullptr;
331 
332   // First, look inwards past parens for a function declarator.
333   for (; i != 0; --i) {
334     DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
335     switch (fnChunk.Kind) {
336     case DeclaratorChunk::Paren:
337       continue;
338 
339     // If we find anything except a function, bail out.
340     case DeclaratorChunk::Pointer:
341     case DeclaratorChunk::BlockPointer:
342     case DeclaratorChunk::Array:
343     case DeclaratorChunk::Reference:
344     case DeclaratorChunk::MemberPointer:
345     case DeclaratorChunk::Pipe:
346       return result;
347 
348     // If we do find a function declarator, scan inwards from that,
349     // looking for a (block-)pointer declarator.
350     case DeclaratorChunk::Function:
351       for (--i; i != 0; --i) {
352         DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
353         switch (ptrChunk.Kind) {
354         case DeclaratorChunk::Paren:
355         case DeclaratorChunk::Array:
356         case DeclaratorChunk::Function:
357         case DeclaratorChunk::Reference:
358         case DeclaratorChunk::Pipe:
359           continue;
360 
361         case DeclaratorChunk::MemberPointer:
362         case DeclaratorChunk::Pointer:
363           if (onlyBlockPointers)
364             continue;
365 
366           // fallthrough
367 
368         case DeclaratorChunk::BlockPointer:
369           result = &ptrChunk;
370           goto continue_outer;
371         }
372         llvm_unreachable("bad declarator chunk kind");
373       }
374 
375       // If we run out of declarators doing that, we're done.
376       return result;
377     }
378     llvm_unreachable("bad declarator chunk kind");
379 
380     // Okay, reconsider from our new point.
381   continue_outer: ;
382   }
383 
384   // Ran out of chunks, bail out.
385   return result;
386 }
387 
388 /// Given that an objc_gc attribute was written somewhere on a
389 /// declaration *other* than on the declarator itself (for which, use
390 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
391 /// didn't apply in whatever position it was written in, try to move
392 /// it to a more appropriate position.
393 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
394                                           AttributeList &attr,
395                                           QualType type) {
396   Declarator &declarator = state.getDeclarator();
397 
398   // Move it to the outermost normal or block pointer declarator.
399   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
400     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
401     switch (chunk.Kind) {
402     case DeclaratorChunk::Pointer:
403     case DeclaratorChunk::BlockPointer: {
404       // But don't move an ARC ownership attribute to the return type
405       // of a block.
406       DeclaratorChunk *destChunk = nullptr;
407       if (state.isProcessingDeclSpec() &&
408           attr.getKind() == AttributeList::AT_ObjCOwnership)
409         destChunk = maybeMovePastReturnType(declarator, i - 1,
410                                             /*onlyBlockPointers=*/true);
411       if (!destChunk) destChunk = &chunk;
412 
413       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
414                              destChunk->getAttrListRef());
415       return;
416     }
417 
418     case DeclaratorChunk::Paren:
419     case DeclaratorChunk::Array:
420       continue;
421 
422     // We may be starting at the return type of a block.
423     case DeclaratorChunk::Function:
424       if (state.isProcessingDeclSpec() &&
425           attr.getKind() == AttributeList::AT_ObjCOwnership) {
426         if (DeclaratorChunk *dest = maybeMovePastReturnType(
427                                       declarator, i,
428                                       /*onlyBlockPointers=*/true)) {
429           moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
430                                  dest->getAttrListRef());
431           return;
432         }
433       }
434       goto error;
435 
436     // Don't walk through these.
437     case DeclaratorChunk::Reference:
438     case DeclaratorChunk::MemberPointer:
439     case DeclaratorChunk::Pipe:
440       goto error;
441     }
442   }
443  error:
444 
445   diagnoseBadTypeAttribute(state.getSema(), attr, type);
446 }
447 
448 /// Distribute an objc_gc type attribute that was written on the
449 /// declarator.
450 static void
451 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
452                                             AttributeList &attr,
453                                             QualType &declSpecType) {
454   Declarator &declarator = state.getDeclarator();
455 
456   // objc_gc goes on the innermost pointer to something that's not a
457   // pointer.
458   unsigned innermost = -1U;
459   bool considerDeclSpec = true;
460   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
461     DeclaratorChunk &chunk = declarator.getTypeObject(i);
462     switch (chunk.Kind) {
463     case DeclaratorChunk::Pointer:
464     case DeclaratorChunk::BlockPointer:
465       innermost = i;
466       continue;
467 
468     case DeclaratorChunk::Reference:
469     case DeclaratorChunk::MemberPointer:
470     case DeclaratorChunk::Paren:
471     case DeclaratorChunk::Array:
472     case DeclaratorChunk::Pipe:
473       continue;
474 
475     case DeclaratorChunk::Function:
476       considerDeclSpec = false;
477       goto done;
478     }
479   }
480  done:
481 
482   // That might actually be the decl spec if we weren't blocked by
483   // anything in the declarator.
484   if (considerDeclSpec) {
485     if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
486       // Splice the attribute into the decl spec.  Prevents the
487       // attribute from being applied multiple times and gives
488       // the source-location-filler something to work with.
489       state.saveDeclSpecAttrs();
490       moveAttrFromListToList(attr, declarator.getAttrListRef(),
491                declarator.getMutableDeclSpec().getAttributes().getListRef());
492       return;
493     }
494   }
495 
496   // Otherwise, if we found an appropriate chunk, splice the attribute
497   // into it.
498   if (innermost != -1U) {
499     moveAttrFromListToList(attr, declarator.getAttrListRef(),
500                        declarator.getTypeObject(innermost).getAttrListRef());
501     return;
502   }
503 
504   // Otherwise, diagnose when we're done building the type.
505   spliceAttrOutOfList(attr, declarator.getAttrListRef());
506   state.addIgnoredTypeAttr(attr);
507 }
508 
509 /// A function type attribute was written somewhere in a declaration
510 /// *other* than on the declarator itself or in the decl spec.  Given
511 /// that it didn't apply in whatever position it was written in, try
512 /// to move it to a more appropriate position.
513 static void distributeFunctionTypeAttr(TypeProcessingState &state,
514                                        AttributeList &attr,
515                                        QualType type) {
516   Declarator &declarator = state.getDeclarator();
517 
518   // Try to push the attribute from the return type of a function to
519   // the function itself.
520   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
521     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
522     switch (chunk.Kind) {
523     case DeclaratorChunk::Function:
524       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
525                              chunk.getAttrListRef());
526       return;
527 
528     case DeclaratorChunk::Paren:
529     case DeclaratorChunk::Pointer:
530     case DeclaratorChunk::BlockPointer:
531     case DeclaratorChunk::Array:
532     case DeclaratorChunk::Reference:
533     case DeclaratorChunk::MemberPointer:
534     case DeclaratorChunk::Pipe:
535       continue;
536     }
537   }
538 
539   diagnoseBadTypeAttribute(state.getSema(), attr, type);
540 }
541 
542 /// Try to distribute a function type attribute to the innermost
543 /// function chunk or type.  Returns true if the attribute was
544 /// distributed, false if no location was found.
545 static bool
546 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
547                                       AttributeList &attr,
548                                       AttributeList *&attrList,
549                                       QualType &declSpecType) {
550   Declarator &declarator = state.getDeclarator();
551 
552   // Put it on the innermost function chunk, if there is one.
553   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
554     DeclaratorChunk &chunk = declarator.getTypeObject(i);
555     if (chunk.Kind != DeclaratorChunk::Function) continue;
556 
557     moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
558     return true;
559   }
560 
561   return handleFunctionTypeAttr(state, attr, declSpecType);
562 }
563 
564 /// A function type attribute was written in the decl spec.  Try to
565 /// apply it somewhere.
566 static void
567 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
568                                        AttributeList &attr,
569                                        QualType &declSpecType) {
570   state.saveDeclSpecAttrs();
571 
572   // C++11 attributes before the decl specifiers actually appertain to
573   // the declarators. Move them straight there. We don't support the
574   // 'put them wherever you like' semantics we allow for GNU attributes.
575   if (attr.isCXX11Attribute()) {
576     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
577                            state.getDeclarator().getAttrListRef());
578     return;
579   }
580 
581   // Try to distribute to the innermost.
582   if (distributeFunctionTypeAttrToInnermost(state, attr,
583                                             state.getCurrentAttrListRef(),
584                                             declSpecType))
585     return;
586 
587   // If that failed, diagnose the bad attribute when the declarator is
588   // fully built.
589   state.addIgnoredTypeAttr(attr);
590 }
591 
592 /// A function type attribute was written on the declarator.  Try to
593 /// apply it somewhere.
594 static void
595 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
596                                          AttributeList &attr,
597                                          QualType &declSpecType) {
598   Declarator &declarator = state.getDeclarator();
599 
600   // Try to distribute to the innermost.
601   if (distributeFunctionTypeAttrToInnermost(state, attr,
602                                             declarator.getAttrListRef(),
603                                             declSpecType))
604     return;
605 
606   // If that failed, diagnose the bad attribute when the declarator is
607   // fully built.
608   spliceAttrOutOfList(attr, declarator.getAttrListRef());
609   state.addIgnoredTypeAttr(attr);
610 }
611 
612 /// \brief Given that there are attributes written on the declarator
613 /// itself, try to distribute any type attributes to the appropriate
614 /// declarator chunk.
615 ///
616 /// These are attributes like the following:
617 ///   int f ATTR;
618 ///   int (f ATTR)();
619 /// but not necessarily this:
620 ///   int f() ATTR;
621 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
622                                               QualType &declSpecType) {
623   // Collect all the type attributes from the declarator itself.
624   assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
625   AttributeList *attr = state.getDeclarator().getAttributes();
626   AttributeList *next;
627   do {
628     next = attr->getNext();
629 
630     // Do not distribute C++11 attributes. They have strict rules for what
631     // they appertain to.
632     if (attr->isCXX11Attribute())
633       continue;
634 
635     switch (attr->getKind()) {
636     OBJC_POINTER_TYPE_ATTRS_CASELIST:
637       distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
638       break;
639 
640     case AttributeList::AT_NSReturnsRetained:
641       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
642         break;
643       // fallthrough
644 
645     FUNCTION_TYPE_ATTRS_CASELIST:
646       distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
647       break;
648 
649     MS_TYPE_ATTRS_CASELIST:
650       // Microsoft type attributes cannot go after the declarator-id.
651       continue;
652 
653     NULLABILITY_TYPE_ATTRS_CASELIST:
654       // Nullability specifiers cannot go after the declarator-id.
655 
656     // Objective-C __kindof does not get distributed.
657     case AttributeList::AT_ObjCKindOf:
658       continue;
659 
660     default:
661       break;
662     }
663   } while ((attr = next));
664 }
665 
666 /// Add a synthetic '()' to a block-literal declarator if it is
667 /// required, given the return type.
668 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
669                                           QualType declSpecType) {
670   Declarator &declarator = state.getDeclarator();
671 
672   // First, check whether the declarator would produce a function,
673   // i.e. whether the innermost semantic chunk is a function.
674   if (declarator.isFunctionDeclarator()) {
675     // If so, make that declarator a prototyped declarator.
676     declarator.getFunctionTypeInfo().hasPrototype = true;
677     return;
678   }
679 
680   // If there are any type objects, the type as written won't name a
681   // function, regardless of the decl spec type.  This is because a
682   // block signature declarator is always an abstract-declarator, and
683   // abstract-declarators can't just be parentheses chunks.  Therefore
684   // we need to build a function chunk unless there are no type
685   // objects and the decl spec type is a function.
686   if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
687     return;
688 
689   // Note that there *are* cases with invalid declarators where
690   // declarators consist solely of parentheses.  In general, these
691   // occur only in failed efforts to make function declarators, so
692   // faking up the function chunk is still the right thing to do.
693 
694   // Otherwise, we need to fake up a function declarator.
695   SourceLocation loc = declarator.getLocStart();
696 
697   // ...and *prepend* it to the declarator.
698   SourceLocation NoLoc;
699   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
700       /*HasProto=*/true,
701       /*IsAmbiguous=*/false,
702       /*LParenLoc=*/NoLoc,
703       /*ArgInfo=*/nullptr,
704       /*NumArgs=*/0,
705       /*EllipsisLoc=*/NoLoc,
706       /*RParenLoc=*/NoLoc,
707       /*TypeQuals=*/0,
708       /*RefQualifierIsLvalueRef=*/true,
709       /*RefQualifierLoc=*/NoLoc,
710       /*ConstQualifierLoc=*/NoLoc,
711       /*VolatileQualifierLoc=*/NoLoc,
712       /*RestrictQualifierLoc=*/NoLoc,
713       /*MutableLoc=*/NoLoc, EST_None,
714       /*ESpecRange=*/SourceRange(),
715       /*Exceptions=*/nullptr,
716       /*ExceptionRanges=*/nullptr,
717       /*NumExceptions=*/0,
718       /*NoexceptExpr=*/nullptr,
719       /*ExceptionSpecTokens=*/nullptr,
720       loc, loc, declarator));
721 
722   // For consistency, make sure the state still has us as processing
723   // the decl spec.
724   assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
725   state.setCurrentChunkIndex(declarator.getNumTypeObjects());
726 }
727 
728 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
729                                             unsigned &TypeQuals,
730                                             QualType TypeSoFar,
731                                             unsigned RemoveTQs,
732                                             unsigned DiagID) {
733   // If this occurs outside a template instantiation, warn the user about
734   // it; they probably didn't mean to specify a redundant qualifier.
735   typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
736   for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
737                        QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
738                        QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
739                        QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
740     if (!(RemoveTQs & Qual.first))
741       continue;
742 
743     if (S.ActiveTemplateInstantiations.empty()) {
744       if (TypeQuals & Qual.first)
745         S.Diag(Qual.second, DiagID)
746           << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
747           << FixItHint::CreateRemoval(Qual.second);
748     }
749 
750     TypeQuals &= ~Qual.first;
751   }
752 }
753 
754 /// Return true if this is omitted block return type. Also check type
755 /// attributes and type qualifiers when returning true.
756 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
757                                         QualType Result) {
758   if (!isOmittedBlockReturnType(declarator))
759     return false;
760 
761   // Warn if we see type attributes for omitted return type on a block literal.
762   AttributeList *&attrs =
763       declarator.getMutableDeclSpec().getAttributes().getListRef();
764   AttributeList *prev = nullptr;
765   for (AttributeList *cur = attrs; cur; cur = cur->getNext()) {
766     AttributeList &attr = *cur;
767     // Skip attributes that were marked to be invalid or non-type
768     // attributes.
769     if (attr.isInvalid() || !attr.isTypeAttr()) {
770       prev = cur;
771       continue;
772     }
773     S.Diag(attr.getLoc(),
774            diag::warn_block_literal_attributes_on_omitted_return_type)
775         << attr.getName();
776     // Remove cur from the list.
777     if (prev) {
778       prev->setNext(cur->getNext());
779       prev = cur;
780     } else {
781       attrs = cur->getNext();
782     }
783   }
784 
785   // Warn if we see type qualifiers for omitted return type on a block literal.
786   const DeclSpec &DS = declarator.getDeclSpec();
787   unsigned TypeQuals = DS.getTypeQualifiers();
788   diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
789       diag::warn_block_literal_qualifiers_on_omitted_return_type);
790   declarator.getMutableDeclSpec().ClearTypeQualifiers();
791 
792   return true;
793 }
794 
795 /// Apply Objective-C type arguments to the given type.
796 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
797                                   ArrayRef<TypeSourceInfo *> typeArgs,
798                                   SourceRange typeArgsRange,
799                                   bool failOnError = false) {
800   // We can only apply type arguments to an Objective-C class type.
801   const auto *objcObjectType = type->getAs<ObjCObjectType>();
802   if (!objcObjectType || !objcObjectType->getInterface()) {
803     S.Diag(loc, diag::err_objc_type_args_non_class)
804       << type
805       << typeArgsRange;
806 
807     if (failOnError)
808       return QualType();
809     return type;
810   }
811 
812   // The class type must be parameterized.
813   ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
814   ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
815   if (!typeParams) {
816     S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
817       << objcClass->getDeclName()
818       << FixItHint::CreateRemoval(typeArgsRange);
819 
820     if (failOnError)
821       return QualType();
822 
823     return type;
824   }
825 
826   // The type must not already be specialized.
827   if (objcObjectType->isSpecialized()) {
828     S.Diag(loc, diag::err_objc_type_args_specialized_class)
829       << type
830       << FixItHint::CreateRemoval(typeArgsRange);
831 
832     if (failOnError)
833       return QualType();
834 
835     return type;
836   }
837 
838   // Check the type arguments.
839   SmallVector<QualType, 4> finalTypeArgs;
840   unsigned numTypeParams = typeParams->size();
841   bool anyPackExpansions = false;
842   for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
843     TypeSourceInfo *typeArgInfo = typeArgs[i];
844     QualType typeArg = typeArgInfo->getType();
845 
846     // Type arguments cannot have explicit qualifiers or nullability.
847     // We ignore indirect sources of these, e.g. behind typedefs or
848     // template arguments.
849     if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
850       bool diagnosed = false;
851       SourceRange rangeToRemove;
852       if (auto attr = qual.getAs<AttributedTypeLoc>()) {
853         rangeToRemove = attr.getLocalSourceRange();
854         if (attr.getTypePtr()->getImmediateNullability()) {
855           typeArg = attr.getTypePtr()->getModifiedType();
856           S.Diag(attr.getLocStart(),
857                  diag::err_objc_type_arg_explicit_nullability)
858             << typeArg << FixItHint::CreateRemoval(rangeToRemove);
859           diagnosed = true;
860         }
861       }
862 
863       if (!diagnosed) {
864         S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
865           << typeArg << typeArg.getQualifiers().getAsString()
866           << FixItHint::CreateRemoval(rangeToRemove);
867       }
868     }
869 
870     // Remove qualifiers even if they're non-local.
871     typeArg = typeArg.getUnqualifiedType();
872 
873     finalTypeArgs.push_back(typeArg);
874 
875     if (typeArg->getAs<PackExpansionType>())
876       anyPackExpansions = true;
877 
878     // Find the corresponding type parameter, if there is one.
879     ObjCTypeParamDecl *typeParam = nullptr;
880     if (!anyPackExpansions) {
881       if (i < numTypeParams) {
882         typeParam = typeParams->begin()[i];
883       } else {
884         // Too many arguments.
885         S.Diag(loc, diag::err_objc_type_args_wrong_arity)
886           << false
887           << objcClass->getDeclName()
888           << (unsigned)typeArgs.size()
889           << numTypeParams;
890         S.Diag(objcClass->getLocation(), diag::note_previous_decl)
891           << objcClass;
892 
893         if (failOnError)
894           return QualType();
895 
896         return type;
897       }
898     }
899 
900     // Objective-C object pointer types must be substitutable for the bounds.
901     if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
902       // If we don't have a type parameter to match against, assume
903       // everything is fine. There was a prior pack expansion that
904       // means we won't be able to match anything.
905       if (!typeParam) {
906         assert(anyPackExpansions && "Too many arguments?");
907         continue;
908       }
909 
910       // Retrieve the bound.
911       QualType bound = typeParam->getUnderlyingType();
912       const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
913 
914       // Determine whether the type argument is substitutable for the bound.
915       if (typeArgObjC->isObjCIdType()) {
916         // When the type argument is 'id', the only acceptable type
917         // parameter bound is 'id'.
918         if (boundObjC->isObjCIdType())
919           continue;
920       } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
921         // Otherwise, we follow the assignability rules.
922         continue;
923       }
924 
925       // Diagnose the mismatch.
926       S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
927              diag::err_objc_type_arg_does_not_match_bound)
928         << typeArg << bound << typeParam->getDeclName();
929       S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
930         << typeParam->getDeclName();
931 
932       if (failOnError)
933         return QualType();
934 
935       return type;
936     }
937 
938     // Block pointer types are permitted for unqualified 'id' bounds.
939     if (typeArg->isBlockPointerType()) {
940       // If we don't have a type parameter to match against, assume
941       // everything is fine. There was a prior pack expansion that
942       // means we won't be able to match anything.
943       if (!typeParam) {
944         assert(anyPackExpansions && "Too many arguments?");
945         continue;
946       }
947 
948       // Retrieve the bound.
949       QualType bound = typeParam->getUnderlyingType();
950       if (bound->isBlockCompatibleObjCPointerType(S.Context))
951         continue;
952 
953       // Diagnose the mismatch.
954       S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
955              diag::err_objc_type_arg_does_not_match_bound)
956         << typeArg << bound << typeParam->getDeclName();
957       S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
958         << typeParam->getDeclName();
959 
960       if (failOnError)
961         return QualType();
962 
963       return type;
964     }
965 
966     // Dependent types will be checked at instantiation time.
967     if (typeArg->isDependentType()) {
968       continue;
969     }
970 
971     // Diagnose non-id-compatible type arguments.
972     S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
973            diag::err_objc_type_arg_not_id_compatible)
974       << typeArg
975       << typeArgInfo->getTypeLoc().getSourceRange();
976 
977     if (failOnError)
978       return QualType();
979 
980     return type;
981   }
982 
983   // Make sure we didn't have the wrong number of arguments.
984   if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
985     S.Diag(loc, diag::err_objc_type_args_wrong_arity)
986       << (typeArgs.size() < typeParams->size())
987       << objcClass->getDeclName()
988       << (unsigned)finalTypeArgs.size()
989       << (unsigned)numTypeParams;
990     S.Diag(objcClass->getLocation(), diag::note_previous_decl)
991       << objcClass;
992 
993     if (failOnError)
994       return QualType();
995 
996     return type;
997   }
998 
999   // Success. Form the specialized type.
1000   return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1001 }
1002 
1003 /// Apply Objective-C protocol qualifiers to the given type.
1004 static QualType applyObjCProtocolQualifiers(
1005                   Sema &S, SourceLocation loc, SourceRange range, QualType type,
1006                   ArrayRef<ObjCProtocolDecl *> protocols,
1007                   const SourceLocation *protocolLocs,
1008                   bool failOnError = false) {
1009   ASTContext &ctx = S.Context;
1010   if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
1011     // FIXME: Check for protocols to which the class type is already
1012     // known to conform.
1013 
1014     return ctx.getObjCObjectType(objT->getBaseType(),
1015                                  objT->getTypeArgsAsWritten(),
1016                                  protocols,
1017                                  objT->isKindOfTypeAsWritten());
1018   }
1019 
1020   if (type->isObjCObjectType()) {
1021     // Silently overwrite any existing protocol qualifiers.
1022     // TODO: determine whether that's the right thing to do.
1023 
1024     // FIXME: Check for protocols to which the class type is already
1025     // known to conform.
1026     return ctx.getObjCObjectType(type, { }, protocols, false);
1027   }
1028 
1029   // id<protocol-list>
1030   if (type->isObjCIdType()) {
1031     const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
1032     type = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, protocols,
1033                                  objPtr->isKindOfType());
1034     return ctx.getObjCObjectPointerType(type);
1035   }
1036 
1037   // Class<protocol-list>
1038   if (type->isObjCClassType()) {
1039     const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
1040     type = ctx.getObjCObjectType(ctx.ObjCBuiltinClassTy, { }, protocols,
1041                                  objPtr->isKindOfType());
1042     return ctx.getObjCObjectPointerType(type);
1043   }
1044 
1045   S.Diag(loc, diag::err_invalid_protocol_qualifiers)
1046     << range;
1047 
1048   if (failOnError)
1049     return QualType();
1050 
1051   return type;
1052 }
1053 
1054 QualType Sema::BuildObjCObjectType(QualType BaseType,
1055                                    SourceLocation Loc,
1056                                    SourceLocation TypeArgsLAngleLoc,
1057                                    ArrayRef<TypeSourceInfo *> TypeArgs,
1058                                    SourceLocation TypeArgsRAngleLoc,
1059                                    SourceLocation ProtocolLAngleLoc,
1060                                    ArrayRef<ObjCProtocolDecl *> Protocols,
1061                                    ArrayRef<SourceLocation> ProtocolLocs,
1062                                    SourceLocation ProtocolRAngleLoc,
1063                                    bool FailOnError) {
1064   QualType Result = BaseType;
1065   if (!TypeArgs.empty()) {
1066     Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1067                                SourceRange(TypeArgsLAngleLoc,
1068                                            TypeArgsRAngleLoc),
1069                                FailOnError);
1070     if (FailOnError && Result.isNull())
1071       return QualType();
1072   }
1073 
1074   if (!Protocols.empty()) {
1075     Result = applyObjCProtocolQualifiers(*this, Loc,
1076                                          SourceRange(ProtocolLAngleLoc,
1077                                                      ProtocolRAngleLoc),
1078                                          Result, Protocols,
1079                                          ProtocolLocs.data(),
1080                                          FailOnError);
1081     if (FailOnError && Result.isNull())
1082       return QualType();
1083   }
1084 
1085   return Result;
1086 }
1087 
1088 TypeResult Sema::actOnObjCProtocolQualifierType(
1089              SourceLocation lAngleLoc,
1090              ArrayRef<Decl *> protocols,
1091              ArrayRef<SourceLocation> protocolLocs,
1092              SourceLocation rAngleLoc) {
1093   // Form id<protocol-list>.
1094   QualType Result = Context.getObjCObjectType(
1095                       Context.ObjCBuiltinIdTy, { },
1096                       llvm::makeArrayRef(
1097                         (ObjCProtocolDecl * const *)protocols.data(),
1098                         protocols.size()),
1099                       false);
1100   Result = Context.getObjCObjectPointerType(Result);
1101 
1102   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1103   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1104 
1105   auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1106   ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1107 
1108   auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1109                         .castAs<ObjCObjectTypeLoc>();
1110   ObjCObjectTL.setHasBaseTypeAsWritten(false);
1111   ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1112 
1113   // No type arguments.
1114   ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1115   ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1116 
1117   // Fill in protocol qualifiers.
1118   ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1119   ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1120   for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1121     ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1122 
1123   // We're done. Return the completed type to the parser.
1124   return CreateParsedType(Result, ResultTInfo);
1125 }
1126 
1127 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1128              Scope *S,
1129              SourceLocation Loc,
1130              ParsedType BaseType,
1131              SourceLocation TypeArgsLAngleLoc,
1132              ArrayRef<ParsedType> TypeArgs,
1133              SourceLocation TypeArgsRAngleLoc,
1134              SourceLocation ProtocolLAngleLoc,
1135              ArrayRef<Decl *> Protocols,
1136              ArrayRef<SourceLocation> ProtocolLocs,
1137              SourceLocation ProtocolRAngleLoc) {
1138   TypeSourceInfo *BaseTypeInfo = nullptr;
1139   QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1140   if (T.isNull())
1141     return true;
1142 
1143   // Handle missing type-source info.
1144   if (!BaseTypeInfo)
1145     BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1146 
1147   // Extract type arguments.
1148   SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1149   for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1150     TypeSourceInfo *TypeArgInfo = nullptr;
1151     QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1152     if (TypeArg.isNull()) {
1153       ActualTypeArgInfos.clear();
1154       break;
1155     }
1156 
1157     assert(TypeArgInfo && "No type source info?");
1158     ActualTypeArgInfos.push_back(TypeArgInfo);
1159   }
1160 
1161   // Build the object type.
1162   QualType Result = BuildObjCObjectType(
1163       T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1164       TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1165       ProtocolLAngleLoc,
1166       llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1167                          Protocols.size()),
1168       ProtocolLocs, ProtocolRAngleLoc,
1169       /*FailOnError=*/false);
1170 
1171   if (Result == T)
1172     return BaseType;
1173 
1174   // Create source information for this type.
1175   TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1176   TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1177 
1178   // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1179   // object pointer type. Fill in source information for it.
1180   if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1181     // The '*' is implicit.
1182     ObjCObjectPointerTL.setStarLoc(SourceLocation());
1183     ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1184   }
1185 
1186   auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1187 
1188   // Type argument information.
1189   if (ObjCObjectTL.getNumTypeArgs() > 0) {
1190     assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1191     ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1192     ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1193     for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1194       ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1195   } else {
1196     ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1197     ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1198   }
1199 
1200   // Protocol qualifier information.
1201   if (ObjCObjectTL.getNumProtocols() > 0) {
1202     assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1203     ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1204     ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1205     for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1206       ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1207   } else {
1208     ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1209     ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1210   }
1211 
1212   // Base type.
1213   ObjCObjectTL.setHasBaseTypeAsWritten(true);
1214   if (ObjCObjectTL.getType() == T)
1215     ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1216   else
1217     ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1218 
1219   // We're done. Return the completed type to the parser.
1220   return CreateParsedType(Result, ResultTInfo);
1221 }
1222 
1223 static StringRef getImageAccessAttrStr(AttributeList *attrs) {
1224   if (attrs) {
1225 
1226     AttributeList *Next;
1227     do {
1228       AttributeList &Attr = *attrs;
1229       Next = Attr.getNext();
1230       if (Attr.getKind() == AttributeList::AT_OpenCLAccess) {
1231         return Attr.getName()->getName();
1232       }
1233     } while (Next);
1234   }
1235   return "";
1236 }
1237 
1238 /// \brief Convert the specified declspec to the appropriate type
1239 /// object.
1240 /// \param state Specifies the declarator containing the declaration specifier
1241 /// to be converted, along with other associated processing state.
1242 /// \returns The type described by the declaration specifiers.  This function
1243 /// never returns null.
1244 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1245   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1246   // checking.
1247 
1248   Sema &S = state.getSema();
1249   Declarator &declarator = state.getDeclarator();
1250   const DeclSpec &DS = declarator.getDeclSpec();
1251   SourceLocation DeclLoc = declarator.getIdentifierLoc();
1252   if (DeclLoc.isInvalid())
1253     DeclLoc = DS.getLocStart();
1254 
1255   ASTContext &Context = S.Context;
1256 
1257   QualType Result;
1258   switch (DS.getTypeSpecType()) {
1259   case DeclSpec::TST_void:
1260     Result = Context.VoidTy;
1261     break;
1262   case DeclSpec::TST_char:
1263     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1264       Result = Context.CharTy;
1265     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1266       Result = Context.SignedCharTy;
1267     else {
1268       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1269              "Unknown TSS value");
1270       Result = Context.UnsignedCharTy;
1271     }
1272     break;
1273   case DeclSpec::TST_wchar:
1274     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1275       Result = Context.WCharTy;
1276     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1277       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1278         << DS.getSpecifierName(DS.getTypeSpecType(),
1279                                Context.getPrintingPolicy());
1280       Result = Context.getSignedWCharType();
1281     } else {
1282       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1283         "Unknown TSS value");
1284       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1285         << DS.getSpecifierName(DS.getTypeSpecType(),
1286                                Context.getPrintingPolicy());
1287       Result = Context.getUnsignedWCharType();
1288     }
1289     break;
1290   case DeclSpec::TST_char16:
1291       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1292         "Unknown TSS value");
1293       Result = Context.Char16Ty;
1294     break;
1295   case DeclSpec::TST_char32:
1296       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1297         "Unknown TSS value");
1298       Result = Context.Char32Ty;
1299     break;
1300   case DeclSpec::TST_unspecified:
1301     // If this is a missing declspec in a block literal return context, then it
1302     // is inferred from the return statements inside the block.
1303     // The declspec is always missing in a lambda expr context; it is either
1304     // specified with a trailing return type or inferred.
1305     if (S.getLangOpts().CPlusPlus14 &&
1306         declarator.getContext() == Declarator::LambdaExprContext) {
1307       // In C++1y, a lambda's implicit return type is 'auto'.
1308       Result = Context.getAutoDeductType();
1309       break;
1310     } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1311                checkOmittedBlockReturnType(S, declarator,
1312                                            Context.DependentTy)) {
1313       Result = Context.DependentTy;
1314       break;
1315     }
1316 
1317     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
1318     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1319     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
1320     // Note that the one exception to this is function definitions, which are
1321     // allowed to be completely missing a declspec.  This is handled in the
1322     // parser already though by it pretending to have seen an 'int' in this
1323     // case.
1324     if (S.getLangOpts().ImplicitInt) {
1325       // In C89 mode, we only warn if there is a completely missing declspec
1326       // when one is not allowed.
1327       if (DS.isEmpty()) {
1328         S.Diag(DeclLoc, diag::ext_missing_declspec)
1329           << DS.getSourceRange()
1330         << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1331       }
1332     } else if (!DS.hasTypeSpecifier()) {
1333       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
1334       // "At least one type specifier shall be given in the declaration
1335       // specifiers in each declaration, and in the specifier-qualifier list in
1336       // each struct declaration and type name."
1337       if (S.getLangOpts().CPlusPlus) {
1338         S.Diag(DeclLoc, diag::err_missing_type_specifier)
1339           << DS.getSourceRange();
1340 
1341         // When this occurs in C++ code, often something is very broken with the
1342         // value being declared, poison it as invalid so we don't get chains of
1343         // errors.
1344         declarator.setInvalidType(true);
1345       } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1346         S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1347           << DS.getSourceRange();
1348         declarator.setInvalidType(true);
1349       } else {
1350         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1351           << DS.getSourceRange();
1352       }
1353     }
1354 
1355     // FALL THROUGH.
1356   case DeclSpec::TST_int: {
1357     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1358       switch (DS.getTypeSpecWidth()) {
1359       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1360       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
1361       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
1362       case DeclSpec::TSW_longlong:
1363         Result = Context.LongLongTy;
1364 
1365         // 'long long' is a C99 or C++11 feature.
1366         if (!S.getLangOpts().C99) {
1367           if (S.getLangOpts().CPlusPlus)
1368             S.Diag(DS.getTypeSpecWidthLoc(),
1369                    S.getLangOpts().CPlusPlus11 ?
1370                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1371           else
1372             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1373         }
1374         break;
1375       }
1376     } else {
1377       switch (DS.getTypeSpecWidth()) {
1378       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1379       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
1380       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
1381       case DeclSpec::TSW_longlong:
1382         Result = Context.UnsignedLongLongTy;
1383 
1384         // 'long long' is a C99 or C++11 feature.
1385         if (!S.getLangOpts().C99) {
1386           if (S.getLangOpts().CPlusPlus)
1387             S.Diag(DS.getTypeSpecWidthLoc(),
1388                    S.getLangOpts().CPlusPlus11 ?
1389                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1390           else
1391             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1392         }
1393         break;
1394       }
1395     }
1396     break;
1397   }
1398   case DeclSpec::TST_int128:
1399     if (!S.Context.getTargetInfo().hasInt128Type())
1400       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1401         << "__int128";
1402     if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1403       Result = Context.UnsignedInt128Ty;
1404     else
1405       Result = Context.Int128Ty;
1406     break;
1407   case DeclSpec::TST_half: Result = Context.HalfTy; break;
1408   case DeclSpec::TST_float: Result = Context.FloatTy; break;
1409   case DeclSpec::TST_double:
1410     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1411       Result = Context.LongDoubleTy;
1412     else
1413       Result = Context.DoubleTy;
1414 
1415     if (S.getLangOpts().OpenCL &&
1416         !((S.getLangOpts().OpenCLVersion >= 120) ||
1417           S.getOpenCLOptions().cl_khr_fp64)) {
1418       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1419           << Result << "cl_khr_fp64";
1420       declarator.setInvalidType(true);
1421     }
1422     break;
1423   case DeclSpec::TST_float128:
1424     if (!S.Context.getTargetInfo().hasFloat128Type())
1425       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1426         << "__float128";
1427     Result = Context.Float128Ty;
1428     break;
1429   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1430     break;
1431   case DeclSpec::TST_decimal32:    // _Decimal32
1432   case DeclSpec::TST_decimal64:    // _Decimal64
1433   case DeclSpec::TST_decimal128:   // _Decimal128
1434     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1435     Result = Context.IntTy;
1436     declarator.setInvalidType(true);
1437     break;
1438   case DeclSpec::TST_class:
1439   case DeclSpec::TST_enum:
1440   case DeclSpec::TST_union:
1441   case DeclSpec::TST_struct:
1442   case DeclSpec::TST_interface: {
1443     TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1444     if (!D) {
1445       // This can happen in C++ with ambiguous lookups.
1446       Result = Context.IntTy;
1447       declarator.setInvalidType(true);
1448       break;
1449     }
1450 
1451     // If the type is deprecated or unavailable, diagnose it.
1452     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1453 
1454     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1455            DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1456 
1457     // TypeQuals handled by caller.
1458     Result = Context.getTypeDeclType(D);
1459 
1460     // In both C and C++, make an ElaboratedType.
1461     ElaboratedTypeKeyword Keyword
1462       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1463     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1464     break;
1465   }
1466   case DeclSpec::TST_typename: {
1467     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1468            DS.getTypeSpecSign() == 0 &&
1469            "Can't handle qualifiers on typedef names yet!");
1470     Result = S.GetTypeFromParser(DS.getRepAsType());
1471     if (Result.isNull()) {
1472       declarator.setInvalidType(true);
1473     } else if (S.getLangOpts().OpenCL) {
1474       if (Result->getAs<AtomicType>()) {
1475         StringRef TypeName = Result.getBaseTypeIdentifier()->getName();
1476         bool NoExtTypes =
1477             llvm::StringSwitch<bool>(TypeName)
1478                 .Cases("atomic_int", "atomic_uint", "atomic_float",
1479                        "atomic_flag", true)
1480                 .Default(false);
1481         if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
1482           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1483               << Result << "cl_khr_int64_base_atomics";
1484           declarator.setInvalidType(true);
1485         }
1486         if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
1487             !NoExtTypes) {
1488           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1489               << Result << "cl_khr_int64_extended_atomics";
1490           declarator.setInvalidType(true);
1491         }
1492         if (!S.getOpenCLOptions().cl_khr_fp64 &&
1493             !TypeName.compare("atomic_double")) {
1494           S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1495               << Result << "cl_khr_fp64";
1496           declarator.setInvalidType(true);
1497         }
1498       } else if (!S.getOpenCLOptions().cl_khr_gl_msaa_sharing &&
1499                  (Result->isOCLImage2dArrayMSAADepthROType() ||
1500                   Result->isOCLImage2dArrayMSAADepthWOType() ||
1501                   Result->isOCLImage2dArrayMSAADepthRWType() ||
1502                   Result->isOCLImage2dArrayMSAAROType() ||
1503                   Result->isOCLImage2dArrayMSAARWType() ||
1504                   Result->isOCLImage2dArrayMSAAWOType() ||
1505                   Result->isOCLImage2dMSAADepthROType() ||
1506                   Result->isOCLImage2dMSAADepthRWType() ||
1507                   Result->isOCLImage2dMSAADepthWOType() ||
1508                   Result->isOCLImage2dMSAAROType() ||
1509                   Result->isOCLImage2dMSAARWType() ||
1510                   Result->isOCLImage2dMSAAWOType())) {
1511         S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1512             << Result << "cl_khr_gl_msaa_sharing";
1513         declarator.setInvalidType(true);
1514       }
1515     }
1516 
1517     // TypeQuals handled by caller.
1518     break;
1519   }
1520   case DeclSpec::TST_typeofType:
1521     // FIXME: Preserve type source info.
1522     Result = S.GetTypeFromParser(DS.getRepAsType());
1523     assert(!Result.isNull() && "Didn't get a type for typeof?");
1524     if (!Result->isDependentType())
1525       if (const TagType *TT = Result->getAs<TagType>())
1526         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1527     // TypeQuals handled by caller.
1528     Result = Context.getTypeOfType(Result);
1529     break;
1530   case DeclSpec::TST_typeofExpr: {
1531     Expr *E = DS.getRepAsExpr();
1532     assert(E && "Didn't get an expression for typeof?");
1533     // TypeQuals handled by caller.
1534     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1535     if (Result.isNull()) {
1536       Result = Context.IntTy;
1537       declarator.setInvalidType(true);
1538     }
1539     break;
1540   }
1541   case DeclSpec::TST_decltype: {
1542     Expr *E = DS.getRepAsExpr();
1543     assert(E && "Didn't get an expression for decltype?");
1544     // TypeQuals handled by caller.
1545     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1546     if (Result.isNull()) {
1547       Result = Context.IntTy;
1548       declarator.setInvalidType(true);
1549     }
1550     break;
1551   }
1552   case DeclSpec::TST_underlyingType:
1553     Result = S.GetTypeFromParser(DS.getRepAsType());
1554     assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1555     Result = S.BuildUnaryTransformType(Result,
1556                                        UnaryTransformType::EnumUnderlyingType,
1557                                        DS.getTypeSpecTypeLoc());
1558     if (Result.isNull()) {
1559       Result = Context.IntTy;
1560       declarator.setInvalidType(true);
1561     }
1562     break;
1563 
1564   case DeclSpec::TST_auto:
1565     // TypeQuals handled by caller.
1566     // If auto is mentioned in a lambda parameter context, convert it to a
1567     // template parameter type immediately, with the appropriate depth and
1568     // index, and update sema's state (LambdaScopeInfo) for the current lambda
1569     // being analyzed (which tracks the invented type template parameter).
1570     if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1571       sema::LambdaScopeInfo *LSI = S.getCurLambda();
1572       assert(LSI && "No LambdaScopeInfo on the stack!");
1573       const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1574       const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1575       const bool IsParameterPack = declarator.hasEllipsis();
1576 
1577       // Turns out we must create the TemplateTypeParmDecl here to
1578       // retrieve the corresponding template parameter type.
1579       TemplateTypeParmDecl *CorrespondingTemplateParam =
1580         TemplateTypeParmDecl::Create(Context,
1581         // Temporarily add to the TranslationUnit DeclContext.  When the
1582         // associated TemplateParameterList is attached to a template
1583         // declaration (such as FunctionTemplateDecl), the DeclContext
1584         // for each template parameter gets updated appropriately via
1585         // a call to AdoptTemplateParameterList.
1586         Context.getTranslationUnitDecl(),
1587         /*KeyLoc*/ SourceLocation(),
1588         /*NameLoc*/ declarator.getLocStart(),
1589         TemplateParameterDepth,
1590         AutoParameterPosition,  // our template param index
1591         /* Identifier*/ nullptr, false, IsParameterPack);
1592       LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1593       // Replace the 'auto' in the function parameter with this invented
1594       // template type parameter.
1595       Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1596     } else {
1597       Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1598     }
1599     break;
1600 
1601   case DeclSpec::TST_auto_type:
1602     Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1603     break;
1604 
1605   case DeclSpec::TST_decltype_auto:
1606     Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1607                                  /*IsDependent*/ false);
1608     break;
1609 
1610   case DeclSpec::TST_unknown_anytype:
1611     Result = Context.UnknownAnyTy;
1612     break;
1613 
1614   case DeclSpec::TST_atomic:
1615     Result = S.GetTypeFromParser(DS.getRepAsType());
1616     assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1617     Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1618     if (Result.isNull()) {
1619       Result = Context.IntTy;
1620       declarator.setInvalidType(true);
1621     }
1622     break;
1623 
1624 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1625   case DeclSpec::TST_##ImgType##_t: \
1626     Result = llvm::StringSwitch<QualType>( \
1627                  getImageAccessAttrStr(DS.getAttributes().getList())) \
1628                  .Cases("write_only", "__write_only", Context.Id##WOTy) \
1629                  .Cases("read_write", "__read_write", Context.Id##RWTy) \
1630                  .Default(Context.Id##ROTy); \
1631     break;
1632 #include "clang/Basic/OpenCLImageTypes.def"
1633 
1634   case DeclSpec::TST_error:
1635     Result = Context.IntTy;
1636     declarator.setInvalidType(true);
1637     break;
1638   }
1639 
1640   // Handle complex types.
1641   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1642     if (S.getLangOpts().Freestanding)
1643       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1644     Result = Context.getComplexType(Result);
1645   } else if (DS.isTypeAltiVecVector()) {
1646     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1647     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1648     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1649     if (DS.isTypeAltiVecPixel())
1650       VecKind = VectorType::AltiVecPixel;
1651     else if (DS.isTypeAltiVecBool())
1652       VecKind = VectorType::AltiVecBool;
1653     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1654   }
1655 
1656   // FIXME: Imaginary.
1657   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1658     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1659 
1660   // Before we process any type attributes, synthesize a block literal
1661   // function declarator if necessary.
1662   if (declarator.getContext() == Declarator::BlockLiteralContext)
1663     maybeSynthesizeBlockSignature(state, Result);
1664 
1665   // Apply any type attributes from the decl spec.  This may cause the
1666   // list of type attributes to be temporarily saved while the type
1667   // attributes are pushed around.
1668   // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1669   if (!DS.isTypeSpecPipe())
1670       processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1671 
1672   // Apply const/volatile/restrict qualifiers to T.
1673   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1674     // Warn about CV qualifiers on function types.
1675     // C99 6.7.3p8:
1676     //   If the specification of a function type includes any type qualifiers,
1677     //   the behavior is undefined.
1678     // C++11 [dcl.fct]p7:
1679     //   The effect of a cv-qualifier-seq in a function declarator is not the
1680     //   same as adding cv-qualification on top of the function type. In the
1681     //   latter case, the cv-qualifiers are ignored.
1682     if (TypeQuals && Result->isFunctionType()) {
1683       diagnoseAndRemoveTypeQualifiers(
1684           S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1685           S.getLangOpts().CPlusPlus
1686               ? diag::warn_typecheck_function_qualifiers_ignored
1687               : diag::warn_typecheck_function_qualifiers_unspecified);
1688       // No diagnostic for 'restrict' or '_Atomic' applied to a
1689       // function type; we'll diagnose those later, in BuildQualifiedType.
1690     }
1691 
1692     // C++11 [dcl.ref]p1:
1693     //   Cv-qualified references are ill-formed except when the
1694     //   cv-qualifiers are introduced through the use of a typedef-name
1695     //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1696     //
1697     // There don't appear to be any other contexts in which a cv-qualified
1698     // reference type could be formed, so the 'ill-formed' clause here appears
1699     // to never happen.
1700     if (TypeQuals && Result->isReferenceType()) {
1701       diagnoseAndRemoveTypeQualifiers(
1702           S, DS, TypeQuals, Result,
1703           DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1704           diag::warn_typecheck_reference_qualifiers);
1705     }
1706 
1707     // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1708     // than once in the same specifier-list or qualifier-list, either directly
1709     // or via one or more typedefs."
1710     if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1711         && TypeQuals & Result.getCVRQualifiers()) {
1712       if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1713         S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1714           << "const";
1715       }
1716 
1717       if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1718         S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1719           << "volatile";
1720       }
1721 
1722       // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1723       // produce a warning in this case.
1724     }
1725 
1726     QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1727 
1728     // If adding qualifiers fails, just use the unqualified type.
1729     if (Qualified.isNull())
1730       declarator.setInvalidType(true);
1731     else
1732       Result = Qualified;
1733   }
1734 
1735   assert(!Result.isNull() && "This function should not return a null type");
1736   return Result;
1737 }
1738 
1739 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1740   if (Entity)
1741     return Entity.getAsString();
1742 
1743   return "type name";
1744 }
1745 
1746 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1747                                   Qualifiers Qs, const DeclSpec *DS) {
1748   if (T.isNull())
1749     return QualType();
1750 
1751   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1752   // object or incomplete types shall not be restrict-qualified."
1753   if (Qs.hasRestrict()) {
1754     unsigned DiagID = 0;
1755     QualType ProblemTy;
1756 
1757     if (T->isAnyPointerType() || T->isReferenceType() ||
1758         T->isMemberPointerType()) {
1759       QualType EltTy;
1760       if (T->isObjCObjectPointerType())
1761         EltTy = T;
1762       else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1763         EltTy = PTy->getPointeeType();
1764       else
1765         EltTy = T->getPointeeType();
1766 
1767       // If we have a pointer or reference, the pointee must have an object
1768       // incomplete type.
1769       if (!EltTy->isIncompleteOrObjectType()) {
1770         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1771         ProblemTy = EltTy;
1772       }
1773     } else if (!T->isDependentType()) {
1774       DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1775       ProblemTy = T;
1776     }
1777 
1778     if (DiagID) {
1779       Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1780       Qs.removeRestrict();
1781     }
1782   }
1783 
1784   return Context.getQualifiedType(T, Qs);
1785 }
1786 
1787 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1788                                   unsigned CVRAU, const DeclSpec *DS) {
1789   if (T.isNull())
1790     return QualType();
1791 
1792   // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1793   // TQ_unaligned;
1794   unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1795 
1796   // C11 6.7.3/5:
1797   //   If the same qualifier appears more than once in the same
1798   //   specifier-qualifier-list, either directly or via one or more typedefs,
1799   //   the behavior is the same as if it appeared only once.
1800   //
1801   // It's not specified what happens when the _Atomic qualifier is applied to
1802   // a type specified with the _Atomic specifier, but we assume that this
1803   // should be treated as if the _Atomic qualifier appeared multiple times.
1804   if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1805     // C11 6.7.3/5:
1806     //   If other qualifiers appear along with the _Atomic qualifier in a
1807     //   specifier-qualifier-list, the resulting type is the so-qualified
1808     //   atomic type.
1809     //
1810     // Don't need to worry about array types here, since _Atomic can't be
1811     // applied to such types.
1812     SplitQualType Split = T.getSplitUnqualifiedType();
1813     T = BuildAtomicType(QualType(Split.Ty, 0),
1814                         DS ? DS->getAtomicSpecLoc() : Loc);
1815     if (T.isNull())
1816       return T;
1817     Split.Quals.addCVRQualifiers(CVR);
1818     return BuildQualifiedType(T, Loc, Split.Quals);
1819   }
1820 
1821   Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1822   Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1823   return BuildQualifiedType(T, Loc, Q, DS);
1824 }
1825 
1826 /// \brief Build a paren type including \p T.
1827 QualType Sema::BuildParenType(QualType T) {
1828   return Context.getParenType(T);
1829 }
1830 
1831 /// Given that we're building a pointer or reference to the given
1832 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1833                                            SourceLocation loc,
1834                                            bool isReference) {
1835   // Bail out if retention is unrequired or already specified.
1836   if (!type->isObjCLifetimeType() ||
1837       type.getObjCLifetime() != Qualifiers::OCL_None)
1838     return type;
1839 
1840   Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1841 
1842   // If the object type is const-qualified, we can safely use
1843   // __unsafe_unretained.  This is safe (because there are no read
1844   // barriers), and it'll be safe to coerce anything but __weak* to
1845   // the resulting type.
1846   if (type.isConstQualified()) {
1847     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1848 
1849   // Otherwise, check whether the static type does not require
1850   // retaining.  This currently only triggers for Class (possibly
1851   // protocol-qualifed, and arrays thereof).
1852   } else if (type->isObjCARCImplicitlyUnretainedType()) {
1853     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1854 
1855   // If we are in an unevaluated context, like sizeof, skip adding a
1856   // qualification.
1857   } else if (S.isUnevaluatedContext()) {
1858     return type;
1859 
1860   // If that failed, give an error and recover using __strong.  __strong
1861   // is the option most likely to prevent spurious second-order diagnostics,
1862   // like when binding a reference to a field.
1863   } else {
1864     // These types can show up in private ivars in system headers, so
1865     // we need this to not be an error in those cases.  Instead we
1866     // want to delay.
1867     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1868       S.DelayedDiagnostics.add(
1869           sema::DelayedDiagnostic::makeForbiddenType(loc,
1870               diag::err_arc_indirect_no_ownership, type, isReference));
1871     } else {
1872       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1873     }
1874     implicitLifetime = Qualifiers::OCL_Strong;
1875   }
1876   assert(implicitLifetime && "didn't infer any lifetime!");
1877 
1878   Qualifiers qs;
1879   qs.addObjCLifetime(implicitLifetime);
1880   return S.Context.getQualifiedType(type, qs);
1881 }
1882 
1883 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1884   std::string Quals =
1885     Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1886 
1887   switch (FnTy->getRefQualifier()) {
1888   case RQ_None:
1889     break;
1890 
1891   case RQ_LValue:
1892     if (!Quals.empty())
1893       Quals += ' ';
1894     Quals += '&';
1895     break;
1896 
1897   case RQ_RValue:
1898     if (!Quals.empty())
1899       Quals += ' ';
1900     Quals += "&&";
1901     break;
1902   }
1903 
1904   return Quals;
1905 }
1906 
1907 namespace {
1908 /// Kinds of declarator that cannot contain a qualified function type.
1909 ///
1910 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1911 ///     a function type with a cv-qualifier or a ref-qualifier can only appear
1912 ///     at the topmost level of a type.
1913 ///
1914 /// Parens and member pointers are permitted. We don't diagnose array and
1915 /// function declarators, because they don't allow function types at all.
1916 ///
1917 /// The values of this enum are used in diagnostics.
1918 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1919 } // end anonymous namespace
1920 
1921 /// Check whether the type T is a qualified function type, and if it is,
1922 /// diagnose that it cannot be contained within the given kind of declarator.
1923 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1924                                    QualifiedFunctionKind QFK) {
1925   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1926   const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1927   if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1928     return false;
1929 
1930   S.Diag(Loc, diag::err_compound_qualified_function_type)
1931     << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1932     << getFunctionQualifiersAsString(FPT);
1933   return true;
1934 }
1935 
1936 /// \brief Build a pointer type.
1937 ///
1938 /// \param T The type to which we'll be building a pointer.
1939 ///
1940 /// \param Loc The location of the entity whose type involves this
1941 /// pointer type or, if there is no such entity, the location of the
1942 /// type that will have pointer type.
1943 ///
1944 /// \param Entity The name of the entity that involves the pointer
1945 /// type, if known.
1946 ///
1947 /// \returns A suitable pointer type, if there are no
1948 /// errors. Otherwise, returns a NULL type.
1949 QualType Sema::BuildPointerType(QualType T,
1950                                 SourceLocation Loc, DeclarationName Entity) {
1951   if (T->isReferenceType()) {
1952     // C++ 8.3.2p4: There shall be no ... pointers to references ...
1953     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1954       << getPrintableNameForEntity(Entity) << T;
1955     return QualType();
1956   }
1957 
1958   if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1959     return QualType();
1960 
1961   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1962 
1963   // In ARC, it is forbidden to build pointers to unqualified pointers.
1964   if (getLangOpts().ObjCAutoRefCount)
1965     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1966 
1967   // Build the pointer type.
1968   return Context.getPointerType(T);
1969 }
1970 
1971 /// \brief Build a reference type.
1972 ///
1973 /// \param T The type to which we'll be building a reference.
1974 ///
1975 /// \param Loc The location of the entity whose type involves this
1976 /// reference type or, if there is no such entity, the location of the
1977 /// type that will have reference type.
1978 ///
1979 /// \param Entity The name of the entity that involves the reference
1980 /// type, if known.
1981 ///
1982 /// \returns A suitable reference type, if there are no
1983 /// errors. Otherwise, returns a NULL type.
1984 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1985                                   SourceLocation Loc,
1986                                   DeclarationName Entity) {
1987   assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1988          "Unresolved overloaded function type");
1989 
1990   // C++0x [dcl.ref]p6:
1991   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1992   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1993   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1994   //   the type "lvalue reference to T", while an attempt to create the type
1995   //   "rvalue reference to cv TR" creates the type TR.
1996   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1997 
1998   // C++ [dcl.ref]p4: There shall be no references to references.
1999   //
2000   // According to C++ DR 106, references to references are only
2001   // diagnosed when they are written directly (e.g., "int & &"),
2002   // but not when they happen via a typedef:
2003   //
2004   //   typedef int& intref;
2005   //   typedef intref& intref2;
2006   //
2007   // Parser::ParseDeclaratorInternal diagnoses the case where
2008   // references are written directly; here, we handle the
2009   // collapsing of references-to-references as described in C++0x.
2010   // DR 106 and 540 introduce reference-collapsing into C++98/03.
2011 
2012   // C++ [dcl.ref]p1:
2013   //   A declarator that specifies the type "reference to cv void"
2014   //   is ill-formed.
2015   if (T->isVoidType()) {
2016     Diag(Loc, diag::err_reference_to_void);
2017     return QualType();
2018   }
2019 
2020   if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2021     return QualType();
2022 
2023   // In ARC, it is forbidden to build references to unqualified pointers.
2024   if (getLangOpts().ObjCAutoRefCount)
2025     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2026 
2027   // Handle restrict on references.
2028   if (LValueRef)
2029     return Context.getLValueReferenceType(T, SpelledAsLValue);
2030   return Context.getRValueReferenceType(T);
2031 }
2032 
2033 /// \brief Build a Pipe type.
2034 ///
2035 /// \param T The type to which we'll be building a Pipe.
2036 ///
2037 /// \param Loc We do not use it for now.
2038 ///
2039 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2040 /// NULL type.
2041 QualType Sema::BuildPipeType(QualType T, SourceLocation Loc) {
2042   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2043 
2044   // Build the pipe type.
2045   return Context.getPipeType(T);
2046 }
2047 
2048 /// Check whether the specified array size makes the array type a VLA.  If so,
2049 /// return true, if not, return the size of the array in SizeVal.
2050 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2051   // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2052   // (like gnu99, but not c99) accept any evaluatable value as an extension.
2053   class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2054   public:
2055     VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2056 
2057     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2058     }
2059 
2060     void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2061       S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2062     }
2063   } Diagnoser;
2064 
2065   return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2066                                            S.LangOpts.GNUMode).isInvalid();
2067 }
2068 
2069 /// \brief Build an array type.
2070 ///
2071 /// \param T The type of each element in the array.
2072 ///
2073 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2074 ///
2075 /// \param ArraySize Expression describing the size of the array.
2076 ///
2077 /// \param Brackets The range from the opening '[' to the closing ']'.
2078 ///
2079 /// \param Entity The name of the entity that involves the array
2080 /// type, if known.
2081 ///
2082 /// \returns A suitable array type, if there are no errors. Otherwise,
2083 /// returns a NULL type.
2084 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2085                               Expr *ArraySize, unsigned Quals,
2086                               SourceRange Brackets, DeclarationName Entity) {
2087 
2088   SourceLocation Loc = Brackets.getBegin();
2089   if (getLangOpts().CPlusPlus) {
2090     // C++ [dcl.array]p1:
2091     //   T is called the array element type; this type shall not be a reference
2092     //   type, the (possibly cv-qualified) type void, a function type or an
2093     //   abstract class type.
2094     //
2095     // C++ [dcl.array]p3:
2096     //   When several "array of" specifications are adjacent, [...] only the
2097     //   first of the constant expressions that specify the bounds of the arrays
2098     //   may be omitted.
2099     //
2100     // Note: function types are handled in the common path with C.
2101     if (T->isReferenceType()) {
2102       Diag(Loc, diag::err_illegal_decl_array_of_references)
2103       << getPrintableNameForEntity(Entity) << T;
2104       return QualType();
2105     }
2106 
2107     if (T->isVoidType() || T->isIncompleteArrayType()) {
2108       Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2109       return QualType();
2110     }
2111 
2112     if (RequireNonAbstractType(Brackets.getBegin(), T,
2113                                diag::err_array_of_abstract_type))
2114       return QualType();
2115 
2116     // Mentioning a member pointer type for an array type causes us to lock in
2117     // an inheritance model, even if it's inside an unused typedef.
2118     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2119       if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2120         if (!MPTy->getClass()->isDependentType())
2121           (void)isCompleteType(Loc, T);
2122 
2123   } else {
2124     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2125     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2126     if (RequireCompleteType(Loc, T,
2127                             diag::err_illegal_decl_array_incomplete_type))
2128       return QualType();
2129   }
2130 
2131   if (T->isFunctionType()) {
2132     Diag(Loc, diag::err_illegal_decl_array_of_functions)
2133       << getPrintableNameForEntity(Entity) << T;
2134     return QualType();
2135   }
2136 
2137   if (const RecordType *EltTy = T->getAs<RecordType>()) {
2138     // If the element type is a struct or union that contains a variadic
2139     // array, accept it as a GNU extension: C99 6.7.2.1p2.
2140     if (EltTy->getDecl()->hasFlexibleArrayMember())
2141       Diag(Loc, diag::ext_flexible_array_in_array) << T;
2142   } else if (T->isObjCObjectType()) {
2143     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2144     return QualType();
2145   }
2146 
2147   // Do placeholder conversions on the array size expression.
2148   if (ArraySize && ArraySize->hasPlaceholderType()) {
2149     ExprResult Result = CheckPlaceholderExpr(ArraySize);
2150     if (Result.isInvalid()) return QualType();
2151     ArraySize = Result.get();
2152   }
2153 
2154   // Do lvalue-to-rvalue conversions on the array size expression.
2155   if (ArraySize && !ArraySize->isRValue()) {
2156     ExprResult Result = DefaultLvalueConversion(ArraySize);
2157     if (Result.isInvalid())
2158       return QualType();
2159 
2160     ArraySize = Result.get();
2161   }
2162 
2163   // C99 6.7.5.2p1: The size expression shall have integer type.
2164   // C++11 allows contextual conversions to such types.
2165   if (!getLangOpts().CPlusPlus11 &&
2166       ArraySize && !ArraySize->isTypeDependent() &&
2167       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2168     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2169       << ArraySize->getType() << ArraySize->getSourceRange();
2170     return QualType();
2171   }
2172 
2173   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2174   if (!ArraySize) {
2175     if (ASM == ArrayType::Star)
2176       T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2177     else
2178       T = Context.getIncompleteArrayType(T, ASM, Quals);
2179   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2180     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2181   } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2182               !T->isConstantSizeType()) ||
2183              isArraySizeVLA(*this, ArraySize, ConstVal)) {
2184     // Even in C++11, don't allow contextual conversions in the array bound
2185     // of a VLA.
2186     if (getLangOpts().CPlusPlus11 &&
2187         !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2188       Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2189         << ArraySize->getType() << ArraySize->getSourceRange();
2190       return QualType();
2191     }
2192 
2193     // C99: an array with an element type that has a non-constant-size is a VLA.
2194     // C99: an array with a non-ICE size is a VLA.  We accept any expression
2195     // that we can fold to a non-zero positive value as an extension.
2196     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2197   } else {
2198     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2199     // have a value greater than zero.
2200     if (ConstVal.isSigned() && ConstVal.isNegative()) {
2201       if (Entity)
2202         Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2203           << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2204       else
2205         Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2206           << ArraySize->getSourceRange();
2207       return QualType();
2208     }
2209     if (ConstVal == 0) {
2210       // GCC accepts zero sized static arrays. We allow them when
2211       // we're not in a SFINAE context.
2212       Diag(ArraySize->getLocStart(),
2213            isSFINAEContext()? diag::err_typecheck_zero_array_size
2214                             : diag::ext_typecheck_zero_array_size)
2215         << ArraySize->getSourceRange();
2216 
2217       if (ASM == ArrayType::Static) {
2218         Diag(ArraySize->getLocStart(),
2219              diag::warn_typecheck_zero_static_array_size)
2220           << ArraySize->getSourceRange();
2221         ASM = ArrayType::Normal;
2222       }
2223     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2224                !T->isIncompleteType() && !T->isUndeducedType()) {
2225       // Is the array too large?
2226       unsigned ActiveSizeBits
2227         = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2228       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2229         Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2230           << ConstVal.toString(10)
2231           << ArraySize->getSourceRange();
2232         return QualType();
2233       }
2234     }
2235 
2236     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2237   }
2238 
2239   // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2240   if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2241     Diag(Loc, diag::err_opencl_vla);
2242     return QualType();
2243   }
2244   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2245   if (!getLangOpts().C99) {
2246     if (T->isVariableArrayType()) {
2247       // Prohibit the use of VLAs during template argument deduction.
2248       if (isSFINAEContext()) {
2249         Diag(Loc, diag::err_vla_in_sfinae);
2250         return QualType();
2251       }
2252       // Just extwarn about VLAs.
2253       else
2254         Diag(Loc, diag::ext_vla);
2255     } else if (ASM != ArrayType::Normal || Quals != 0)
2256       Diag(Loc,
2257            getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2258                                   : diag::ext_c99_array_usage) << ASM;
2259   }
2260 
2261   if (T->isVariableArrayType()) {
2262     // Warn about VLAs for -Wvla.
2263     Diag(Loc, diag::warn_vla_used);
2264   }
2265 
2266   // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2267   // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2268   // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2269   if (getLangOpts().OpenCL) {
2270     const QualType ArrType = Context.getBaseElementType(T);
2271     if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2272         ArrType->isSamplerT() || ArrType->isImageType()) {
2273       Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2274       return QualType();
2275     }
2276   }
2277 
2278   return T;
2279 }
2280 
2281 /// \brief Build an ext-vector type.
2282 ///
2283 /// Run the required checks for the extended vector type.
2284 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2285                                   SourceLocation AttrLoc) {
2286   // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2287   // in conjunction with complex types (pointers, arrays, functions, etc.).
2288   //
2289   // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2290   // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2291   // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2292   // of bool aren't allowed.
2293   if ((!T->isDependentType() && !T->isIntegerType() &&
2294        !T->isRealFloatingType()) ||
2295       T->isBooleanType()) {
2296     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2297     return QualType();
2298   }
2299 
2300   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2301     llvm::APSInt vecSize(32);
2302     if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2303       Diag(AttrLoc, diag::err_attribute_argument_type)
2304         << "ext_vector_type" << AANT_ArgumentIntegerConstant
2305         << ArraySize->getSourceRange();
2306       return QualType();
2307     }
2308 
2309     // Unlike gcc's vector_size attribute, the size is specified as the
2310     // number of elements, not the number of bytes.
2311     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2312 
2313     if (vectorSize == 0) {
2314       Diag(AttrLoc, diag::err_attribute_zero_size)
2315       << ArraySize->getSourceRange();
2316       return QualType();
2317     }
2318 
2319     if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2320       Diag(AttrLoc, diag::err_attribute_size_too_large)
2321         << ArraySize->getSourceRange();
2322       return QualType();
2323     }
2324 
2325     return Context.getExtVectorType(T, vectorSize);
2326   }
2327 
2328   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2329 }
2330 
2331 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2332   if (T->isArrayType() || T->isFunctionType()) {
2333     Diag(Loc, diag::err_func_returning_array_function)
2334       << T->isFunctionType() << T;
2335     return true;
2336   }
2337 
2338   // Functions cannot return half FP.
2339   if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2340     Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2341       FixItHint::CreateInsertion(Loc, "*");
2342     return true;
2343   }
2344 
2345   // Methods cannot return interface types. All ObjC objects are
2346   // passed by reference.
2347   if (T->isObjCObjectType()) {
2348     Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
2349     return 0;
2350   }
2351 
2352   return false;
2353 }
2354 
2355 /// Check the extended parameter information.  Most of the necessary
2356 /// checking should occur when applying the parameter attribute; the
2357 /// only other checks required are positional restrictions.
2358 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2359                     const FunctionProtoType::ExtProtoInfo &EPI,
2360                     llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2361   assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2362 
2363   bool hasCheckedSwiftCall = false;
2364   auto checkForSwiftCC = [&](unsigned paramIndex) {
2365     // Only do this once.
2366     if (hasCheckedSwiftCall) return;
2367     hasCheckedSwiftCall = true;
2368     if (EPI.ExtInfo.getCC() == CC_Swift) return;
2369     S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2370       << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2371   };
2372 
2373   for (size_t paramIndex = 0, numParams = paramTypes.size();
2374           paramIndex != numParams; ++paramIndex) {
2375     switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2376     // Nothing interesting to check for orindary-ABI parameters.
2377     case ParameterABI::Ordinary:
2378       continue;
2379 
2380     // swift_indirect_result parameters must be a prefix of the function
2381     // arguments.
2382     case ParameterABI::SwiftIndirectResult:
2383       checkForSwiftCC(paramIndex);
2384       if (paramIndex != 0 &&
2385           EPI.ExtParameterInfos[paramIndex - 1].getABI()
2386             != ParameterABI::SwiftIndirectResult) {
2387         S.Diag(getParamLoc(paramIndex),
2388                diag::err_swift_indirect_result_not_first);
2389       }
2390       continue;
2391 
2392     // swift_context parameters must be the last parameter except for
2393     // a possible swift_error parameter.
2394     case ParameterABI::SwiftContext:
2395       checkForSwiftCC(paramIndex);
2396       if (!(paramIndex == numParams - 1 ||
2397             (paramIndex == numParams - 2 &&
2398              EPI.ExtParameterInfos[numParams - 1].getABI()
2399                == ParameterABI::SwiftErrorResult))) {
2400         S.Diag(getParamLoc(paramIndex),
2401                diag::err_swift_context_not_before_swift_error_result);
2402       }
2403       continue;
2404 
2405     // swift_error parameters must be the last parameter.
2406     case ParameterABI::SwiftErrorResult:
2407       checkForSwiftCC(paramIndex);
2408       if (paramIndex != numParams - 1) {
2409         S.Diag(getParamLoc(paramIndex),
2410                diag::err_swift_error_result_not_last);
2411       } else if (paramIndex == 0 ||
2412                  EPI.ExtParameterInfos[paramIndex - 1].getABI()
2413                    != ParameterABI::SwiftContext) {
2414         S.Diag(getParamLoc(paramIndex),
2415                diag::err_swift_error_result_not_after_swift_context);
2416       }
2417       continue;
2418     }
2419     llvm_unreachable("bad ABI kind");
2420   }
2421 }
2422 
2423 QualType Sema::BuildFunctionType(QualType T,
2424                                  MutableArrayRef<QualType> ParamTypes,
2425                                  SourceLocation Loc, DeclarationName Entity,
2426                                  const FunctionProtoType::ExtProtoInfo &EPI) {
2427   bool Invalid = false;
2428 
2429   Invalid |= CheckFunctionReturnType(T, Loc);
2430 
2431   for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2432     // FIXME: Loc is too inprecise here, should use proper locations for args.
2433     QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2434     if (ParamType->isVoidType()) {
2435       Diag(Loc, diag::err_param_with_void_type);
2436       Invalid = true;
2437     } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2438       // Disallow half FP arguments.
2439       Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2440         FixItHint::CreateInsertion(Loc, "*");
2441       Invalid = true;
2442     }
2443 
2444     ParamTypes[Idx] = ParamType;
2445   }
2446 
2447   if (EPI.ExtParameterInfos) {
2448     checkExtParameterInfos(*this, ParamTypes, EPI,
2449                            [=](unsigned i) { return Loc; });
2450   }
2451 
2452   if (Invalid)
2453     return QualType();
2454 
2455   return Context.getFunctionType(T, ParamTypes, EPI);
2456 }
2457 
2458 /// \brief Build a member pointer type \c T Class::*.
2459 ///
2460 /// \param T the type to which the member pointer refers.
2461 /// \param Class the class type into which the member pointer points.
2462 /// \param Loc the location where this type begins
2463 /// \param Entity the name of the entity that will have this member pointer type
2464 ///
2465 /// \returns a member pointer type, if successful, or a NULL type if there was
2466 /// an error.
2467 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2468                                       SourceLocation Loc,
2469                                       DeclarationName Entity) {
2470   // Verify that we're not building a pointer to pointer to function with
2471   // exception specification.
2472   if (CheckDistantExceptionSpec(T)) {
2473     Diag(Loc, diag::err_distant_exception_spec);
2474     return QualType();
2475   }
2476 
2477   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2478   //   with reference type, or "cv void."
2479   if (T->isReferenceType()) {
2480     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2481       << getPrintableNameForEntity(Entity) << T;
2482     return QualType();
2483   }
2484 
2485   if (T->isVoidType()) {
2486     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2487       << getPrintableNameForEntity(Entity);
2488     return QualType();
2489   }
2490 
2491   if (!Class->isDependentType() && !Class->isRecordType()) {
2492     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2493     return QualType();
2494   }
2495 
2496   // Adjust the default free function calling convention to the default method
2497   // calling convention.
2498   bool IsCtorOrDtor =
2499       (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2500       (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2501   if (T->isFunctionType())
2502     adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2503 
2504   return Context.getMemberPointerType(T, Class.getTypePtr());
2505 }
2506 
2507 /// \brief Build a block pointer type.
2508 ///
2509 /// \param T The type to which we'll be building a block pointer.
2510 ///
2511 /// \param Loc The source location, used for diagnostics.
2512 ///
2513 /// \param Entity The name of the entity that involves the block pointer
2514 /// type, if known.
2515 ///
2516 /// \returns A suitable block pointer type, if there are no
2517 /// errors. Otherwise, returns a NULL type.
2518 QualType Sema::BuildBlockPointerType(QualType T,
2519                                      SourceLocation Loc,
2520                                      DeclarationName Entity) {
2521   if (!T->isFunctionType()) {
2522     Diag(Loc, diag::err_nonfunction_block_type);
2523     return QualType();
2524   }
2525 
2526   if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2527     return QualType();
2528 
2529   return Context.getBlockPointerType(T);
2530 }
2531 
2532 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2533   QualType QT = Ty.get();
2534   if (QT.isNull()) {
2535     if (TInfo) *TInfo = nullptr;
2536     return QualType();
2537   }
2538 
2539   TypeSourceInfo *DI = nullptr;
2540   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2541     QT = LIT->getType();
2542     DI = LIT->getTypeSourceInfo();
2543   }
2544 
2545   if (TInfo) *TInfo = DI;
2546   return QT;
2547 }
2548 
2549 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2550                                             Qualifiers::ObjCLifetime ownership,
2551                                             unsigned chunkIndex);
2552 
2553 /// Given that this is the declaration of a parameter under ARC,
2554 /// attempt to infer attributes and such for pointer-to-whatever
2555 /// types.
2556 static void inferARCWriteback(TypeProcessingState &state,
2557                               QualType &declSpecType) {
2558   Sema &S = state.getSema();
2559   Declarator &declarator = state.getDeclarator();
2560 
2561   // TODO: should we care about decl qualifiers?
2562 
2563   // Check whether the declarator has the expected form.  We walk
2564   // from the inside out in order to make the block logic work.
2565   unsigned outermostPointerIndex = 0;
2566   bool isBlockPointer = false;
2567   unsigned numPointers = 0;
2568   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2569     unsigned chunkIndex = i;
2570     DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2571     switch (chunk.Kind) {
2572     case DeclaratorChunk::Paren:
2573       // Ignore parens.
2574       break;
2575 
2576     case DeclaratorChunk::Reference:
2577     case DeclaratorChunk::Pointer:
2578       // Count the number of pointers.  Treat references
2579       // interchangeably as pointers; if they're mis-ordered, normal
2580       // type building will discover that.
2581       outermostPointerIndex = chunkIndex;
2582       numPointers++;
2583       break;
2584 
2585     case DeclaratorChunk::BlockPointer:
2586       // If we have a pointer to block pointer, that's an acceptable
2587       // indirect reference; anything else is not an application of
2588       // the rules.
2589       if (numPointers != 1) return;
2590       numPointers++;
2591       outermostPointerIndex = chunkIndex;
2592       isBlockPointer = true;
2593 
2594       // We don't care about pointer structure in return values here.
2595       goto done;
2596 
2597     case DeclaratorChunk::Array: // suppress if written (id[])?
2598     case DeclaratorChunk::Function:
2599     case DeclaratorChunk::MemberPointer:
2600     case DeclaratorChunk::Pipe:
2601       return;
2602     }
2603   }
2604  done:
2605 
2606   // If we have *one* pointer, then we want to throw the qualifier on
2607   // the declaration-specifiers, which means that it needs to be a
2608   // retainable object type.
2609   if (numPointers == 1) {
2610     // If it's not a retainable object type, the rule doesn't apply.
2611     if (!declSpecType->isObjCRetainableType()) return;
2612 
2613     // If it already has lifetime, don't do anything.
2614     if (declSpecType.getObjCLifetime()) return;
2615 
2616     // Otherwise, modify the type in-place.
2617     Qualifiers qs;
2618 
2619     if (declSpecType->isObjCARCImplicitlyUnretainedType())
2620       qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2621     else
2622       qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2623     declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2624 
2625   // If we have *two* pointers, then we want to throw the qualifier on
2626   // the outermost pointer.
2627   } else if (numPointers == 2) {
2628     // If we don't have a block pointer, we need to check whether the
2629     // declaration-specifiers gave us something that will turn into a
2630     // retainable object pointer after we slap the first pointer on it.
2631     if (!isBlockPointer && !declSpecType->isObjCObjectType())
2632       return;
2633 
2634     // Look for an explicit lifetime attribute there.
2635     DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2636     if (chunk.Kind != DeclaratorChunk::Pointer &&
2637         chunk.Kind != DeclaratorChunk::BlockPointer)
2638       return;
2639     for (const AttributeList *attr = chunk.getAttrs(); attr;
2640            attr = attr->getNext())
2641       if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2642         return;
2643 
2644     transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2645                                           outermostPointerIndex);
2646 
2647   // Any other number of pointers/references does not trigger the rule.
2648   } else return;
2649 
2650   // TODO: mark whether we did this inference?
2651 }
2652 
2653 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2654                                      SourceLocation FallbackLoc,
2655                                      SourceLocation ConstQualLoc,
2656                                      SourceLocation VolatileQualLoc,
2657                                      SourceLocation RestrictQualLoc,
2658                                      SourceLocation AtomicQualLoc,
2659                                      SourceLocation UnalignedQualLoc) {
2660   if (!Quals)
2661     return;
2662 
2663   struct Qual {
2664     const char *Name;
2665     unsigned Mask;
2666     SourceLocation Loc;
2667   } const QualKinds[5] = {
2668     { "const", DeclSpec::TQ_const, ConstQualLoc },
2669     { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2670     { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2671     { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2672     { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2673   };
2674 
2675   SmallString<32> QualStr;
2676   unsigned NumQuals = 0;
2677   SourceLocation Loc;
2678   FixItHint FixIts[5];
2679 
2680   // Build a string naming the redundant qualifiers.
2681   for (auto &E : QualKinds) {
2682     if (Quals & E.Mask) {
2683       if (!QualStr.empty()) QualStr += ' ';
2684       QualStr += E.Name;
2685 
2686       // If we have a location for the qualifier, offer a fixit.
2687       SourceLocation QualLoc = E.Loc;
2688       if (QualLoc.isValid()) {
2689         FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2690         if (Loc.isInvalid() ||
2691             getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2692           Loc = QualLoc;
2693       }
2694 
2695       ++NumQuals;
2696     }
2697   }
2698 
2699   Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2700     << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2701 }
2702 
2703 // Diagnose pointless type qualifiers on the return type of a function.
2704 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2705                                                   Declarator &D,
2706                                                   unsigned FunctionChunkIndex) {
2707   if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2708     // FIXME: TypeSourceInfo doesn't preserve location information for
2709     // qualifiers.
2710     S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2711                                 RetTy.getLocalCVRQualifiers(),
2712                                 D.getIdentifierLoc());
2713     return;
2714   }
2715 
2716   for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2717                 End = D.getNumTypeObjects();
2718        OuterChunkIndex != End; ++OuterChunkIndex) {
2719     DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2720     switch (OuterChunk.Kind) {
2721     case DeclaratorChunk::Paren:
2722       continue;
2723 
2724     case DeclaratorChunk::Pointer: {
2725       DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2726       S.diagnoseIgnoredQualifiers(
2727           diag::warn_qual_return_type,
2728           PTI.TypeQuals,
2729           SourceLocation(),
2730           SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2731           SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2732           SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2733           SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2734           SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2735       return;
2736     }
2737 
2738     case DeclaratorChunk::Function:
2739     case DeclaratorChunk::BlockPointer:
2740     case DeclaratorChunk::Reference:
2741     case DeclaratorChunk::Array:
2742     case DeclaratorChunk::MemberPointer:
2743     case DeclaratorChunk::Pipe:
2744       // FIXME: We can't currently provide an accurate source location and a
2745       // fix-it hint for these.
2746       unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2747       S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2748                                   RetTy.getCVRQualifiers() | AtomicQual,
2749                                   D.getIdentifierLoc());
2750       return;
2751     }
2752 
2753     llvm_unreachable("unknown declarator chunk kind");
2754   }
2755 
2756   // If the qualifiers come from a conversion function type, don't diagnose
2757   // them -- they're not necessarily redundant, since such a conversion
2758   // operator can be explicitly called as "x.operator const int()".
2759   if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2760     return;
2761 
2762   // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2763   // which are present there.
2764   S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2765                               D.getDeclSpec().getTypeQualifiers(),
2766                               D.getIdentifierLoc(),
2767                               D.getDeclSpec().getConstSpecLoc(),
2768                               D.getDeclSpec().getVolatileSpecLoc(),
2769                               D.getDeclSpec().getRestrictSpecLoc(),
2770                               D.getDeclSpec().getAtomicSpecLoc(),
2771                               D.getDeclSpec().getUnalignedSpecLoc());
2772 }
2773 
2774 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2775                                              TypeSourceInfo *&ReturnTypeInfo) {
2776   Sema &SemaRef = state.getSema();
2777   Declarator &D = state.getDeclarator();
2778   QualType T;
2779   ReturnTypeInfo = nullptr;
2780 
2781   // The TagDecl owned by the DeclSpec.
2782   TagDecl *OwnedTagDecl = nullptr;
2783 
2784   switch (D.getName().getKind()) {
2785   case UnqualifiedId::IK_ImplicitSelfParam:
2786   case UnqualifiedId::IK_OperatorFunctionId:
2787   case UnqualifiedId::IK_Identifier:
2788   case UnqualifiedId::IK_LiteralOperatorId:
2789   case UnqualifiedId::IK_TemplateId:
2790     T = ConvertDeclSpecToType(state);
2791 
2792     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2793       OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2794       // Owned declaration is embedded in declarator.
2795       OwnedTagDecl->setEmbeddedInDeclarator(true);
2796     }
2797     break;
2798 
2799   case UnqualifiedId::IK_ConstructorName:
2800   case UnqualifiedId::IK_ConstructorTemplateId:
2801   case UnqualifiedId::IK_DestructorName:
2802     // Constructors and destructors don't have return types. Use
2803     // "void" instead.
2804     T = SemaRef.Context.VoidTy;
2805     processTypeAttrs(state, T, TAL_DeclSpec,
2806                      D.getDeclSpec().getAttributes().getList());
2807     break;
2808 
2809   case UnqualifiedId::IK_ConversionFunctionId:
2810     // The result type of a conversion function is the type that it
2811     // converts to.
2812     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2813                                   &ReturnTypeInfo);
2814     break;
2815   }
2816 
2817   if (D.getAttributes())
2818     distributeTypeAttrsFromDeclarator(state, T);
2819 
2820   // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2821   if (D.getDeclSpec().containsPlaceholderType()) {
2822     int Error = -1;
2823 
2824     switch (D.getContext()) {
2825     case Declarator::LambdaExprContext:
2826       llvm_unreachable("Can't specify a type specifier in lambda grammar");
2827     case Declarator::ObjCParameterContext:
2828     case Declarator::ObjCResultContext:
2829     case Declarator::PrototypeContext:
2830       Error = 0;
2831       break;
2832     case Declarator::LambdaExprParameterContext:
2833       // In C++14, generic lambdas allow 'auto' in their parameters.
2834       if (!(SemaRef.getLangOpts().CPlusPlus14
2835               && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2836         Error = 16;
2837       break;
2838     case Declarator::MemberContext: {
2839       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2840           D.isFunctionDeclarator())
2841         break;
2842       bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2843       switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2844       case TTK_Enum: llvm_unreachable("unhandled tag kind");
2845       case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2846       case TTK_Union:  Error = Cxx ? 3 : 4; /* Union member */ break;
2847       case TTK_Class:  Error = 5; /* Class member */ break;
2848       case TTK_Interface: Error = 6; /* Interface member */ break;
2849       }
2850       break;
2851     }
2852     case Declarator::CXXCatchContext:
2853     case Declarator::ObjCCatchContext:
2854       Error = 7; // Exception declaration
2855       break;
2856     case Declarator::TemplateParamContext:
2857       Error = 8; // Template parameter
2858       break;
2859     case Declarator::BlockLiteralContext:
2860       Error = 9; // Block literal
2861       break;
2862     case Declarator::TemplateTypeArgContext:
2863       Error = 10; // Template type argument
2864       break;
2865     case Declarator::AliasDeclContext:
2866     case Declarator::AliasTemplateContext:
2867       Error = 12; // Type alias
2868       break;
2869     case Declarator::TrailingReturnContext:
2870       if (!SemaRef.getLangOpts().CPlusPlus14 ||
2871           D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2872         Error = 13; // Function return type
2873       break;
2874     case Declarator::ConversionIdContext:
2875       if (!SemaRef.getLangOpts().CPlusPlus14 ||
2876           D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2877         Error = 14; // conversion-type-id
2878       break;
2879     case Declarator::TypeNameContext:
2880       Error = 15; // Generic
2881       break;
2882     case Declarator::FileContext:
2883     case Declarator::BlockContext:
2884     case Declarator::ForContext:
2885     case Declarator::ConditionContext:
2886       break;
2887     case Declarator::CXXNewContext:
2888       if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2889         Error = 17; // 'new' type
2890       break;
2891     case Declarator::KNRTypeListContext:
2892       Error = 18; // K&R function parameter
2893       break;
2894     }
2895 
2896     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2897       Error = 11;
2898 
2899     // In Objective-C it is an error to use 'auto' on a function declarator
2900     // (and everywhere for '__auto_type').
2901     if (D.isFunctionDeclarator() &&
2902         (!SemaRef.getLangOpts().CPlusPlus11 ||
2903          D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type))
2904       Error = 13;
2905 
2906     bool HaveTrailing = false;
2907 
2908     // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2909     // contains a trailing return type. That is only legal at the outermost
2910     // level. Check all declarator chunks (outermost first) anyway, to give
2911     // better diagnostics.
2912     // We don't support '__auto_type' with trailing return types.
2913     if (SemaRef.getLangOpts().CPlusPlus11 &&
2914         D.getDeclSpec().getTypeSpecType() != DeclSpec::TST_auto_type) {
2915       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2916         unsigned chunkIndex = e - i - 1;
2917         state.setCurrentChunkIndex(chunkIndex);
2918         DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2919         if (DeclType.Kind == DeclaratorChunk::Function) {
2920           const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2921           if (FTI.hasTrailingReturnType()) {
2922             HaveTrailing = true;
2923             Error = -1;
2924             break;
2925           }
2926         }
2927       }
2928     }
2929 
2930     SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2931     if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2932       AutoRange = D.getName().getSourceRange();
2933 
2934     if (Error != -1) {
2935       unsigned Keyword;
2936       switch (D.getDeclSpec().getTypeSpecType()) {
2937       case DeclSpec::TST_auto: Keyword = 0; break;
2938       case DeclSpec::TST_decltype_auto: Keyword = 1; break;
2939       case DeclSpec::TST_auto_type: Keyword = 2; break;
2940       default: llvm_unreachable("unknown auto TypeSpecType");
2941       }
2942       SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2943         << Keyword << Error << AutoRange;
2944       T = SemaRef.Context.IntTy;
2945       D.setInvalidType(true);
2946     } else if (!HaveTrailing) {
2947       // If there was a trailing return type, we already got
2948       // warn_cxx98_compat_trailing_return_type in the parser.
2949       SemaRef.Diag(AutoRange.getBegin(),
2950                    diag::warn_cxx98_compat_auto_type_specifier)
2951         << AutoRange;
2952     }
2953   }
2954 
2955   if (SemaRef.getLangOpts().CPlusPlus &&
2956       OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2957     // Check the contexts where C++ forbids the declaration of a new class
2958     // or enumeration in a type-specifier-seq.
2959     unsigned DiagID = 0;
2960     switch (D.getContext()) {
2961     case Declarator::TrailingReturnContext:
2962       // Class and enumeration definitions are syntactically not allowed in
2963       // trailing return types.
2964       llvm_unreachable("parser should not have allowed this");
2965       break;
2966     case Declarator::FileContext:
2967     case Declarator::MemberContext:
2968     case Declarator::BlockContext:
2969     case Declarator::ForContext:
2970     case Declarator::BlockLiteralContext:
2971     case Declarator::LambdaExprContext:
2972       // C++11 [dcl.type]p3:
2973       //   A type-specifier-seq shall not define a class or enumeration unless
2974       //   it appears in the type-id of an alias-declaration (7.1.3) that is not
2975       //   the declaration of a template-declaration.
2976     case Declarator::AliasDeclContext:
2977       break;
2978     case Declarator::AliasTemplateContext:
2979       DiagID = diag::err_type_defined_in_alias_template;
2980       break;
2981     case Declarator::TypeNameContext:
2982     case Declarator::ConversionIdContext:
2983     case Declarator::TemplateParamContext:
2984     case Declarator::CXXNewContext:
2985     case Declarator::CXXCatchContext:
2986     case Declarator::ObjCCatchContext:
2987     case Declarator::TemplateTypeArgContext:
2988       DiagID = diag::err_type_defined_in_type_specifier;
2989       break;
2990     case Declarator::PrototypeContext:
2991     case Declarator::LambdaExprParameterContext:
2992     case Declarator::ObjCParameterContext:
2993     case Declarator::ObjCResultContext:
2994     case Declarator::KNRTypeListContext:
2995       // C++ [dcl.fct]p6:
2996       //   Types shall not be defined in return or parameter types.
2997       DiagID = diag::err_type_defined_in_param_type;
2998       break;
2999     case Declarator::ConditionContext:
3000       // C++ 6.4p2:
3001       // The type-specifier-seq shall not contain typedef and shall not declare
3002       // a new class or enumeration.
3003       DiagID = diag::err_type_defined_in_condition;
3004       break;
3005     }
3006 
3007     if (DiagID != 0) {
3008       SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3009           << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3010       D.setInvalidType(true);
3011     }
3012   }
3013 
3014   assert(!T.isNull() && "This function should not return a null type");
3015   return T;
3016 }
3017 
3018 /// Produce an appropriate diagnostic for an ambiguity between a function
3019 /// declarator and a C++ direct-initializer.
3020 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3021                                        DeclaratorChunk &DeclType, QualType RT) {
3022   const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3023   assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3024 
3025   // If the return type is void there is no ambiguity.
3026   if (RT->isVoidType())
3027     return;
3028 
3029   // An initializer for a non-class type can have at most one argument.
3030   if (!RT->isRecordType() && FTI.NumParams > 1)
3031     return;
3032 
3033   // An initializer for a reference must have exactly one argument.
3034   if (RT->isReferenceType() && FTI.NumParams != 1)
3035     return;
3036 
3037   // Only warn if this declarator is declaring a function at block scope, and
3038   // doesn't have a storage class (such as 'extern') specified.
3039   if (!D.isFunctionDeclarator() ||
3040       D.getFunctionDefinitionKind() != FDK_Declaration ||
3041       !S.CurContext->isFunctionOrMethod() ||
3042       D.getDeclSpec().getStorageClassSpec()
3043         != DeclSpec::SCS_unspecified)
3044     return;
3045 
3046   // Inside a condition, a direct initializer is not permitted. We allow one to
3047   // be parsed in order to give better diagnostics in condition parsing.
3048   if (D.getContext() == Declarator::ConditionContext)
3049     return;
3050 
3051   SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3052 
3053   S.Diag(DeclType.Loc,
3054          FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3055                        : diag::warn_empty_parens_are_function_decl)
3056       << ParenRange;
3057 
3058   // If the declaration looks like:
3059   //   T var1,
3060   //   f();
3061   // and name lookup finds a function named 'f', then the ',' was
3062   // probably intended to be a ';'.
3063   if (!D.isFirstDeclarator() && D.getIdentifier()) {
3064     FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3065     FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3066     if (Comma.getFileID() != Name.getFileID() ||
3067         Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3068       LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3069                           Sema::LookupOrdinaryName);
3070       if (S.LookupName(Result, S.getCurScope()))
3071         S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3072           << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3073           << D.getIdentifier();
3074     }
3075   }
3076 
3077   if (FTI.NumParams > 0) {
3078     // For a declaration with parameters, eg. "T var(T());", suggest adding
3079     // parens around the first parameter to turn the declaration into a
3080     // variable declaration.
3081     SourceRange Range = FTI.Params[0].Param->getSourceRange();
3082     SourceLocation B = Range.getBegin();
3083     SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3084     // FIXME: Maybe we should suggest adding braces instead of parens
3085     // in C++11 for classes that don't have an initializer_list constructor.
3086     S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3087       << FixItHint::CreateInsertion(B, "(")
3088       << FixItHint::CreateInsertion(E, ")");
3089   } else {
3090     // For a declaration without parameters, eg. "T var();", suggest replacing
3091     // the parens with an initializer to turn the declaration into a variable
3092     // declaration.
3093     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3094 
3095     // Empty parens mean value-initialization, and no parens mean
3096     // default initialization. These are equivalent if the default
3097     // constructor is user-provided or if zero-initialization is a
3098     // no-op.
3099     if (RD && RD->hasDefinition() &&
3100         (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3101       S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3102         << FixItHint::CreateRemoval(ParenRange);
3103     else {
3104       std::string Init =
3105           S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3106       if (Init.empty() && S.LangOpts.CPlusPlus11)
3107         Init = "{}";
3108       if (!Init.empty())
3109         S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3110           << FixItHint::CreateReplacement(ParenRange, Init);
3111     }
3112   }
3113 }
3114 
3115 /// Helper for figuring out the default CC for a function declarator type.  If
3116 /// this is the outermost chunk, then we can determine the CC from the
3117 /// declarator context.  If not, then this could be either a member function
3118 /// type or normal function type.
3119 static CallingConv
3120 getCCForDeclaratorChunk(Sema &S, Declarator &D,
3121                         const DeclaratorChunk::FunctionTypeInfo &FTI,
3122                         unsigned ChunkIndex) {
3123   assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3124 
3125   // Check for an explicit CC attribute.
3126   for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3127     switch (Attr->getKind()) {
3128     CALLING_CONV_ATTRS_CASELIST: {
3129       // Ignore attributes that don't validate or can't apply to the
3130       // function type.  We'll diagnose the failure to apply them in
3131       // handleFunctionTypeAttr.
3132       CallingConv CC;
3133       if (!S.CheckCallingConvAttr(*Attr, CC) &&
3134           (!FTI.isVariadic || supportsVariadicCall(CC))) {
3135         return CC;
3136       }
3137       break;
3138     }
3139 
3140     default:
3141       break;
3142     }
3143   }
3144 
3145   bool IsCXXInstanceMethod = false;
3146 
3147   if (S.getLangOpts().CPlusPlus) {
3148     // Look inwards through parentheses to see if this chunk will form a
3149     // member pointer type or if we're the declarator.  Any type attributes
3150     // between here and there will override the CC we choose here.
3151     unsigned I = ChunkIndex;
3152     bool FoundNonParen = false;
3153     while (I && !FoundNonParen) {
3154       --I;
3155       if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3156         FoundNonParen = true;
3157     }
3158 
3159     if (FoundNonParen) {
3160       // If we're not the declarator, we're a regular function type unless we're
3161       // in a member pointer.
3162       IsCXXInstanceMethod =
3163           D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3164     } else if (D.getContext() == Declarator::LambdaExprContext) {
3165       // This can only be a call operator for a lambda, which is an instance
3166       // method.
3167       IsCXXInstanceMethod = true;
3168     } else {
3169       // We're the innermost decl chunk, so must be a function declarator.
3170       assert(D.isFunctionDeclarator());
3171 
3172       // If we're inside a record, we're declaring a method, but it could be
3173       // explicitly or implicitly static.
3174       IsCXXInstanceMethod =
3175           D.isFirstDeclarationOfMember() &&
3176           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3177           !D.isStaticMember();
3178     }
3179   }
3180 
3181   CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3182                                                          IsCXXInstanceMethod);
3183 
3184   // Attribute AT_OpenCLKernel affects the calling convention only on
3185   // the SPIR target, hence it cannot be treated as a calling
3186   // convention attribute. This is the simplest place to infer
3187   // "spir_kernel" for OpenCL kernels on SPIR.
3188   if (CC == CC_SpirFunction) {
3189     for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3190          Attr; Attr = Attr->getNext()) {
3191       if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3192         CC = CC_SpirKernel;
3193         break;
3194       }
3195     }
3196   }
3197 
3198   return CC;
3199 }
3200 
3201 namespace {
3202   /// A simple notion of pointer kinds, which matches up with the various
3203   /// pointer declarators.
3204   enum class SimplePointerKind {
3205     Pointer,
3206     BlockPointer,
3207     MemberPointer,
3208   };
3209 } // end anonymous namespace
3210 
3211 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3212   switch (nullability) {
3213   case NullabilityKind::NonNull:
3214     if (!Ident__Nonnull)
3215       Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3216     return Ident__Nonnull;
3217 
3218   case NullabilityKind::Nullable:
3219     if (!Ident__Nullable)
3220       Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3221     return Ident__Nullable;
3222 
3223   case NullabilityKind::Unspecified:
3224     if (!Ident__Null_unspecified)
3225       Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3226     return Ident__Null_unspecified;
3227   }
3228   llvm_unreachable("Unknown nullability kind.");
3229 }
3230 
3231 /// Retrieve the identifier "NSError".
3232 IdentifierInfo *Sema::getNSErrorIdent() {
3233   if (!Ident_NSError)
3234     Ident_NSError = PP.getIdentifierInfo("NSError");
3235 
3236   return Ident_NSError;
3237 }
3238 
3239 /// Check whether there is a nullability attribute of any kind in the given
3240 /// attribute list.
3241 static bool hasNullabilityAttr(const AttributeList *attrs) {
3242   for (const AttributeList *attr = attrs; attr;
3243        attr = attr->getNext()) {
3244     if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3245         attr->getKind() == AttributeList::AT_TypeNullable ||
3246         attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3247       return true;
3248   }
3249 
3250   return false;
3251 }
3252 
3253 namespace {
3254   /// Describes the kind of a pointer a declarator describes.
3255   enum class PointerDeclaratorKind {
3256     // Not a pointer.
3257     NonPointer,
3258     // Single-level pointer.
3259     SingleLevelPointer,
3260     // Multi-level pointer (of any pointer kind).
3261     MultiLevelPointer,
3262     // CFFooRef*
3263     MaybePointerToCFRef,
3264     // CFErrorRef*
3265     CFErrorRefPointer,
3266     // NSError**
3267     NSErrorPointerPointer,
3268   };
3269 } // end anonymous namespace
3270 
3271 /// Classify the given declarator, whose type-specified is \c type, based on
3272 /// what kind of pointer it refers to.
3273 ///
3274 /// This is used to determine the default nullability.
3275 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S,
3276                                                        QualType type,
3277                                                        Declarator &declarator) {
3278   unsigned numNormalPointers = 0;
3279 
3280   // For any dependent type, we consider it a non-pointer.
3281   if (type->isDependentType())
3282     return PointerDeclaratorKind::NonPointer;
3283 
3284   // Look through the declarator chunks to identify pointers.
3285   for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3286     DeclaratorChunk &chunk = declarator.getTypeObject(i);
3287     switch (chunk.Kind) {
3288     case DeclaratorChunk::Array:
3289     case DeclaratorChunk::Function:
3290     case DeclaratorChunk::Pipe:
3291       break;
3292 
3293     case DeclaratorChunk::BlockPointer:
3294     case DeclaratorChunk::MemberPointer:
3295       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3296                                    : PointerDeclaratorKind::SingleLevelPointer;
3297 
3298     case DeclaratorChunk::Paren:
3299     case DeclaratorChunk::Reference:
3300       continue;
3301 
3302     case DeclaratorChunk::Pointer:
3303       ++numNormalPointers;
3304       if (numNormalPointers > 2)
3305         return PointerDeclaratorKind::MultiLevelPointer;
3306       continue;
3307     }
3308   }
3309 
3310   // Then, dig into the type specifier itself.
3311   unsigned numTypeSpecifierPointers = 0;
3312   do {
3313     // Decompose normal pointers.
3314     if (auto ptrType = type->getAs<PointerType>()) {
3315       ++numNormalPointers;
3316 
3317       if (numNormalPointers > 2)
3318         return PointerDeclaratorKind::MultiLevelPointer;
3319 
3320       type = ptrType->getPointeeType();
3321       ++numTypeSpecifierPointers;
3322       continue;
3323     }
3324 
3325     // Decompose block pointers.
3326     if (type->getAs<BlockPointerType>()) {
3327       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3328                                    : PointerDeclaratorKind::SingleLevelPointer;
3329     }
3330 
3331     // Decompose member pointers.
3332     if (type->getAs<MemberPointerType>()) {
3333       return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3334                                    : PointerDeclaratorKind::SingleLevelPointer;
3335     }
3336 
3337     // Look at Objective-C object pointers.
3338     if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3339       ++numNormalPointers;
3340       ++numTypeSpecifierPointers;
3341 
3342       // If this is NSError**, report that.
3343       if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3344         if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3345             numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3346           return PointerDeclaratorKind::NSErrorPointerPointer;
3347         }
3348       }
3349 
3350       break;
3351     }
3352 
3353     // Look at Objective-C class types.
3354     if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3355       if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3356         if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3357           return PointerDeclaratorKind::NSErrorPointerPointer;;
3358       }
3359 
3360       break;
3361     }
3362 
3363     // If at this point we haven't seen a pointer, we won't see one.
3364     if (numNormalPointers == 0)
3365       return PointerDeclaratorKind::NonPointer;
3366 
3367     if (auto recordType = type->getAs<RecordType>()) {
3368       RecordDecl *recordDecl = recordType->getDecl();
3369 
3370       bool isCFError = false;
3371       if (S.CFError) {
3372         // If we already know about CFError, test it directly.
3373         isCFError = (S.CFError == recordDecl);
3374       } else {
3375         // Check whether this is CFError, which we identify based on its bridge
3376         // to NSError.
3377         if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3378           if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3379             if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3380               S.CFError = recordDecl;
3381               isCFError = true;
3382             }
3383           }
3384         }
3385       }
3386 
3387       // If this is CFErrorRef*, report it as such.
3388       if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3389         return PointerDeclaratorKind::CFErrorRefPointer;
3390       }
3391       break;
3392     }
3393 
3394     break;
3395   } while (true);
3396 
3397   switch (numNormalPointers) {
3398   case 0:
3399     return PointerDeclaratorKind::NonPointer;
3400 
3401   case 1:
3402     return PointerDeclaratorKind::SingleLevelPointer;
3403 
3404   case 2:
3405     return PointerDeclaratorKind::MaybePointerToCFRef;
3406 
3407   default:
3408     return PointerDeclaratorKind::MultiLevelPointer;
3409   }
3410 }
3411 
3412 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3413                                                     SourceLocation loc) {
3414   // If we're anywhere in a function, method, or closure context, don't perform
3415   // completeness checks.
3416   for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3417     if (ctx->isFunctionOrMethod())
3418       return FileID();
3419 
3420     if (ctx->isFileContext())
3421       break;
3422   }
3423 
3424   // We only care about the expansion location.
3425   loc = S.SourceMgr.getExpansionLoc(loc);
3426   FileID file = S.SourceMgr.getFileID(loc);
3427   if (file.isInvalid())
3428     return FileID();
3429 
3430   // Retrieve file information.
3431   bool invalid = false;
3432   const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3433   if (invalid || !sloc.isFile())
3434     return FileID();
3435 
3436   // We don't want to perform completeness checks on the main file or in
3437   // system headers.
3438   const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3439   if (fileInfo.getIncludeLoc().isInvalid())
3440     return FileID();
3441   if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3442       S.Diags.getSuppressSystemWarnings()) {
3443     return FileID();
3444   }
3445 
3446   return file;
3447 }
3448 
3449 /// Check for consistent use of nullability.
3450 static void checkNullabilityConsistency(TypeProcessingState &state,
3451                                         SimplePointerKind pointerKind,
3452                                         SourceLocation pointerLoc) {
3453   Sema &S = state.getSema();
3454 
3455   // Determine which file we're performing consistency checking for.
3456   FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3457   if (file.isInvalid())
3458     return;
3459 
3460   // If we haven't seen any type nullability in this file, we won't warn now
3461   // about anything.
3462   FileNullability &fileNullability = S.NullabilityMap[file];
3463   if (!fileNullability.SawTypeNullability) {
3464     // If this is the first pointer declarator in the file, record it.
3465     if (fileNullability.PointerLoc.isInvalid() &&
3466         !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing,
3467                                               pointerLoc)) {
3468       fileNullability.PointerLoc = pointerLoc;
3469       fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3470     }
3471 
3472     return;
3473   }
3474 
3475   // Complain about missing nullability.
3476   S.Diag(pointerLoc, diag::warn_nullability_missing)
3477     << static_cast<unsigned>(pointerKind);
3478 }
3479 
3480 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3481                                                 QualType declSpecType,
3482                                                 TypeSourceInfo *TInfo) {
3483   // The TypeSourceInfo that this function returns will not be a null type.
3484   // If there is an error, this function will fill in a dummy type as fallback.
3485   QualType T = declSpecType;
3486   Declarator &D = state.getDeclarator();
3487   Sema &S = state.getSema();
3488   ASTContext &Context = S.Context;
3489   const LangOptions &LangOpts = S.getLangOpts();
3490 
3491   // The name we're declaring, if any.
3492   DeclarationName Name;
3493   if (D.getIdentifier())
3494     Name = D.getIdentifier();
3495 
3496   // Does this declaration declare a typedef-name?
3497   bool IsTypedefName =
3498     D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3499     D.getContext() == Declarator::AliasDeclContext ||
3500     D.getContext() == Declarator::AliasTemplateContext;
3501 
3502   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3503   bool IsQualifiedFunction = T->isFunctionProtoType() &&
3504       (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3505        T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3506 
3507   // If T is 'decltype(auto)', the only declarators we can have are parens
3508   // and at most one function declarator if this is a function declaration.
3509   if (const AutoType *AT = T->getAs<AutoType>()) {
3510     if (AT->isDecltypeAuto()) {
3511       for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3512         unsigned Index = E - I - 1;
3513         DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3514         unsigned DiagId = diag::err_decltype_auto_compound_type;
3515         unsigned DiagKind = 0;
3516         switch (DeclChunk.Kind) {
3517         case DeclaratorChunk::Paren:
3518           continue;
3519         case DeclaratorChunk::Function: {
3520           unsigned FnIndex;
3521           if (D.isFunctionDeclarationContext() &&
3522               D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3523             continue;
3524           DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3525           break;
3526         }
3527         case DeclaratorChunk::Pointer:
3528         case DeclaratorChunk::BlockPointer:
3529         case DeclaratorChunk::MemberPointer:
3530           DiagKind = 0;
3531           break;
3532         case DeclaratorChunk::Reference:
3533           DiagKind = 1;
3534           break;
3535         case DeclaratorChunk::Array:
3536           DiagKind = 2;
3537           break;
3538         case DeclaratorChunk::Pipe:
3539           break;
3540         }
3541 
3542         S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3543         D.setInvalidType(true);
3544         break;
3545       }
3546     }
3547   }
3548 
3549   // Determine whether we should infer _Nonnull on pointer types.
3550   Optional<NullabilityKind> inferNullability;
3551   bool inferNullabilityCS = false;
3552   bool inferNullabilityInnerOnly = false;
3553   bool inferNullabilityInnerOnlyComplete = false;
3554 
3555   // Are we in an assume-nonnull region?
3556   bool inAssumeNonNullRegion = false;
3557   if (S.PP.getPragmaAssumeNonNullLoc().isValid()) {
3558     inAssumeNonNullRegion = true;
3559     // Determine which file we saw the assume-nonnull region in.
3560     FileID file = getNullabilityCompletenessCheckFileID(
3561                     S, S.PP.getPragmaAssumeNonNullLoc());
3562     if (file.isValid()) {
3563       FileNullability &fileNullability = S.NullabilityMap[file];
3564 
3565       // If we haven't seen any type nullability before, now we have.
3566       if (!fileNullability.SawTypeNullability) {
3567         if (fileNullability.PointerLoc.isValid()) {
3568           S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
3569             << static_cast<unsigned>(fileNullability.PointerKind);
3570         }
3571 
3572         fileNullability.SawTypeNullability = true;
3573       }
3574     }
3575   }
3576 
3577   // Whether to complain about missing nullability specifiers or not.
3578   enum {
3579     /// Never complain.
3580     CAMN_No,
3581     /// Complain on the inner pointers (but not the outermost
3582     /// pointer).
3583     CAMN_InnerPointers,
3584     /// Complain about any pointers that don't have nullability
3585     /// specified or inferred.
3586     CAMN_Yes
3587   } complainAboutMissingNullability = CAMN_No;
3588   unsigned NumPointersRemaining = 0;
3589 
3590   if (IsTypedefName) {
3591     // For typedefs, we do not infer any nullability (the default),
3592     // and we only complain about missing nullability specifiers on
3593     // inner pointers.
3594     complainAboutMissingNullability = CAMN_InnerPointers;
3595 
3596     if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3597       ++NumPointersRemaining;
3598     }
3599 
3600     for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3601       DeclaratorChunk &chunk = D.getTypeObject(i);
3602       switch (chunk.Kind) {
3603       case DeclaratorChunk::Array:
3604       case DeclaratorChunk::Function:
3605       case DeclaratorChunk::Pipe:
3606         break;
3607 
3608       case DeclaratorChunk::BlockPointer:
3609       case DeclaratorChunk::MemberPointer:
3610         ++NumPointersRemaining;
3611         break;
3612 
3613       case DeclaratorChunk::Paren:
3614       case DeclaratorChunk::Reference:
3615         continue;
3616 
3617       case DeclaratorChunk::Pointer:
3618         ++NumPointersRemaining;
3619         continue;
3620       }
3621     }
3622   } else {
3623     bool isFunctionOrMethod = false;
3624     switch (auto context = state.getDeclarator().getContext()) {
3625     case Declarator::ObjCParameterContext:
3626     case Declarator::ObjCResultContext:
3627     case Declarator::PrototypeContext:
3628     case Declarator::TrailingReturnContext:
3629       isFunctionOrMethod = true;
3630       // fallthrough
3631 
3632     case Declarator::MemberContext:
3633       if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3634         complainAboutMissingNullability = CAMN_No;
3635         break;
3636       }
3637 
3638       // Weak properties are inferred to be nullable.
3639       if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3640         inferNullability = NullabilityKind::Nullable;
3641         break;
3642       }
3643 
3644       // fallthrough
3645 
3646     case Declarator::FileContext:
3647     case Declarator::KNRTypeListContext:
3648       complainAboutMissingNullability = CAMN_Yes;
3649 
3650       // Nullability inference depends on the type and declarator.
3651       switch (classifyPointerDeclarator(S, T, D)) {
3652       case PointerDeclaratorKind::NonPointer:
3653       case PointerDeclaratorKind::MultiLevelPointer:
3654         // Cannot infer nullability.
3655         break;
3656 
3657       case PointerDeclaratorKind::SingleLevelPointer:
3658         // Infer _Nonnull if we are in an assumes-nonnull region.
3659         if (inAssumeNonNullRegion) {
3660           inferNullability = NullabilityKind::NonNull;
3661           inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3662                                 context == Declarator::ObjCResultContext);
3663         }
3664         break;
3665 
3666       case PointerDeclaratorKind::CFErrorRefPointer:
3667       case PointerDeclaratorKind::NSErrorPointerPointer:
3668         // Within a function or method signature, infer _Nullable at both
3669         // levels.
3670         if (isFunctionOrMethod && inAssumeNonNullRegion)
3671           inferNullability = NullabilityKind::Nullable;
3672         break;
3673 
3674       case PointerDeclaratorKind::MaybePointerToCFRef:
3675         if (isFunctionOrMethod) {
3676           // On pointer-to-pointer parameters marked cf_returns_retained or
3677           // cf_returns_not_retained, if the outer pointer is explicit then
3678           // infer the inner pointer as _Nullable.
3679           auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3680             while (NextAttr) {
3681               if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3682                   NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3683                 return true;
3684               NextAttr = NextAttr->getNext();
3685             }
3686             return false;
3687           };
3688           if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3689             if (hasCFReturnsAttr(D.getAttributes()) ||
3690                 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3691                 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3692               inferNullability = NullabilityKind::Nullable;
3693               inferNullabilityInnerOnly = true;
3694             }
3695           }
3696         }
3697         break;
3698       }
3699       break;
3700 
3701     case Declarator::ConversionIdContext:
3702       complainAboutMissingNullability = CAMN_Yes;
3703       break;
3704 
3705     case Declarator::AliasDeclContext:
3706     case Declarator::AliasTemplateContext:
3707     case Declarator::BlockContext:
3708     case Declarator::BlockLiteralContext:
3709     case Declarator::ConditionContext:
3710     case Declarator::CXXCatchContext:
3711     case Declarator::CXXNewContext:
3712     case Declarator::ForContext:
3713     case Declarator::LambdaExprContext:
3714     case Declarator::LambdaExprParameterContext:
3715     case Declarator::ObjCCatchContext:
3716     case Declarator::TemplateParamContext:
3717     case Declarator::TemplateTypeArgContext:
3718     case Declarator::TypeNameContext:
3719       // Don't infer in these contexts.
3720       break;
3721     }
3722   }
3723 
3724   // Local function that checks the nullability for a given pointer declarator.
3725   // Returns true if _Nonnull was inferred.
3726   auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3727                                      SourceLocation pointerLoc,
3728                                      AttributeList *&attrs) -> AttributeList * {
3729     // We've seen a pointer.
3730     if (NumPointersRemaining > 0)
3731       --NumPointersRemaining;
3732 
3733     // If a nullability attribute is present, there's nothing to do.
3734     if (hasNullabilityAttr(attrs))
3735       return nullptr;
3736 
3737     // If we're supposed to infer nullability, do so now.
3738     if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3739       AttributeList::Syntax syntax
3740         = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3741                              : AttributeList::AS_Keyword;
3742       AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3743                                          .create(
3744                                            S.getNullabilityKeyword(
3745                                              *inferNullability),
3746                                            SourceRange(pointerLoc),
3747                                            nullptr, SourceLocation(),
3748                                            nullptr, 0, syntax);
3749 
3750       spliceAttrIntoList(*nullabilityAttr, attrs);
3751 
3752       if (inferNullabilityCS) {
3753         state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3754           ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3755       }
3756 
3757       if (inferNullabilityInnerOnly)
3758         inferNullabilityInnerOnlyComplete = true;
3759       return nullabilityAttr;
3760     }
3761 
3762     // If we're supposed to complain about missing nullability, do so
3763     // now if it's truly missing.
3764     switch (complainAboutMissingNullability) {
3765     case CAMN_No:
3766       break;
3767 
3768     case CAMN_InnerPointers:
3769       if (NumPointersRemaining == 0)
3770         break;
3771       // Fallthrough.
3772 
3773     case CAMN_Yes:
3774       checkNullabilityConsistency(state, pointerKind, pointerLoc);
3775     }
3776     return nullptr;
3777   };
3778 
3779   // If the type itself could have nullability but does not, infer pointer
3780   // nullability and perform consistency checking.
3781   if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() &&
3782       !T->getNullability(S.Context)) {
3783     SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3784     if (T->isBlockPointerType())
3785       pointerKind = SimplePointerKind::BlockPointer;
3786     else if (T->isMemberPointerType())
3787       pointerKind = SimplePointerKind::MemberPointer;
3788 
3789     if (auto *attr = inferPointerNullability(
3790                        pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3791                        D.getMutableDeclSpec().getAttributes().getListRef())) {
3792       T = Context.getAttributedType(
3793             AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
3794       attr->setUsedAsTypeAttr();
3795     }
3796   }
3797 
3798   // Walk the DeclTypeInfo, building the recursive type as we go.
3799   // DeclTypeInfos are ordered from the identifier out, which is
3800   // opposite of what we want :).
3801   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3802     unsigned chunkIndex = e - i - 1;
3803     state.setCurrentChunkIndex(chunkIndex);
3804     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3805     IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3806     switch (DeclType.Kind) {
3807     case DeclaratorChunk::Paren:
3808       T = S.BuildParenType(T);
3809       break;
3810     case DeclaratorChunk::BlockPointer:
3811       // If blocks are disabled, emit an error.
3812       if (!LangOpts.Blocks)
3813         S.Diag(DeclType.Loc, diag::err_blocks_disable);
3814 
3815       // Handle pointer nullability.
3816       inferPointerNullability(SimplePointerKind::BlockPointer,
3817                               DeclType.Loc, DeclType.getAttrListRef());
3818 
3819       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
3820       if (DeclType.Cls.TypeQuals)
3821         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3822       break;
3823     case DeclaratorChunk::Pointer:
3824       // Verify that we're not building a pointer to pointer to function with
3825       // exception specification.
3826       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3827         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3828         D.setInvalidType(true);
3829         // Build the type anyway.
3830       }
3831 
3832       // Handle pointer nullability
3833       inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3834                               DeclType.getAttrListRef());
3835 
3836       if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
3837         T = Context.getObjCObjectPointerType(T);
3838         if (DeclType.Ptr.TypeQuals)
3839           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3840         break;
3841       }
3842       T = S.BuildPointerType(T, DeclType.Loc, Name);
3843       if (DeclType.Ptr.TypeQuals)
3844         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3845       break;
3846     case DeclaratorChunk::Reference: {
3847       // Verify that we're not building a reference to pointer to function with
3848       // exception specification.
3849       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3850         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3851         D.setInvalidType(true);
3852         // Build the type anyway.
3853       }
3854       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
3855 
3856       if (DeclType.Ref.HasRestrict)
3857         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
3858       break;
3859     }
3860     case DeclaratorChunk::Array: {
3861       // Verify that we're not building an array of pointers to function with
3862       // exception specification.
3863       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3864         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3865         D.setInvalidType(true);
3866         // Build the type anyway.
3867       }
3868       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
3869       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
3870       ArrayType::ArraySizeModifier ASM;
3871       if (ATI.isStar)
3872         ASM = ArrayType::Star;
3873       else if (ATI.hasStatic)
3874         ASM = ArrayType::Static;
3875       else
3876         ASM = ArrayType::Normal;
3877       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
3878         // FIXME: This check isn't quite right: it allows star in prototypes
3879         // for function definitions, and disallows some edge cases detailed
3880         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
3881         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
3882         ASM = ArrayType::Normal;
3883         D.setInvalidType(true);
3884       }
3885 
3886       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
3887       // shall appear only in a declaration of a function parameter with an
3888       // array type, ...
3889       if (ASM == ArrayType::Static || ATI.TypeQuals) {
3890         if (!(D.isPrototypeContext() ||
3891               D.getContext() == Declarator::KNRTypeListContext)) {
3892           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
3893               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3894           // Remove the 'static' and the type qualifiers.
3895           if (ASM == ArrayType::Static)
3896             ASM = ArrayType::Normal;
3897           ATI.TypeQuals = 0;
3898           D.setInvalidType(true);
3899         }
3900 
3901         // C99 6.7.5.2p1: ... and then only in the outermost array type
3902         // derivation.
3903         unsigned x = chunkIndex;
3904         while (x != 0) {
3905           // Walk outwards along the declarator chunks.
3906           x--;
3907           const DeclaratorChunk &DC = D.getTypeObject(x);
3908           switch (DC.Kind) {
3909           case DeclaratorChunk::Paren:
3910             continue;
3911           case DeclaratorChunk::Array:
3912           case DeclaratorChunk::Pointer:
3913           case DeclaratorChunk::Reference:
3914           case DeclaratorChunk::MemberPointer:
3915             S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
3916               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3917             if (ASM == ArrayType::Static)
3918               ASM = ArrayType::Normal;
3919             ATI.TypeQuals = 0;
3920             D.setInvalidType(true);
3921             break;
3922           case DeclaratorChunk::Function:
3923           case DeclaratorChunk::BlockPointer:
3924           case DeclaratorChunk::Pipe:
3925             // These are invalid anyway, so just ignore.
3926             break;
3927           }
3928         }
3929       }
3930       const AutoType *AT = T->getContainedAutoType();
3931       // Allow arrays of auto if we are a generic lambda parameter.
3932       // i.e. [](auto (&array)[5]) { return array[0]; }; OK
3933       if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
3934         // We've already diagnosed this for decltype(auto).
3935         if (!AT->isDecltypeAuto())
3936           S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
3937             << getPrintableNameForEntity(Name) << T;
3938         T = QualType();
3939         break;
3940       }
3941 
3942       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
3943                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
3944       break;
3945     }
3946     case DeclaratorChunk::Function: {
3947       // If the function declarator has a prototype (i.e. it is not () and
3948       // does not have a K&R-style identifier list), then the arguments are part
3949       // of the type, otherwise the argument list is ().
3950       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3951       IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
3952 
3953       // Check for auto functions and trailing return type and adjust the
3954       // return type accordingly.
3955       if (!D.isInvalidType()) {
3956         // trailing-return-type is only required if we're declaring a function,
3957         // and not, for instance, a pointer to a function.
3958         if (D.getDeclSpec().containsPlaceholderType() &&
3959             !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
3960             !S.getLangOpts().CPlusPlus14) {
3961           S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3962                  D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
3963                      ? diag::err_auto_missing_trailing_return
3964                      : diag::err_deduced_return_type);
3965           T = Context.IntTy;
3966           D.setInvalidType(true);
3967         } else if (FTI.hasTrailingReturnType()) {
3968           // T must be exactly 'auto' at this point. See CWG issue 681.
3969           if (isa<ParenType>(T)) {
3970             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3971                  diag::err_trailing_return_in_parens)
3972               << T << D.getDeclSpec().getSourceRange();
3973             D.setInvalidType(true);
3974           } else if (D.getContext() != Declarator::LambdaExprContext &&
3975                      (T.hasQualifiers() || !isa<AutoType>(T) ||
3976                       cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) {
3977             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3978                  diag::err_trailing_return_without_auto)
3979               << T << D.getDeclSpec().getSourceRange();
3980             D.setInvalidType(true);
3981           }
3982           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
3983           if (T.isNull()) {
3984             // An error occurred parsing the trailing return type.
3985             T = Context.IntTy;
3986             D.setInvalidType(true);
3987           }
3988         }
3989       }
3990 
3991       // C99 6.7.5.3p1: The return type may not be a function or array type.
3992       // For conversion functions, we'll diagnose this particular error later.
3993       if ((T->isArrayType() || T->isFunctionType()) &&
3994           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
3995         unsigned diagID = diag::err_func_returning_array_function;
3996         // Last processing chunk in block context means this function chunk
3997         // represents the block.
3998         if (chunkIndex == 0 &&
3999             D.getContext() == Declarator::BlockLiteralContext)
4000           diagID = diag::err_block_returning_array_function;
4001         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4002         T = Context.IntTy;
4003         D.setInvalidType(true);
4004       }
4005 
4006       // Do not allow returning half FP value.
4007       // FIXME: This really should be in BuildFunctionType.
4008       if (T->isHalfType()) {
4009         if (S.getLangOpts().OpenCL) {
4010           if (!S.getOpenCLOptions().cl_khr_fp16) {
4011             S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4012                 << T << 0 /*pointer hint*/;
4013             D.setInvalidType(true);
4014           }
4015         } else if (!S.getLangOpts().HalfArgsAndReturns) {
4016           S.Diag(D.getIdentifierLoc(),
4017             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4018           D.setInvalidType(true);
4019         }
4020       }
4021 
4022         // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4023         // function.
4024       if (LangOpts.OpenCL && T->isBlockPointerType()) {
4025         S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4026             << T << 1 /*hint off*/;
4027         D.setInvalidType(true);
4028       }
4029 
4030       // Methods cannot return interface types. All ObjC objects are
4031       // passed by reference.
4032       if (T->isObjCObjectType()) {
4033         SourceLocation DiagLoc, FixitLoc;
4034         if (TInfo) {
4035           DiagLoc = TInfo->getTypeLoc().getLocStart();
4036           FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4037         } else {
4038           DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4039           FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4040         }
4041         S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4042           << 0 << T
4043           << FixItHint::CreateInsertion(FixitLoc, "*");
4044 
4045         T = Context.getObjCObjectPointerType(T);
4046         if (TInfo) {
4047           TypeLocBuilder TLB;
4048           TLB.pushFullCopy(TInfo->getTypeLoc());
4049           ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4050           TLoc.setStarLoc(FixitLoc);
4051           TInfo = TLB.getTypeSourceInfo(Context, T);
4052         }
4053 
4054         D.setInvalidType(true);
4055       }
4056 
4057       // cv-qualifiers on return types are pointless except when the type is a
4058       // class type in C++.
4059       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4060           !(S.getLangOpts().CPlusPlus &&
4061             (T->isDependentType() || T->isRecordType()))) {
4062         if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4063             D.getFunctionDefinitionKind() == FDK_Definition) {
4064           // [6.9.1/3] qualified void return is invalid on a C
4065           // function definition.  Apparently ok on declarations and
4066           // in C++ though (!)
4067           S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4068         } else
4069           diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4070       }
4071 
4072       // Objective-C ARC ownership qualifiers are ignored on the function
4073       // return type (by type canonicalization). Complain if this attribute
4074       // was written here.
4075       if (T.getQualifiers().hasObjCLifetime()) {
4076         SourceLocation AttrLoc;
4077         if (chunkIndex + 1 < D.getNumTypeObjects()) {
4078           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4079           for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4080                Attr; Attr = Attr->getNext()) {
4081             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4082               AttrLoc = Attr->getLoc();
4083               break;
4084             }
4085           }
4086         }
4087         if (AttrLoc.isInvalid()) {
4088           for (const AttributeList *Attr
4089                  = D.getDeclSpec().getAttributes().getList();
4090                Attr; Attr = Attr->getNext()) {
4091             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4092               AttrLoc = Attr->getLoc();
4093               break;
4094             }
4095           }
4096         }
4097 
4098         if (AttrLoc.isValid()) {
4099           // The ownership attributes are almost always written via
4100           // the predefined
4101           // __strong/__weak/__autoreleasing/__unsafe_unretained.
4102           if (AttrLoc.isMacroID())
4103             AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
4104 
4105           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4106             << T.getQualifiers().getObjCLifetime();
4107         }
4108       }
4109 
4110       if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4111         // C++ [dcl.fct]p6:
4112         //   Types shall not be defined in return or parameter types.
4113         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4114         S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4115           << Context.getTypeDeclType(Tag);
4116       }
4117 
4118       // Exception specs are not allowed in typedefs. Complain, but add it
4119       // anyway.
4120       if (IsTypedefName && FTI.getExceptionSpecType())
4121         S.Diag(FTI.getExceptionSpecLocBeg(),
4122                diag::err_exception_spec_in_typedef)
4123             << (D.getContext() == Declarator::AliasDeclContext ||
4124                 D.getContext() == Declarator::AliasTemplateContext);
4125 
4126       // If we see "T var();" or "T var(T());" at block scope, it is probably
4127       // an attempt to initialize a variable, not a function declaration.
4128       if (FTI.isAmbiguous)
4129         warnAboutAmbiguousFunction(S, D, DeclType, T);
4130 
4131       FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4132 
4133       if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
4134         // Simple void foo(), where the incoming T is the result type.
4135         T = Context.getFunctionNoProtoType(T, EI);
4136       } else {
4137         // We allow a zero-parameter variadic function in C if the
4138         // function is marked with the "overloadable" attribute. Scan
4139         // for this attribute now.
4140         if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4141           bool Overloadable = false;
4142           for (const AttributeList *Attrs = D.getAttributes();
4143                Attrs; Attrs = Attrs->getNext()) {
4144             if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4145               Overloadable = true;
4146               break;
4147             }
4148           }
4149 
4150           if (!Overloadable)
4151             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4152         }
4153 
4154         if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4155           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4156           // definition.
4157           S.Diag(FTI.Params[0].IdentLoc,
4158                  diag::err_ident_list_in_fn_declaration);
4159           D.setInvalidType(true);
4160           // Recover by creating a K&R-style function type.
4161           T = Context.getFunctionNoProtoType(T, EI);
4162           break;
4163         }
4164 
4165         FunctionProtoType::ExtProtoInfo EPI;
4166         EPI.ExtInfo = EI;
4167         EPI.Variadic = FTI.isVariadic;
4168         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4169         EPI.TypeQuals = FTI.TypeQuals;
4170         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4171                     : FTI.RefQualifierIsLValueRef? RQ_LValue
4172                     : RQ_RValue;
4173 
4174         // Otherwise, we have a function with a parameter list that is
4175         // potentially variadic.
4176         SmallVector<QualType, 16> ParamTys;
4177         ParamTys.reserve(FTI.NumParams);
4178 
4179         SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4180           ExtParameterInfos(FTI.NumParams);
4181         bool HasAnyInterestingExtParameterInfos = false;
4182 
4183         for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4184           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4185           QualType ParamTy = Param->getType();
4186           assert(!ParamTy.isNull() && "Couldn't parse type?");
4187 
4188           // Look for 'void'.  void is allowed only as a single parameter to a
4189           // function with no other parameters (C99 6.7.5.3p10).  We record
4190           // int(void) as a FunctionProtoType with an empty parameter list.
4191           if (ParamTy->isVoidType()) {
4192             // If this is something like 'float(int, void)', reject it.  'void'
4193             // is an incomplete type (C99 6.2.5p19) and function decls cannot
4194             // have parameters of incomplete type.
4195             if (FTI.NumParams != 1 || FTI.isVariadic) {
4196               S.Diag(DeclType.Loc, diag::err_void_only_param);
4197               ParamTy = Context.IntTy;
4198               Param->setType(ParamTy);
4199             } else if (FTI.Params[i].Ident) {
4200               // Reject, but continue to parse 'int(void abc)'.
4201               S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4202               ParamTy = Context.IntTy;
4203               Param->setType(ParamTy);
4204             } else {
4205               // Reject, but continue to parse 'float(const void)'.
4206               if (ParamTy.hasQualifiers())
4207                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4208 
4209               // Do not add 'void' to the list.
4210               break;
4211             }
4212           } else if (ParamTy->isHalfType()) {
4213             // Disallow half FP parameters.
4214             // FIXME: This really should be in BuildFunctionType.
4215             if (S.getLangOpts().OpenCL) {
4216               if (!S.getOpenCLOptions().cl_khr_fp16) {
4217                 S.Diag(Param->getLocation(),
4218                   diag::err_opencl_half_param) << ParamTy;
4219                 D.setInvalidType();
4220                 Param->setInvalidDecl();
4221               }
4222             } else if (!S.getLangOpts().HalfArgsAndReturns) {
4223               S.Diag(Param->getLocation(),
4224                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4225               D.setInvalidType();
4226             }
4227           } else if (!FTI.hasPrototype) {
4228             if (ParamTy->isPromotableIntegerType()) {
4229               ParamTy = Context.getPromotedIntegerType(ParamTy);
4230               Param->setKNRPromoted(true);
4231             } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4232               if (BTy->getKind() == BuiltinType::Float) {
4233                 ParamTy = Context.DoubleTy;
4234                 Param->setKNRPromoted(true);
4235               }
4236             }
4237           }
4238 
4239           if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4240             ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4241             HasAnyInterestingExtParameterInfos = true;
4242           }
4243 
4244           if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4245             ExtParameterInfos[i] =
4246               ExtParameterInfos[i].withABI(attr->getABI());
4247             HasAnyInterestingExtParameterInfos = true;
4248           }
4249 
4250           ParamTys.push_back(ParamTy);
4251         }
4252 
4253         if (HasAnyInterestingExtParameterInfos) {
4254           EPI.ExtParameterInfos = ExtParameterInfos.data();
4255           checkExtParameterInfos(S, ParamTys, EPI,
4256               [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4257         }
4258 
4259         SmallVector<QualType, 4> Exceptions;
4260         SmallVector<ParsedType, 2> DynamicExceptions;
4261         SmallVector<SourceRange, 2> DynamicExceptionRanges;
4262         Expr *NoexceptExpr = nullptr;
4263 
4264         if (FTI.getExceptionSpecType() == EST_Dynamic) {
4265           // FIXME: It's rather inefficient to have to split into two vectors
4266           // here.
4267           unsigned N = FTI.NumExceptions;
4268           DynamicExceptions.reserve(N);
4269           DynamicExceptionRanges.reserve(N);
4270           for (unsigned I = 0; I != N; ++I) {
4271             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4272             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4273           }
4274         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4275           NoexceptExpr = FTI.NoexceptExpr;
4276         }
4277 
4278         S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4279                                       FTI.getExceptionSpecType(),
4280                                       DynamicExceptions,
4281                                       DynamicExceptionRanges,
4282                                       NoexceptExpr,
4283                                       Exceptions,
4284                                       EPI.ExceptionSpec);
4285 
4286         T = Context.getFunctionType(T, ParamTys, EPI);
4287       }
4288       break;
4289     }
4290     case DeclaratorChunk::MemberPointer: {
4291       // The scope spec must refer to a class, or be dependent.
4292       CXXScopeSpec &SS = DeclType.Mem.Scope();
4293       QualType ClsType;
4294 
4295       // Handle pointer nullability.
4296       inferPointerNullability(SimplePointerKind::MemberPointer,
4297                               DeclType.Loc, DeclType.getAttrListRef());
4298 
4299       if (SS.isInvalid()) {
4300         // Avoid emitting extra errors if we already errored on the scope.
4301         D.setInvalidType(true);
4302       } else if (S.isDependentScopeSpecifier(SS) ||
4303                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4304         NestedNameSpecifier *NNS = SS.getScopeRep();
4305         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4306         switch (NNS->getKind()) {
4307         case NestedNameSpecifier::Identifier:
4308           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4309                                                  NNS->getAsIdentifier());
4310           break;
4311 
4312         case NestedNameSpecifier::Namespace:
4313         case NestedNameSpecifier::NamespaceAlias:
4314         case NestedNameSpecifier::Global:
4315         case NestedNameSpecifier::Super:
4316           llvm_unreachable("Nested-name-specifier must name a type");
4317 
4318         case NestedNameSpecifier::TypeSpec:
4319         case NestedNameSpecifier::TypeSpecWithTemplate:
4320           ClsType = QualType(NNS->getAsType(), 0);
4321           // Note: if the NNS has a prefix and ClsType is a nondependent
4322           // TemplateSpecializationType, then the NNS prefix is NOT included
4323           // in ClsType; hence we wrap ClsType into an ElaboratedType.
4324           // NOTE: in particular, no wrap occurs if ClsType already is an
4325           // Elaborated, DependentName, or DependentTemplateSpecialization.
4326           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4327             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4328           break;
4329         }
4330       } else {
4331         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4332              diag::err_illegal_decl_mempointer_in_nonclass)
4333           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4334           << DeclType.Mem.Scope().getRange();
4335         D.setInvalidType(true);
4336       }
4337 
4338       if (!ClsType.isNull())
4339         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4340                                      D.getIdentifier());
4341       if (T.isNull()) {
4342         T = Context.IntTy;
4343         D.setInvalidType(true);
4344       } else if (DeclType.Mem.TypeQuals) {
4345         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4346       }
4347       break;
4348     }
4349 
4350     case DeclaratorChunk::Pipe: {
4351       T = S.BuildPipeType(T, DeclType.Loc );
4352       break;
4353     }
4354     }
4355 
4356     if (T.isNull()) {
4357       D.setInvalidType(true);
4358       T = Context.IntTy;
4359     }
4360 
4361     // See if there are any attributes on this declarator chunk.
4362     processTypeAttrs(state, T, TAL_DeclChunk,
4363                      const_cast<AttributeList *>(DeclType.getAttrs()));
4364   }
4365 
4366   assert(!T.isNull() && "T must not be null after this point");
4367 
4368   if (LangOpts.CPlusPlus && T->isFunctionType()) {
4369     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4370     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4371 
4372     // C++ 8.3.5p4:
4373     //   A cv-qualifier-seq shall only be part of the function type
4374     //   for a nonstatic member function, the function type to which a pointer
4375     //   to member refers, or the top-level function type of a function typedef
4376     //   declaration.
4377     //
4378     // Core issue 547 also allows cv-qualifiers on function types that are
4379     // top-level template type arguments.
4380     bool FreeFunction;
4381     if (!D.getCXXScopeSpec().isSet()) {
4382       FreeFunction = ((D.getContext() != Declarator::MemberContext &&
4383                        D.getContext() != Declarator::LambdaExprContext) ||
4384                       D.getDeclSpec().isFriendSpecified());
4385     } else {
4386       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4387       FreeFunction = (DC && !DC->isRecord());
4388     }
4389 
4390     // C++11 [dcl.fct]p6 (w/DR1417):
4391     // An attempt to specify a function type with a cv-qualifier-seq or a
4392     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4393     //  - the function type for a non-static member function,
4394     //  - the function type to which a pointer to member refers,
4395     //  - the top-level function type of a function typedef declaration or
4396     //    alias-declaration,
4397     //  - the type-id in the default argument of a type-parameter, or
4398     //  - the type-id of a template-argument for a type-parameter
4399     //
4400     // FIXME: Checking this here is insufficient. We accept-invalid on:
4401     //
4402     //   template<typename T> struct S { void f(T); };
4403     //   S<int() const> s;
4404     //
4405     // ... for instance.
4406     if (IsQualifiedFunction &&
4407         !(!FreeFunction &&
4408           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4409         !IsTypedefName &&
4410         D.getContext() != Declarator::TemplateTypeArgContext) {
4411       SourceLocation Loc = D.getLocStart();
4412       SourceRange RemovalRange;
4413       unsigned I;
4414       if (D.isFunctionDeclarator(I)) {
4415         SmallVector<SourceLocation, 4> RemovalLocs;
4416         const DeclaratorChunk &Chunk = D.getTypeObject(I);
4417         assert(Chunk.Kind == DeclaratorChunk::Function);
4418         if (Chunk.Fun.hasRefQualifier())
4419           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4420         if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4421           RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4422         if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4423           RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4424         if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4425           RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4426         if (!RemovalLocs.empty()) {
4427           std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4428                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4429           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4430           Loc = RemovalLocs.front();
4431         }
4432       }
4433 
4434       S.Diag(Loc, diag::err_invalid_qualified_function_type)
4435         << FreeFunction << D.isFunctionDeclarator() << T
4436         << getFunctionQualifiersAsString(FnTy)
4437         << FixItHint::CreateRemoval(RemovalRange);
4438 
4439       // Strip the cv-qualifiers and ref-qualifiers from the type.
4440       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4441       EPI.TypeQuals = 0;
4442       EPI.RefQualifier = RQ_None;
4443 
4444       T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4445                                   EPI);
4446       // Rebuild any parens around the identifier in the function type.
4447       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4448         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4449           break;
4450         T = S.BuildParenType(T);
4451       }
4452     }
4453   }
4454 
4455   // Apply any undistributed attributes from the declarator.
4456   processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4457 
4458   // Diagnose any ignored type attributes.
4459   state.diagnoseIgnoredTypeAttrs(T);
4460 
4461   // C++0x [dcl.constexpr]p9:
4462   //  A constexpr specifier used in an object declaration declares the object
4463   //  as const.
4464   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4465     T.addConst();
4466   }
4467 
4468   // If there was an ellipsis in the declarator, the declaration declares a
4469   // parameter pack whose type may be a pack expansion type.
4470   if (D.hasEllipsis()) {
4471     // C++0x [dcl.fct]p13:
4472     //   A declarator-id or abstract-declarator containing an ellipsis shall
4473     //   only be used in a parameter-declaration. Such a parameter-declaration
4474     //   is a parameter pack (14.5.3). [...]
4475     switch (D.getContext()) {
4476     case Declarator::PrototypeContext:
4477     case Declarator::LambdaExprParameterContext:
4478       // C++0x [dcl.fct]p13:
4479       //   [...] When it is part of a parameter-declaration-clause, the
4480       //   parameter pack is a function parameter pack (14.5.3). The type T
4481       //   of the declarator-id of the function parameter pack shall contain
4482       //   a template parameter pack; each template parameter pack in T is
4483       //   expanded by the function parameter pack.
4484       //
4485       // We represent function parameter packs as function parameters whose
4486       // type is a pack expansion.
4487       if (!T->containsUnexpandedParameterPack()) {
4488         S.Diag(D.getEllipsisLoc(),
4489              diag::err_function_parameter_pack_without_parameter_packs)
4490           << T <<  D.getSourceRange();
4491         D.setEllipsisLoc(SourceLocation());
4492       } else {
4493         T = Context.getPackExpansionType(T, None);
4494       }
4495       break;
4496     case Declarator::TemplateParamContext:
4497       // C++0x [temp.param]p15:
4498       //   If a template-parameter is a [...] is a parameter-declaration that
4499       //   declares a parameter pack (8.3.5), then the template-parameter is a
4500       //   template parameter pack (14.5.3).
4501       //
4502       // Note: core issue 778 clarifies that, if there are any unexpanded
4503       // parameter packs in the type of the non-type template parameter, then
4504       // it expands those parameter packs.
4505       if (T->containsUnexpandedParameterPack())
4506         T = Context.getPackExpansionType(T, None);
4507       else
4508         S.Diag(D.getEllipsisLoc(),
4509                LangOpts.CPlusPlus11
4510                  ? diag::warn_cxx98_compat_variadic_templates
4511                  : diag::ext_variadic_templates);
4512       break;
4513 
4514     case Declarator::FileContext:
4515     case Declarator::KNRTypeListContext:
4516     case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
4517     case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
4518     case Declarator::TypeNameContext:
4519     case Declarator::CXXNewContext:
4520     case Declarator::AliasDeclContext:
4521     case Declarator::AliasTemplateContext:
4522     case Declarator::MemberContext:
4523     case Declarator::BlockContext:
4524     case Declarator::ForContext:
4525     case Declarator::ConditionContext:
4526     case Declarator::CXXCatchContext:
4527     case Declarator::ObjCCatchContext:
4528     case Declarator::BlockLiteralContext:
4529     case Declarator::LambdaExprContext:
4530     case Declarator::ConversionIdContext:
4531     case Declarator::TrailingReturnContext:
4532     case Declarator::TemplateTypeArgContext:
4533       // FIXME: We may want to allow parameter packs in block-literal contexts
4534       // in the future.
4535       S.Diag(D.getEllipsisLoc(),
4536              diag::err_ellipsis_in_declarator_not_parameter);
4537       D.setEllipsisLoc(SourceLocation());
4538       break;
4539     }
4540   }
4541 
4542   assert(!T.isNull() && "T must not be null at the end of this function");
4543   if (D.isInvalidType())
4544     return Context.getTrivialTypeSourceInfo(T);
4545 
4546   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4547 }
4548 
4549 /// GetTypeForDeclarator - Convert the type for the specified
4550 /// declarator to Type instances.
4551 ///
4552 /// The result of this call will never be null, but the associated
4553 /// type may be a null type if there's an unrecoverable error.
4554 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4555   // Determine the type of the declarator. Not all forms of declarator
4556   // have a type.
4557 
4558   TypeProcessingState state(*this, D);
4559 
4560   TypeSourceInfo *ReturnTypeInfo = nullptr;
4561   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4562 
4563   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4564     inferARCWriteback(state, T);
4565 
4566   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4567 }
4568 
4569 static void transferARCOwnershipToDeclSpec(Sema &S,
4570                                            QualType &declSpecTy,
4571                                            Qualifiers::ObjCLifetime ownership) {
4572   if (declSpecTy->isObjCRetainableType() &&
4573       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4574     Qualifiers qs;
4575     qs.addObjCLifetime(ownership);
4576     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4577   }
4578 }
4579 
4580 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4581                                             Qualifiers::ObjCLifetime ownership,
4582                                             unsigned chunkIndex) {
4583   Sema &S = state.getSema();
4584   Declarator &D = state.getDeclarator();
4585 
4586   // Look for an explicit lifetime attribute.
4587   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4588   for (const AttributeList *attr = chunk.getAttrs(); attr;
4589          attr = attr->getNext())
4590     if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4591       return;
4592 
4593   const char *attrStr = nullptr;
4594   switch (ownership) {
4595   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4596   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4597   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4598   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4599   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4600   }
4601 
4602   IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4603   Arg->Ident = &S.Context.Idents.get(attrStr);
4604   Arg->Loc = SourceLocation();
4605 
4606   ArgsUnion Args(Arg);
4607 
4608   // If there wasn't one, add one (with an invalid source location
4609   // so that we don't make an AttributedType for it).
4610   AttributeList *attr = D.getAttributePool()
4611     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4612             /*scope*/ nullptr, SourceLocation(),
4613             /*args*/ &Args, 1, AttributeList::AS_GNU);
4614   spliceAttrIntoList(*attr, chunk.getAttrListRef());
4615 
4616   // TODO: mark whether we did this inference?
4617 }
4618 
4619 /// \brief Used for transferring ownership in casts resulting in l-values.
4620 static void transferARCOwnership(TypeProcessingState &state,
4621                                  QualType &declSpecTy,
4622                                  Qualifiers::ObjCLifetime ownership) {
4623   Sema &S = state.getSema();
4624   Declarator &D = state.getDeclarator();
4625 
4626   int inner = -1;
4627   bool hasIndirection = false;
4628   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4629     DeclaratorChunk &chunk = D.getTypeObject(i);
4630     switch (chunk.Kind) {
4631     case DeclaratorChunk::Paren:
4632       // Ignore parens.
4633       break;
4634 
4635     case DeclaratorChunk::Array:
4636     case DeclaratorChunk::Reference:
4637     case DeclaratorChunk::Pointer:
4638       if (inner != -1)
4639         hasIndirection = true;
4640       inner = i;
4641       break;
4642 
4643     case DeclaratorChunk::BlockPointer:
4644       if (inner != -1)
4645         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4646       return;
4647 
4648     case DeclaratorChunk::Function:
4649     case DeclaratorChunk::MemberPointer:
4650     case DeclaratorChunk::Pipe:
4651       return;
4652     }
4653   }
4654 
4655   if (inner == -1)
4656     return;
4657 
4658   DeclaratorChunk &chunk = D.getTypeObject(inner);
4659   if (chunk.Kind == DeclaratorChunk::Pointer) {
4660     if (declSpecTy->isObjCRetainableType())
4661       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4662     if (declSpecTy->isObjCObjectType() && hasIndirection)
4663       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4664   } else {
4665     assert(chunk.Kind == DeclaratorChunk::Array ||
4666            chunk.Kind == DeclaratorChunk::Reference);
4667     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4668   }
4669 }
4670 
4671 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4672   TypeProcessingState state(*this, D);
4673 
4674   TypeSourceInfo *ReturnTypeInfo = nullptr;
4675   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4676 
4677   if (getLangOpts().ObjC1) {
4678     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4679     if (ownership != Qualifiers::OCL_None)
4680       transferARCOwnership(state, declSpecTy, ownership);
4681   }
4682 
4683   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4684 }
4685 
4686 /// Map an AttributedType::Kind to an AttributeList::Kind.
4687 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4688   switch (kind) {
4689   case AttributedType::attr_address_space:
4690     return AttributeList::AT_AddressSpace;
4691   case AttributedType::attr_regparm:
4692     return AttributeList::AT_Regparm;
4693   case AttributedType::attr_vector_size:
4694     return AttributeList::AT_VectorSize;
4695   case AttributedType::attr_neon_vector_type:
4696     return AttributeList::AT_NeonVectorType;
4697   case AttributedType::attr_neon_polyvector_type:
4698     return AttributeList::AT_NeonPolyVectorType;
4699   case AttributedType::attr_objc_gc:
4700     return AttributeList::AT_ObjCGC;
4701   case AttributedType::attr_objc_ownership:
4702   case AttributedType::attr_objc_inert_unsafe_unretained:
4703     return AttributeList::AT_ObjCOwnership;
4704   case AttributedType::attr_noreturn:
4705     return AttributeList::AT_NoReturn;
4706   case AttributedType::attr_cdecl:
4707     return AttributeList::AT_CDecl;
4708   case AttributedType::attr_fastcall:
4709     return AttributeList::AT_FastCall;
4710   case AttributedType::attr_stdcall:
4711     return AttributeList::AT_StdCall;
4712   case AttributedType::attr_thiscall:
4713     return AttributeList::AT_ThisCall;
4714   case AttributedType::attr_pascal:
4715     return AttributeList::AT_Pascal;
4716   case AttributedType::attr_swiftcall:
4717     return AttributeList::AT_SwiftCall;
4718   case AttributedType::attr_vectorcall:
4719     return AttributeList::AT_VectorCall;
4720   case AttributedType::attr_pcs:
4721   case AttributedType::attr_pcs_vfp:
4722     return AttributeList::AT_Pcs;
4723   case AttributedType::attr_inteloclbicc:
4724     return AttributeList::AT_IntelOclBicc;
4725   case AttributedType::attr_ms_abi:
4726     return AttributeList::AT_MSABI;
4727   case AttributedType::attr_sysv_abi:
4728     return AttributeList::AT_SysVABI;
4729   case AttributedType::attr_preserve_most:
4730     return AttributeList::AT_PreserveMost;
4731   case AttributedType::attr_preserve_all:
4732     return AttributeList::AT_PreserveAll;
4733   case AttributedType::attr_ptr32:
4734     return AttributeList::AT_Ptr32;
4735   case AttributedType::attr_ptr64:
4736     return AttributeList::AT_Ptr64;
4737   case AttributedType::attr_sptr:
4738     return AttributeList::AT_SPtr;
4739   case AttributedType::attr_uptr:
4740     return AttributeList::AT_UPtr;
4741   case AttributedType::attr_nonnull:
4742     return AttributeList::AT_TypeNonNull;
4743   case AttributedType::attr_nullable:
4744     return AttributeList::AT_TypeNullable;
4745   case AttributedType::attr_null_unspecified:
4746     return AttributeList::AT_TypeNullUnspecified;
4747   case AttributedType::attr_objc_kindof:
4748     return AttributeList::AT_ObjCKindOf;
4749   }
4750   llvm_unreachable("unexpected attribute kind!");
4751 }
4752 
4753 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
4754                                   const AttributeList *attrs,
4755                                   const AttributeList *DeclAttrs = nullptr) {
4756   // DeclAttrs and attrs cannot be both empty.
4757   assert((attrs || DeclAttrs) &&
4758          "no type attributes in the expected location!");
4759 
4760   AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
4761   // Try to search for an attribute of matching kind in attrs list.
4762   while (attrs && attrs->getKind() != parsedKind)
4763     attrs = attrs->getNext();
4764   if (!attrs) {
4765     // No matching type attribute in attrs list found.
4766     // Try searching through C++11 attributes in the declarator attribute list.
4767     while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
4768                          DeclAttrs->getKind() != parsedKind))
4769       DeclAttrs = DeclAttrs->getNext();
4770     attrs = DeclAttrs;
4771   }
4772 
4773   assert(attrs && "no matching type attribute in expected location!");
4774 
4775   TL.setAttrNameLoc(attrs->getLoc());
4776   if (TL.hasAttrExprOperand()) {
4777     assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
4778     TL.setAttrExprOperand(attrs->getArgAsExpr(0));
4779   } else if (TL.hasAttrEnumOperand()) {
4780     assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
4781            "unexpected attribute operand kind");
4782     if (attrs->isArgIdent(0))
4783       TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
4784     else
4785       TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
4786   }
4787 
4788   // FIXME: preserve this information to here.
4789   if (TL.hasAttrOperand())
4790     TL.setAttrOperandParensRange(SourceRange());
4791 }
4792 
4793 namespace {
4794   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4795     ASTContext &Context;
4796     const DeclSpec &DS;
4797 
4798   public:
4799     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
4800       : Context(Context), DS(DS) {}
4801 
4802     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4803       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
4804       Visit(TL.getModifiedLoc());
4805     }
4806     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4807       Visit(TL.getUnqualifiedLoc());
4808     }
4809     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4810       TL.setNameLoc(DS.getTypeSpecTypeLoc());
4811     }
4812     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4813       TL.setNameLoc(DS.getTypeSpecTypeLoc());
4814       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
4815       // addition field. What we have is good enough for dispay of location
4816       // of 'fixit' on interface name.
4817       TL.setNameEndLoc(DS.getLocEnd());
4818     }
4819     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4820       TypeSourceInfo *RepTInfo = nullptr;
4821       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4822       TL.copy(RepTInfo->getTypeLoc());
4823     }
4824     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4825       TypeSourceInfo *RepTInfo = nullptr;
4826       Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4827       TL.copy(RepTInfo->getTypeLoc());
4828     }
4829     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
4830       TypeSourceInfo *TInfo = nullptr;
4831       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4832 
4833       // If we got no declarator info from previous Sema routines,
4834       // just fill with the typespec loc.
4835       if (!TInfo) {
4836         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
4837         return;
4838       }
4839 
4840       TypeLoc OldTL = TInfo->getTypeLoc();
4841       if (TInfo->getType()->getAs<ElaboratedType>()) {
4842         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
4843         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
4844             .castAs<TemplateSpecializationTypeLoc>();
4845         TL.copy(NamedTL);
4846       } else {
4847         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
4848         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
4849       }
4850 
4851     }
4852     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4853       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
4854       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4855       TL.setParensRange(DS.getTypeofParensRange());
4856     }
4857     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4858       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
4859       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4860       TL.setParensRange(DS.getTypeofParensRange());
4861       assert(DS.getRepAsType());
4862       TypeSourceInfo *TInfo = nullptr;
4863       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4864       TL.setUnderlyingTInfo(TInfo);
4865     }
4866     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4867       // FIXME: This holds only because we only have one unary transform.
4868       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
4869       TL.setKWLoc(DS.getTypeSpecTypeLoc());
4870       TL.setParensRange(DS.getTypeofParensRange());
4871       assert(DS.getRepAsType());
4872       TypeSourceInfo *TInfo = nullptr;
4873       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4874       TL.setUnderlyingTInfo(TInfo);
4875     }
4876     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4877       // By default, use the source location of the type specifier.
4878       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
4879       if (TL.needsExtraLocalData()) {
4880         // Set info for the written builtin specifiers.
4881         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
4882         // Try to have a meaningful source location.
4883         if (TL.getWrittenSignSpec() != TSS_unspecified)
4884           // Sign spec loc overrides the others (e.g., 'unsigned long').
4885           TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
4886         else if (TL.getWrittenWidthSpec() != TSW_unspecified)
4887           // Width spec loc overrides type spec loc (e.g., 'short int').
4888           TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
4889       }
4890     }
4891     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4892       ElaboratedTypeKeyword Keyword
4893         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
4894       if (DS.getTypeSpecType() == TST_typename) {
4895         TypeSourceInfo *TInfo = nullptr;
4896         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4897         if (TInfo) {
4898           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
4899           return;
4900         }
4901       }
4902       TL.setElaboratedKeywordLoc(Keyword != ETK_None
4903                                  ? DS.getTypeSpecTypeLoc()
4904                                  : SourceLocation());
4905       const CXXScopeSpec& SS = DS.getTypeSpecScope();
4906       TL.setQualifierLoc(SS.getWithLocInContext(Context));
4907       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
4908     }
4909     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4910       assert(DS.getTypeSpecType() == TST_typename);
4911       TypeSourceInfo *TInfo = nullptr;
4912       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4913       assert(TInfo);
4914       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
4915     }
4916     void VisitDependentTemplateSpecializationTypeLoc(
4917                                  DependentTemplateSpecializationTypeLoc TL) {
4918       assert(DS.getTypeSpecType() == TST_typename);
4919       TypeSourceInfo *TInfo = nullptr;
4920       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4921       assert(TInfo);
4922       TL.copy(
4923           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
4924     }
4925     void VisitTagTypeLoc(TagTypeLoc TL) {
4926       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
4927     }
4928     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4929       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
4930       // or an _Atomic qualifier.
4931       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
4932         TL.setKWLoc(DS.getTypeSpecTypeLoc());
4933         TL.setParensRange(DS.getTypeofParensRange());
4934 
4935         TypeSourceInfo *TInfo = nullptr;
4936         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4937         assert(TInfo);
4938         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4939       } else {
4940         TL.setKWLoc(DS.getAtomicSpecLoc());
4941         // No parens, to indicate this was spelled as an _Atomic qualifier.
4942         TL.setParensRange(SourceRange());
4943         Visit(TL.getValueLoc());
4944       }
4945     }
4946 
4947     void VisitPipeTypeLoc(PipeTypeLoc TL) {
4948       TL.setKWLoc(DS.getTypeSpecTypeLoc());
4949 
4950       TypeSourceInfo *TInfo = nullptr;
4951       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4952       TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4953     }
4954 
4955     void VisitTypeLoc(TypeLoc TL) {
4956       // FIXME: add other typespec types and change this to an assert.
4957       TL.initialize(Context, DS.getTypeSpecTypeLoc());
4958     }
4959   };
4960 
4961   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
4962     ASTContext &Context;
4963     const DeclaratorChunk &Chunk;
4964 
4965   public:
4966     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
4967       : Context(Context), Chunk(Chunk) {}
4968 
4969     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4970       llvm_unreachable("qualified type locs not expected here!");
4971     }
4972     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
4973       llvm_unreachable("decayed type locs not expected here!");
4974     }
4975 
4976     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4977       fillAttributedTypeLoc(TL, Chunk.getAttrs());
4978     }
4979     void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
4980       // nothing
4981     }
4982     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4983       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
4984       TL.setCaretLoc(Chunk.Loc);
4985     }
4986     void VisitPointerTypeLoc(PointerTypeLoc TL) {
4987       assert(Chunk.Kind == DeclaratorChunk::Pointer);
4988       TL.setStarLoc(Chunk.Loc);
4989     }
4990     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4991       assert(Chunk.Kind == DeclaratorChunk::Pointer);
4992       TL.setStarLoc(Chunk.Loc);
4993     }
4994     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4995       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
4996       const CXXScopeSpec& SS = Chunk.Mem.Scope();
4997       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
4998 
4999       const Type* ClsTy = TL.getClass();
5000       QualType ClsQT = QualType(ClsTy, 0);
5001       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5002       // Now copy source location info into the type loc component.
5003       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5004       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5005       case NestedNameSpecifier::Identifier:
5006         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5007         {
5008           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5009           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5010           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5011           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5012         }
5013         break;
5014 
5015       case NestedNameSpecifier::TypeSpec:
5016       case NestedNameSpecifier::TypeSpecWithTemplate:
5017         if (isa<ElaboratedType>(ClsTy)) {
5018           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5019           ETLoc.setElaboratedKeywordLoc(SourceLocation());
5020           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5021           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5022           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5023         } else {
5024           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5025         }
5026         break;
5027 
5028       case NestedNameSpecifier::Namespace:
5029       case NestedNameSpecifier::NamespaceAlias:
5030       case NestedNameSpecifier::Global:
5031       case NestedNameSpecifier::Super:
5032         llvm_unreachable("Nested-name-specifier must name a type");
5033       }
5034 
5035       // Finally fill in MemberPointerLocInfo fields.
5036       TL.setStarLoc(Chunk.Loc);
5037       TL.setClassTInfo(ClsTInfo);
5038     }
5039     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5040       assert(Chunk.Kind == DeclaratorChunk::Reference);
5041       // 'Amp' is misleading: this might have been originally
5042       /// spelled with AmpAmp.
5043       TL.setAmpLoc(Chunk.Loc);
5044     }
5045     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5046       assert(Chunk.Kind == DeclaratorChunk::Reference);
5047       assert(!Chunk.Ref.LValueRef);
5048       TL.setAmpAmpLoc(Chunk.Loc);
5049     }
5050     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5051       assert(Chunk.Kind == DeclaratorChunk::Array);
5052       TL.setLBracketLoc(Chunk.Loc);
5053       TL.setRBracketLoc(Chunk.EndLoc);
5054       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5055     }
5056     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5057       assert(Chunk.Kind == DeclaratorChunk::Function);
5058       TL.setLocalRangeBegin(Chunk.Loc);
5059       TL.setLocalRangeEnd(Chunk.EndLoc);
5060 
5061       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5062       TL.setLParenLoc(FTI.getLParenLoc());
5063       TL.setRParenLoc(FTI.getRParenLoc());
5064       for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5065         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5066         TL.setParam(tpi++, Param);
5067       }
5068       // FIXME: exception specs
5069     }
5070     void VisitParenTypeLoc(ParenTypeLoc TL) {
5071       assert(Chunk.Kind == DeclaratorChunk::Paren);
5072       TL.setLParenLoc(Chunk.Loc);
5073       TL.setRParenLoc(Chunk.EndLoc);
5074     }
5075     void VisitPipeTypeLoc(PipeTypeLoc TL) {
5076       assert(Chunk.Kind == DeclaratorChunk::Pipe);
5077       TL.setKWLoc(Chunk.Loc);
5078     }
5079 
5080     void VisitTypeLoc(TypeLoc TL) {
5081       llvm_unreachable("unsupported TypeLoc kind in declarator!");
5082     }
5083   };
5084 } // end anonymous namespace
5085 
5086 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5087   SourceLocation Loc;
5088   switch (Chunk.Kind) {
5089   case DeclaratorChunk::Function:
5090   case DeclaratorChunk::Array:
5091   case DeclaratorChunk::Paren:
5092   case DeclaratorChunk::Pipe:
5093     llvm_unreachable("cannot be _Atomic qualified");
5094 
5095   case DeclaratorChunk::Pointer:
5096     Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5097     break;
5098 
5099   case DeclaratorChunk::BlockPointer:
5100   case DeclaratorChunk::Reference:
5101   case DeclaratorChunk::MemberPointer:
5102     // FIXME: Provide a source location for the _Atomic keyword.
5103     break;
5104   }
5105 
5106   ATL.setKWLoc(Loc);
5107   ATL.setParensRange(SourceRange());
5108 }
5109 
5110 /// \brief Create and instantiate a TypeSourceInfo with type source information.
5111 ///
5112 /// \param T QualType referring to the type as written in source code.
5113 ///
5114 /// \param ReturnTypeInfo For declarators whose return type does not show
5115 /// up in the normal place in the declaration specifiers (such as a C++
5116 /// conversion function), this pointer will refer to a type source information
5117 /// for that return type.
5118 TypeSourceInfo *
5119 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5120                                      TypeSourceInfo *ReturnTypeInfo) {
5121   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5122   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5123   const AttributeList *DeclAttrs = D.getAttributes();
5124 
5125   // Handle parameter packs whose type is a pack expansion.
5126   if (isa<PackExpansionType>(T)) {
5127     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5128     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5129   }
5130 
5131   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5132     // An AtomicTypeLoc might be produced by an atomic qualifier in this
5133     // declarator chunk.
5134     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5135       fillAtomicQualLoc(ATL, D.getTypeObject(i));
5136       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5137     }
5138 
5139     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5140       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
5141       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5142     }
5143 
5144     // FIXME: Ordering here?
5145     while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5146       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5147 
5148     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5149     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5150   }
5151 
5152   // If we have different source information for the return type, use
5153   // that.  This really only applies to C++ conversion functions.
5154   if (ReturnTypeInfo) {
5155     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5156     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5157     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5158   } else {
5159     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
5160   }
5161 
5162   return TInfo;
5163 }
5164 
5165 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5166 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5167   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5168   // and Sema during declaration parsing. Try deallocating/caching them when
5169   // it's appropriate, instead of allocating them and keeping them around.
5170   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5171                                                        TypeAlignment);
5172   new (LocT) LocInfoType(T, TInfo);
5173   assert(LocT->getTypeClass() != T->getTypeClass() &&
5174          "LocInfoType's TypeClass conflicts with an existing Type class");
5175   return ParsedType::make(QualType(LocT, 0));
5176 }
5177 
5178 void LocInfoType::getAsStringInternal(std::string &Str,
5179                                       const PrintingPolicy &Policy) const {
5180   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5181          " was used directly instead of getting the QualType through"
5182          " GetTypeFromParser");
5183 }
5184 
5185 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5186   // C99 6.7.6: Type names have no identifier.  This is already validated by
5187   // the parser.
5188   assert(D.getIdentifier() == nullptr &&
5189          "Type name should have no identifier!");
5190 
5191   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5192   QualType T = TInfo->getType();
5193   if (D.isInvalidType())
5194     return true;
5195 
5196   // Make sure there are no unused decl attributes on the declarator.
5197   // We don't want to do this for ObjC parameters because we're going
5198   // to apply them to the actual parameter declaration.
5199   // Likewise, we don't want to do this for alias declarations, because
5200   // we are actually going to build a declaration from this eventually.
5201   if (D.getContext() != Declarator::ObjCParameterContext &&
5202       D.getContext() != Declarator::AliasDeclContext &&
5203       D.getContext() != Declarator::AliasTemplateContext)
5204     checkUnusedDeclAttributes(D);
5205 
5206   if (getLangOpts().CPlusPlus) {
5207     // Check that there are no default arguments (C++ only).
5208     CheckExtraCXXDefaultArguments(D);
5209   }
5210 
5211   return CreateParsedType(T, TInfo);
5212 }
5213 
5214 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5215   QualType T = Context.getObjCInstanceType();
5216   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5217   return CreateParsedType(T, TInfo);
5218 }
5219 
5220 //===----------------------------------------------------------------------===//
5221 // Type Attribute Processing
5222 //===----------------------------------------------------------------------===//
5223 
5224 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5225 /// specified type.  The attribute contains 1 argument, the id of the address
5226 /// space for the type.
5227 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5228                                             const AttributeList &Attr, Sema &S){
5229 
5230   // If this type is already address space qualified, reject it.
5231   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5232   // qualifiers for two or more different address spaces."
5233   if (Type.getAddressSpace()) {
5234     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5235     Attr.setInvalid();
5236     return;
5237   }
5238 
5239   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5240   // qualified by an address-space qualifier."
5241   if (Type->isFunctionType()) {
5242     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5243     Attr.setInvalid();
5244     return;
5245   }
5246 
5247   unsigned ASIdx;
5248   if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5249     // Check the attribute arguments.
5250     if (Attr.getNumArgs() != 1) {
5251       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5252         << Attr.getName() << 1;
5253       Attr.setInvalid();
5254       return;
5255     }
5256     Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5257     llvm::APSInt addrSpace(32);
5258     if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
5259         !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
5260       S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5261         << Attr.getName() << AANT_ArgumentIntegerConstant
5262         << ASArgExpr->getSourceRange();
5263       Attr.setInvalid();
5264       return;
5265     }
5266 
5267     // Bounds checking.
5268     if (addrSpace.isSigned()) {
5269       if (addrSpace.isNegative()) {
5270         S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5271           << ASArgExpr->getSourceRange();
5272         Attr.setInvalid();
5273         return;
5274       }
5275       addrSpace.setIsSigned(false);
5276     }
5277     llvm::APSInt max(addrSpace.getBitWidth());
5278     max = Qualifiers::MaxAddressSpace;
5279     if (addrSpace > max) {
5280       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5281         << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
5282       Attr.setInvalid();
5283       return;
5284     }
5285     ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
5286   } else {
5287     // The keyword-based type attributes imply which address space to use.
5288     switch (Attr.getKind()) {
5289     case AttributeList::AT_OpenCLGlobalAddressSpace:
5290       ASIdx = LangAS::opencl_global; break;
5291     case AttributeList::AT_OpenCLLocalAddressSpace:
5292       ASIdx = LangAS::opencl_local; break;
5293     case AttributeList::AT_OpenCLConstantAddressSpace:
5294       ASIdx = LangAS::opencl_constant; break;
5295     case AttributeList::AT_OpenCLGenericAddressSpace:
5296       ASIdx = LangAS::opencl_generic; break;
5297     default:
5298       assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5299       ASIdx = 0; break;
5300     }
5301   }
5302 
5303   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5304 }
5305 
5306 /// Does this type have a "direct" ownership qualifier?  That is,
5307 /// is it written like "__strong id", as opposed to something like
5308 /// "typeof(foo)", where that happens to be strong?
5309 static bool hasDirectOwnershipQualifier(QualType type) {
5310   // Fast path: no qualifier at all.
5311   assert(type.getQualifiers().hasObjCLifetime());
5312 
5313   while (true) {
5314     // __strong id
5315     if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5316       if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5317         return true;
5318 
5319       type = attr->getModifiedType();
5320 
5321     // X *__strong (...)
5322     } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5323       type = paren->getInnerType();
5324 
5325     // That's it for things we want to complain about.  In particular,
5326     // we do not want to look through typedefs, typeof(expr),
5327     // typeof(type), or any other way that the type is somehow
5328     // abstracted.
5329     } else {
5330 
5331       return false;
5332     }
5333   }
5334 }
5335 
5336 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5337 /// attribute on the specified type.
5338 ///
5339 /// Returns 'true' if the attribute was handled.
5340 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5341                                        AttributeList &attr,
5342                                        QualType &type) {
5343   bool NonObjCPointer = false;
5344 
5345   if (!type->isDependentType() && !type->isUndeducedType()) {
5346     if (const PointerType *ptr = type->getAs<PointerType>()) {
5347       QualType pointee = ptr->getPointeeType();
5348       if (pointee->isObjCRetainableType() || pointee->isPointerType())
5349         return false;
5350       // It is important not to lose the source info that there was an attribute
5351       // applied to non-objc pointer. We will create an attributed type but
5352       // its type will be the same as the original type.
5353       NonObjCPointer = true;
5354     } else if (!type->isObjCRetainableType()) {
5355       return false;
5356     }
5357 
5358     // Don't accept an ownership attribute in the declspec if it would
5359     // just be the return type of a block pointer.
5360     if (state.isProcessingDeclSpec()) {
5361       Declarator &D = state.getDeclarator();
5362       if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5363                                   /*onlyBlockPointers=*/true))
5364         return false;
5365     }
5366   }
5367 
5368   Sema &S = state.getSema();
5369   SourceLocation AttrLoc = attr.getLoc();
5370   if (AttrLoc.isMacroID())
5371     AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5372 
5373   if (!attr.isArgIdent(0)) {
5374     S.Diag(AttrLoc, diag::err_attribute_argument_type)
5375       << attr.getName() << AANT_ArgumentString;
5376     attr.setInvalid();
5377     return true;
5378   }
5379 
5380   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5381   Qualifiers::ObjCLifetime lifetime;
5382   if (II->isStr("none"))
5383     lifetime = Qualifiers::OCL_ExplicitNone;
5384   else if (II->isStr("strong"))
5385     lifetime = Qualifiers::OCL_Strong;
5386   else if (II->isStr("weak"))
5387     lifetime = Qualifiers::OCL_Weak;
5388   else if (II->isStr("autoreleasing"))
5389     lifetime = Qualifiers::OCL_Autoreleasing;
5390   else {
5391     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5392       << attr.getName() << II;
5393     attr.setInvalid();
5394     return true;
5395   }
5396 
5397   // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5398   // outside of ARC mode.
5399   if (!S.getLangOpts().ObjCAutoRefCount &&
5400       lifetime != Qualifiers::OCL_Weak &&
5401       lifetime != Qualifiers::OCL_ExplicitNone) {
5402     return true;
5403   }
5404 
5405   SplitQualType underlyingType = type.split();
5406 
5407   // Check for redundant/conflicting ownership qualifiers.
5408   if (Qualifiers::ObjCLifetime previousLifetime
5409         = type.getQualifiers().getObjCLifetime()) {
5410     // If it's written directly, that's an error.
5411     if (hasDirectOwnershipQualifier(type)) {
5412       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5413         << type;
5414       return true;
5415     }
5416 
5417     // Otherwise, if the qualifiers actually conflict, pull sugar off
5418     // until we reach a type that is directly qualified.
5419     if (previousLifetime != lifetime) {
5420       // This should always terminate: the canonical type is
5421       // qualified, so some bit of sugar must be hiding it.
5422       while (!underlyingType.Quals.hasObjCLifetime()) {
5423         underlyingType = underlyingType.getSingleStepDesugaredType();
5424       }
5425       underlyingType.Quals.removeObjCLifetime();
5426     }
5427   }
5428 
5429   underlyingType.Quals.addObjCLifetime(lifetime);
5430 
5431   if (NonObjCPointer) {
5432     StringRef name = attr.getName()->getName();
5433     switch (lifetime) {
5434     case Qualifiers::OCL_None:
5435     case Qualifiers::OCL_ExplicitNone:
5436       break;
5437     case Qualifiers::OCL_Strong: name = "__strong"; break;
5438     case Qualifiers::OCL_Weak: name = "__weak"; break;
5439     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5440     }
5441     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5442       << TDS_ObjCObjOrBlock << type;
5443   }
5444 
5445   // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5446   // because having both 'T' and '__unsafe_unretained T' exist in the type
5447   // system causes unfortunate widespread consistency problems.  (For example,
5448   // they're not considered compatible types, and we mangle them identicially
5449   // as template arguments.)  These problems are all individually fixable,
5450   // but it's easier to just not add the qualifier and instead sniff it out
5451   // in specific places using isObjCInertUnsafeUnretainedType().
5452   //
5453   // Doing this does means we miss some trivial consistency checks that
5454   // would've triggered in ARC, but that's better than trying to solve all
5455   // the coexistence problems with __unsafe_unretained.
5456   if (!S.getLangOpts().ObjCAutoRefCount &&
5457       lifetime == Qualifiers::OCL_ExplicitNone) {
5458     type = S.Context.getAttributedType(
5459                              AttributedType::attr_objc_inert_unsafe_unretained,
5460                                        type, type);
5461     return true;
5462   }
5463 
5464   QualType origType = type;
5465   if (!NonObjCPointer)
5466     type = S.Context.getQualifiedType(underlyingType);
5467 
5468   // If we have a valid source location for the attribute, use an
5469   // AttributedType instead.
5470   if (AttrLoc.isValid())
5471     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5472                                        origType, type);
5473 
5474   auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5475                             unsigned diagnostic, QualType type) {
5476     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5477       S.DelayedDiagnostics.add(
5478           sema::DelayedDiagnostic::makeForbiddenType(
5479               S.getSourceManager().getExpansionLoc(loc),
5480               diagnostic, type, /*ignored*/ 0));
5481     } else {
5482       S.Diag(loc, diagnostic);
5483     }
5484   };
5485 
5486   // Sometimes, __weak isn't allowed.
5487   if (lifetime == Qualifiers::OCL_Weak &&
5488       !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5489 
5490     // Use a specialized diagnostic if the runtime just doesn't support them.
5491     unsigned diagnostic =
5492       (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5493                                        : diag::err_arc_weak_no_runtime);
5494 
5495     // In any case, delay the diagnostic until we know what we're parsing.
5496     diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5497 
5498     attr.setInvalid();
5499     return true;
5500   }
5501 
5502   // Forbid __weak for class objects marked as
5503   // objc_arc_weak_reference_unavailable
5504   if (lifetime == Qualifiers::OCL_Weak) {
5505     if (const ObjCObjectPointerType *ObjT =
5506           type->getAs<ObjCObjectPointerType>()) {
5507       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5508         if (Class->isArcWeakrefUnavailable()) {
5509           S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5510           S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5511                   diag::note_class_declared);
5512         }
5513       }
5514     }
5515   }
5516 
5517   return true;
5518 }
5519 
5520 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5521 /// attribute on the specified type.  Returns true to indicate that
5522 /// the attribute was handled, false to indicate that the type does
5523 /// not permit the attribute.
5524 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5525                                  AttributeList &attr,
5526                                  QualType &type) {
5527   Sema &S = state.getSema();
5528 
5529   // Delay if this isn't some kind of pointer.
5530   if (!type->isPointerType() &&
5531       !type->isObjCObjectPointerType() &&
5532       !type->isBlockPointerType())
5533     return false;
5534 
5535   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5536     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5537     attr.setInvalid();
5538     return true;
5539   }
5540 
5541   // Check the attribute arguments.
5542   if (!attr.isArgIdent(0)) {
5543     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5544       << attr.getName() << AANT_ArgumentString;
5545     attr.setInvalid();
5546     return true;
5547   }
5548   Qualifiers::GC GCAttr;
5549   if (attr.getNumArgs() > 1) {
5550     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5551       << attr.getName() << 1;
5552     attr.setInvalid();
5553     return true;
5554   }
5555 
5556   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5557   if (II->isStr("weak"))
5558     GCAttr = Qualifiers::Weak;
5559   else if (II->isStr("strong"))
5560     GCAttr = Qualifiers::Strong;
5561   else {
5562     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5563       << attr.getName() << II;
5564     attr.setInvalid();
5565     return true;
5566   }
5567 
5568   QualType origType = type;
5569   type = S.Context.getObjCGCQualType(origType, GCAttr);
5570 
5571   // Make an attributed type to preserve the source information.
5572   if (attr.getLoc().isValid())
5573     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5574                                        origType, type);
5575 
5576   return true;
5577 }
5578 
5579 namespace {
5580   /// A helper class to unwrap a type down to a function for the
5581   /// purposes of applying attributes there.
5582   ///
5583   /// Use:
5584   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
5585   ///   if (unwrapped.isFunctionType()) {
5586   ///     const FunctionType *fn = unwrapped.get();
5587   ///     // change fn somehow
5588   ///     T = unwrapped.wrap(fn);
5589   ///   }
5590   struct FunctionTypeUnwrapper {
5591     enum WrapKind {
5592       Desugar,
5593       Attributed,
5594       Parens,
5595       Pointer,
5596       BlockPointer,
5597       Reference,
5598       MemberPointer
5599     };
5600 
5601     QualType Original;
5602     const FunctionType *Fn;
5603     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5604 
5605     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5606       while (true) {
5607         const Type *Ty = T.getTypePtr();
5608         if (isa<FunctionType>(Ty)) {
5609           Fn = cast<FunctionType>(Ty);
5610           return;
5611         } else if (isa<ParenType>(Ty)) {
5612           T = cast<ParenType>(Ty)->getInnerType();
5613           Stack.push_back(Parens);
5614         } else if (isa<PointerType>(Ty)) {
5615           T = cast<PointerType>(Ty)->getPointeeType();
5616           Stack.push_back(Pointer);
5617         } else if (isa<BlockPointerType>(Ty)) {
5618           T = cast<BlockPointerType>(Ty)->getPointeeType();
5619           Stack.push_back(BlockPointer);
5620         } else if (isa<MemberPointerType>(Ty)) {
5621           T = cast<MemberPointerType>(Ty)->getPointeeType();
5622           Stack.push_back(MemberPointer);
5623         } else if (isa<ReferenceType>(Ty)) {
5624           T = cast<ReferenceType>(Ty)->getPointeeType();
5625           Stack.push_back(Reference);
5626         } else if (isa<AttributedType>(Ty)) {
5627           T = cast<AttributedType>(Ty)->getEquivalentType();
5628           Stack.push_back(Attributed);
5629         } else {
5630           const Type *DTy = Ty->getUnqualifiedDesugaredType();
5631           if (Ty == DTy) {
5632             Fn = nullptr;
5633             return;
5634           }
5635 
5636           T = QualType(DTy, 0);
5637           Stack.push_back(Desugar);
5638         }
5639       }
5640     }
5641 
5642     bool isFunctionType() const { return (Fn != nullptr); }
5643     const FunctionType *get() const { return Fn; }
5644 
5645     QualType wrap(Sema &S, const FunctionType *New) {
5646       // If T wasn't modified from the unwrapped type, do nothing.
5647       if (New == get()) return Original;
5648 
5649       Fn = New;
5650       return wrap(S.Context, Original, 0);
5651     }
5652 
5653   private:
5654     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5655       if (I == Stack.size())
5656         return C.getQualifiedType(Fn, Old.getQualifiers());
5657 
5658       // Build up the inner type, applying the qualifiers from the old
5659       // type to the new type.
5660       SplitQualType SplitOld = Old.split();
5661 
5662       // As a special case, tail-recurse if there are no qualifiers.
5663       if (SplitOld.Quals.empty())
5664         return wrap(C, SplitOld.Ty, I);
5665       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5666     }
5667 
5668     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5669       if (I == Stack.size()) return QualType(Fn, 0);
5670 
5671       switch (static_cast<WrapKind>(Stack[I++])) {
5672       case Desugar:
5673         // This is the point at which we potentially lose source
5674         // information.
5675         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5676 
5677       case Attributed:
5678         return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
5679 
5680       case Parens: {
5681         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5682         return C.getParenType(New);
5683       }
5684 
5685       case Pointer: {
5686         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5687         return C.getPointerType(New);
5688       }
5689 
5690       case BlockPointer: {
5691         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5692         return C.getBlockPointerType(New);
5693       }
5694 
5695       case MemberPointer: {
5696         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5697         QualType New = wrap(C, OldMPT->getPointeeType(), I);
5698         return C.getMemberPointerType(New, OldMPT->getClass());
5699       }
5700 
5701       case Reference: {
5702         const ReferenceType *OldRef = cast<ReferenceType>(Old);
5703         QualType New = wrap(C, OldRef->getPointeeType(), I);
5704         if (isa<LValueReferenceType>(OldRef))
5705           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5706         else
5707           return C.getRValueReferenceType(New);
5708       }
5709       }
5710 
5711       llvm_unreachable("unknown wrapping kind");
5712     }
5713   };
5714 } // end anonymous namespace
5715 
5716 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5717                                              AttributeList &Attr,
5718                                              QualType &Type) {
5719   Sema &S = State.getSema();
5720 
5721   AttributeList::Kind Kind = Attr.getKind();
5722   QualType Desugared = Type;
5723   const AttributedType *AT = dyn_cast<AttributedType>(Type);
5724   while (AT) {
5725     AttributedType::Kind CurAttrKind = AT->getAttrKind();
5726 
5727     // You cannot specify duplicate type attributes, so if the attribute has
5728     // already been applied, flag it.
5729     if (getAttrListKind(CurAttrKind) == Kind) {
5730       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5731         << Attr.getName();
5732       return true;
5733     }
5734 
5735     // You cannot have both __sptr and __uptr on the same type, nor can you
5736     // have __ptr32 and __ptr64.
5737     if ((CurAttrKind == AttributedType::attr_ptr32 &&
5738          Kind == AttributeList::AT_Ptr64) ||
5739         (CurAttrKind == AttributedType::attr_ptr64 &&
5740          Kind == AttributeList::AT_Ptr32)) {
5741       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5742         << "'__ptr32'" << "'__ptr64'";
5743       return true;
5744     } else if ((CurAttrKind == AttributedType::attr_sptr &&
5745                 Kind == AttributeList::AT_UPtr) ||
5746                (CurAttrKind == AttributedType::attr_uptr &&
5747                 Kind == AttributeList::AT_SPtr)) {
5748       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5749         << "'__sptr'" << "'__uptr'";
5750       return true;
5751     }
5752 
5753     Desugared = AT->getEquivalentType();
5754     AT = dyn_cast<AttributedType>(Desugared);
5755   }
5756 
5757   // Pointer type qualifiers can only operate on pointer types, but not
5758   // pointer-to-member types.
5759   if (!isa<PointerType>(Desugared)) {
5760     if (Type->isMemberPointerType())
5761       S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
5762           << Attr.getName();
5763     else
5764       S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
5765           << Attr.getName() << 0;
5766     return true;
5767   }
5768 
5769   AttributedType::Kind TAK;
5770   switch (Kind) {
5771   default: llvm_unreachable("Unknown attribute kind");
5772   case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5773   case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5774   case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5775   case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5776   }
5777 
5778   Type = S.Context.getAttributedType(TAK, Type, Type);
5779   return false;
5780 }
5781 
5782 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
5783                                          NullabilityKind nullability,
5784                                          SourceLocation nullabilityLoc,
5785                                          bool isContextSensitive) {
5786   // We saw a nullability type specifier. If this is the first one for
5787   // this file, note that.
5788   FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
5789   if (!file.isInvalid()) {
5790     FileNullability &fileNullability = NullabilityMap[file];
5791     if (!fileNullability.SawTypeNullability) {
5792       // If we have already seen a pointer declarator without a nullability
5793       // annotation, complain about it.
5794       if (fileNullability.PointerLoc.isValid()) {
5795         Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
5796           << static_cast<unsigned>(fileNullability.PointerKind);
5797       }
5798 
5799       fileNullability.SawTypeNullability = true;
5800     }
5801   }
5802 
5803   // Check for existing nullability attributes on the type.
5804   QualType desugared = type;
5805   while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5806     // Check whether there is already a null
5807     if (auto existingNullability = attributed->getImmediateNullability()) {
5808       // Duplicated nullability.
5809       if (nullability == *existingNullability) {
5810         Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5811           << DiagNullabilityKind(nullability, isContextSensitive)
5812           << FixItHint::CreateRemoval(nullabilityLoc);
5813 
5814         break;
5815       }
5816 
5817       // Conflicting nullability.
5818       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5819         << DiagNullabilityKind(nullability, isContextSensitive)
5820         << DiagNullabilityKind(*existingNullability, false);
5821       return true;
5822     }
5823 
5824     desugared = attributed->getModifiedType();
5825   }
5826 
5827   // If there is already a different nullability specifier, complain.
5828   // This (unlike the code above) looks through typedefs that might
5829   // have nullability specifiers on them, which means we cannot
5830   // provide a useful Fix-It.
5831   if (auto existingNullability = desugared->getNullability(Context)) {
5832     if (nullability != *existingNullability) {
5833       Diag(nullabilityLoc, diag::err_nullability_conflicting)
5834         << DiagNullabilityKind(nullability, isContextSensitive)
5835         << DiagNullabilityKind(*existingNullability, false);
5836 
5837       // Try to find the typedef with the existing nullability specifier.
5838       if (auto typedefType = desugared->getAs<TypedefType>()) {
5839         TypedefNameDecl *typedefDecl = typedefType->getDecl();
5840         QualType underlyingType = typedefDecl->getUnderlyingType();
5841         if (auto typedefNullability
5842               = AttributedType::stripOuterNullability(underlyingType)) {
5843           if (*typedefNullability == *existingNullability) {
5844             Diag(typedefDecl->getLocation(), diag::note_nullability_here)
5845               << DiagNullabilityKind(*existingNullability, false);
5846           }
5847         }
5848       }
5849 
5850       return true;
5851     }
5852   }
5853 
5854   // If this definitely isn't a pointer type, reject the specifier.
5855   if (!desugared->canHaveNullability()) {
5856     Diag(nullabilityLoc, diag::err_nullability_nonpointer)
5857       << DiagNullabilityKind(nullability, isContextSensitive) << type;
5858     return true;
5859   }
5860 
5861   // For the context-sensitive keywords/Objective-C property
5862   // attributes, require that the type be a single-level pointer.
5863   if (isContextSensitive) {
5864     // Make sure that the pointee isn't itself a pointer type.
5865     QualType pointeeType = desugared->getPointeeType();
5866     if (pointeeType->isAnyPointerType() ||
5867         pointeeType->isObjCObjectPointerType() ||
5868         pointeeType->isMemberPointerType()) {
5869       Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5870         << DiagNullabilityKind(nullability, true)
5871         << type;
5872       Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5873         << DiagNullabilityKind(nullability, false)
5874         << type
5875         << FixItHint::CreateReplacement(nullabilityLoc,
5876                                         getNullabilitySpelling(nullability));
5877       return true;
5878     }
5879   }
5880 
5881   // Form the attributed type.
5882   type = Context.getAttributedType(
5883            AttributedType::getNullabilityAttrKind(nullability), type, type);
5884   return false;
5885 }
5886 
5887 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
5888   // Find out if it's an Objective-C object or object pointer type;
5889   const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
5890   const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
5891                                           : type->getAs<ObjCObjectType>();
5892 
5893   // If not, we can't apply __kindof.
5894   if (!objType) {
5895     // FIXME: Handle dependent types that aren't yet object types.
5896     Diag(loc, diag::err_objc_kindof_nonobject)
5897       << type;
5898     return true;
5899   }
5900 
5901   // Rebuild the "equivalent" type, which pushes __kindof down into
5902   // the object type.
5903   // There is no need to apply kindof on an unqualified id type.
5904   QualType equivType = Context.getObjCObjectType(
5905       objType->getBaseType(), objType->getTypeArgsAsWritten(),
5906       objType->getProtocols(),
5907       /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
5908 
5909   // If we started with an object pointer type, rebuild it.
5910   if (ptrType) {
5911     equivType = Context.getObjCObjectPointerType(equivType);
5912     if (auto nullability = type->getNullability(Context)) {
5913       auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
5914       equivType = Context.getAttributedType(attrKind, equivType, equivType);
5915     }
5916   }
5917 
5918   // Build the attributed type to record where __kindof occurred.
5919   type = Context.getAttributedType(AttributedType::attr_objc_kindof,
5920                                    type,
5921                                    equivType);
5922 
5923   return false;
5924 }
5925 
5926 /// Map a nullability attribute kind to a nullability kind.
5927 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5928   switch (kind) {
5929   case AttributeList::AT_TypeNonNull:
5930     return NullabilityKind::NonNull;
5931 
5932   case AttributeList::AT_TypeNullable:
5933     return NullabilityKind::Nullable;
5934 
5935   case AttributeList::AT_TypeNullUnspecified:
5936     return NullabilityKind::Unspecified;
5937 
5938   default:
5939     llvm_unreachable("not a nullability attribute kind");
5940   }
5941 }
5942 
5943 /// Distribute a nullability type attribute that cannot be applied to
5944 /// the type specifier to a pointer, block pointer, or member pointer
5945 /// declarator, complaining if necessary.
5946 ///
5947 /// \returns true if the nullability annotation was distributed, false
5948 /// otherwise.
5949 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5950                                           QualType type,
5951                                           AttributeList &attr) {
5952   Declarator &declarator = state.getDeclarator();
5953 
5954   /// Attempt to move the attribute to the specified chunk.
5955   auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
5956     // If there is already a nullability attribute there, don't add
5957     // one.
5958     if (hasNullabilityAttr(chunk.getAttrListRef()))
5959       return false;
5960 
5961     // Complain about the nullability qualifier being in the wrong
5962     // place.
5963     enum {
5964       PK_Pointer,
5965       PK_BlockPointer,
5966       PK_MemberPointer,
5967       PK_FunctionPointer,
5968       PK_MemberFunctionPointer,
5969     } pointerKind
5970       = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
5971                                                              : PK_Pointer)
5972         : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
5973         : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
5974 
5975     auto diag = state.getSema().Diag(attr.getLoc(),
5976                                      diag::warn_nullability_declspec)
5977       << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
5978                              attr.isContextSensitiveKeywordAttribute())
5979       << type
5980       << static_cast<unsigned>(pointerKind);
5981 
5982     // FIXME: MemberPointer chunks don't carry the location of the *.
5983     if (chunk.Kind != DeclaratorChunk::MemberPointer) {
5984       diag << FixItHint::CreateRemoval(attr.getLoc())
5985            << FixItHint::CreateInsertion(
5986                 state.getSema().getPreprocessor()
5987                   .getLocForEndOfToken(chunk.Loc),
5988                 " " + attr.getName()->getName().str() + " ");
5989     }
5990 
5991     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
5992                            chunk.getAttrListRef());
5993     return true;
5994   };
5995 
5996   // Move it to the outermost pointer, member pointer, or block
5997   // pointer declarator.
5998   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
5999     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6000     switch (chunk.Kind) {
6001     case DeclaratorChunk::Pointer:
6002     case DeclaratorChunk::BlockPointer:
6003     case DeclaratorChunk::MemberPointer:
6004       return moveToChunk(chunk, false);
6005 
6006     case DeclaratorChunk::Paren:
6007     case DeclaratorChunk::Array:
6008       continue;
6009 
6010     case DeclaratorChunk::Function:
6011       // Try to move past the return type to a function/block/member
6012       // function pointer.
6013       if (DeclaratorChunk *dest = maybeMovePastReturnType(
6014                                     declarator, i,
6015                                     /*onlyBlockPointers=*/false)) {
6016         return moveToChunk(*dest, true);
6017       }
6018 
6019       return false;
6020 
6021     // Don't walk through these.
6022     case DeclaratorChunk::Reference:
6023     case DeclaratorChunk::Pipe:
6024       return false;
6025     }
6026   }
6027 
6028   return false;
6029 }
6030 
6031 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6032   assert(!Attr.isInvalid());
6033   switch (Attr.getKind()) {
6034   default:
6035     llvm_unreachable("not a calling convention attribute");
6036   case AttributeList::AT_CDecl:
6037     return AttributedType::attr_cdecl;
6038   case AttributeList::AT_FastCall:
6039     return AttributedType::attr_fastcall;
6040   case AttributeList::AT_StdCall:
6041     return AttributedType::attr_stdcall;
6042   case AttributeList::AT_ThisCall:
6043     return AttributedType::attr_thiscall;
6044   case AttributeList::AT_Pascal:
6045     return AttributedType::attr_pascal;
6046   case AttributeList::AT_SwiftCall:
6047     return AttributedType::attr_swiftcall;
6048   case AttributeList::AT_VectorCall:
6049     return AttributedType::attr_vectorcall;
6050   case AttributeList::AT_Pcs: {
6051     // The attribute may have had a fixit applied where we treated an
6052     // identifier as a string literal.  The contents of the string are valid,
6053     // but the form may not be.
6054     StringRef Str;
6055     if (Attr.isArgExpr(0))
6056       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6057     else
6058       Str = Attr.getArgAsIdent(0)->Ident->getName();
6059     return llvm::StringSwitch<AttributedType::Kind>(Str)
6060         .Case("aapcs", AttributedType::attr_pcs)
6061         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6062   }
6063   case AttributeList::AT_IntelOclBicc:
6064     return AttributedType::attr_inteloclbicc;
6065   case AttributeList::AT_MSABI:
6066     return AttributedType::attr_ms_abi;
6067   case AttributeList::AT_SysVABI:
6068     return AttributedType::attr_sysv_abi;
6069   case AttributeList::AT_PreserveMost:
6070     return AttributedType::attr_preserve_most;
6071   case AttributeList::AT_PreserveAll:
6072     return AttributedType::attr_preserve_all;
6073   }
6074   llvm_unreachable("unexpected attribute kind!");
6075 }
6076 
6077 /// Process an individual function attribute.  Returns true to
6078 /// indicate that the attribute was handled, false if it wasn't.
6079 static bool handleFunctionTypeAttr(TypeProcessingState &state,
6080                                    AttributeList &attr,
6081                                    QualType &type) {
6082   Sema &S = state.getSema();
6083 
6084   FunctionTypeUnwrapper unwrapped(S, type);
6085 
6086   if (attr.getKind() == AttributeList::AT_NoReturn) {
6087     if (S.CheckNoReturnAttr(attr))
6088       return true;
6089 
6090     // Delay if this is not a function type.
6091     if (!unwrapped.isFunctionType())
6092       return false;
6093 
6094     // Otherwise we can process right away.
6095     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6096     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6097     return true;
6098   }
6099 
6100   // ns_returns_retained is not always a type attribute, but if we got
6101   // here, we're treating it as one right now.
6102   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6103     assert(S.getLangOpts().ObjCAutoRefCount &&
6104            "ns_returns_retained treated as type attribute in non-ARC");
6105     if (attr.getNumArgs()) return true;
6106 
6107     // Delay if this is not a function type.
6108     if (!unwrapped.isFunctionType())
6109       return false;
6110 
6111     FunctionType::ExtInfo EI
6112       = unwrapped.get()->getExtInfo().withProducesResult(true);
6113     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6114     return true;
6115   }
6116 
6117   if (attr.getKind() == AttributeList::AT_Regparm) {
6118     unsigned value;
6119     if (S.CheckRegparmAttr(attr, value))
6120       return true;
6121 
6122     // Delay if this is not a function type.
6123     if (!unwrapped.isFunctionType())
6124       return false;
6125 
6126     // Diagnose regparm with fastcall.
6127     const FunctionType *fn = unwrapped.get();
6128     CallingConv CC = fn->getCallConv();
6129     if (CC == CC_X86FastCall) {
6130       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6131         << FunctionType::getNameForCallConv(CC)
6132         << "regparm";
6133       attr.setInvalid();
6134       return true;
6135     }
6136 
6137     FunctionType::ExtInfo EI =
6138       unwrapped.get()->getExtInfo().withRegParm(value);
6139     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6140     return true;
6141   }
6142 
6143   // Delay if the type didn't work out to a function.
6144   if (!unwrapped.isFunctionType()) return false;
6145 
6146   // Otherwise, a calling convention.
6147   CallingConv CC;
6148   if (S.CheckCallingConvAttr(attr, CC))
6149     return true;
6150 
6151   const FunctionType *fn = unwrapped.get();
6152   CallingConv CCOld = fn->getCallConv();
6153   AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6154 
6155   if (CCOld != CC) {
6156     // Error out on when there's already an attribute on the type
6157     // and the CCs don't match.
6158     const AttributedType *AT = S.getCallingConvAttributedType(type);
6159     if (AT && AT->getAttrKind() != CCAttrKind) {
6160       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6161         << FunctionType::getNameForCallConv(CC)
6162         << FunctionType::getNameForCallConv(CCOld);
6163       attr.setInvalid();
6164       return true;
6165     }
6166   }
6167 
6168   // Diagnose use of variadic functions with calling conventions that
6169   // don't support them (e.g. because they're callee-cleanup).
6170   // We delay warning about this on unprototyped function declarations
6171   // until after redeclaration checking, just in case we pick up a
6172   // prototype that way.  And apparently we also "delay" warning about
6173   // unprototyped function types in general, despite not necessarily having
6174   // much ability to diagnose it later.
6175   if (!supportsVariadicCall(CC)) {
6176     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6177     if (FnP && FnP->isVariadic()) {
6178       unsigned DiagID = diag::err_cconv_varargs;
6179 
6180       // stdcall and fastcall are ignored with a warning for GCC and MS
6181       // compatibility.
6182       bool IsInvalid = true;
6183       if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6184         DiagID = diag::warn_cconv_varargs;
6185         IsInvalid = false;
6186       }
6187 
6188       S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6189       if (IsInvalid) attr.setInvalid();
6190       return true;
6191     }
6192   }
6193 
6194   // Also diagnose fastcall with regparm.
6195   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6196     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6197         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6198     attr.setInvalid();
6199     return true;
6200   }
6201 
6202   // Modify the CC from the wrapped function type, wrap it all back, and then
6203   // wrap the whole thing in an AttributedType as written.  The modified type
6204   // might have a different CC if we ignored the attribute.
6205   QualType Equivalent;
6206   if (CCOld == CC) {
6207     Equivalent = type;
6208   } else {
6209     auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6210     Equivalent =
6211       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6212   }
6213   type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6214   return true;
6215 }
6216 
6217 bool Sema::hasExplicitCallingConv(QualType &T) {
6218   QualType R = T.IgnoreParens();
6219   while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6220     if (AT->isCallingConv())
6221       return true;
6222     R = AT->getModifiedType().IgnoreParens();
6223   }
6224   return false;
6225 }
6226 
6227 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6228                                   SourceLocation Loc) {
6229   FunctionTypeUnwrapper Unwrapped(*this, T);
6230   const FunctionType *FT = Unwrapped.get();
6231   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6232                      cast<FunctionProtoType>(FT)->isVariadic());
6233   CallingConv CurCC = FT->getCallConv();
6234   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6235 
6236   if (CurCC == ToCC)
6237     return;
6238 
6239   // MS compiler ignores explicit calling convention attributes on structors. We
6240   // should do the same.
6241   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6242     // Issue a warning on ignored calling convention -- except of __stdcall.
6243     // Again, this is what MS compiler does.
6244     if (CurCC != CC_X86StdCall)
6245       Diag(Loc, diag::warn_cconv_structors)
6246           << FunctionType::getNameForCallConv(CurCC);
6247   // Default adjustment.
6248   } else {
6249     // Only adjust types with the default convention.  For example, on Windows
6250     // we should adjust a __cdecl type to __thiscall for instance methods, and a
6251     // __thiscall type to __cdecl for static methods.
6252     CallingConv DefaultCC =
6253         Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6254 
6255     if (CurCC != DefaultCC || DefaultCC == ToCC)
6256       return;
6257 
6258     if (hasExplicitCallingConv(T))
6259       return;
6260   }
6261 
6262   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6263   QualType Wrapped = Unwrapped.wrap(*this, FT);
6264   T = Context.getAdjustedType(T, Wrapped);
6265 }
6266 
6267 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6268 /// and float scalars, although arrays, pointers, and function return values are
6269 /// allowed in conjunction with this construct. Aggregates with this attribute
6270 /// are invalid, even if they are of the same size as a corresponding scalar.
6271 /// The raw attribute should contain precisely 1 argument, the vector size for
6272 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6273 /// this routine will return a new vector type.
6274 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6275                                  Sema &S) {
6276   // Check the attribute arguments.
6277   if (Attr.getNumArgs() != 1) {
6278     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6279       << Attr.getName() << 1;
6280     Attr.setInvalid();
6281     return;
6282   }
6283   Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6284   llvm::APSInt vecSize(32);
6285   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6286       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6287     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6288       << Attr.getName() << AANT_ArgumentIntegerConstant
6289       << sizeExpr->getSourceRange();
6290     Attr.setInvalid();
6291     return;
6292   }
6293   // The base type must be integer (not Boolean or enumeration) or float, and
6294   // can't already be a vector.
6295   if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6296       (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6297     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6298     Attr.setInvalid();
6299     return;
6300   }
6301   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6302   // vecSize is specified in bytes - convert to bits.
6303   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6304 
6305   // the vector size needs to be an integral multiple of the type size.
6306   if (vectorSize % typeSize) {
6307     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6308       << sizeExpr->getSourceRange();
6309     Attr.setInvalid();
6310     return;
6311   }
6312   if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6313     S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6314       << sizeExpr->getSourceRange();
6315     Attr.setInvalid();
6316     return;
6317   }
6318   if (vectorSize == 0) {
6319     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6320       << sizeExpr->getSourceRange();
6321     Attr.setInvalid();
6322     return;
6323   }
6324 
6325   // Success! Instantiate the vector type, the number of elements is > 0, and
6326   // not required to be a power of 2, unlike GCC.
6327   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6328                                     VectorType::GenericVector);
6329 }
6330 
6331 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6332 /// a type.
6333 static void HandleExtVectorTypeAttr(QualType &CurType,
6334                                     const AttributeList &Attr,
6335                                     Sema &S) {
6336   // check the attribute arguments.
6337   if (Attr.getNumArgs() != 1) {
6338     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6339       << Attr.getName() << 1;
6340     return;
6341   }
6342 
6343   Expr *sizeExpr;
6344 
6345   // Special case where the argument is a template id.
6346   if (Attr.isArgIdent(0)) {
6347     CXXScopeSpec SS;
6348     SourceLocation TemplateKWLoc;
6349     UnqualifiedId id;
6350     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6351 
6352     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6353                                           id, false, false);
6354     if (Size.isInvalid())
6355       return;
6356 
6357     sizeExpr = Size.get();
6358   } else {
6359     sizeExpr = Attr.getArgAsExpr(0);
6360   }
6361 
6362   // Create the vector type.
6363   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6364   if (!T.isNull())
6365     CurType = T;
6366 }
6367 
6368 static bool isPermittedNeonBaseType(QualType &Ty,
6369                                     VectorType::VectorKind VecKind, Sema &S) {
6370   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6371   if (!BTy)
6372     return false;
6373 
6374   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6375 
6376   // Signed poly is mathematically wrong, but has been baked into some ABIs by
6377   // now.
6378   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6379                         Triple.getArch() == llvm::Triple::aarch64_be;
6380   if (VecKind == VectorType::NeonPolyVector) {
6381     if (IsPolyUnsigned) {
6382       // AArch64 polynomial vectors are unsigned and support poly64.
6383       return BTy->getKind() == BuiltinType::UChar ||
6384              BTy->getKind() == BuiltinType::UShort ||
6385              BTy->getKind() == BuiltinType::ULong ||
6386              BTy->getKind() == BuiltinType::ULongLong;
6387     } else {
6388       // AArch32 polynomial vector are signed.
6389       return BTy->getKind() == BuiltinType::SChar ||
6390              BTy->getKind() == BuiltinType::Short;
6391     }
6392   }
6393 
6394   // Non-polynomial vector types: the usual suspects are allowed, as well as
6395   // float64_t on AArch64.
6396   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6397                  Triple.getArch() == llvm::Triple::aarch64_be;
6398 
6399   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6400     return true;
6401 
6402   return BTy->getKind() == BuiltinType::SChar ||
6403          BTy->getKind() == BuiltinType::UChar ||
6404          BTy->getKind() == BuiltinType::Short ||
6405          BTy->getKind() == BuiltinType::UShort ||
6406          BTy->getKind() == BuiltinType::Int ||
6407          BTy->getKind() == BuiltinType::UInt ||
6408          BTy->getKind() == BuiltinType::Long ||
6409          BTy->getKind() == BuiltinType::ULong ||
6410          BTy->getKind() == BuiltinType::LongLong ||
6411          BTy->getKind() == BuiltinType::ULongLong ||
6412          BTy->getKind() == BuiltinType::Float ||
6413          BTy->getKind() == BuiltinType::Half;
6414 }
6415 
6416 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6417 /// "neon_polyvector_type" attributes are used to create vector types that
6418 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
6419 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
6420 /// the argument to these Neon attributes is the number of vector elements,
6421 /// not the vector size in bytes.  The vector width and element type must
6422 /// match one of the standard Neon vector types.
6423 static void HandleNeonVectorTypeAttr(QualType& CurType,
6424                                      const AttributeList &Attr, Sema &S,
6425                                      VectorType::VectorKind VecKind) {
6426   // Target must have NEON
6427   if (!S.Context.getTargetInfo().hasFeature("neon")) {
6428     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6429     Attr.setInvalid();
6430     return;
6431   }
6432   // Check the attribute arguments.
6433   if (Attr.getNumArgs() != 1) {
6434     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6435       << Attr.getName() << 1;
6436     Attr.setInvalid();
6437     return;
6438   }
6439   // The number of elements must be an ICE.
6440   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6441   llvm::APSInt numEltsInt(32);
6442   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6443       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6444     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6445       << Attr.getName() << AANT_ArgumentIntegerConstant
6446       << numEltsExpr->getSourceRange();
6447     Attr.setInvalid();
6448     return;
6449   }
6450   // Only certain element types are supported for Neon vectors.
6451   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6452     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6453     Attr.setInvalid();
6454     return;
6455   }
6456 
6457   // The total size of the vector must be 64 or 128 bits.
6458   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6459   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6460   unsigned vecSize = typeSize * numElts;
6461   if (vecSize != 64 && vecSize != 128) {
6462     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6463     Attr.setInvalid();
6464     return;
6465   }
6466 
6467   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6468 }
6469 
6470 /// Handle OpenCL Access Qualifier Attribute.
6471 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
6472                                    Sema &S) {
6473   // OpenCL v2.0 s6.6 - Access qualifier can used only for image and pipe type.
6474   if (!(CurType->isImageType() || CurType->isPipeType())) {
6475     S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
6476     Attr.setInvalid();
6477     return;
6478   }
6479 }
6480 
6481 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6482                              TypeAttrLocation TAL, AttributeList *attrs) {
6483   // Scan through and apply attributes to this type where it makes sense.  Some
6484   // attributes (such as __address_space__, __vector_size__, etc) apply to the
6485   // type, but others can be present in the type specifiers even though they
6486   // apply to the decl.  Here we apply type attributes and ignore the rest.
6487 
6488   bool hasOpenCLAddressSpace = false;
6489   while (attrs) {
6490     AttributeList &attr = *attrs;
6491     attrs = attr.getNext(); // reset to the next here due to early loop continue
6492                             // stmts
6493 
6494     // Skip attributes that were marked to be invalid.
6495     if (attr.isInvalid())
6496       continue;
6497 
6498     if (attr.isCXX11Attribute()) {
6499       // [[gnu::...]] attributes are treated as declaration attributes, so may
6500       // not appertain to a DeclaratorChunk, even if we handle them as type
6501       // attributes.
6502       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6503         if (TAL == TAL_DeclChunk) {
6504           state.getSema().Diag(attr.getLoc(),
6505                                diag::warn_cxx11_gnu_attribute_on_type)
6506               << attr.getName();
6507           continue;
6508         }
6509       } else if (TAL != TAL_DeclChunk) {
6510         // Otherwise, only consider type processing for a C++11 attribute if
6511         // it's actually been applied to a type.
6512         continue;
6513       }
6514     }
6515 
6516     // If this is an attribute we can handle, do so now,
6517     // otherwise, add it to the FnAttrs list for rechaining.
6518     switch (attr.getKind()) {
6519     default:
6520       // A C++11 attribute on a declarator chunk must appertain to a type.
6521       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6522         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6523           << attr.getName();
6524         attr.setUsedAsTypeAttr();
6525       }
6526       break;
6527 
6528     case AttributeList::UnknownAttribute:
6529       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6530         state.getSema().Diag(attr.getLoc(),
6531                              diag::warn_unknown_attribute_ignored)
6532           << attr.getName();
6533       break;
6534 
6535     case AttributeList::IgnoredAttribute:
6536       break;
6537 
6538     case AttributeList::AT_MayAlias:
6539       // FIXME: This attribute needs to actually be handled, but if we ignore
6540       // it it breaks large amounts of Linux software.
6541       attr.setUsedAsTypeAttr();
6542       break;
6543     case AttributeList::AT_OpenCLPrivateAddressSpace:
6544     case AttributeList::AT_OpenCLGlobalAddressSpace:
6545     case AttributeList::AT_OpenCLLocalAddressSpace:
6546     case AttributeList::AT_OpenCLConstantAddressSpace:
6547     case AttributeList::AT_OpenCLGenericAddressSpace:
6548     case AttributeList::AT_AddressSpace:
6549       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6550       attr.setUsedAsTypeAttr();
6551       hasOpenCLAddressSpace = true;
6552       break;
6553     OBJC_POINTER_TYPE_ATTRS_CASELIST:
6554       if (!handleObjCPointerTypeAttr(state, attr, type))
6555         distributeObjCPointerTypeAttr(state, attr, type);
6556       attr.setUsedAsTypeAttr();
6557       break;
6558     case AttributeList::AT_VectorSize:
6559       HandleVectorSizeAttr(type, attr, state.getSema());
6560       attr.setUsedAsTypeAttr();
6561       break;
6562     case AttributeList::AT_ExtVectorType:
6563       HandleExtVectorTypeAttr(type, attr, state.getSema());
6564       attr.setUsedAsTypeAttr();
6565       break;
6566     case AttributeList::AT_NeonVectorType:
6567       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6568                                VectorType::NeonVector);
6569       attr.setUsedAsTypeAttr();
6570       break;
6571     case AttributeList::AT_NeonPolyVectorType:
6572       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6573                                VectorType::NeonPolyVector);
6574       attr.setUsedAsTypeAttr();
6575       break;
6576     case AttributeList::AT_OpenCLAccess:
6577       HandleOpenCLAccessAttr(type, attr, state.getSema());
6578       attr.setUsedAsTypeAttr();
6579       break;
6580 
6581     MS_TYPE_ATTRS_CASELIST:
6582       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6583         attr.setUsedAsTypeAttr();
6584       break;
6585 
6586 
6587     NULLABILITY_TYPE_ATTRS_CASELIST:
6588       // Either add nullability here or try to distribute it.  We
6589       // don't want to distribute the nullability specifier past any
6590       // dependent type, because that complicates the user model.
6591       if (type->canHaveNullability() || type->isDependentType() ||
6592           !distributeNullabilityTypeAttr(state, type, attr)) {
6593         if (state.getSema().checkNullabilityTypeSpecifier(
6594               type,
6595               mapNullabilityAttrKind(attr.getKind()),
6596               attr.getLoc(),
6597               attr.isContextSensitiveKeywordAttribute())) {
6598           attr.setInvalid();
6599         }
6600 
6601         attr.setUsedAsTypeAttr();
6602       }
6603       break;
6604 
6605     case AttributeList::AT_ObjCKindOf:
6606       // '__kindof' must be part of the decl-specifiers.
6607       switch (TAL) {
6608       case TAL_DeclSpec:
6609         break;
6610 
6611       case TAL_DeclChunk:
6612       case TAL_DeclName:
6613         state.getSema().Diag(attr.getLoc(),
6614                              diag::err_objc_kindof_wrong_position)
6615           << FixItHint::CreateRemoval(attr.getLoc())
6616           << FixItHint::CreateInsertion(
6617                state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6618         break;
6619       }
6620 
6621       // Apply it regardless.
6622       if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6623         attr.setInvalid();
6624       attr.setUsedAsTypeAttr();
6625       break;
6626 
6627     case AttributeList::AT_NSReturnsRetained:
6628       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6629         break;
6630       // fallthrough into the function attrs
6631 
6632     FUNCTION_TYPE_ATTRS_CASELIST:
6633       attr.setUsedAsTypeAttr();
6634 
6635       // Never process function type attributes as part of the
6636       // declaration-specifiers.
6637       if (TAL == TAL_DeclSpec)
6638         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6639 
6640       // Otherwise, handle the possible delays.
6641       else if (!handleFunctionTypeAttr(state, attr, type))
6642         distributeFunctionTypeAttr(state, attr, type);
6643       break;
6644     }
6645   }
6646 
6647   // If address space is not set, OpenCL 2.0 defines non private default
6648   // address spaces for some cases:
6649   // OpenCL 2.0, section 6.5:
6650   // The address space for a variable at program scope or a static variable
6651   // inside a function can either be __global or __constant, but defaults to
6652   // __global if not specified.
6653   // (...)
6654   // Pointers that are declared without pointing to a named address space point
6655   // to the generic address space.
6656   if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6657       !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6658       (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6659     Declarator &D = state.getDeclarator();
6660     if (state.getCurrentChunkIndex() > 0 &&
6661         D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6662             DeclaratorChunk::Pointer) {
6663       type = state.getSema().Context.getAddrSpaceQualType(
6664           type, LangAS::opencl_generic);
6665     } else if (state.getCurrentChunkIndex() == 0 &&
6666                D.getContext() == Declarator::FileContext &&
6667                !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6668                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6669                !type->isSamplerT())
6670       type = state.getSema().Context.getAddrSpaceQualType(
6671           type, LangAS::opencl_global);
6672     else if (state.getCurrentChunkIndex() == 0 &&
6673              D.getContext() == Declarator::BlockContext &&
6674              D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6675       type = state.getSema().Context.getAddrSpaceQualType(
6676           type, LangAS::opencl_global);
6677   }
6678 }
6679 
6680 void Sema::completeExprArrayBound(Expr *E) {
6681   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6682     if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6683       if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6684         SourceLocation PointOfInstantiation = E->getExprLoc();
6685 
6686         if (MemberSpecializationInfo *MSInfo =
6687                 Var->getMemberSpecializationInfo()) {
6688           // If we don't already have a point of instantiation, this is it.
6689           if (MSInfo->getPointOfInstantiation().isInvalid()) {
6690             MSInfo->setPointOfInstantiation(PointOfInstantiation);
6691 
6692             // This is a modification of an existing AST node. Notify
6693             // listeners.
6694             if (ASTMutationListener *L = getASTMutationListener())
6695               L->StaticDataMemberInstantiated(Var);
6696           }
6697         } else {
6698           VarTemplateSpecializationDecl *VarSpec =
6699               cast<VarTemplateSpecializationDecl>(Var);
6700           if (VarSpec->getPointOfInstantiation().isInvalid())
6701             VarSpec->setPointOfInstantiation(PointOfInstantiation);
6702         }
6703 
6704         InstantiateVariableDefinition(PointOfInstantiation, Var);
6705 
6706         // Update the type to the newly instantiated definition's type both
6707         // here and within the expression.
6708         if (VarDecl *Def = Var->getDefinition()) {
6709           DRE->setDecl(Def);
6710           QualType T = Def->getType();
6711           DRE->setType(T);
6712           // FIXME: Update the type on all intervening expressions.
6713           E->setType(T);
6714         }
6715 
6716         // We still go on to try to complete the type independently, as it
6717         // may also require instantiations or diagnostics if it remains
6718         // incomplete.
6719       }
6720     }
6721   }
6722 }
6723 
6724 /// \brief Ensure that the type of the given expression is complete.
6725 ///
6726 /// This routine checks whether the expression \p E has a complete type. If the
6727 /// expression refers to an instantiable construct, that instantiation is
6728 /// performed as needed to complete its type. Furthermore
6729 /// Sema::RequireCompleteType is called for the expression's type (or in the
6730 /// case of a reference type, the referred-to type).
6731 ///
6732 /// \param E The expression whose type is required to be complete.
6733 /// \param Diagnoser The object that will emit a diagnostic if the type is
6734 /// incomplete.
6735 ///
6736 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6737 /// otherwise.
6738 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
6739   QualType T = E->getType();
6740 
6741   // Incomplete array types may be completed by the initializer attached to
6742   // their definitions. For static data members of class templates and for
6743   // variable templates, we need to instantiate the definition to get this
6744   // initializer and complete the type.
6745   if (T->isIncompleteArrayType()) {
6746     completeExprArrayBound(E);
6747     T = E->getType();
6748   }
6749 
6750   // FIXME: Are there other cases which require instantiating something other
6751   // than the type to complete the type of an expression?
6752 
6753   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6754 }
6755 
6756 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6757   BoundTypeDiagnoser<> Diagnoser(DiagID);
6758   return RequireCompleteExprType(E, Diagnoser);
6759 }
6760 
6761 /// @brief Ensure that the type T is a complete type.
6762 ///
6763 /// This routine checks whether the type @p T is complete in any
6764 /// context where a complete type is required. If @p T is a complete
6765 /// type, returns false. If @p T is a class template specialization,
6766 /// this routine then attempts to perform class template
6767 /// instantiation. If instantiation fails, or if @p T is incomplete
6768 /// and cannot be completed, issues the diagnostic @p diag (giving it
6769 /// the type @p T) and returns true.
6770 ///
6771 /// @param Loc  The location in the source that the incomplete type
6772 /// diagnostic should refer to.
6773 ///
6774 /// @param T  The type that this routine is examining for completeness.
6775 ///
6776 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
6777 /// @c false otherwise.
6778 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6779                                TypeDiagnoser &Diagnoser) {
6780   if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
6781     return true;
6782   if (const TagType *Tag = T->getAs<TagType>()) {
6783     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
6784       Tag->getDecl()->setCompleteDefinitionRequired();
6785       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
6786     }
6787   }
6788   return false;
6789 }
6790 
6791 /// \brief Determine whether there is any declaration of \p D that was ever a
6792 ///        definition (perhaps before module merging) and is currently visible.
6793 /// \param D The definition of the entity.
6794 /// \param Suggested Filled in with the declaration that should be made visible
6795 ///        in order to provide a definition of this entity.
6796 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
6797 ///        not defined. This only matters for enums with a fixed underlying
6798 ///        type, since in all other cases, a type is complete if and only if it
6799 ///        is defined.
6800 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
6801                                 bool OnlyNeedComplete) {
6802   // Easy case: if we don't have modules, all declarations are visible.
6803   if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
6804     return true;
6805 
6806   // If this definition was instantiated from a template, map back to the
6807   // pattern from which it was instantiated.
6808   if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
6809     // We're in the middle of defining it; this definition should be treated
6810     // as visible.
6811     return true;
6812   } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6813     if (auto *Pattern = RD->getTemplateInstantiationPattern())
6814       RD = Pattern;
6815     D = RD->getDefinition();
6816   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
6817     if (auto *Pattern = ED->getTemplateInstantiationPattern())
6818       ED = Pattern;
6819     if (OnlyNeedComplete && ED->isFixed()) {
6820       // If the enum has a fixed underlying type, and we're only looking for a
6821       // complete type (not a definition), any visible declaration of it will
6822       // do.
6823       *Suggested = nullptr;
6824       for (auto *Redecl : ED->redecls()) {
6825         if (isVisible(Redecl))
6826           return true;
6827         if (Redecl->isThisDeclarationADefinition() ||
6828             (Redecl->isCanonicalDecl() && !*Suggested))
6829           *Suggested = Redecl;
6830       }
6831       return false;
6832     }
6833     D = ED->getDefinition();
6834   }
6835   assert(D && "missing definition for pattern of instantiated definition");
6836 
6837   *Suggested = D;
6838   if (isVisible(D))
6839     return true;
6840 
6841   // The external source may have additional definitions of this type that are
6842   // visible, so complete the redeclaration chain now and ask again.
6843   if (auto *Source = Context.getExternalSource()) {
6844     Source->CompleteRedeclChain(D);
6845     return isVisible(D);
6846   }
6847 
6848   return false;
6849 }
6850 
6851 /// Locks in the inheritance model for the given class and all of its bases.
6852 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
6853   RD = RD->getMostRecentDecl();
6854   if (!RD->hasAttr<MSInheritanceAttr>()) {
6855     MSInheritanceAttr::Spelling IM;
6856 
6857     switch (S.MSPointerToMemberRepresentationMethod) {
6858     case LangOptions::PPTMK_BestCase:
6859       IM = RD->calculateInheritanceModel();
6860       break;
6861     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6862       IM = MSInheritanceAttr::Keyword_single_inheritance;
6863       break;
6864     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6865       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6866       break;
6867     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6868       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6869       break;
6870     }
6871 
6872     RD->addAttr(MSInheritanceAttr::CreateImplicit(
6873         S.getASTContext(), IM,
6874         /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6875             LangOptions::PPTMK_BestCase,
6876         S.ImplicitMSInheritanceAttrLoc.isValid()
6877             ? S.ImplicitMSInheritanceAttrLoc
6878             : RD->getSourceRange()));
6879     S.Consumer.AssignInheritanceModel(RD);
6880   }
6881 }
6882 
6883 /// \brief The implementation of RequireCompleteType
6884 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6885                                    TypeDiagnoser *Diagnoser) {
6886   // FIXME: Add this assertion to make sure we always get instantiation points.
6887   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6888   // FIXME: Add this assertion to help us flush out problems with
6889   // checking for dependent types and type-dependent expressions.
6890   //
6891   //  assert(!T->isDependentType() &&
6892   //         "Can't ask whether a dependent type is complete");
6893 
6894   // We lock in the inheritance model once somebody has asked us to ensure
6895   // that a pointer-to-member type is complete.
6896   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6897     if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6898       if (!MPTy->getClass()->isDependentType()) {
6899         (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
6900         assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6901       }
6902     }
6903   }
6904 
6905   NamedDecl *Def = nullptr;
6906   bool Incomplete = T->isIncompleteType(&Def);
6907 
6908   // Check that any necessary explicit specializations are visible. For an
6909   // enum, we just need the declaration, so don't check this.
6910   if (Def && !isa<EnumDecl>(Def))
6911     checkSpecializationVisibility(Loc, Def);
6912 
6913   // If we have a complete type, we're done.
6914   if (!Incomplete) {
6915     // If we know about the definition but it is not visible, complain.
6916     NamedDecl *SuggestedDef = nullptr;
6917     if (Def &&
6918         !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
6919       // If the user is going to see an error here, recover by making the
6920       // definition visible.
6921       bool TreatAsComplete = Diagnoser && !isSFINAEContext();
6922       if (Diagnoser)
6923         diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
6924                               /*Recover*/TreatAsComplete);
6925       return !TreatAsComplete;
6926     }
6927 
6928     return false;
6929   }
6930 
6931   const TagType *Tag = T->getAs<TagType>();
6932   const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
6933 
6934   // If there's an unimported definition of this type in a module (for
6935   // instance, because we forward declared it, then imported the definition),
6936   // import that definition now.
6937   //
6938   // FIXME: What about other cases where an import extends a redeclaration
6939   // chain for a declaration that can be accessed through a mechanism other
6940   // than name lookup (eg, referenced in a template, or a variable whose type
6941   // could be completed by the module)?
6942   //
6943   // FIXME: Should we map through to the base array element type before
6944   // checking for a tag type?
6945   if (Tag || IFace) {
6946     NamedDecl *D =
6947         Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6948 
6949     // Avoid diagnosing invalid decls as incomplete.
6950     if (D->isInvalidDecl())
6951       return true;
6952 
6953     // Give the external AST source a chance to complete the type.
6954     if (auto *Source = Context.getExternalSource()) {
6955       if (Tag)
6956         Source->CompleteType(Tag->getDecl());
6957       else
6958         Source->CompleteType(IFace->getDecl());
6959 
6960       // If the external source completed the type, go through the motions
6961       // again to ensure we're allowed to use the completed type.
6962       if (!T->isIncompleteType())
6963         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6964     }
6965   }
6966 
6967   // If we have a class template specialization or a class member of a
6968   // class template specialization, or an array with known size of such,
6969   // try to instantiate it.
6970   QualType MaybeTemplate = T;
6971   while (const ConstantArrayType *Array
6972            = Context.getAsConstantArrayType(MaybeTemplate))
6973     MaybeTemplate = Array->getElementType();
6974   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
6975     bool Instantiated = false;
6976     bool Diagnosed = false;
6977     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
6978           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
6979       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
6980         Diagnosed = InstantiateClassTemplateSpecialization(
6981             Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
6982             /*Complain=*/Diagnoser);
6983         Instantiated = true;
6984       }
6985     } else if (CXXRecordDecl *Rec
6986                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
6987       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
6988       if (!Rec->isBeingDefined() && Pattern) {
6989         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
6990         assert(MSI && "Missing member specialization information?");
6991         // This record was instantiated from a class within a template.
6992         if (MSI->getTemplateSpecializationKind() !=
6993             TSK_ExplicitSpecialization) {
6994           Diagnosed = InstantiateClass(Loc, Rec, Pattern,
6995                                        getTemplateInstantiationArgs(Rec),
6996                                        TSK_ImplicitInstantiation,
6997                                        /*Complain=*/Diagnoser);
6998           Instantiated = true;
6999         }
7000       }
7001     }
7002 
7003     if (Instantiated) {
7004       // Instantiate* might have already complained that the template is not
7005       // defined, if we asked it to.
7006       if (Diagnoser && Diagnosed)
7007         return true;
7008       // If we instantiated a definition, check that it's usable, even if
7009       // instantiation produced an error, so that repeated calls to this
7010       // function give consistent answers.
7011       if (!T->isIncompleteType())
7012         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7013     }
7014   }
7015 
7016   // FIXME: If we didn't instantiate a definition because of an explicit
7017   // specialization declaration, check that it's visible.
7018 
7019   if (!Diagnoser)
7020     return true;
7021 
7022   Diagnoser->diagnose(*this, Loc, T);
7023 
7024   // If the type was a forward declaration of a class/struct/union
7025   // type, produce a note.
7026   if (Tag && !Tag->getDecl()->isInvalidDecl())
7027     Diag(Tag->getDecl()->getLocation(),
7028          Tag->isBeingDefined() ? diag::note_type_being_defined
7029                                : diag::note_forward_declaration)
7030       << QualType(Tag, 0);
7031 
7032   // If the Objective-C class was a forward declaration, produce a note.
7033   if (IFace && !IFace->getDecl()->isInvalidDecl())
7034     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7035 
7036   // If we have external information that we can use to suggest a fix,
7037   // produce a note.
7038   if (ExternalSource)
7039     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7040 
7041   return true;
7042 }
7043 
7044 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7045                                unsigned DiagID) {
7046   BoundTypeDiagnoser<> Diagnoser(DiagID);
7047   return RequireCompleteType(Loc, T, Diagnoser);
7048 }
7049 
7050 /// \brief Get diagnostic %select index for tag kind for
7051 /// literal type diagnostic message.
7052 /// WARNING: Indexes apply to particular diagnostics only!
7053 ///
7054 /// \returns diagnostic %select index.
7055 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7056   switch (Tag) {
7057   case TTK_Struct: return 0;
7058   case TTK_Interface: return 1;
7059   case TTK_Class:  return 2;
7060   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7061   }
7062 }
7063 
7064 /// @brief Ensure that the type T is a literal type.
7065 ///
7066 /// This routine checks whether the type @p T is a literal type. If @p T is an
7067 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7068 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7069 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7070 /// it the type @p T), along with notes explaining why the type is not a
7071 /// literal type, and returns true.
7072 ///
7073 /// @param Loc  The location in the source that the non-literal type
7074 /// diagnostic should refer to.
7075 ///
7076 /// @param T  The type that this routine is examining for literalness.
7077 ///
7078 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7079 ///
7080 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7081 /// @c false otherwise.
7082 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7083                               TypeDiagnoser &Diagnoser) {
7084   assert(!T->isDependentType() && "type should not be dependent");
7085 
7086   QualType ElemType = Context.getBaseElementType(T);
7087   if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7088       T->isLiteralType(Context))
7089     return false;
7090 
7091   Diagnoser.diagnose(*this, Loc, T);
7092 
7093   if (T->isVariableArrayType())
7094     return true;
7095 
7096   const RecordType *RT = ElemType->getAs<RecordType>();
7097   if (!RT)
7098     return true;
7099 
7100   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7101 
7102   // A partially-defined class type can't be a literal type, because a literal
7103   // class type must have a trivial destructor (which can't be checked until
7104   // the class definition is complete).
7105   if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7106     return true;
7107 
7108   // If the class has virtual base classes, then it's not an aggregate, and
7109   // cannot have any constexpr constructors or a trivial default constructor,
7110   // so is non-literal. This is better to diagnose than the resulting absence
7111   // of constexpr constructors.
7112   if (RD->getNumVBases()) {
7113     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7114       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7115     for (const auto &I : RD->vbases())
7116       Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7117           << I.getSourceRange();
7118   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7119              !RD->hasTrivialDefaultConstructor()) {
7120     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7121   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7122     for (const auto &I : RD->bases()) {
7123       if (!I.getType()->isLiteralType(Context)) {
7124         Diag(I.getLocStart(),
7125              diag::note_non_literal_base_class)
7126           << RD << I.getType() << I.getSourceRange();
7127         return true;
7128       }
7129     }
7130     for (const auto *I : RD->fields()) {
7131       if (!I->getType()->isLiteralType(Context) ||
7132           I->getType().isVolatileQualified()) {
7133         Diag(I->getLocation(), diag::note_non_literal_field)
7134           << RD << I << I->getType()
7135           << I->getType().isVolatileQualified();
7136         return true;
7137       }
7138     }
7139   } else if (!RD->hasTrivialDestructor()) {
7140     // All fields and bases are of literal types, so have trivial destructors.
7141     // If this class's destructor is non-trivial it must be user-declared.
7142     CXXDestructorDecl *Dtor = RD->getDestructor();
7143     assert(Dtor && "class has literal fields and bases but no dtor?");
7144     if (!Dtor)
7145       return true;
7146 
7147     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7148          diag::note_non_literal_user_provided_dtor :
7149          diag::note_non_literal_nontrivial_dtor) << RD;
7150     if (!Dtor->isUserProvided())
7151       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
7152   }
7153 
7154   return true;
7155 }
7156 
7157 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7158   BoundTypeDiagnoser<> Diagnoser(DiagID);
7159   return RequireLiteralType(Loc, T, Diagnoser);
7160 }
7161 
7162 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
7163 /// and qualified by the nested-name-specifier contained in SS.
7164 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7165                                  const CXXScopeSpec &SS, QualType T) {
7166   if (T.isNull())
7167     return T;
7168   NestedNameSpecifier *NNS;
7169   if (SS.isValid())
7170     NNS = SS.getScopeRep();
7171   else {
7172     if (Keyword == ETK_None)
7173       return T;
7174     NNS = nullptr;
7175   }
7176   return Context.getElaboratedType(Keyword, NNS, T);
7177 }
7178 
7179 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7180   ExprResult ER = CheckPlaceholderExpr(E);
7181   if (ER.isInvalid()) return QualType();
7182   E = ER.get();
7183 
7184   if (!getLangOpts().CPlusPlus && E->refersToBitField())
7185     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7186 
7187   if (!E->isTypeDependent()) {
7188     QualType T = E->getType();
7189     if (const TagType *TT = T->getAs<TagType>())
7190       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7191   }
7192   return Context.getTypeOfExprType(E);
7193 }
7194 
7195 /// getDecltypeForExpr - Given an expr, will return the decltype for
7196 /// that expression, according to the rules in C++11
7197 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7198 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7199   if (E->isTypeDependent())
7200     return S.Context.DependentTy;
7201 
7202   // C++11 [dcl.type.simple]p4:
7203   //   The type denoted by decltype(e) is defined as follows:
7204   //
7205   //     - if e is an unparenthesized id-expression or an unparenthesized class
7206   //       member access (5.2.5), decltype(e) is the type of the entity named
7207   //       by e. If there is no such entity, or if e names a set of overloaded
7208   //       functions, the program is ill-formed;
7209   //
7210   // We apply the same rules for Objective-C ivar and property references.
7211   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7212     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
7213       return VD->getType();
7214   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7215     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
7216       return FD->getType();
7217   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7218     return IR->getDecl()->getType();
7219   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7220     if (PR->isExplicitProperty())
7221       return PR->getExplicitProperty()->getType();
7222   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7223     return PE->getType();
7224   }
7225 
7226   // C++11 [expr.lambda.prim]p18:
7227   //   Every occurrence of decltype((x)) where x is a possibly
7228   //   parenthesized id-expression that names an entity of automatic
7229   //   storage duration is treated as if x were transformed into an
7230   //   access to a corresponding data member of the closure type that
7231   //   would have been declared if x were an odr-use of the denoted
7232   //   entity.
7233   using namespace sema;
7234   if (S.getCurLambda()) {
7235     if (isa<ParenExpr>(E)) {
7236       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7237         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7238           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
7239           if (!T.isNull())
7240             return S.Context.getLValueReferenceType(T);
7241         }
7242       }
7243     }
7244   }
7245 
7246 
7247   // C++11 [dcl.type.simple]p4:
7248   //   [...]
7249   QualType T = E->getType();
7250   switch (E->getValueKind()) {
7251   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
7252   //       type of e;
7253   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
7254   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
7255   //       type of e;
7256   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
7257   //  - otherwise, decltype(e) is the type of e.
7258   case VK_RValue: break;
7259   }
7260 
7261   return T;
7262 }
7263 
7264 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
7265                                  bool AsUnevaluated) {
7266   ExprResult ER = CheckPlaceholderExpr(E);
7267   if (ER.isInvalid()) return QualType();
7268   E = ER.get();
7269 
7270   if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
7271       E->HasSideEffects(Context, false)) {
7272     // The expression operand for decltype is in an unevaluated expression
7273     // context, so side effects could result in unintended consequences.
7274     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7275   }
7276 
7277   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7278 }
7279 
7280 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7281                                        UnaryTransformType::UTTKind UKind,
7282                                        SourceLocation Loc) {
7283   switch (UKind) {
7284   case UnaryTransformType::EnumUnderlyingType:
7285     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7286       Diag(Loc, diag::err_only_enums_have_underlying_types);
7287       return QualType();
7288     } else {
7289       QualType Underlying = BaseType;
7290       if (!BaseType->isDependentType()) {
7291         // The enum could be incomplete if we're parsing its definition or
7292         // recovering from an error.
7293         NamedDecl *FwdDecl = nullptr;
7294         if (BaseType->isIncompleteType(&FwdDecl)) {
7295           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7296           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7297           return QualType();
7298         }
7299 
7300         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7301         assert(ED && "EnumType has no EnumDecl");
7302 
7303         DiagnoseUseOfDecl(ED, Loc);
7304 
7305         Underlying = ED->getIntegerType();
7306         assert(!Underlying.isNull());
7307       }
7308       return Context.getUnaryTransformType(BaseType, Underlying,
7309                                         UnaryTransformType::EnumUnderlyingType);
7310     }
7311   }
7312   llvm_unreachable("unknown unary transform type");
7313 }
7314 
7315 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
7316   if (!T->isDependentType()) {
7317     // FIXME: It isn't entirely clear whether incomplete atomic types
7318     // are allowed or not; for simplicity, ban them for the moment.
7319     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7320       return QualType();
7321 
7322     int DisallowedKind = -1;
7323     if (T->isArrayType())
7324       DisallowedKind = 1;
7325     else if (T->isFunctionType())
7326       DisallowedKind = 2;
7327     else if (T->isReferenceType())
7328       DisallowedKind = 3;
7329     else if (T->isAtomicType())
7330       DisallowedKind = 4;
7331     else if (T.hasQualifiers())
7332       DisallowedKind = 5;
7333     else if (!T.isTriviallyCopyableType(Context))
7334       // Some other non-trivially-copyable type (probably a C++ class)
7335       DisallowedKind = 6;
7336 
7337     if (DisallowedKind != -1) {
7338       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7339       return QualType();
7340     }
7341 
7342     // FIXME: Do we need any handling for ARC here?
7343   }
7344 
7345   // Build the pointer type.
7346   return Context.getAtomicType(T);
7347 }
7348