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