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