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