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