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 "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Parse/ParseDiagnostic.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/ScopeInfo.h"
32 #include "clang/Sema/Template.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/Support/ErrorHandling.h"
36 
37 using namespace clang;
38 
39 enum TypeDiagSelector {
40   TDS_Function,
41   TDS_Pointer,
42   TDS_ObjCObjOrBlock
43 };
44 
45 /// isOmittedBlockReturnType - Return true if this declarator is missing a
46 /// return type because this is a omitted return type on a block literal.
isOmittedBlockReturnType(const Declarator & D)47 static bool isOmittedBlockReturnType(const Declarator &D) {
48   if (D.getContext() != Declarator::BlockLiteralContext ||
49       D.getDeclSpec().hasTypeSpecifier())
50     return false;
51 
52   if (D.getNumTypeObjects() == 0)
53     return true;   // ^{ ... }
54 
55   if (D.getNumTypeObjects() == 1 &&
56       D.getTypeObject(0).Kind == DeclaratorChunk::Function)
57     return true;   // ^(int X, float Y) { ... }
58 
59   return false;
60 }
61 
62 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
63 /// doesn't apply to the given type.
diagnoseBadTypeAttribute(Sema & S,const AttributeList & attr,QualType type)64 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
65                                      QualType type) {
66   TypeDiagSelector WhichType;
67   bool useExpansionLoc = true;
68   switch (attr.getKind()) {
69   case AttributeList::AT_ObjCGC:        WhichType = TDS_Pointer; break;
70   case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
71   default:
72     // Assume everything else was a function attribute.
73     WhichType = TDS_Function;
74     useExpansionLoc = false;
75     break;
76   }
77 
78   SourceLocation loc = attr.getLoc();
79   StringRef name = attr.getName()->getName();
80 
81   // The GC attributes are usually written with macros;  special-case them.
82   IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
83                                           : nullptr;
84   if (useExpansionLoc && loc.isMacroID() && II) {
85     if (II->isStr("strong")) {
86       if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
87     } else if (II->isStr("weak")) {
88       if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
89     }
90   }
91 
92   S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
93     << type;
94 }
95 
96 // objc_gc applies to Objective-C pointers or, otherwise, to the
97 // smallest available pointer type (i.e. 'void*' in 'void**').
98 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
99     case AttributeList::AT_ObjCGC: \
100     case AttributeList::AT_ObjCOwnership
101 
102 // Function type attributes.
103 #define FUNCTION_TYPE_ATTRS_CASELIST \
104     case AttributeList::AT_NoReturn: \
105     case AttributeList::AT_CDecl: \
106     case AttributeList::AT_FastCall: \
107     case AttributeList::AT_StdCall: \
108     case AttributeList::AT_ThisCall: \
109     case AttributeList::AT_Pascal: \
110     case AttributeList::AT_VectorCall: \
111     case AttributeList::AT_MSABI: \
112     case AttributeList::AT_SysVABI: \
113     case AttributeList::AT_Regparm: \
114     case AttributeList::AT_Pcs: \
115     case AttributeList::AT_PnaclCall: \
116     case AttributeList::AT_IntelOclBicc
117 
118 // Microsoft-specific type qualifiers.
119 #define MS_TYPE_ATTRS_CASELIST  \
120     case AttributeList::AT_Ptr32: \
121     case AttributeList::AT_Ptr64: \
122     case AttributeList::AT_SPtr: \
123     case AttributeList::AT_UPtr
124 
125 namespace {
126   /// An object which stores processing state for the entire
127   /// GetTypeForDeclarator process.
128   class TypeProcessingState {
129     Sema &sema;
130 
131     /// The declarator being processed.
132     Declarator &declarator;
133 
134     /// The index of the declarator chunk we're currently processing.
135     /// May be the total number of valid chunks, indicating the
136     /// DeclSpec.
137     unsigned chunkIndex;
138 
139     /// Whether there are non-trivial modifications to the decl spec.
140     bool trivial;
141 
142     /// Whether we saved the attributes in the decl spec.
143     bool hasSavedAttrs;
144 
145     /// The original set of attributes on the DeclSpec.
146     SmallVector<AttributeList*, 2> savedAttrs;
147 
148     /// A list of attributes to diagnose the uselessness of when the
149     /// processing is complete.
150     SmallVector<AttributeList*, 2> ignoredTypeAttrs;
151 
152   public:
TypeProcessingState(Sema & sema,Declarator & declarator)153     TypeProcessingState(Sema &sema, Declarator &declarator)
154       : sema(sema), declarator(declarator),
155         chunkIndex(declarator.getNumTypeObjects()),
156         trivial(true), hasSavedAttrs(false) {}
157 
getSema() const158     Sema &getSema() const {
159       return sema;
160     }
161 
getDeclarator() const162     Declarator &getDeclarator() const {
163       return declarator;
164     }
165 
isProcessingDeclSpec() const166     bool isProcessingDeclSpec() const {
167       return chunkIndex == declarator.getNumTypeObjects();
168     }
169 
getCurrentChunkIndex() const170     unsigned getCurrentChunkIndex() const {
171       return chunkIndex;
172     }
173 
setCurrentChunkIndex(unsigned idx)174     void setCurrentChunkIndex(unsigned idx) {
175       assert(idx <= declarator.getNumTypeObjects());
176       chunkIndex = idx;
177     }
178 
getCurrentAttrListRef() const179     AttributeList *&getCurrentAttrListRef() const {
180       if (isProcessingDeclSpec())
181         return getMutableDeclSpec().getAttributes().getListRef();
182       return declarator.getTypeObject(chunkIndex).getAttrListRef();
183     }
184 
185     /// Save the current set of attributes on the DeclSpec.
saveDeclSpecAttrs()186     void saveDeclSpecAttrs() {
187       // Don't try to save them multiple times.
188       if (hasSavedAttrs) return;
189 
190       DeclSpec &spec = getMutableDeclSpec();
191       for (AttributeList *attr = spec.getAttributes().getList(); attr;
192              attr = attr->getNext())
193         savedAttrs.push_back(attr);
194       trivial &= savedAttrs.empty();
195       hasSavedAttrs = true;
196     }
197 
198     /// Record that we had nowhere to put the given type attribute.
199     /// We will diagnose such attributes later.
addIgnoredTypeAttr(AttributeList & attr)200     void addIgnoredTypeAttr(AttributeList &attr) {
201       ignoredTypeAttrs.push_back(&attr);
202     }
203 
204     /// Diagnose all the ignored type attributes, given that the
205     /// declarator worked out to the given type.
diagnoseIgnoredTypeAttrs(QualType type) const206     void diagnoseIgnoredTypeAttrs(QualType type) const {
207       for (SmallVectorImpl<AttributeList*>::const_iterator
208              i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
209            i != e; ++i)
210         diagnoseBadTypeAttribute(getSema(), **i, type);
211     }
212 
~TypeProcessingState()213     ~TypeProcessingState() {
214       if (trivial) return;
215 
216       restoreDeclSpecAttrs();
217     }
218 
219   private:
getMutableDeclSpec() const220     DeclSpec &getMutableDeclSpec() const {
221       return const_cast<DeclSpec&>(declarator.getDeclSpec());
222     }
223 
restoreDeclSpecAttrs()224     void restoreDeclSpecAttrs() {
225       assert(hasSavedAttrs);
226 
227       if (savedAttrs.empty()) {
228         getMutableDeclSpec().getAttributes().set(nullptr);
229         return;
230       }
231 
232       getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
233       for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
234         savedAttrs[i]->setNext(savedAttrs[i+1]);
235       savedAttrs.back()->setNext(nullptr);
236     }
237   };
238 }
239 
spliceAttrIntoList(AttributeList & attr,AttributeList * & head)240 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
241   attr.setNext(head);
242   head = &attr;
243 }
244 
spliceAttrOutOfList(AttributeList & attr,AttributeList * & head)245 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
246   if (head == &attr) {
247     head = attr.getNext();
248     return;
249   }
250 
251   AttributeList *cur = head;
252   while (true) {
253     assert(cur && cur->getNext() && "ran out of attrs?");
254     if (cur->getNext() == &attr) {
255       cur->setNext(attr.getNext());
256       return;
257     }
258     cur = cur->getNext();
259   }
260 }
261 
moveAttrFromListToList(AttributeList & attr,AttributeList * & fromList,AttributeList * & toList)262 static void moveAttrFromListToList(AttributeList &attr,
263                                    AttributeList *&fromList,
264                                    AttributeList *&toList) {
265   spliceAttrOutOfList(attr, fromList);
266   spliceAttrIntoList(attr, toList);
267 }
268 
269 /// The location of a type attribute.
270 enum TypeAttrLocation {
271   /// The attribute is in the decl-specifier-seq.
272   TAL_DeclSpec,
273   /// The attribute is part of a DeclaratorChunk.
274   TAL_DeclChunk,
275   /// The attribute is immediately after the declaration's name.
276   TAL_DeclName
277 };
278 
279 static void processTypeAttrs(TypeProcessingState &state,
280                              QualType &type, TypeAttrLocation TAL,
281                              AttributeList *attrs);
282 
283 static bool handleFunctionTypeAttr(TypeProcessingState &state,
284                                    AttributeList &attr,
285                                    QualType &type);
286 
287 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
288                                              AttributeList &attr,
289                                              QualType &type);
290 
291 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
292                                  AttributeList &attr, QualType &type);
293 
294 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
295                                        AttributeList &attr, QualType &type);
296 
handleObjCPointerTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)297 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
298                                       AttributeList &attr, QualType &type) {
299   if (attr.getKind() == AttributeList::AT_ObjCGC)
300     return handleObjCGCTypeAttr(state, attr, type);
301   assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
302   return handleObjCOwnershipTypeAttr(state, attr, type);
303 }
304 
305 /// Given the index of a declarator chunk, check whether that chunk
306 /// directly specifies the return type of a function and, if so, find
307 /// an appropriate place for it.
308 ///
309 /// \param i - a notional index which the search will start
310 ///   immediately inside
maybeMovePastReturnType(Declarator & declarator,unsigned i)311 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
312                                                 unsigned i) {
313   assert(i <= declarator.getNumTypeObjects());
314 
315   DeclaratorChunk *result = nullptr;
316 
317   // First, look inwards past parens for a function declarator.
318   for (; i != 0; --i) {
319     DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
320     switch (fnChunk.Kind) {
321     case DeclaratorChunk::Paren:
322       continue;
323 
324     // If we find anything except a function, bail out.
325     case DeclaratorChunk::Pointer:
326     case DeclaratorChunk::BlockPointer:
327     case DeclaratorChunk::Array:
328     case DeclaratorChunk::Reference:
329     case DeclaratorChunk::MemberPointer:
330       return result;
331 
332     // If we do find a function declarator, scan inwards from that,
333     // looking for a block-pointer declarator.
334     case DeclaratorChunk::Function:
335       for (--i; i != 0; --i) {
336         DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1);
337         switch (blockChunk.Kind) {
338         case DeclaratorChunk::Paren:
339         case DeclaratorChunk::Pointer:
340         case DeclaratorChunk::Array:
341         case DeclaratorChunk::Function:
342         case DeclaratorChunk::Reference:
343         case DeclaratorChunk::MemberPointer:
344           continue;
345         case DeclaratorChunk::BlockPointer:
346           result = &blockChunk;
347           goto continue_outer;
348         }
349         llvm_unreachable("bad declarator chunk kind");
350       }
351 
352       // If we run out of declarators doing that, we're done.
353       return result;
354     }
355     llvm_unreachable("bad declarator chunk kind");
356 
357     // Okay, reconsider from our new point.
358   continue_outer: ;
359   }
360 
361   // Ran out of chunks, bail out.
362   return result;
363 }
364 
365 /// Given that an objc_gc attribute was written somewhere on a
366 /// declaration *other* than on the declarator itself (for which, use
367 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
368 /// didn't apply in whatever position it was written in, try to move
369 /// it to a more appropriate position.
distributeObjCPointerTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType type)370 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
371                                           AttributeList &attr,
372                                           QualType type) {
373   Declarator &declarator = state.getDeclarator();
374 
375   // Move it to the outermost normal or block pointer declarator.
376   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
377     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
378     switch (chunk.Kind) {
379     case DeclaratorChunk::Pointer:
380     case DeclaratorChunk::BlockPointer: {
381       // But don't move an ARC ownership attribute to the return type
382       // of a block.
383       DeclaratorChunk *destChunk = nullptr;
384       if (state.isProcessingDeclSpec() &&
385           attr.getKind() == AttributeList::AT_ObjCOwnership)
386         destChunk = maybeMovePastReturnType(declarator, i - 1);
387       if (!destChunk) destChunk = &chunk;
388 
389       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
390                              destChunk->getAttrListRef());
391       return;
392     }
393 
394     case DeclaratorChunk::Paren:
395     case DeclaratorChunk::Array:
396       continue;
397 
398     // We may be starting at the return type of a block.
399     case DeclaratorChunk::Function:
400       if (state.isProcessingDeclSpec() &&
401           attr.getKind() == AttributeList::AT_ObjCOwnership) {
402         if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) {
403           moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
404                                  dest->getAttrListRef());
405           return;
406         }
407       }
408       goto error;
409 
410     // Don't walk through these.
411     case DeclaratorChunk::Reference:
412     case DeclaratorChunk::MemberPointer:
413       goto error;
414     }
415   }
416  error:
417 
418   diagnoseBadTypeAttribute(state.getSema(), attr, type);
419 }
420 
421 /// Distribute an objc_gc type attribute that was written on the
422 /// declarator.
423 static void
distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState & state,AttributeList & attr,QualType & declSpecType)424 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
425                                             AttributeList &attr,
426                                             QualType &declSpecType) {
427   Declarator &declarator = state.getDeclarator();
428 
429   // objc_gc goes on the innermost pointer to something that's not a
430   // pointer.
431   unsigned innermost = -1U;
432   bool considerDeclSpec = true;
433   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
434     DeclaratorChunk &chunk = declarator.getTypeObject(i);
435     switch (chunk.Kind) {
436     case DeclaratorChunk::Pointer:
437     case DeclaratorChunk::BlockPointer:
438       innermost = i;
439       continue;
440 
441     case DeclaratorChunk::Reference:
442     case DeclaratorChunk::MemberPointer:
443     case DeclaratorChunk::Paren:
444     case DeclaratorChunk::Array:
445       continue;
446 
447     case DeclaratorChunk::Function:
448       considerDeclSpec = false;
449       goto done;
450     }
451   }
452  done:
453 
454   // That might actually be the decl spec if we weren't blocked by
455   // anything in the declarator.
456   if (considerDeclSpec) {
457     if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
458       // Splice the attribute into the decl spec.  Prevents the
459       // attribute from being applied multiple times and gives
460       // the source-location-filler something to work with.
461       state.saveDeclSpecAttrs();
462       moveAttrFromListToList(attr, declarator.getAttrListRef(),
463                declarator.getMutableDeclSpec().getAttributes().getListRef());
464       return;
465     }
466   }
467 
468   // Otherwise, if we found an appropriate chunk, splice the attribute
469   // into it.
470   if (innermost != -1U) {
471     moveAttrFromListToList(attr, declarator.getAttrListRef(),
472                        declarator.getTypeObject(innermost).getAttrListRef());
473     return;
474   }
475 
476   // Otherwise, diagnose when we're done building the type.
477   spliceAttrOutOfList(attr, declarator.getAttrListRef());
478   state.addIgnoredTypeAttr(attr);
479 }
480 
481 /// A function type attribute was written somewhere in a declaration
482 /// *other* than on the declarator itself or in the decl spec.  Given
483 /// that it didn't apply in whatever position it was written in, try
484 /// to move it to a more appropriate position.
distributeFunctionTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType type)485 static void distributeFunctionTypeAttr(TypeProcessingState &state,
486                                        AttributeList &attr,
487                                        QualType type) {
488   Declarator &declarator = state.getDeclarator();
489 
490   // Try to push the attribute from the return type of a function to
491   // the function itself.
492   for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
493     DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
494     switch (chunk.Kind) {
495     case DeclaratorChunk::Function:
496       moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
497                              chunk.getAttrListRef());
498       return;
499 
500     case DeclaratorChunk::Paren:
501     case DeclaratorChunk::Pointer:
502     case DeclaratorChunk::BlockPointer:
503     case DeclaratorChunk::Array:
504     case DeclaratorChunk::Reference:
505     case DeclaratorChunk::MemberPointer:
506       continue;
507     }
508   }
509 
510   diagnoseBadTypeAttribute(state.getSema(), attr, type);
511 }
512 
513 /// Try to distribute a function type attribute to the innermost
514 /// function chunk or type.  Returns true if the attribute was
515 /// distributed, false if no location was found.
516 static bool
distributeFunctionTypeAttrToInnermost(TypeProcessingState & state,AttributeList & attr,AttributeList * & attrList,QualType & declSpecType)517 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
518                                       AttributeList &attr,
519                                       AttributeList *&attrList,
520                                       QualType &declSpecType) {
521   Declarator &declarator = state.getDeclarator();
522 
523   // Put it on the innermost function chunk, if there is one.
524   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
525     DeclaratorChunk &chunk = declarator.getTypeObject(i);
526     if (chunk.Kind != DeclaratorChunk::Function) continue;
527 
528     moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
529     return true;
530   }
531 
532   return handleFunctionTypeAttr(state, attr, declSpecType);
533 }
534 
535 /// A function type attribute was written in the decl spec.  Try to
536 /// apply it somewhere.
537 static void
distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState & state,AttributeList & attr,QualType & declSpecType)538 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
539                                        AttributeList &attr,
540                                        QualType &declSpecType) {
541   state.saveDeclSpecAttrs();
542 
543   // C++11 attributes before the decl specifiers actually appertain to
544   // the declarators. Move them straight there. We don't support the
545   // 'put them wherever you like' semantics we allow for GNU attributes.
546   if (attr.isCXX11Attribute()) {
547     moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
548                            state.getDeclarator().getAttrListRef());
549     return;
550   }
551 
552   // Try to distribute to the innermost.
553   if (distributeFunctionTypeAttrToInnermost(state, attr,
554                                             state.getCurrentAttrListRef(),
555                                             declSpecType))
556     return;
557 
558   // If that failed, diagnose the bad attribute when the declarator is
559   // fully built.
560   state.addIgnoredTypeAttr(attr);
561 }
562 
563 /// A function type attribute was written on the declarator.  Try to
564 /// apply it somewhere.
565 static void
distributeFunctionTypeAttrFromDeclarator(TypeProcessingState & state,AttributeList & attr,QualType & declSpecType)566 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
567                                          AttributeList &attr,
568                                          QualType &declSpecType) {
569   Declarator &declarator = state.getDeclarator();
570 
571   // Try to distribute to the innermost.
572   if (distributeFunctionTypeAttrToInnermost(state, attr,
573                                             declarator.getAttrListRef(),
574                                             declSpecType))
575     return;
576 
577   // If that failed, diagnose the bad attribute when the declarator is
578   // fully built.
579   spliceAttrOutOfList(attr, declarator.getAttrListRef());
580   state.addIgnoredTypeAttr(attr);
581 }
582 
583 /// \brief Given that there are attributes written on the declarator
584 /// itself, try to distribute any type attributes to the appropriate
585 /// declarator chunk.
586 ///
587 /// These are attributes like the following:
588 ///   int f ATTR;
589 ///   int (f ATTR)();
590 /// but not necessarily this:
591 ///   int f() ATTR;
distributeTypeAttrsFromDeclarator(TypeProcessingState & state,QualType & declSpecType)592 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
593                                               QualType &declSpecType) {
594   // Collect all the type attributes from the declarator itself.
595   assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
596   AttributeList *attr = state.getDeclarator().getAttributes();
597   AttributeList *next;
598   do {
599     next = attr->getNext();
600 
601     // Do not distribute C++11 attributes. They have strict rules for what
602     // they appertain to.
603     if (attr->isCXX11Attribute())
604       continue;
605 
606     switch (attr->getKind()) {
607     OBJC_POINTER_TYPE_ATTRS_CASELIST:
608       distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
609       break;
610 
611     case AttributeList::AT_NSReturnsRetained:
612       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
613         break;
614       // fallthrough
615 
616     FUNCTION_TYPE_ATTRS_CASELIST:
617       distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
618       break;
619 
620     MS_TYPE_ATTRS_CASELIST:
621       // Microsoft type attributes cannot go after the declarator-id.
622       continue;
623 
624     default:
625       break;
626     }
627   } while ((attr = next));
628 }
629 
630 /// Add a synthetic '()' to a block-literal declarator if it is
631 /// required, given the return type.
maybeSynthesizeBlockSignature(TypeProcessingState & state,QualType declSpecType)632 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
633                                           QualType declSpecType) {
634   Declarator &declarator = state.getDeclarator();
635 
636   // First, check whether the declarator would produce a function,
637   // i.e. whether the innermost semantic chunk is a function.
638   if (declarator.isFunctionDeclarator()) {
639     // If so, make that declarator a prototyped declarator.
640     declarator.getFunctionTypeInfo().hasPrototype = true;
641     return;
642   }
643 
644   // If there are any type objects, the type as written won't name a
645   // function, regardless of the decl spec type.  This is because a
646   // block signature declarator is always an abstract-declarator, and
647   // abstract-declarators can't just be parentheses chunks.  Therefore
648   // we need to build a function chunk unless there are no type
649   // objects and the decl spec type is a function.
650   if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
651     return;
652 
653   // Note that there *are* cases with invalid declarators where
654   // declarators consist solely of parentheses.  In general, these
655   // occur only in failed efforts to make function declarators, so
656   // faking up the function chunk is still the right thing to do.
657 
658   // Otherwise, we need to fake up a function declarator.
659   SourceLocation loc = declarator.getLocStart();
660 
661   // ...and *prepend* it to the declarator.
662   SourceLocation NoLoc;
663   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
664       /*HasProto=*/true,
665       /*IsAmbiguous=*/false,
666       /*LParenLoc=*/NoLoc,
667       /*ArgInfo=*/nullptr,
668       /*NumArgs=*/0,
669       /*EllipsisLoc=*/NoLoc,
670       /*RParenLoc=*/NoLoc,
671       /*TypeQuals=*/0,
672       /*RefQualifierIsLvalueRef=*/true,
673       /*RefQualifierLoc=*/NoLoc,
674       /*ConstQualifierLoc=*/NoLoc,
675       /*VolatileQualifierLoc=*/NoLoc,
676       /*RestrictQualifierLoc=*/NoLoc,
677       /*MutableLoc=*/NoLoc, EST_None,
678       /*ESpecLoc=*/NoLoc,
679       /*Exceptions=*/nullptr,
680       /*ExceptionRanges=*/nullptr,
681       /*NumExceptions=*/0,
682       /*NoexceptExpr=*/nullptr,
683       /*ExceptionSpecTokens=*/nullptr,
684       loc, loc, declarator));
685 
686   // For consistency, make sure the state still has us as processing
687   // the decl spec.
688   assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
689   state.setCurrentChunkIndex(declarator.getNumTypeObjects());
690 }
691 
692 /// \brief Convert the specified declspec to the appropriate type
693 /// object.
694 /// \param state Specifies the declarator containing the declaration specifier
695 /// to be converted, along with other associated processing state.
696 /// \returns The type described by the declaration specifiers.  This function
697 /// never returns null.
ConvertDeclSpecToType(TypeProcessingState & state)698 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
699   // FIXME: Should move the logic from DeclSpec::Finish to here for validity
700   // checking.
701 
702   Sema &S = state.getSema();
703   Declarator &declarator = state.getDeclarator();
704   const DeclSpec &DS = declarator.getDeclSpec();
705   SourceLocation DeclLoc = declarator.getIdentifierLoc();
706   if (DeclLoc.isInvalid())
707     DeclLoc = DS.getLocStart();
708 
709   ASTContext &Context = S.Context;
710 
711   QualType Result;
712   switch (DS.getTypeSpecType()) {
713   case DeclSpec::TST_void:
714     Result = Context.VoidTy;
715     break;
716   case DeclSpec::TST_char:
717     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
718       Result = Context.CharTy;
719     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
720       Result = Context.SignedCharTy;
721     else {
722       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
723              "Unknown TSS value");
724       Result = Context.UnsignedCharTy;
725     }
726     break;
727   case DeclSpec::TST_wchar:
728     if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
729       Result = Context.WCharTy;
730     else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
731       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
732         << DS.getSpecifierName(DS.getTypeSpecType(),
733                                Context.getPrintingPolicy());
734       Result = Context.getSignedWCharType();
735     } else {
736       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
737         "Unknown TSS value");
738       S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
739         << DS.getSpecifierName(DS.getTypeSpecType(),
740                                Context.getPrintingPolicy());
741       Result = Context.getUnsignedWCharType();
742     }
743     break;
744   case DeclSpec::TST_char16:
745       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
746         "Unknown TSS value");
747       Result = Context.Char16Ty;
748     break;
749   case DeclSpec::TST_char32:
750       assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
751         "Unknown TSS value");
752       Result = Context.Char32Ty;
753     break;
754   case DeclSpec::TST_unspecified:
755     // "<proto1,proto2>" is an objc qualified ID with a missing id.
756     if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
757       Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
758                                          (ObjCProtocolDecl*const*)PQ,
759                                          DS.getNumProtocolQualifiers());
760       Result = Context.getObjCObjectPointerType(Result);
761       break;
762     }
763 
764     // If this is a missing declspec in a block literal return context, then it
765     // is inferred from the return statements inside the block.
766     // The declspec is always missing in a lambda expr context; it is either
767     // specified with a trailing return type or inferred.
768     if (S.getLangOpts().CPlusPlus14 &&
769         declarator.getContext() == Declarator::LambdaExprContext) {
770       // In C++1y, a lambda's implicit return type is 'auto'.
771       Result = Context.getAutoDeductType();
772       break;
773     } else if (declarator.getContext() == Declarator::LambdaExprContext ||
774                isOmittedBlockReturnType(declarator)) {
775       Result = Context.DependentTy;
776       break;
777     }
778 
779     // Unspecified typespec defaults to int in C90.  However, the C90 grammar
780     // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
781     // type-qualifier, or storage-class-specifier.  If not, emit an extwarn.
782     // Note that the one exception to this is function definitions, which are
783     // allowed to be completely missing a declspec.  This is handled in the
784     // parser already though by it pretending to have seen an 'int' in this
785     // case.
786     if (S.getLangOpts().ImplicitInt) {
787       // In C89 mode, we only warn if there is a completely missing declspec
788       // when one is not allowed.
789       if (DS.isEmpty()) {
790         S.Diag(DeclLoc, diag::ext_missing_declspec)
791           << DS.getSourceRange()
792         << FixItHint::CreateInsertion(DS.getLocStart(), "int");
793       }
794     } else if (!DS.hasTypeSpecifier()) {
795       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 says:
796       // "At least one type specifier shall be given in the declaration
797       // specifiers in each declaration, and in the specifier-qualifier list in
798       // each struct declaration and type name."
799       if (S.getLangOpts().CPlusPlus) {
800         S.Diag(DeclLoc, diag::err_missing_type_specifier)
801           << DS.getSourceRange();
802 
803         // When this occurs in C++ code, often something is very broken with the
804         // value being declared, poison it as invalid so we don't get chains of
805         // errors.
806         declarator.setInvalidType(true);
807       } else {
808         S.Diag(DeclLoc, diag::ext_missing_type_specifier)
809           << DS.getSourceRange();
810       }
811     }
812 
813     // FALL THROUGH.
814   case DeclSpec::TST_int: {
815     if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
816       switch (DS.getTypeSpecWidth()) {
817       case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
818       case DeclSpec::TSW_short:       Result = Context.ShortTy; break;
819       case DeclSpec::TSW_long:        Result = Context.LongTy; break;
820       case DeclSpec::TSW_longlong:
821         Result = Context.LongLongTy;
822 
823         // 'long long' is a C99 or C++11 feature.
824         if (!S.getLangOpts().C99) {
825           if (S.getLangOpts().CPlusPlus)
826             S.Diag(DS.getTypeSpecWidthLoc(),
827                    S.getLangOpts().CPlusPlus11 ?
828                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
829           else
830             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
831         }
832         break;
833       }
834     } else {
835       switch (DS.getTypeSpecWidth()) {
836       case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
837       case DeclSpec::TSW_short:       Result = Context.UnsignedShortTy; break;
838       case DeclSpec::TSW_long:        Result = Context.UnsignedLongTy; break;
839       case DeclSpec::TSW_longlong:
840         Result = Context.UnsignedLongLongTy;
841 
842         // 'long long' is a C99 or C++11 feature.
843         if (!S.getLangOpts().C99) {
844           if (S.getLangOpts().CPlusPlus)
845             S.Diag(DS.getTypeSpecWidthLoc(),
846                    S.getLangOpts().CPlusPlus11 ?
847                    diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
848           else
849             S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
850         }
851         break;
852       }
853     }
854     break;
855   }
856   case DeclSpec::TST_int128:
857     if (!S.Context.getTargetInfo().hasInt128Type())
858       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
859     if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
860       Result = Context.UnsignedInt128Ty;
861     else
862       Result = Context.Int128Ty;
863     break;
864   case DeclSpec::TST_half: Result = Context.HalfTy; break;
865   case DeclSpec::TST_float: Result = Context.FloatTy; break;
866   case DeclSpec::TST_double:
867     if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
868       Result = Context.LongDoubleTy;
869     else
870       Result = Context.DoubleTy;
871 
872     if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
873       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
874       declarator.setInvalidType(true);
875     }
876     break;
877   case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
878   case DeclSpec::TST_decimal32:    // _Decimal32
879   case DeclSpec::TST_decimal64:    // _Decimal64
880   case DeclSpec::TST_decimal128:   // _Decimal128
881     S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
882     Result = Context.IntTy;
883     declarator.setInvalidType(true);
884     break;
885   case DeclSpec::TST_class:
886   case DeclSpec::TST_enum:
887   case DeclSpec::TST_union:
888   case DeclSpec::TST_struct:
889   case DeclSpec::TST_interface: {
890     TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
891     if (!D) {
892       // This can happen in C++ with ambiguous lookups.
893       Result = Context.IntTy;
894       declarator.setInvalidType(true);
895       break;
896     }
897 
898     // If the type is deprecated or unavailable, diagnose it.
899     S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
900 
901     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
902            DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
903 
904     // TypeQuals handled by caller.
905     Result = Context.getTypeDeclType(D);
906 
907     // In both C and C++, make an ElaboratedType.
908     ElaboratedTypeKeyword Keyword
909       = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
910     Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
911     break;
912   }
913   case DeclSpec::TST_typename: {
914     assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
915            DS.getTypeSpecSign() == 0 &&
916            "Can't handle qualifiers on typedef names yet!");
917     Result = S.GetTypeFromParser(DS.getRepAsType());
918     if (Result.isNull())
919       declarator.setInvalidType(true);
920     else if (DeclSpec::ProtocolQualifierListTy PQ
921                = DS.getProtocolQualifiers()) {
922       if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
923         // Silently drop any existing protocol qualifiers.
924         // TODO: determine whether that's the right thing to do.
925         if (ObjT->getNumProtocols())
926           Result = ObjT->getBaseType();
927 
928         if (DS.getNumProtocolQualifiers())
929           Result = Context.getObjCObjectType(Result,
930                                              (ObjCProtocolDecl*const*) PQ,
931                                              DS.getNumProtocolQualifiers());
932       } else if (Result->isObjCIdType()) {
933         // id<protocol-list>
934         Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
935                                            (ObjCProtocolDecl*const*) PQ,
936                                            DS.getNumProtocolQualifiers());
937         Result = Context.getObjCObjectPointerType(Result);
938       } else if (Result->isObjCClassType()) {
939         // Class<protocol-list>
940         Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
941                                            (ObjCProtocolDecl*const*) PQ,
942                                            DS.getNumProtocolQualifiers());
943         Result = Context.getObjCObjectPointerType(Result);
944       } else {
945         S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
946           << DS.getSourceRange();
947         declarator.setInvalidType(true);
948       }
949     }
950 
951     // TypeQuals handled by caller.
952     break;
953   }
954   case DeclSpec::TST_typeofType:
955     // FIXME: Preserve type source info.
956     Result = S.GetTypeFromParser(DS.getRepAsType());
957     assert(!Result.isNull() && "Didn't get a type for typeof?");
958     if (!Result->isDependentType())
959       if (const TagType *TT = Result->getAs<TagType>())
960         S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
961     // TypeQuals handled by caller.
962     Result = Context.getTypeOfType(Result);
963     break;
964   case DeclSpec::TST_typeofExpr: {
965     Expr *E = DS.getRepAsExpr();
966     assert(E && "Didn't get an expression for typeof?");
967     // TypeQuals handled by caller.
968     Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
969     if (Result.isNull()) {
970       Result = Context.IntTy;
971       declarator.setInvalidType(true);
972     }
973     break;
974   }
975   case DeclSpec::TST_decltype: {
976     Expr *E = DS.getRepAsExpr();
977     assert(E && "Didn't get an expression for decltype?");
978     // TypeQuals handled by caller.
979     Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
980     if (Result.isNull()) {
981       Result = Context.IntTy;
982       declarator.setInvalidType(true);
983     }
984     break;
985   }
986   case DeclSpec::TST_underlyingType:
987     Result = S.GetTypeFromParser(DS.getRepAsType());
988     assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
989     Result = S.BuildUnaryTransformType(Result,
990                                        UnaryTransformType::EnumUnderlyingType,
991                                        DS.getTypeSpecTypeLoc());
992     if (Result.isNull()) {
993       Result = Context.IntTy;
994       declarator.setInvalidType(true);
995     }
996     break;
997 
998   case DeclSpec::TST_auto:
999     // TypeQuals handled by caller.
1000     // If auto is mentioned in a lambda parameter context, convert it to a
1001     // template parameter type immediately, with the appropriate depth and
1002     // index, and update sema's state (LambdaScopeInfo) for the current lambda
1003     // being analyzed (which tracks the invented type template parameter).
1004     if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1005       sema::LambdaScopeInfo *LSI = S.getCurLambda();
1006       assert(LSI && "No LambdaScopeInfo on the stack!");
1007       const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1008       const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1009       const bool IsParameterPack = declarator.hasEllipsis();
1010 
1011       // Turns out we must create the TemplateTypeParmDecl here to
1012       // retrieve the corresponding template parameter type.
1013       TemplateTypeParmDecl *CorrespondingTemplateParam =
1014         TemplateTypeParmDecl::Create(Context,
1015         // Temporarily add to the TranslationUnit DeclContext.  When the
1016         // associated TemplateParameterList is attached to a template
1017         // declaration (such as FunctionTemplateDecl), the DeclContext
1018         // for each template parameter gets updated appropriately via
1019         // a call to AdoptTemplateParameterList.
1020         Context.getTranslationUnitDecl(),
1021         /*KeyLoc*/ SourceLocation(),
1022         /*NameLoc*/ declarator.getLocStart(),
1023         TemplateParameterDepth,
1024         AutoParameterPosition,  // our template param index
1025         /* Identifier*/ nullptr, false, IsParameterPack);
1026       LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1027       // Replace the 'auto' in the function parameter with this invented
1028       // template type parameter.
1029       Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1030     } else {
1031       Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false);
1032     }
1033     break;
1034 
1035   case DeclSpec::TST_decltype_auto:
1036     Result = Context.getAutoType(QualType(),
1037                                  /*decltype(auto)*/true,
1038                                  /*IsDependent*/   false);
1039     break;
1040 
1041   case DeclSpec::TST_unknown_anytype:
1042     Result = Context.UnknownAnyTy;
1043     break;
1044 
1045   case DeclSpec::TST_atomic:
1046     Result = S.GetTypeFromParser(DS.getRepAsType());
1047     assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1048     Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1049     if (Result.isNull()) {
1050       Result = Context.IntTy;
1051       declarator.setInvalidType(true);
1052     }
1053     break;
1054 
1055   case DeclSpec::TST_error:
1056     Result = Context.IntTy;
1057     declarator.setInvalidType(true);
1058     break;
1059   }
1060 
1061   // Handle complex types.
1062   if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1063     if (S.getLangOpts().Freestanding)
1064       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1065     Result = Context.getComplexType(Result);
1066   } else if (DS.isTypeAltiVecVector()) {
1067     unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1068     assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1069     VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1070     if (DS.isTypeAltiVecPixel())
1071       VecKind = VectorType::AltiVecPixel;
1072     else if (DS.isTypeAltiVecBool())
1073       VecKind = VectorType::AltiVecBool;
1074     Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1075   }
1076 
1077   // FIXME: Imaginary.
1078   if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1079     S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1080 
1081   // Before we process any type attributes, synthesize a block literal
1082   // function declarator if necessary.
1083   if (declarator.getContext() == Declarator::BlockLiteralContext)
1084     maybeSynthesizeBlockSignature(state, Result);
1085 
1086   // Apply any type attributes from the decl spec.  This may cause the
1087   // list of type attributes to be temporarily saved while the type
1088   // attributes are pushed around.
1089   if (AttributeList *attrs = DS.getAttributes().getList())
1090     processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
1091 
1092   // Apply const/volatile/restrict qualifiers to T.
1093   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1094 
1095     // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
1096     // of a function type includes any type qualifiers, the behavior is
1097     // undefined."
1098     if (Result->isFunctionType() && TypeQuals) {
1099       if (TypeQuals & DeclSpec::TQ_const)
1100         S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers)
1101           << Result << DS.getSourceRange();
1102       else if (TypeQuals & DeclSpec::TQ_volatile)
1103         S.Diag(DS.getVolatileSpecLoc(),
1104                diag::warn_typecheck_function_qualifiers)
1105             << Result << DS.getSourceRange();
1106       else {
1107         assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) &&
1108                "Has CVRA quals but not C, V, R, or A?");
1109         // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a
1110         // function type later, in BuildQualifiedType.
1111       }
1112     }
1113 
1114     // C++11 [dcl.ref]p1:
1115     //   Cv-qualified references are ill-formed except when the
1116     //   cv-qualifiers are introduced through the use of a typedef-name
1117     //   or decltype-specifier, in which case the cv-qualifiers are ignored.
1118     //
1119     // There don't appear to be any other contexts in which a cv-qualified
1120     // reference type could be formed, so the 'ill-formed' clause here appears
1121     // to never happen.
1122     if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
1123         TypeQuals && Result->isReferenceType()) {
1124       // If this occurs outside a template instantiation, warn the user about
1125       // it; they probably didn't mean to specify a redundant qualifier.
1126       typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
1127       QualLoc Quals[] = {
1128         QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
1129         QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
1130         QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())
1131       };
1132       for (unsigned I = 0, N = llvm::array_lengthof(Quals); I != N; ++I) {
1133         if (S.ActiveTemplateInstantiations.empty()) {
1134           if (TypeQuals & Quals[I].first)
1135             S.Diag(Quals[I].second, diag::warn_typecheck_reference_qualifiers)
1136               << DeclSpec::getSpecifierName(Quals[I].first) << Result
1137               << FixItHint::CreateRemoval(Quals[I].second);
1138         }
1139         TypeQuals &= ~Quals[I].first;
1140       }
1141     }
1142 
1143     // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1144     // than once in the same specifier-list or qualifier-list, either directly
1145     // or via one or more typedefs."
1146     if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1147         && TypeQuals & Result.getCVRQualifiers()) {
1148       if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1149         S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1150           << "const";
1151       }
1152 
1153       if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1154         S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1155           << "volatile";
1156       }
1157 
1158       // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1159       // produce a warning in this case.
1160     }
1161 
1162     QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1163 
1164     // If adding qualifiers fails, just use the unqualified type.
1165     if (Qualified.isNull())
1166       declarator.setInvalidType(true);
1167     else
1168       Result = Qualified;
1169   }
1170 
1171   assert(!Result.isNull() && "This function should not return a null type");
1172   return Result;
1173 }
1174 
getPrintableNameForEntity(DeclarationName Entity)1175 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1176   if (Entity)
1177     return Entity.getAsString();
1178 
1179   return "type name";
1180 }
1181 
BuildQualifiedType(QualType T,SourceLocation Loc,Qualifiers Qs,const DeclSpec * DS)1182 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1183                                   Qualifiers Qs, const DeclSpec *DS) {
1184   if (T.isNull())
1185     return QualType();
1186 
1187   // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1188   // object or incomplete types shall not be restrict-qualified."
1189   if (Qs.hasRestrict()) {
1190     unsigned DiagID = 0;
1191     QualType ProblemTy;
1192 
1193     if (T->isAnyPointerType() || T->isReferenceType() ||
1194         T->isMemberPointerType()) {
1195       QualType EltTy;
1196       if (T->isObjCObjectPointerType())
1197         EltTy = T;
1198       else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1199         EltTy = PTy->getPointeeType();
1200       else
1201         EltTy = T->getPointeeType();
1202 
1203       // If we have a pointer or reference, the pointee must have an object
1204       // incomplete type.
1205       if (!EltTy->isIncompleteOrObjectType()) {
1206         DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1207         ProblemTy = EltTy;
1208       }
1209     } else if (!T->isDependentType()) {
1210       DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1211       ProblemTy = T;
1212     }
1213 
1214     if (DiagID) {
1215       Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1216       Qs.removeRestrict();
1217     }
1218   }
1219 
1220   return Context.getQualifiedType(T, Qs);
1221 }
1222 
BuildQualifiedType(QualType T,SourceLocation Loc,unsigned CVRA,const DeclSpec * DS)1223 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1224                                   unsigned CVRA, const DeclSpec *DS) {
1225   if (T.isNull())
1226     return QualType();
1227 
1228   // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1229   unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1230 
1231   // C11 6.7.3/5:
1232   //   If the same qualifier appears more than once in the same
1233   //   specifier-qualifier-list, either directly or via one or more typedefs,
1234   //   the behavior is the same as if it appeared only once.
1235   //
1236   // It's not specified what happens when the _Atomic qualifier is applied to
1237   // a type specified with the _Atomic specifier, but we assume that this
1238   // should be treated as if the _Atomic qualifier appeared multiple times.
1239   if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1240     // C11 6.7.3/5:
1241     //   If other qualifiers appear along with the _Atomic qualifier in a
1242     //   specifier-qualifier-list, the resulting type is the so-qualified
1243     //   atomic type.
1244     //
1245     // Don't need to worry about array types here, since _Atomic can't be
1246     // applied to such types.
1247     SplitQualType Split = T.getSplitUnqualifiedType();
1248     T = BuildAtomicType(QualType(Split.Ty, 0),
1249                         DS ? DS->getAtomicSpecLoc() : Loc);
1250     if (T.isNull())
1251       return T;
1252     Split.Quals.addCVRQualifiers(CVR);
1253     return BuildQualifiedType(T, Loc, Split.Quals);
1254   }
1255 
1256   return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1257 }
1258 
1259 /// \brief Build a paren type including \p T.
BuildParenType(QualType T)1260 QualType Sema::BuildParenType(QualType T) {
1261   return Context.getParenType(T);
1262 }
1263 
1264 /// Given that we're building a pointer or reference to the given
inferARCLifetimeForPointee(Sema & S,QualType type,SourceLocation loc,bool isReference)1265 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1266                                            SourceLocation loc,
1267                                            bool isReference) {
1268   // Bail out if retention is unrequired or already specified.
1269   if (!type->isObjCLifetimeType() ||
1270       type.getObjCLifetime() != Qualifiers::OCL_None)
1271     return type;
1272 
1273   Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1274 
1275   // If the object type is const-qualified, we can safely use
1276   // __unsafe_unretained.  This is safe (because there are no read
1277   // barriers), and it'll be safe to coerce anything but __weak* to
1278   // the resulting type.
1279   if (type.isConstQualified()) {
1280     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1281 
1282   // Otherwise, check whether the static type does not require
1283   // retaining.  This currently only triggers for Class (possibly
1284   // protocol-qualifed, and arrays thereof).
1285   } else if (type->isObjCARCImplicitlyUnretainedType()) {
1286     implicitLifetime = Qualifiers::OCL_ExplicitNone;
1287 
1288   // If we are in an unevaluated context, like sizeof, skip adding a
1289   // qualification.
1290   } else if (S.isUnevaluatedContext()) {
1291     return type;
1292 
1293   // If that failed, give an error and recover using __strong.  __strong
1294   // is the option most likely to prevent spurious second-order diagnostics,
1295   // like when binding a reference to a field.
1296   } else {
1297     // These types can show up in private ivars in system headers, so
1298     // we need this to not be an error in those cases.  Instead we
1299     // want to delay.
1300     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1301       S.DelayedDiagnostics.add(
1302           sema::DelayedDiagnostic::makeForbiddenType(loc,
1303               diag::err_arc_indirect_no_ownership, type, isReference));
1304     } else {
1305       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1306     }
1307     implicitLifetime = Qualifiers::OCL_Strong;
1308   }
1309   assert(implicitLifetime && "didn't infer any lifetime!");
1310 
1311   Qualifiers qs;
1312   qs.addObjCLifetime(implicitLifetime);
1313   return S.Context.getQualifiedType(type, qs);
1314 }
1315 
getFunctionQualifiersAsString(const FunctionProtoType * FnTy)1316 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1317   std::string Quals =
1318     Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1319 
1320   switch (FnTy->getRefQualifier()) {
1321   case RQ_None:
1322     break;
1323 
1324   case RQ_LValue:
1325     if (!Quals.empty())
1326       Quals += ' ';
1327     Quals += '&';
1328     break;
1329 
1330   case RQ_RValue:
1331     if (!Quals.empty())
1332       Quals += ' ';
1333     Quals += "&&";
1334     break;
1335   }
1336 
1337   return Quals;
1338 }
1339 
1340 namespace {
1341 /// Kinds of declarator that cannot contain a qualified function type.
1342 ///
1343 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1344 ///     a function type with a cv-qualifier or a ref-qualifier can only appear
1345 ///     at the topmost level of a type.
1346 ///
1347 /// Parens and member pointers are permitted. We don't diagnose array and
1348 /// function declarators, because they don't allow function types at all.
1349 ///
1350 /// The values of this enum are used in diagnostics.
1351 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1352 }
1353 
1354 /// Check whether the type T is a qualified function type, and if it is,
1355 /// diagnose that it cannot be contained within the given kind of declarator.
checkQualifiedFunction(Sema & S,QualType T,SourceLocation Loc,QualifiedFunctionKind QFK)1356 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1357                                    QualifiedFunctionKind QFK) {
1358   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1359   const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1360   if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1361     return false;
1362 
1363   S.Diag(Loc, diag::err_compound_qualified_function_type)
1364     << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1365     << getFunctionQualifiersAsString(FPT);
1366   return true;
1367 }
1368 
1369 /// \brief Build a pointer type.
1370 ///
1371 /// \param T The type to which we'll be building a pointer.
1372 ///
1373 /// \param Loc The location of the entity whose type involves this
1374 /// pointer type or, if there is no such entity, the location of the
1375 /// type that will have pointer type.
1376 ///
1377 /// \param Entity The name of the entity that involves the pointer
1378 /// type, if known.
1379 ///
1380 /// \returns A suitable pointer type, if there are no
1381 /// errors. Otherwise, returns a NULL type.
BuildPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)1382 QualType Sema::BuildPointerType(QualType T,
1383                                 SourceLocation Loc, DeclarationName Entity) {
1384   if (T->isReferenceType()) {
1385     // C++ 8.3.2p4: There shall be no ... pointers to references ...
1386     Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1387       << getPrintableNameForEntity(Entity) << T;
1388     return QualType();
1389   }
1390 
1391   if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1392     return QualType();
1393 
1394   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1395 
1396   // In ARC, it is forbidden to build pointers to unqualified pointers.
1397   if (getLangOpts().ObjCAutoRefCount)
1398     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1399 
1400   // Build the pointer type.
1401   return Context.getPointerType(T);
1402 }
1403 
1404 /// \brief Build a reference type.
1405 ///
1406 /// \param T The type to which we'll be building a reference.
1407 ///
1408 /// \param Loc The location of the entity whose type involves this
1409 /// reference type or, if there is no such entity, the location of the
1410 /// type that will have reference type.
1411 ///
1412 /// \param Entity The name of the entity that involves the reference
1413 /// type, if known.
1414 ///
1415 /// \returns A suitable reference type, if there are no
1416 /// errors. Otherwise, returns a NULL type.
BuildReferenceType(QualType T,bool SpelledAsLValue,SourceLocation Loc,DeclarationName Entity)1417 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1418                                   SourceLocation Loc,
1419                                   DeclarationName Entity) {
1420   assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1421          "Unresolved overloaded function type");
1422 
1423   // C++0x [dcl.ref]p6:
1424   //   If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1425   //   decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1426   //   type T, an attempt to create the type "lvalue reference to cv TR" creates
1427   //   the type "lvalue reference to T", while an attempt to create the type
1428   //   "rvalue reference to cv TR" creates the type TR.
1429   bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1430 
1431   // C++ [dcl.ref]p4: There shall be no references to references.
1432   //
1433   // According to C++ DR 106, references to references are only
1434   // diagnosed when they are written directly (e.g., "int & &"),
1435   // but not when they happen via a typedef:
1436   //
1437   //   typedef int& intref;
1438   //   typedef intref& intref2;
1439   //
1440   // Parser::ParseDeclaratorInternal diagnoses the case where
1441   // references are written directly; here, we handle the
1442   // collapsing of references-to-references as described in C++0x.
1443   // DR 106 and 540 introduce reference-collapsing into C++98/03.
1444 
1445   // C++ [dcl.ref]p1:
1446   //   A declarator that specifies the type "reference to cv void"
1447   //   is ill-formed.
1448   if (T->isVoidType()) {
1449     Diag(Loc, diag::err_reference_to_void);
1450     return QualType();
1451   }
1452 
1453   if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1454     return QualType();
1455 
1456   // In ARC, it is forbidden to build references to unqualified pointers.
1457   if (getLangOpts().ObjCAutoRefCount)
1458     T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1459 
1460   // Handle restrict on references.
1461   if (LValueRef)
1462     return Context.getLValueReferenceType(T, SpelledAsLValue);
1463   return Context.getRValueReferenceType(T);
1464 }
1465 
1466 /// Check whether the specified array size makes the array type a VLA.  If so,
1467 /// return true, if not, return the size of the array in SizeVal.
isArraySizeVLA(Sema & S,Expr * ArraySize,llvm::APSInt & SizeVal)1468 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1469   // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1470   // (like gnu99, but not c99) accept any evaluatable value as an extension.
1471   class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1472   public:
1473     VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1474 
1475     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1476     }
1477 
1478     void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1479       S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1480     }
1481   } Diagnoser;
1482 
1483   return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1484                                            S.LangOpts.GNUMode).isInvalid();
1485 }
1486 
1487 
1488 /// \brief Build an array type.
1489 ///
1490 /// \param T The type of each element in the array.
1491 ///
1492 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1493 ///
1494 /// \param ArraySize Expression describing the size of the array.
1495 ///
1496 /// \param Brackets The range from the opening '[' to the closing ']'.
1497 ///
1498 /// \param Entity The name of the entity that involves the array
1499 /// type, if known.
1500 ///
1501 /// \returns A suitable array type, if there are no errors. Otherwise,
1502 /// returns a NULL type.
BuildArrayType(QualType T,ArrayType::ArraySizeModifier ASM,Expr * ArraySize,unsigned Quals,SourceRange Brackets,DeclarationName Entity)1503 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1504                               Expr *ArraySize, unsigned Quals,
1505                               SourceRange Brackets, DeclarationName Entity) {
1506 
1507   SourceLocation Loc = Brackets.getBegin();
1508   if (getLangOpts().CPlusPlus) {
1509     // C++ [dcl.array]p1:
1510     //   T is called the array element type; this type shall not be a reference
1511     //   type, the (possibly cv-qualified) type void, a function type or an
1512     //   abstract class type.
1513     //
1514     // C++ [dcl.array]p3:
1515     //   When several "array of" specifications are adjacent, [...] only the
1516     //   first of the constant expressions that specify the bounds of the arrays
1517     //   may be omitted.
1518     //
1519     // Note: function types are handled in the common path with C.
1520     if (T->isReferenceType()) {
1521       Diag(Loc, diag::err_illegal_decl_array_of_references)
1522       << getPrintableNameForEntity(Entity) << T;
1523       return QualType();
1524     }
1525 
1526     if (T->isVoidType() || T->isIncompleteArrayType()) {
1527       Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1528       return QualType();
1529     }
1530 
1531     if (RequireNonAbstractType(Brackets.getBegin(), T,
1532                                diag::err_array_of_abstract_type))
1533       return QualType();
1534 
1535     // Mentioning a member pointer type for an array type causes us to lock in
1536     // an inheritance model, even if it's inside an unused typedef.
1537     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
1538       if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
1539         if (!MPTy->getClass()->isDependentType())
1540           RequireCompleteType(Loc, T, 0);
1541 
1542   } else {
1543     // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1544     // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1545     if (RequireCompleteType(Loc, T,
1546                             diag::err_illegal_decl_array_incomplete_type))
1547       return QualType();
1548   }
1549 
1550   if (T->isFunctionType()) {
1551     Diag(Loc, diag::err_illegal_decl_array_of_functions)
1552       << getPrintableNameForEntity(Entity) << T;
1553     return QualType();
1554   }
1555 
1556   if (const RecordType *EltTy = T->getAs<RecordType>()) {
1557     // If the element type is a struct or union that contains a variadic
1558     // array, accept it as a GNU extension: C99 6.7.2.1p2.
1559     if (EltTy->getDecl()->hasFlexibleArrayMember())
1560       Diag(Loc, diag::ext_flexible_array_in_array) << T;
1561   } else if (T->isObjCObjectType()) {
1562     Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1563     return QualType();
1564   }
1565 
1566   // Do placeholder conversions on the array size expression.
1567   if (ArraySize && ArraySize->hasPlaceholderType()) {
1568     ExprResult Result = CheckPlaceholderExpr(ArraySize);
1569     if (Result.isInvalid()) return QualType();
1570     ArraySize = Result.get();
1571   }
1572 
1573   // Do lvalue-to-rvalue conversions on the array size expression.
1574   if (ArraySize && !ArraySize->isRValue()) {
1575     ExprResult Result = DefaultLvalueConversion(ArraySize);
1576     if (Result.isInvalid())
1577       return QualType();
1578 
1579     ArraySize = Result.get();
1580   }
1581 
1582   // C99 6.7.5.2p1: The size expression shall have integer type.
1583   // C++11 allows contextual conversions to such types.
1584   if (!getLangOpts().CPlusPlus11 &&
1585       ArraySize && !ArraySize->isTypeDependent() &&
1586       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1587     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1588       << ArraySize->getType() << ArraySize->getSourceRange();
1589     return QualType();
1590   }
1591 
1592   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1593   if (!ArraySize) {
1594     if (ASM == ArrayType::Star)
1595       T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
1596     else
1597       T = Context.getIncompleteArrayType(T, ASM, Quals);
1598   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1599     T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1600   } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1601               !T->isConstantSizeType()) ||
1602              isArraySizeVLA(*this, ArraySize, ConstVal)) {
1603     // Even in C++11, don't allow contextual conversions in the array bound
1604     // of a VLA.
1605     if (getLangOpts().CPlusPlus11 &&
1606         !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1607       Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1608         << ArraySize->getType() << ArraySize->getSourceRange();
1609       return QualType();
1610     }
1611 
1612     // C99: an array with an element type that has a non-constant-size is a VLA.
1613     // C99: an array with a non-ICE size is a VLA.  We accept any expression
1614     // that we can fold to a non-zero positive value as an extension.
1615     T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1616   } else {
1617     // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1618     // have a value greater than zero.
1619     if (ConstVal.isSigned() && ConstVal.isNegative()) {
1620       if (Entity)
1621         Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1622           << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1623       else
1624         Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1625           << ArraySize->getSourceRange();
1626       return QualType();
1627     }
1628     if (ConstVal == 0) {
1629       // GCC accepts zero sized static arrays. We allow them when
1630       // we're not in a SFINAE context.
1631       Diag(ArraySize->getLocStart(),
1632            isSFINAEContext()? diag::err_typecheck_zero_array_size
1633                             : diag::ext_typecheck_zero_array_size)
1634         << ArraySize->getSourceRange();
1635 
1636       if (ASM == ArrayType::Static) {
1637         Diag(ArraySize->getLocStart(),
1638              diag::warn_typecheck_zero_static_array_size)
1639           << ArraySize->getSourceRange();
1640         ASM = ArrayType::Normal;
1641       }
1642     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1643                !T->isIncompleteType() && !T->isUndeducedType()) {
1644       // Is the array too large?
1645       unsigned ActiveSizeBits
1646         = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1647       if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1648         Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1649           << ConstVal.toString(10)
1650           << ArraySize->getSourceRange();
1651         return QualType();
1652       }
1653     }
1654 
1655     T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1656   }
1657 
1658   // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1659   if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1660     Diag(Loc, diag::err_opencl_vla);
1661     return QualType();
1662   }
1663   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1664   if (!getLangOpts().C99) {
1665     if (T->isVariableArrayType()) {
1666       // Prohibit the use of non-POD types in VLAs.
1667       QualType BaseT = Context.getBaseElementType(T);
1668       if (!T->isDependentType() &&
1669           !RequireCompleteType(Loc, BaseT, 0) &&
1670           !BaseT.isPODType(Context) &&
1671           !BaseT->isObjCLifetimeType()) {
1672         Diag(Loc, diag::err_vla_non_pod)
1673           << BaseT;
1674         return QualType();
1675       }
1676       // Prohibit the use of VLAs during template argument deduction.
1677       else if (isSFINAEContext()) {
1678         Diag(Loc, diag::err_vla_in_sfinae);
1679         return QualType();
1680       }
1681       // Just extwarn about VLAs.
1682       else
1683         Diag(Loc, diag::ext_vla);
1684     } else if (ASM != ArrayType::Normal || Quals != 0)
1685       Diag(Loc,
1686            getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1687                                      : diag::ext_c99_array_usage) << ASM;
1688   }
1689 
1690   if (T->isVariableArrayType()) {
1691     // Warn about VLAs for -Wvla.
1692     Diag(Loc, diag::warn_vla_used);
1693   }
1694 
1695   return T;
1696 }
1697 
1698 /// \brief Build an ext-vector type.
1699 ///
1700 /// Run the required checks for the extended vector type.
BuildExtVectorType(QualType T,Expr * ArraySize,SourceLocation AttrLoc)1701 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1702                                   SourceLocation AttrLoc) {
1703   // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1704   // in conjunction with complex types (pointers, arrays, functions, etc.).
1705   if (!T->isDependentType() &&
1706       !T->isIntegerType() && !T->isRealFloatingType()) {
1707     Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1708     return QualType();
1709   }
1710 
1711   if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1712     llvm::APSInt vecSize(32);
1713     if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1714       Diag(AttrLoc, diag::err_attribute_argument_type)
1715         << "ext_vector_type" << AANT_ArgumentIntegerConstant
1716         << ArraySize->getSourceRange();
1717       return QualType();
1718     }
1719 
1720     // unlike gcc's vector_size attribute, the size is specified as the
1721     // number of elements, not the number of bytes.
1722     unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1723 
1724     if (vectorSize == 0) {
1725       Diag(AttrLoc, diag::err_attribute_zero_size)
1726       << ArraySize->getSourceRange();
1727       return QualType();
1728     }
1729 
1730     if (VectorType::isVectorSizeTooLarge(vectorSize)) {
1731       Diag(AttrLoc, diag::err_attribute_size_too_large)
1732         << ArraySize->getSourceRange();
1733       return QualType();
1734     }
1735 
1736     return Context.getExtVectorType(T, vectorSize);
1737   }
1738 
1739   return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1740 }
1741 
CheckFunctionReturnType(QualType T,SourceLocation Loc)1742 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
1743   if (T->isArrayType() || T->isFunctionType()) {
1744     Diag(Loc, diag::err_func_returning_array_function)
1745       << T->isFunctionType() << T;
1746     return true;
1747   }
1748 
1749   // Functions cannot return half FP.
1750   if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
1751     Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1752       FixItHint::CreateInsertion(Loc, "*");
1753     return true;
1754   }
1755 
1756   // Methods cannot return interface types. All ObjC objects are
1757   // passed by reference.
1758   if (T->isObjCObjectType()) {
1759     Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
1760     return 0;
1761   }
1762 
1763   return false;
1764 }
1765 
BuildFunctionType(QualType T,MutableArrayRef<QualType> ParamTypes,SourceLocation Loc,DeclarationName Entity,const FunctionProtoType::ExtProtoInfo & EPI)1766 QualType Sema::BuildFunctionType(QualType T,
1767                                  MutableArrayRef<QualType> ParamTypes,
1768                                  SourceLocation Loc, DeclarationName Entity,
1769                                  const FunctionProtoType::ExtProtoInfo &EPI) {
1770   bool Invalid = false;
1771 
1772   Invalid |= CheckFunctionReturnType(T, Loc);
1773 
1774   for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
1775     // FIXME: Loc is too inprecise here, should use proper locations for args.
1776     QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1777     if (ParamType->isVoidType()) {
1778       Diag(Loc, diag::err_param_with_void_type);
1779       Invalid = true;
1780     } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
1781       // Disallow half FP arguments.
1782       Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1783         FixItHint::CreateInsertion(Loc, "*");
1784       Invalid = true;
1785     }
1786 
1787     ParamTypes[Idx] = ParamType;
1788   }
1789 
1790   if (Invalid)
1791     return QualType();
1792 
1793   return Context.getFunctionType(T, ParamTypes, EPI);
1794 }
1795 
1796 /// \brief Build a member pointer type \c T Class::*.
1797 ///
1798 /// \param T the type to which the member pointer refers.
1799 /// \param Class the class type into which the member pointer points.
1800 /// \param Loc the location where this type begins
1801 /// \param Entity the name of the entity that will have this member pointer type
1802 ///
1803 /// \returns a member pointer type, if successful, or a NULL type if there was
1804 /// an error.
BuildMemberPointerType(QualType T,QualType Class,SourceLocation Loc,DeclarationName Entity)1805 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1806                                       SourceLocation Loc,
1807                                       DeclarationName Entity) {
1808   // Verify that we're not building a pointer to pointer to function with
1809   // exception specification.
1810   if (CheckDistantExceptionSpec(T)) {
1811     Diag(Loc, diag::err_distant_exception_spec);
1812 
1813     // FIXME: If we're doing this as part of template instantiation,
1814     // we should return immediately.
1815 
1816     // Build the type anyway, but use the canonical type so that the
1817     // exception specifiers are stripped off.
1818     T = Context.getCanonicalType(T);
1819   }
1820 
1821   // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1822   //   with reference type, or "cv void."
1823   if (T->isReferenceType()) {
1824     Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1825       << getPrintableNameForEntity(Entity) << T;
1826     return QualType();
1827   }
1828 
1829   if (T->isVoidType()) {
1830     Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1831       << getPrintableNameForEntity(Entity);
1832     return QualType();
1833   }
1834 
1835   if (!Class->isDependentType() && !Class->isRecordType()) {
1836     Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1837     return QualType();
1838   }
1839 
1840   // Adjust the default free function calling convention to the default method
1841   // calling convention.
1842   if (T->isFunctionType())
1843     adjustMemberFunctionCC(T, /*IsStatic=*/false);
1844 
1845   return Context.getMemberPointerType(T, Class.getTypePtr());
1846 }
1847 
1848 /// \brief Build a block pointer type.
1849 ///
1850 /// \param T The type to which we'll be building a block pointer.
1851 ///
1852 /// \param Loc The source location, used for diagnostics.
1853 ///
1854 /// \param Entity The name of the entity that involves the block pointer
1855 /// type, if known.
1856 ///
1857 /// \returns A suitable block pointer type, if there are no
1858 /// errors. Otherwise, returns a NULL type.
BuildBlockPointerType(QualType T,SourceLocation Loc,DeclarationName Entity)1859 QualType Sema::BuildBlockPointerType(QualType T,
1860                                      SourceLocation Loc,
1861                                      DeclarationName Entity) {
1862   if (!T->isFunctionType()) {
1863     Diag(Loc, diag::err_nonfunction_block_type);
1864     return QualType();
1865   }
1866 
1867   if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
1868     return QualType();
1869 
1870   return Context.getBlockPointerType(T);
1871 }
1872 
GetTypeFromParser(ParsedType Ty,TypeSourceInfo ** TInfo)1873 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1874   QualType QT = Ty.get();
1875   if (QT.isNull()) {
1876     if (TInfo) *TInfo = nullptr;
1877     return QualType();
1878   }
1879 
1880   TypeSourceInfo *DI = nullptr;
1881   if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1882     QT = LIT->getType();
1883     DI = LIT->getTypeSourceInfo();
1884   }
1885 
1886   if (TInfo) *TInfo = DI;
1887   return QT;
1888 }
1889 
1890 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1891                                             Qualifiers::ObjCLifetime ownership,
1892                                             unsigned chunkIndex);
1893 
1894 /// Given that this is the declaration of a parameter under ARC,
1895 /// attempt to infer attributes and such for pointer-to-whatever
1896 /// types.
inferARCWriteback(TypeProcessingState & state,QualType & declSpecType)1897 static void inferARCWriteback(TypeProcessingState &state,
1898                               QualType &declSpecType) {
1899   Sema &S = state.getSema();
1900   Declarator &declarator = state.getDeclarator();
1901 
1902   // TODO: should we care about decl qualifiers?
1903 
1904   // Check whether the declarator has the expected form.  We walk
1905   // from the inside out in order to make the block logic work.
1906   unsigned outermostPointerIndex = 0;
1907   bool isBlockPointer = false;
1908   unsigned numPointers = 0;
1909   for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1910     unsigned chunkIndex = i;
1911     DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1912     switch (chunk.Kind) {
1913     case DeclaratorChunk::Paren:
1914       // Ignore parens.
1915       break;
1916 
1917     case DeclaratorChunk::Reference:
1918     case DeclaratorChunk::Pointer:
1919       // Count the number of pointers.  Treat references
1920       // interchangeably as pointers; if they're mis-ordered, normal
1921       // type building will discover that.
1922       outermostPointerIndex = chunkIndex;
1923       numPointers++;
1924       break;
1925 
1926     case DeclaratorChunk::BlockPointer:
1927       // If we have a pointer to block pointer, that's an acceptable
1928       // indirect reference; anything else is not an application of
1929       // the rules.
1930       if (numPointers != 1) return;
1931       numPointers++;
1932       outermostPointerIndex = chunkIndex;
1933       isBlockPointer = true;
1934 
1935       // We don't care about pointer structure in return values here.
1936       goto done;
1937 
1938     case DeclaratorChunk::Array: // suppress if written (id[])?
1939     case DeclaratorChunk::Function:
1940     case DeclaratorChunk::MemberPointer:
1941       return;
1942     }
1943   }
1944  done:
1945 
1946   // If we have *one* pointer, then we want to throw the qualifier on
1947   // the declaration-specifiers, which means that it needs to be a
1948   // retainable object type.
1949   if (numPointers == 1) {
1950     // If it's not a retainable object type, the rule doesn't apply.
1951     if (!declSpecType->isObjCRetainableType()) return;
1952 
1953     // If it already has lifetime, don't do anything.
1954     if (declSpecType.getObjCLifetime()) return;
1955 
1956     // Otherwise, modify the type in-place.
1957     Qualifiers qs;
1958 
1959     if (declSpecType->isObjCARCImplicitlyUnretainedType())
1960       qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1961     else
1962       qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1963     declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1964 
1965   // If we have *two* pointers, then we want to throw the qualifier on
1966   // the outermost pointer.
1967   } else if (numPointers == 2) {
1968     // If we don't have a block pointer, we need to check whether the
1969     // declaration-specifiers gave us something that will turn into a
1970     // retainable object pointer after we slap the first pointer on it.
1971     if (!isBlockPointer && !declSpecType->isObjCObjectType())
1972       return;
1973 
1974     // Look for an explicit lifetime attribute there.
1975     DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1976     if (chunk.Kind != DeclaratorChunk::Pointer &&
1977         chunk.Kind != DeclaratorChunk::BlockPointer)
1978       return;
1979     for (const AttributeList *attr = chunk.getAttrs(); attr;
1980            attr = attr->getNext())
1981       if (attr->getKind() == AttributeList::AT_ObjCOwnership)
1982         return;
1983 
1984     transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1985                                           outermostPointerIndex);
1986 
1987   // Any other number of pointers/references does not trigger the rule.
1988   } else return;
1989 
1990   // TODO: mark whether we did this inference?
1991 }
1992 
diagnoseIgnoredQualifiers(unsigned DiagID,unsigned Quals,SourceLocation FallbackLoc,SourceLocation ConstQualLoc,SourceLocation VolatileQualLoc,SourceLocation RestrictQualLoc,SourceLocation AtomicQualLoc)1993 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1994                                      SourceLocation FallbackLoc,
1995                                      SourceLocation ConstQualLoc,
1996                                      SourceLocation VolatileQualLoc,
1997                                      SourceLocation RestrictQualLoc,
1998                                      SourceLocation AtomicQualLoc) {
1999   if (!Quals)
2000     return;
2001 
2002   struct Qual {
2003     unsigned Mask;
2004     const char *Name;
2005     SourceLocation Loc;
2006   } const QualKinds[4] = {
2007     { DeclSpec::TQ_const, "const", ConstQualLoc },
2008     { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc },
2009     { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc },
2010     { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc }
2011   };
2012 
2013   SmallString<32> QualStr;
2014   unsigned NumQuals = 0;
2015   SourceLocation Loc;
2016   FixItHint FixIts[4];
2017 
2018   // Build a string naming the redundant qualifiers.
2019   for (unsigned I = 0; I != 4; ++I) {
2020     if (Quals & QualKinds[I].Mask) {
2021       if (!QualStr.empty()) QualStr += ' ';
2022       QualStr += QualKinds[I].Name;
2023 
2024       // If we have a location for the qualifier, offer a fixit.
2025       SourceLocation QualLoc = QualKinds[I].Loc;
2026       if (!QualLoc.isInvalid()) {
2027         FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2028         if (Loc.isInvalid() ||
2029             getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2030           Loc = QualLoc;
2031       }
2032 
2033       ++NumQuals;
2034     }
2035   }
2036 
2037   Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2038     << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2039 }
2040 
2041 // Diagnose pointless type qualifiers on the return type of a function.
diagnoseRedundantReturnTypeQualifiers(Sema & S,QualType RetTy,Declarator & D,unsigned FunctionChunkIndex)2042 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2043                                                   Declarator &D,
2044                                                   unsigned FunctionChunkIndex) {
2045   if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2046     // FIXME: TypeSourceInfo doesn't preserve location information for
2047     // qualifiers.
2048     S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2049                                 RetTy.getLocalCVRQualifiers(),
2050                                 D.getIdentifierLoc());
2051     return;
2052   }
2053 
2054   for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2055                 End = D.getNumTypeObjects();
2056        OuterChunkIndex != End; ++OuterChunkIndex) {
2057     DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2058     switch (OuterChunk.Kind) {
2059     case DeclaratorChunk::Paren:
2060       continue;
2061 
2062     case DeclaratorChunk::Pointer: {
2063       DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2064       S.diagnoseIgnoredQualifiers(
2065           diag::warn_qual_return_type,
2066           PTI.TypeQuals,
2067           SourceLocation(),
2068           SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2069           SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2070           SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2071           SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2072       return;
2073     }
2074 
2075     case DeclaratorChunk::Function:
2076     case DeclaratorChunk::BlockPointer:
2077     case DeclaratorChunk::Reference:
2078     case DeclaratorChunk::Array:
2079     case DeclaratorChunk::MemberPointer:
2080       // FIXME: We can't currently provide an accurate source location and a
2081       // fix-it hint for these.
2082       unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2083       S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2084                                   RetTy.getCVRQualifiers() | AtomicQual,
2085                                   D.getIdentifierLoc());
2086       return;
2087     }
2088 
2089     llvm_unreachable("unknown declarator chunk kind");
2090   }
2091 
2092   // If the qualifiers come from a conversion function type, don't diagnose
2093   // them -- they're not necessarily redundant, since such a conversion
2094   // operator can be explicitly called as "x.operator const int()".
2095   if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2096     return;
2097 
2098   // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2099   // which are present there.
2100   S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2101                               D.getDeclSpec().getTypeQualifiers(),
2102                               D.getIdentifierLoc(),
2103                               D.getDeclSpec().getConstSpecLoc(),
2104                               D.getDeclSpec().getVolatileSpecLoc(),
2105                               D.getDeclSpec().getRestrictSpecLoc(),
2106                               D.getDeclSpec().getAtomicSpecLoc());
2107 }
2108 
GetDeclSpecTypeForDeclarator(TypeProcessingState & state,TypeSourceInfo * & ReturnTypeInfo)2109 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2110                                              TypeSourceInfo *&ReturnTypeInfo) {
2111   Sema &SemaRef = state.getSema();
2112   Declarator &D = state.getDeclarator();
2113   QualType T;
2114   ReturnTypeInfo = nullptr;
2115 
2116   // The TagDecl owned by the DeclSpec.
2117   TagDecl *OwnedTagDecl = nullptr;
2118 
2119   bool ContainsPlaceholderType = false;
2120 
2121   switch (D.getName().getKind()) {
2122   case UnqualifiedId::IK_ImplicitSelfParam:
2123   case UnqualifiedId::IK_OperatorFunctionId:
2124   case UnqualifiedId::IK_Identifier:
2125   case UnqualifiedId::IK_LiteralOperatorId:
2126   case UnqualifiedId::IK_TemplateId:
2127     T = ConvertDeclSpecToType(state);
2128     ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType();
2129 
2130     if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2131       OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2132       // Owned declaration is embedded in declarator.
2133       OwnedTagDecl->setEmbeddedInDeclarator(true);
2134     }
2135     break;
2136 
2137   case UnqualifiedId::IK_ConstructorName:
2138   case UnqualifiedId::IK_ConstructorTemplateId:
2139   case UnqualifiedId::IK_DestructorName:
2140     // Constructors and destructors don't have return types. Use
2141     // "void" instead.
2142     T = SemaRef.Context.VoidTy;
2143     if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
2144       processTypeAttrs(state, T, TAL_DeclSpec, attrs);
2145     break;
2146 
2147   case UnqualifiedId::IK_ConversionFunctionId:
2148     // The result type of a conversion function is the type that it
2149     // converts to.
2150     T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2151                                   &ReturnTypeInfo);
2152     ContainsPlaceholderType = T->getContainedAutoType();
2153     break;
2154   }
2155 
2156   if (D.getAttributes())
2157     distributeTypeAttrsFromDeclarator(state, T);
2158 
2159   // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2160   // In C++11, a function declarator using 'auto' must have a trailing return
2161   // type (this is checked later) and we can skip this. In other languages
2162   // using auto, we need to check regardless.
2163   // C++14 In generic lambdas allow 'auto' in their parameters.
2164   if (ContainsPlaceholderType &&
2165       (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
2166     int Error = -1;
2167 
2168     switch (D.getContext()) {
2169     case Declarator::KNRTypeListContext:
2170       llvm_unreachable("K&R type lists aren't allowed in C++");
2171     case Declarator::LambdaExprContext:
2172       llvm_unreachable("Can't specify a type specifier in lambda grammar");
2173     case Declarator::ObjCParameterContext:
2174     case Declarator::ObjCResultContext:
2175     case Declarator::PrototypeContext:
2176       Error = 0;
2177       break;
2178     case Declarator::LambdaExprParameterContext:
2179       if (!(SemaRef.getLangOpts().CPlusPlus14
2180               && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2181         Error = 14;
2182       break;
2183     case Declarator::MemberContext:
2184       if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2185         break;
2186       switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2187       case TTK_Enum: llvm_unreachable("unhandled tag kind");
2188       case TTK_Struct: Error = 1; /* Struct member */ break;
2189       case TTK_Union:  Error = 2; /* Union member */ break;
2190       case TTK_Class:  Error = 3; /* Class member */ break;
2191       case TTK_Interface: Error = 4; /* Interface member */ break;
2192       }
2193       break;
2194     case Declarator::CXXCatchContext:
2195     case Declarator::ObjCCatchContext:
2196       Error = 5; // Exception declaration
2197       break;
2198     case Declarator::TemplateParamContext:
2199       Error = 6; // Template parameter
2200       break;
2201     case Declarator::BlockLiteralContext:
2202       Error = 7; // Block literal
2203       break;
2204     case Declarator::TemplateTypeArgContext:
2205       Error = 8; // Template type argument
2206       break;
2207     case Declarator::AliasDeclContext:
2208     case Declarator::AliasTemplateContext:
2209       Error = 10; // Type alias
2210       break;
2211     case Declarator::TrailingReturnContext:
2212       if (!SemaRef.getLangOpts().CPlusPlus14)
2213         Error = 11; // Function return type
2214       break;
2215     case Declarator::ConversionIdContext:
2216       if (!SemaRef.getLangOpts().CPlusPlus14)
2217         Error = 12; // conversion-type-id
2218       break;
2219     case Declarator::TypeNameContext:
2220       Error = 13; // Generic
2221       break;
2222     case Declarator::FileContext:
2223     case Declarator::BlockContext:
2224     case Declarator::ForContext:
2225     case Declarator::ConditionContext:
2226     case Declarator::CXXNewContext:
2227       break;
2228     }
2229 
2230     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2231       Error = 9;
2232 
2233     // In Objective-C it is an error to use 'auto' on a function declarator.
2234     if (D.isFunctionDeclarator())
2235       Error = 11;
2236 
2237     // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2238     // contains a trailing return type. That is only legal at the outermost
2239     // level. Check all declarator chunks (outermost first) anyway, to give
2240     // better diagnostics.
2241     if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
2242       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2243         unsigned chunkIndex = e - i - 1;
2244         state.setCurrentChunkIndex(chunkIndex);
2245         DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2246         if (DeclType.Kind == DeclaratorChunk::Function) {
2247           const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2248           if (FTI.hasTrailingReturnType()) {
2249             Error = -1;
2250             break;
2251           }
2252         }
2253       }
2254     }
2255 
2256     SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2257     if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2258       AutoRange = D.getName().getSourceRange();
2259 
2260     if (Error != -1) {
2261       const bool IsDeclTypeAuto =
2262           D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto;
2263       SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2264         << IsDeclTypeAuto << Error << AutoRange;
2265       T = SemaRef.Context.IntTy;
2266       D.setInvalidType(true);
2267     } else
2268       SemaRef.Diag(AutoRange.getBegin(),
2269                    diag::warn_cxx98_compat_auto_type_specifier)
2270         << AutoRange;
2271   }
2272 
2273   if (SemaRef.getLangOpts().CPlusPlus &&
2274       OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2275     // Check the contexts where C++ forbids the declaration of a new class
2276     // or enumeration in a type-specifier-seq.
2277     switch (D.getContext()) {
2278     case Declarator::TrailingReturnContext:
2279       // Class and enumeration definitions are syntactically not allowed in
2280       // trailing return types.
2281       llvm_unreachable("parser should not have allowed this");
2282       break;
2283     case Declarator::FileContext:
2284     case Declarator::MemberContext:
2285     case Declarator::BlockContext:
2286     case Declarator::ForContext:
2287     case Declarator::BlockLiteralContext:
2288     case Declarator::LambdaExprContext:
2289       // C++11 [dcl.type]p3:
2290       //   A type-specifier-seq shall not define a class or enumeration unless
2291       //   it appears in the type-id of an alias-declaration (7.1.3) that is not
2292       //   the declaration of a template-declaration.
2293     case Declarator::AliasDeclContext:
2294       break;
2295     case Declarator::AliasTemplateContext:
2296       SemaRef.Diag(OwnedTagDecl->getLocation(),
2297              diag::err_type_defined_in_alias_template)
2298         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2299       D.setInvalidType(true);
2300       break;
2301     case Declarator::TypeNameContext:
2302     case Declarator::ConversionIdContext:
2303     case Declarator::TemplateParamContext:
2304     case Declarator::CXXNewContext:
2305     case Declarator::CXXCatchContext:
2306     case Declarator::ObjCCatchContext:
2307     case Declarator::TemplateTypeArgContext:
2308       SemaRef.Diag(OwnedTagDecl->getLocation(),
2309              diag::err_type_defined_in_type_specifier)
2310         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2311       D.setInvalidType(true);
2312       break;
2313     case Declarator::PrototypeContext:
2314     case Declarator::LambdaExprParameterContext:
2315     case Declarator::ObjCParameterContext:
2316     case Declarator::ObjCResultContext:
2317     case Declarator::KNRTypeListContext:
2318       // C++ [dcl.fct]p6:
2319       //   Types shall not be defined in return or parameter types.
2320       SemaRef.Diag(OwnedTagDecl->getLocation(),
2321                    diag::err_type_defined_in_param_type)
2322         << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2323       D.setInvalidType(true);
2324       break;
2325     case Declarator::ConditionContext:
2326       // C++ 6.4p2:
2327       // The type-specifier-seq shall not contain typedef and shall not declare
2328       // a new class or enumeration.
2329       SemaRef.Diag(OwnedTagDecl->getLocation(),
2330                    diag::err_type_defined_in_condition);
2331       D.setInvalidType(true);
2332       break;
2333     }
2334   }
2335 
2336   assert(!T.isNull() && "This function should not return a null type");
2337   return T;
2338 }
2339 
2340 /// Produce an appropriate diagnostic for an ambiguity between a function
2341 /// declarator and a C++ direct-initializer.
warnAboutAmbiguousFunction(Sema & S,Declarator & D,DeclaratorChunk & DeclType,QualType RT)2342 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2343                                        DeclaratorChunk &DeclType, QualType RT) {
2344   const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2345   assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2346 
2347   // If the return type is void there is no ambiguity.
2348   if (RT->isVoidType())
2349     return;
2350 
2351   // An initializer for a non-class type can have at most one argument.
2352   if (!RT->isRecordType() && FTI.NumParams > 1)
2353     return;
2354 
2355   // An initializer for a reference must have exactly one argument.
2356   if (RT->isReferenceType() && FTI.NumParams != 1)
2357     return;
2358 
2359   // Only warn if this declarator is declaring a function at block scope, and
2360   // doesn't have a storage class (such as 'extern') specified.
2361   if (!D.isFunctionDeclarator() ||
2362       D.getFunctionDefinitionKind() != FDK_Declaration ||
2363       !S.CurContext->isFunctionOrMethod() ||
2364       D.getDeclSpec().getStorageClassSpec()
2365         != DeclSpec::SCS_unspecified)
2366     return;
2367 
2368   // Inside a condition, a direct initializer is not permitted. We allow one to
2369   // be parsed in order to give better diagnostics in condition parsing.
2370   if (D.getContext() == Declarator::ConditionContext)
2371     return;
2372 
2373   SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2374 
2375   S.Diag(DeclType.Loc,
2376          FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
2377                        : diag::warn_empty_parens_are_function_decl)
2378       << ParenRange;
2379 
2380   // If the declaration looks like:
2381   //   T var1,
2382   //   f();
2383   // and name lookup finds a function named 'f', then the ',' was
2384   // probably intended to be a ';'.
2385   if (!D.isFirstDeclarator() && D.getIdentifier()) {
2386     FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2387     FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2388     if (Comma.getFileID() != Name.getFileID() ||
2389         Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2390       LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2391                           Sema::LookupOrdinaryName);
2392       if (S.LookupName(Result, S.getCurScope()))
2393         S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2394           << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2395           << D.getIdentifier();
2396     }
2397   }
2398 
2399   if (FTI.NumParams > 0) {
2400     // For a declaration with parameters, eg. "T var(T());", suggest adding
2401     // parens around the first parameter to turn the declaration into a
2402     // variable declaration.
2403     SourceRange Range = FTI.Params[0].Param->getSourceRange();
2404     SourceLocation B = Range.getBegin();
2405     SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
2406     // FIXME: Maybe we should suggest adding braces instead of parens
2407     // in C++11 for classes that don't have an initializer_list constructor.
2408     S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2409       << FixItHint::CreateInsertion(B, "(")
2410       << FixItHint::CreateInsertion(E, ")");
2411   } else {
2412     // For a declaration without parameters, eg. "T var();", suggest replacing
2413     // the parens with an initializer to turn the declaration into a variable
2414     // declaration.
2415     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2416 
2417     // Empty parens mean value-initialization, and no parens mean
2418     // default initialization. These are equivalent if the default
2419     // constructor is user-provided or if zero-initialization is a
2420     // no-op.
2421     if (RD && RD->hasDefinition() &&
2422         (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2423       S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2424         << FixItHint::CreateRemoval(ParenRange);
2425     else {
2426       std::string Init =
2427           S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2428       if (Init.empty() && S.LangOpts.CPlusPlus11)
2429         Init = "{}";
2430       if (!Init.empty())
2431         S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2432           << FixItHint::CreateReplacement(ParenRange, Init);
2433     }
2434   }
2435 }
2436 
2437 /// Helper for figuring out the default CC for a function declarator type.  If
2438 /// this is the outermost chunk, then we can determine the CC from the
2439 /// declarator context.  If not, then this could be either a member function
2440 /// type or normal function type.
2441 static CallingConv
getCCForDeclaratorChunk(Sema & S,Declarator & D,const DeclaratorChunk::FunctionTypeInfo & FTI,unsigned ChunkIndex)2442 getCCForDeclaratorChunk(Sema &S, Declarator &D,
2443                         const DeclaratorChunk::FunctionTypeInfo &FTI,
2444                         unsigned ChunkIndex) {
2445   assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2446 
2447   bool IsCXXInstanceMethod = false;
2448 
2449   if (S.getLangOpts().CPlusPlus) {
2450     // Look inwards through parentheses to see if this chunk will form a
2451     // member pointer type or if we're the declarator.  Any type attributes
2452     // between here and there will override the CC we choose here.
2453     unsigned I = ChunkIndex;
2454     bool FoundNonParen = false;
2455     while (I && !FoundNonParen) {
2456       --I;
2457       if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2458         FoundNonParen = true;
2459     }
2460 
2461     if (FoundNonParen) {
2462       // If we're not the declarator, we're a regular function type unless we're
2463       // in a member pointer.
2464       IsCXXInstanceMethod =
2465           D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2466     } else {
2467       // We're the innermost decl chunk, so must be a function declarator.
2468       assert(D.isFunctionDeclarator());
2469 
2470       // If we're inside a record, we're declaring a method, but it could be
2471       // explicitly or implicitly static.
2472       IsCXXInstanceMethod =
2473           D.isFirstDeclarationOfMember() &&
2474           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2475           !D.isStaticMember();
2476     }
2477   }
2478 
2479   return S.Context.getDefaultCallingConvention(FTI.isVariadic,
2480                                                IsCXXInstanceMethod);
2481 }
2482 
GetFullTypeForDeclarator(TypeProcessingState & state,QualType declSpecType,TypeSourceInfo * TInfo)2483 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2484                                                 QualType declSpecType,
2485                                                 TypeSourceInfo *TInfo) {
2486   // The TypeSourceInfo that this function returns will not be a null type.
2487   // If there is an error, this function will fill in a dummy type as fallback.
2488   QualType T = declSpecType;
2489   Declarator &D = state.getDeclarator();
2490   Sema &S = state.getSema();
2491   ASTContext &Context = S.Context;
2492   const LangOptions &LangOpts = S.getLangOpts();
2493 
2494   // The name we're declaring, if any.
2495   DeclarationName Name;
2496   if (D.getIdentifier())
2497     Name = D.getIdentifier();
2498 
2499   // Does this declaration declare a typedef-name?
2500   bool IsTypedefName =
2501     D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2502     D.getContext() == Declarator::AliasDeclContext ||
2503     D.getContext() == Declarator::AliasTemplateContext;
2504 
2505   // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2506   bool IsQualifiedFunction = T->isFunctionProtoType() &&
2507       (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2508        T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2509 
2510   // If T is 'decltype(auto)', the only declarators we can have are parens
2511   // and at most one function declarator if this is a function declaration.
2512   if (const AutoType *AT = T->getAs<AutoType>()) {
2513     if (AT->isDecltypeAuto()) {
2514       for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2515         unsigned Index = E - I - 1;
2516         DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
2517         unsigned DiagId = diag::err_decltype_auto_compound_type;
2518         unsigned DiagKind = 0;
2519         switch (DeclChunk.Kind) {
2520         case DeclaratorChunk::Paren:
2521           continue;
2522         case DeclaratorChunk::Function: {
2523           unsigned FnIndex;
2524           if (D.isFunctionDeclarationContext() &&
2525               D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
2526             continue;
2527           DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
2528           break;
2529         }
2530         case DeclaratorChunk::Pointer:
2531         case DeclaratorChunk::BlockPointer:
2532         case DeclaratorChunk::MemberPointer:
2533           DiagKind = 0;
2534           break;
2535         case DeclaratorChunk::Reference:
2536           DiagKind = 1;
2537           break;
2538         case DeclaratorChunk::Array:
2539           DiagKind = 2;
2540           break;
2541         }
2542 
2543         S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
2544         D.setInvalidType(true);
2545         break;
2546       }
2547     }
2548   }
2549 
2550   // Walk the DeclTypeInfo, building the recursive type as we go.
2551   // DeclTypeInfos are ordered from the identifier out, which is
2552   // opposite of what we want :).
2553   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2554     unsigned chunkIndex = e - i - 1;
2555     state.setCurrentChunkIndex(chunkIndex);
2556     DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2557     IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
2558     switch (DeclType.Kind) {
2559     case DeclaratorChunk::Paren:
2560       T = S.BuildParenType(T);
2561       break;
2562     case DeclaratorChunk::BlockPointer:
2563       // If blocks are disabled, emit an error.
2564       if (!LangOpts.Blocks)
2565         S.Diag(DeclType.Loc, diag::err_blocks_disable);
2566 
2567       T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
2568       if (DeclType.Cls.TypeQuals)
2569         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
2570       break;
2571     case DeclaratorChunk::Pointer:
2572       // Verify that we're not building a pointer to pointer to function with
2573       // exception specification.
2574       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2575         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2576         D.setInvalidType(true);
2577         // Build the type anyway.
2578       }
2579       if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
2580         T = Context.getObjCObjectPointerType(T);
2581         if (DeclType.Ptr.TypeQuals)
2582           T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2583         break;
2584       }
2585       T = S.BuildPointerType(T, DeclType.Loc, Name);
2586       if (DeclType.Ptr.TypeQuals)
2587         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2588 
2589       break;
2590     case DeclaratorChunk::Reference: {
2591       // Verify that we're not building a reference to pointer to function with
2592       // exception specification.
2593       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2594         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2595         D.setInvalidType(true);
2596         // Build the type anyway.
2597       }
2598       T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
2599 
2600       if (DeclType.Ref.HasRestrict)
2601         T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
2602       break;
2603     }
2604     case DeclaratorChunk::Array: {
2605       // Verify that we're not building an array of pointers to function with
2606       // exception specification.
2607       if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2608         S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2609         D.setInvalidType(true);
2610         // Build the type anyway.
2611       }
2612       DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2613       Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2614       ArrayType::ArraySizeModifier ASM;
2615       if (ATI.isStar)
2616         ASM = ArrayType::Star;
2617       else if (ATI.hasStatic)
2618         ASM = ArrayType::Static;
2619       else
2620         ASM = ArrayType::Normal;
2621       if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2622         // FIXME: This check isn't quite right: it allows star in prototypes
2623         // for function definitions, and disallows some edge cases detailed
2624         // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2625         S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2626         ASM = ArrayType::Normal;
2627         D.setInvalidType(true);
2628       }
2629 
2630       // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2631       // shall appear only in a declaration of a function parameter with an
2632       // array type, ...
2633       if (ASM == ArrayType::Static || ATI.TypeQuals) {
2634         if (!(D.isPrototypeContext() ||
2635               D.getContext() == Declarator::KNRTypeListContext)) {
2636           S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2637               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2638           // Remove the 'static' and the type qualifiers.
2639           if (ASM == ArrayType::Static)
2640             ASM = ArrayType::Normal;
2641           ATI.TypeQuals = 0;
2642           D.setInvalidType(true);
2643         }
2644 
2645         // C99 6.7.5.2p1: ... and then only in the outermost array type
2646         // derivation.
2647         unsigned x = chunkIndex;
2648         while (x != 0) {
2649           // Walk outwards along the declarator chunks.
2650           x--;
2651           const DeclaratorChunk &DC = D.getTypeObject(x);
2652           switch (DC.Kind) {
2653           case DeclaratorChunk::Paren:
2654             continue;
2655           case DeclaratorChunk::Array:
2656           case DeclaratorChunk::Pointer:
2657           case DeclaratorChunk::Reference:
2658           case DeclaratorChunk::MemberPointer:
2659             S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2660               (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2661             if (ASM == ArrayType::Static)
2662               ASM = ArrayType::Normal;
2663             ATI.TypeQuals = 0;
2664             D.setInvalidType(true);
2665             break;
2666           case DeclaratorChunk::Function:
2667           case DeclaratorChunk::BlockPointer:
2668             // These are invalid anyway, so just ignore.
2669             break;
2670           }
2671         }
2672       }
2673       const AutoType *AT = T->getContainedAutoType();
2674       // Allow arrays of auto if we are a generic lambda parameter.
2675       // i.e. [](auto (&array)[5]) { return array[0]; }; OK
2676       if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
2677         // We've already diagnosed this for decltype(auto).
2678         if (!AT->isDecltypeAuto())
2679           S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
2680             << getPrintableNameForEntity(Name) << T;
2681         T = QualType();
2682         break;
2683       }
2684 
2685       T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
2686                            SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2687       break;
2688     }
2689     case DeclaratorChunk::Function: {
2690       // If the function declarator has a prototype (i.e. it is not () and
2691       // does not have a K&R-style identifier list), then the arguments are part
2692       // of the type, otherwise the argument list is ().
2693       const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2694       IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
2695 
2696       // Check for auto functions and trailing return type and adjust the
2697       // return type accordingly.
2698       if (!D.isInvalidType()) {
2699         // trailing-return-type is only required if we're declaring a function,
2700         // and not, for instance, a pointer to a function.
2701         if (D.getDeclSpec().containsPlaceholderType() &&
2702             !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
2703             !S.getLangOpts().CPlusPlus14) {
2704           S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2705                  D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
2706                      ? diag::err_auto_missing_trailing_return
2707                      : diag::err_deduced_return_type);
2708           T = Context.IntTy;
2709           D.setInvalidType(true);
2710         } else if (FTI.hasTrailingReturnType()) {
2711           // T must be exactly 'auto' at this point. See CWG issue 681.
2712           if (isa<ParenType>(T)) {
2713             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2714                  diag::err_trailing_return_in_parens)
2715               << T << D.getDeclSpec().getSourceRange();
2716             D.setInvalidType(true);
2717           } else if (D.getContext() != Declarator::LambdaExprContext &&
2718                      (T.hasQualifiers() || !isa<AutoType>(T) ||
2719                       cast<AutoType>(T)->isDecltypeAuto())) {
2720             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2721                  diag::err_trailing_return_without_auto)
2722               << T << D.getDeclSpec().getSourceRange();
2723             D.setInvalidType(true);
2724           }
2725           T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2726           if (T.isNull()) {
2727             // An error occurred parsing the trailing return type.
2728             T = Context.IntTy;
2729             D.setInvalidType(true);
2730           }
2731         }
2732       }
2733 
2734       // C99 6.7.5.3p1: The return type may not be a function or array type.
2735       // For conversion functions, we'll diagnose this particular error later.
2736       if ((T->isArrayType() || T->isFunctionType()) &&
2737           (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2738         unsigned diagID = diag::err_func_returning_array_function;
2739         // Last processing chunk in block context means this function chunk
2740         // represents the block.
2741         if (chunkIndex == 0 &&
2742             D.getContext() == Declarator::BlockLiteralContext)
2743           diagID = diag::err_block_returning_array_function;
2744         S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2745         T = Context.IntTy;
2746         D.setInvalidType(true);
2747       }
2748 
2749       // Do not allow returning half FP value.
2750       // FIXME: This really should be in BuildFunctionType.
2751       if (T->isHalfType()) {
2752         if (S.getLangOpts().OpenCL) {
2753           if (!S.getOpenCLOptions().cl_khr_fp16) {
2754             S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
2755             D.setInvalidType(true);
2756           }
2757         } else if (!S.getLangOpts().HalfArgsAndReturns) {
2758           S.Diag(D.getIdentifierLoc(),
2759             diag::err_parameters_retval_cannot_have_fp16_type) << 1;
2760           D.setInvalidType(true);
2761         }
2762       }
2763 
2764       // Methods cannot return interface types. All ObjC objects are
2765       // passed by reference.
2766       if (T->isObjCObjectType()) {
2767         SourceLocation DiagLoc, FixitLoc;
2768         if (TInfo) {
2769           DiagLoc = TInfo->getTypeLoc().getLocStart();
2770           FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
2771         } else {
2772           DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
2773           FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
2774         }
2775         S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
2776           << 0 << T
2777           << FixItHint::CreateInsertion(FixitLoc, "*");
2778 
2779         T = Context.getObjCObjectPointerType(T);
2780         if (TInfo) {
2781           TypeLocBuilder TLB;
2782           TLB.pushFullCopy(TInfo->getTypeLoc());
2783           ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
2784           TLoc.setStarLoc(FixitLoc);
2785           TInfo = TLB.getTypeSourceInfo(Context, T);
2786         }
2787 
2788         D.setInvalidType(true);
2789       }
2790 
2791       // cv-qualifiers on return types are pointless except when the type is a
2792       // class type in C++.
2793       if ((T.getCVRQualifiers() || T->isAtomicType()) &&
2794           !(S.getLangOpts().CPlusPlus &&
2795             (T->isDependentType() || T->isRecordType())))
2796         diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
2797 
2798       // Objective-C ARC ownership qualifiers are ignored on the function
2799       // return type (by type canonicalization). Complain if this attribute
2800       // was written here.
2801       if (T.getQualifiers().hasObjCLifetime()) {
2802         SourceLocation AttrLoc;
2803         if (chunkIndex + 1 < D.getNumTypeObjects()) {
2804           DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2805           for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
2806                Attr; Attr = Attr->getNext()) {
2807             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2808               AttrLoc = Attr->getLoc();
2809               break;
2810             }
2811           }
2812         }
2813         if (AttrLoc.isInvalid()) {
2814           for (const AttributeList *Attr
2815                  = D.getDeclSpec().getAttributes().getList();
2816                Attr; Attr = Attr->getNext()) {
2817             if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2818               AttrLoc = Attr->getLoc();
2819               break;
2820             }
2821           }
2822         }
2823 
2824         if (AttrLoc.isValid()) {
2825           // The ownership attributes are almost always written via
2826           // the predefined
2827           // __strong/__weak/__autoreleasing/__unsafe_unretained.
2828           if (AttrLoc.isMacroID())
2829             AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
2830 
2831           S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
2832             << T.getQualifiers().getObjCLifetime();
2833         }
2834       }
2835 
2836       if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
2837         // C++ [dcl.fct]p6:
2838         //   Types shall not be defined in return or parameter types.
2839         TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2840         S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2841           << Context.getTypeDeclType(Tag);
2842       }
2843 
2844       // Exception specs are not allowed in typedefs. Complain, but add it
2845       // anyway.
2846       if (IsTypedefName && FTI.getExceptionSpecType())
2847         S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2848           << (D.getContext() == Declarator::AliasDeclContext ||
2849               D.getContext() == Declarator::AliasTemplateContext);
2850 
2851       // If we see "T var();" or "T var(T());" at block scope, it is probably
2852       // an attempt to initialize a variable, not a function declaration.
2853       if (FTI.isAmbiguous)
2854         warnAboutAmbiguousFunction(S, D, DeclType, T);
2855 
2856       FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
2857 
2858       if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2859         // Simple void foo(), where the incoming T is the result type.
2860         T = Context.getFunctionNoProtoType(T, EI);
2861       } else {
2862         // We allow a zero-parameter variadic function in C if the
2863         // function is marked with the "overloadable" attribute. Scan
2864         // for this attribute now.
2865         if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
2866           bool Overloadable = false;
2867           for (const AttributeList *Attrs = D.getAttributes();
2868                Attrs; Attrs = Attrs->getNext()) {
2869             if (Attrs->getKind() == AttributeList::AT_Overloadable) {
2870               Overloadable = true;
2871               break;
2872             }
2873           }
2874 
2875           if (!Overloadable)
2876             S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
2877         }
2878 
2879         if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
2880           // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2881           // definition.
2882           S.Diag(FTI.Params[0].IdentLoc,
2883                  diag::err_ident_list_in_fn_declaration);
2884           D.setInvalidType(true);
2885           // Recover by creating a K&R-style function type.
2886           T = Context.getFunctionNoProtoType(T, EI);
2887           break;
2888         }
2889 
2890         FunctionProtoType::ExtProtoInfo EPI;
2891         EPI.ExtInfo = EI;
2892         EPI.Variadic = FTI.isVariadic;
2893         EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
2894         EPI.TypeQuals = FTI.TypeQuals;
2895         EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2896                     : FTI.RefQualifierIsLValueRef? RQ_LValue
2897                     : RQ_RValue;
2898 
2899         // Otherwise, we have a function with a parameter list that is
2900         // potentially variadic.
2901         SmallVector<QualType, 16> ParamTys;
2902         ParamTys.reserve(FTI.NumParams);
2903 
2904         SmallVector<bool, 16> ConsumedParameters;
2905         ConsumedParameters.reserve(FTI.NumParams);
2906         bool HasAnyConsumedParameters = false;
2907 
2908         for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
2909           ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
2910           QualType ParamTy = Param->getType();
2911           assert(!ParamTy.isNull() && "Couldn't parse type?");
2912 
2913           // Look for 'void'.  void is allowed only as a single parameter to a
2914           // function with no other parameters (C99 6.7.5.3p10).  We record
2915           // int(void) as a FunctionProtoType with an empty parameter list.
2916           if (ParamTy->isVoidType()) {
2917             // If this is something like 'float(int, void)', reject it.  'void'
2918             // is an incomplete type (C99 6.2.5p19) and function decls cannot
2919             // have parameters of incomplete type.
2920             if (FTI.NumParams != 1 || FTI.isVariadic) {
2921               S.Diag(DeclType.Loc, diag::err_void_only_param);
2922               ParamTy = Context.IntTy;
2923               Param->setType(ParamTy);
2924             } else if (FTI.Params[i].Ident) {
2925               // Reject, but continue to parse 'int(void abc)'.
2926               S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
2927               ParamTy = Context.IntTy;
2928               Param->setType(ParamTy);
2929             } else {
2930               // Reject, but continue to parse 'float(const void)'.
2931               if (ParamTy.hasQualifiers())
2932                 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2933 
2934               // Do not add 'void' to the list.
2935               break;
2936             }
2937           } else if (ParamTy->isHalfType()) {
2938             // Disallow half FP parameters.
2939             // FIXME: This really should be in BuildFunctionType.
2940             if (S.getLangOpts().OpenCL) {
2941               if (!S.getOpenCLOptions().cl_khr_fp16) {
2942                 S.Diag(Param->getLocation(),
2943                   diag::err_opencl_half_param) << ParamTy;
2944                 D.setInvalidType();
2945                 Param->setInvalidDecl();
2946               }
2947             } else if (!S.getLangOpts().HalfArgsAndReturns) {
2948               S.Diag(Param->getLocation(),
2949                 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
2950               D.setInvalidType();
2951             }
2952           } else if (!FTI.hasPrototype) {
2953             if (ParamTy->isPromotableIntegerType()) {
2954               ParamTy = Context.getPromotedIntegerType(ParamTy);
2955               Param->setKNRPromoted(true);
2956             } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
2957               if (BTy->getKind() == BuiltinType::Float) {
2958                 ParamTy = Context.DoubleTy;
2959                 Param->setKNRPromoted(true);
2960               }
2961             }
2962           }
2963 
2964           if (LangOpts.ObjCAutoRefCount) {
2965             bool Consumed = Param->hasAttr<NSConsumedAttr>();
2966             ConsumedParameters.push_back(Consumed);
2967             HasAnyConsumedParameters |= Consumed;
2968           }
2969 
2970           ParamTys.push_back(ParamTy);
2971         }
2972 
2973         if (HasAnyConsumedParameters)
2974           EPI.ConsumedParameters = ConsumedParameters.data();
2975 
2976         SmallVector<QualType, 4> Exceptions;
2977         SmallVector<ParsedType, 2> DynamicExceptions;
2978         SmallVector<SourceRange, 2> DynamicExceptionRanges;
2979         Expr *NoexceptExpr = nullptr;
2980 
2981         if (FTI.getExceptionSpecType() == EST_Dynamic) {
2982           // FIXME: It's rather inefficient to have to split into two vectors
2983           // here.
2984           unsigned N = FTI.NumExceptions;
2985           DynamicExceptions.reserve(N);
2986           DynamicExceptionRanges.reserve(N);
2987           for (unsigned I = 0; I != N; ++I) {
2988             DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
2989             DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
2990           }
2991         } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
2992           NoexceptExpr = FTI.NoexceptExpr;
2993         }
2994 
2995         S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
2996                                       FTI.getExceptionSpecType(),
2997                                       DynamicExceptions,
2998                                       DynamicExceptionRanges,
2999                                       NoexceptExpr,
3000                                       Exceptions,
3001                                       EPI.ExceptionSpec);
3002 
3003         T = Context.getFunctionType(T, ParamTys, EPI);
3004       }
3005 
3006       break;
3007     }
3008     case DeclaratorChunk::MemberPointer:
3009       // The scope spec must refer to a class, or be dependent.
3010       CXXScopeSpec &SS = DeclType.Mem.Scope();
3011       QualType ClsType;
3012       if (SS.isInvalid()) {
3013         // Avoid emitting extra errors if we already errored on the scope.
3014         D.setInvalidType(true);
3015       } else if (S.isDependentScopeSpecifier(SS) ||
3016                  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
3017         NestedNameSpecifier *NNS = SS.getScopeRep();
3018         NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
3019         switch (NNS->getKind()) {
3020         case NestedNameSpecifier::Identifier:
3021           ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
3022                                                  NNS->getAsIdentifier());
3023           break;
3024 
3025         case NestedNameSpecifier::Namespace:
3026         case NestedNameSpecifier::NamespaceAlias:
3027         case NestedNameSpecifier::Global:
3028         case NestedNameSpecifier::Super:
3029           llvm_unreachable("Nested-name-specifier must name a type");
3030 
3031         case NestedNameSpecifier::TypeSpec:
3032         case NestedNameSpecifier::TypeSpecWithTemplate:
3033           ClsType = QualType(NNS->getAsType(), 0);
3034           // Note: if the NNS has a prefix and ClsType is a nondependent
3035           // TemplateSpecializationType, then the NNS prefix is NOT included
3036           // in ClsType; hence we wrap ClsType into an ElaboratedType.
3037           // NOTE: in particular, no wrap occurs if ClsType already is an
3038           // Elaborated, DependentName, or DependentTemplateSpecialization.
3039           if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
3040             ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
3041           break;
3042         }
3043       } else {
3044         S.Diag(DeclType.Mem.Scope().getBeginLoc(),
3045              diag::err_illegal_decl_mempointer_in_nonclass)
3046           << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
3047           << DeclType.Mem.Scope().getRange();
3048         D.setInvalidType(true);
3049       }
3050 
3051       if (!ClsType.isNull())
3052         T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
3053                                      D.getIdentifier());
3054       if (T.isNull()) {
3055         T = Context.IntTy;
3056         D.setInvalidType(true);
3057       } else if (DeclType.Mem.TypeQuals) {
3058         T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
3059       }
3060       break;
3061     }
3062 
3063     if (T.isNull()) {
3064       D.setInvalidType(true);
3065       T = Context.IntTy;
3066     }
3067 
3068     // See if there are any attributes on this declarator chunk.
3069     if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
3070       processTypeAttrs(state, T, TAL_DeclChunk, attrs);
3071   }
3072 
3073   assert(!T.isNull() && "T must not be null after this point");
3074 
3075   if (LangOpts.CPlusPlus && T->isFunctionType()) {
3076     const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
3077     assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
3078 
3079     // C++ 8.3.5p4:
3080     //   A cv-qualifier-seq shall only be part of the function type
3081     //   for a nonstatic member function, the function type to which a pointer
3082     //   to member refers, or the top-level function type of a function typedef
3083     //   declaration.
3084     //
3085     // Core issue 547 also allows cv-qualifiers on function types that are
3086     // top-level template type arguments.
3087     bool FreeFunction;
3088     if (!D.getCXXScopeSpec().isSet()) {
3089       FreeFunction = ((D.getContext() != Declarator::MemberContext &&
3090                        D.getContext() != Declarator::LambdaExprContext) ||
3091                       D.getDeclSpec().isFriendSpecified());
3092     } else {
3093       DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
3094       FreeFunction = (DC && !DC->isRecord());
3095     }
3096 
3097     // C++11 [dcl.fct]p6 (w/DR1417):
3098     // An attempt to specify a function type with a cv-qualifier-seq or a
3099     // ref-qualifier (including by typedef-name) is ill-formed unless it is:
3100     //  - the function type for a non-static member function,
3101     //  - the function type to which a pointer to member refers,
3102     //  - the top-level function type of a function typedef declaration or
3103     //    alias-declaration,
3104     //  - the type-id in the default argument of a type-parameter, or
3105     //  - the type-id of a template-argument for a type-parameter
3106     //
3107     // FIXME: Checking this here is insufficient. We accept-invalid on:
3108     //
3109     //   template<typename T> struct S { void f(T); };
3110     //   S<int() const> s;
3111     //
3112     // ... for instance.
3113     if (IsQualifiedFunction &&
3114         !(!FreeFunction &&
3115           D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
3116         !IsTypedefName &&
3117         D.getContext() != Declarator::TemplateTypeArgContext) {
3118       SourceLocation Loc = D.getLocStart();
3119       SourceRange RemovalRange;
3120       unsigned I;
3121       if (D.isFunctionDeclarator(I)) {
3122         SmallVector<SourceLocation, 4> RemovalLocs;
3123         const DeclaratorChunk &Chunk = D.getTypeObject(I);
3124         assert(Chunk.Kind == DeclaratorChunk::Function);
3125         if (Chunk.Fun.hasRefQualifier())
3126           RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
3127         if (Chunk.Fun.TypeQuals & Qualifiers::Const)
3128           RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
3129         if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
3130           RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
3131         if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
3132           RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
3133         if (!RemovalLocs.empty()) {
3134           std::sort(RemovalLocs.begin(), RemovalLocs.end(),
3135                     BeforeThanCompare<SourceLocation>(S.getSourceManager()));
3136           RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
3137           Loc = RemovalLocs.front();
3138         }
3139       }
3140 
3141       S.Diag(Loc, diag::err_invalid_qualified_function_type)
3142         << FreeFunction << D.isFunctionDeclarator() << T
3143         << getFunctionQualifiersAsString(FnTy)
3144         << FixItHint::CreateRemoval(RemovalRange);
3145 
3146       // Strip the cv-qualifiers and ref-qualifiers from the type.
3147       FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
3148       EPI.TypeQuals = 0;
3149       EPI.RefQualifier = RQ_None;
3150 
3151       T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
3152                                   EPI);
3153       // Rebuild any parens around the identifier in the function type.
3154       for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3155         if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
3156           break;
3157         T = S.BuildParenType(T);
3158       }
3159     }
3160   }
3161 
3162   // Apply any undistributed attributes from the declarator.
3163   if (AttributeList *attrs = D.getAttributes())
3164     processTypeAttrs(state, T, TAL_DeclName, attrs);
3165 
3166   // Diagnose any ignored type attributes.
3167   state.diagnoseIgnoredTypeAttrs(T);
3168 
3169   // C++0x [dcl.constexpr]p9:
3170   //  A constexpr specifier used in an object declaration declares the object
3171   //  as const.
3172   if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
3173     T.addConst();
3174   }
3175 
3176   // If there was an ellipsis in the declarator, the declaration declares a
3177   // parameter pack whose type may be a pack expansion type.
3178   if (D.hasEllipsis()) {
3179     // C++0x [dcl.fct]p13:
3180     //   A declarator-id or abstract-declarator containing an ellipsis shall
3181     //   only be used in a parameter-declaration. Such a parameter-declaration
3182     //   is a parameter pack (14.5.3). [...]
3183     switch (D.getContext()) {
3184     case Declarator::PrototypeContext:
3185     case Declarator::LambdaExprParameterContext:
3186       // C++0x [dcl.fct]p13:
3187       //   [...] When it is part of a parameter-declaration-clause, the
3188       //   parameter pack is a function parameter pack (14.5.3). The type T
3189       //   of the declarator-id of the function parameter pack shall contain
3190       //   a template parameter pack; each template parameter pack in T is
3191       //   expanded by the function parameter pack.
3192       //
3193       // We represent function parameter packs as function parameters whose
3194       // type is a pack expansion.
3195       if (!T->containsUnexpandedParameterPack()) {
3196         S.Diag(D.getEllipsisLoc(),
3197              diag::err_function_parameter_pack_without_parameter_packs)
3198           << T <<  D.getSourceRange();
3199         D.setEllipsisLoc(SourceLocation());
3200       } else {
3201         T = Context.getPackExpansionType(T, None);
3202       }
3203       break;
3204     case Declarator::TemplateParamContext:
3205       // C++0x [temp.param]p15:
3206       //   If a template-parameter is a [...] is a parameter-declaration that
3207       //   declares a parameter pack (8.3.5), then the template-parameter is a
3208       //   template parameter pack (14.5.3).
3209       //
3210       // Note: core issue 778 clarifies that, if there are any unexpanded
3211       // parameter packs in the type of the non-type template parameter, then
3212       // it expands those parameter packs.
3213       if (T->containsUnexpandedParameterPack())
3214         T = Context.getPackExpansionType(T, None);
3215       else
3216         S.Diag(D.getEllipsisLoc(),
3217                LangOpts.CPlusPlus11
3218                  ? diag::warn_cxx98_compat_variadic_templates
3219                  : diag::ext_variadic_templates);
3220       break;
3221 
3222     case Declarator::FileContext:
3223     case Declarator::KNRTypeListContext:
3224     case Declarator::ObjCParameterContext:  // FIXME: special diagnostic here?
3225     case Declarator::ObjCResultContext:     // FIXME: special diagnostic here?
3226     case Declarator::TypeNameContext:
3227     case Declarator::CXXNewContext:
3228     case Declarator::AliasDeclContext:
3229     case Declarator::AliasTemplateContext:
3230     case Declarator::MemberContext:
3231     case Declarator::BlockContext:
3232     case Declarator::ForContext:
3233     case Declarator::ConditionContext:
3234     case Declarator::CXXCatchContext:
3235     case Declarator::ObjCCatchContext:
3236     case Declarator::BlockLiteralContext:
3237     case Declarator::LambdaExprContext:
3238     case Declarator::ConversionIdContext:
3239     case Declarator::TrailingReturnContext:
3240     case Declarator::TemplateTypeArgContext:
3241       // FIXME: We may want to allow parameter packs in block-literal contexts
3242       // in the future.
3243       S.Diag(D.getEllipsisLoc(),
3244              diag::err_ellipsis_in_declarator_not_parameter);
3245       D.setEllipsisLoc(SourceLocation());
3246       break;
3247     }
3248   }
3249 
3250   assert(!T.isNull() && "T must not be null at the end of this function");
3251   if (D.isInvalidType())
3252     return Context.getTrivialTypeSourceInfo(T);
3253 
3254   return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3255 }
3256 
3257 /// GetTypeForDeclarator - Convert the type for the specified
3258 /// declarator to Type instances.
3259 ///
3260 /// The result of this call will never be null, but the associated
3261 /// type may be a null type if there's an unrecoverable error.
GetTypeForDeclarator(Declarator & D,Scope * S)3262 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3263   // Determine the type of the declarator. Not all forms of declarator
3264   // have a type.
3265 
3266   TypeProcessingState state(*this, D);
3267 
3268   TypeSourceInfo *ReturnTypeInfo = nullptr;
3269   QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3270 
3271   if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
3272     inferARCWriteback(state, T);
3273 
3274   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
3275 }
3276 
transferARCOwnershipToDeclSpec(Sema & S,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)3277 static void transferARCOwnershipToDeclSpec(Sema &S,
3278                                            QualType &declSpecTy,
3279                                            Qualifiers::ObjCLifetime ownership) {
3280   if (declSpecTy->isObjCRetainableType() &&
3281       declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3282     Qualifiers qs;
3283     qs.addObjCLifetime(ownership);
3284     declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3285   }
3286 }
3287 
transferARCOwnershipToDeclaratorChunk(TypeProcessingState & state,Qualifiers::ObjCLifetime ownership,unsigned chunkIndex)3288 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3289                                             Qualifiers::ObjCLifetime ownership,
3290                                             unsigned chunkIndex) {
3291   Sema &S = state.getSema();
3292   Declarator &D = state.getDeclarator();
3293 
3294   // Look for an explicit lifetime attribute.
3295   DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3296   for (const AttributeList *attr = chunk.getAttrs(); attr;
3297          attr = attr->getNext())
3298     if (attr->getKind() == AttributeList::AT_ObjCOwnership)
3299       return;
3300 
3301   const char *attrStr = nullptr;
3302   switch (ownership) {
3303   case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
3304   case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3305   case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3306   case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3307   case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3308   }
3309 
3310   IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
3311   Arg->Ident = &S.Context.Idents.get(attrStr);
3312   Arg->Loc = SourceLocation();
3313 
3314   ArgsUnion Args(Arg);
3315 
3316   // If there wasn't one, add one (with an invalid source location
3317   // so that we don't make an AttributedType for it).
3318   AttributeList *attr = D.getAttributePool()
3319     .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3320             /*scope*/ nullptr, SourceLocation(),
3321             /*args*/ &Args, 1, AttributeList::AS_GNU);
3322   spliceAttrIntoList(*attr, chunk.getAttrListRef());
3323 
3324   // TODO: mark whether we did this inference?
3325 }
3326 
3327 /// \brief Used for transferring ownership in casts resulting in l-values.
transferARCOwnership(TypeProcessingState & state,QualType & declSpecTy,Qualifiers::ObjCLifetime ownership)3328 static void transferARCOwnership(TypeProcessingState &state,
3329                                  QualType &declSpecTy,
3330                                  Qualifiers::ObjCLifetime ownership) {
3331   Sema &S = state.getSema();
3332   Declarator &D = state.getDeclarator();
3333 
3334   int inner = -1;
3335   bool hasIndirection = false;
3336   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3337     DeclaratorChunk &chunk = D.getTypeObject(i);
3338     switch (chunk.Kind) {
3339     case DeclaratorChunk::Paren:
3340       // Ignore parens.
3341       break;
3342 
3343     case DeclaratorChunk::Array:
3344     case DeclaratorChunk::Reference:
3345     case DeclaratorChunk::Pointer:
3346       if (inner != -1)
3347         hasIndirection = true;
3348       inner = i;
3349       break;
3350 
3351     case DeclaratorChunk::BlockPointer:
3352       if (inner != -1)
3353         transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3354       return;
3355 
3356     case DeclaratorChunk::Function:
3357     case DeclaratorChunk::MemberPointer:
3358       return;
3359     }
3360   }
3361 
3362   if (inner == -1)
3363     return;
3364 
3365   DeclaratorChunk &chunk = D.getTypeObject(inner);
3366   if (chunk.Kind == DeclaratorChunk::Pointer) {
3367     if (declSpecTy->isObjCRetainableType())
3368       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3369     if (declSpecTy->isObjCObjectType() && hasIndirection)
3370       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3371   } else {
3372     assert(chunk.Kind == DeclaratorChunk::Array ||
3373            chunk.Kind == DeclaratorChunk::Reference);
3374     return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3375   }
3376 }
3377 
GetTypeForDeclaratorCast(Declarator & D,QualType FromTy)3378 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3379   TypeProcessingState state(*this, D);
3380 
3381   TypeSourceInfo *ReturnTypeInfo = nullptr;
3382   QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3383 
3384   if (getLangOpts().ObjCAutoRefCount) {
3385     Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3386     if (ownership != Qualifiers::OCL_None)
3387       transferARCOwnership(state, declSpecTy, ownership);
3388   }
3389 
3390   return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3391 }
3392 
3393 /// Map an AttributedType::Kind to an AttributeList::Kind.
getAttrListKind(AttributedType::Kind kind)3394 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3395   switch (kind) {
3396   case AttributedType::attr_address_space:
3397     return AttributeList::AT_AddressSpace;
3398   case AttributedType::attr_regparm:
3399     return AttributeList::AT_Regparm;
3400   case AttributedType::attr_vector_size:
3401     return AttributeList::AT_VectorSize;
3402   case AttributedType::attr_neon_vector_type:
3403     return AttributeList::AT_NeonVectorType;
3404   case AttributedType::attr_neon_polyvector_type:
3405     return AttributeList::AT_NeonPolyVectorType;
3406   case AttributedType::attr_objc_gc:
3407     return AttributeList::AT_ObjCGC;
3408   case AttributedType::attr_objc_ownership:
3409     return AttributeList::AT_ObjCOwnership;
3410   case AttributedType::attr_noreturn:
3411     return AttributeList::AT_NoReturn;
3412   case AttributedType::attr_cdecl:
3413     return AttributeList::AT_CDecl;
3414   case AttributedType::attr_fastcall:
3415     return AttributeList::AT_FastCall;
3416   case AttributedType::attr_stdcall:
3417     return AttributeList::AT_StdCall;
3418   case AttributedType::attr_thiscall:
3419     return AttributeList::AT_ThisCall;
3420   case AttributedType::attr_pascal:
3421     return AttributeList::AT_Pascal;
3422   case AttributedType::attr_vectorcall:
3423     return AttributeList::AT_VectorCall;
3424   case AttributedType::attr_pcs:
3425   case AttributedType::attr_pcs_vfp:
3426     return AttributeList::AT_Pcs;
3427   case AttributedType::attr_pnaclcall:
3428     return AttributeList::AT_PnaclCall;
3429   case AttributedType::attr_inteloclbicc:
3430     return AttributeList::AT_IntelOclBicc;
3431   case AttributedType::attr_ms_abi:
3432     return AttributeList::AT_MSABI;
3433   case AttributedType::attr_sysv_abi:
3434     return AttributeList::AT_SysVABI;
3435   case AttributedType::attr_ptr32:
3436     return AttributeList::AT_Ptr32;
3437   case AttributedType::attr_ptr64:
3438     return AttributeList::AT_Ptr64;
3439   case AttributedType::attr_sptr:
3440     return AttributeList::AT_SPtr;
3441   case AttributedType::attr_uptr:
3442     return AttributeList::AT_UPtr;
3443   }
3444   llvm_unreachable("unexpected attribute kind!");
3445 }
3446 
fillAttributedTypeLoc(AttributedTypeLoc TL,const AttributeList * attrs)3447 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
3448                                   const AttributeList *attrs) {
3449   AttributedType::Kind kind = TL.getAttrKind();
3450 
3451   assert(attrs && "no type attributes in the expected location!");
3452   AttributeList::Kind parsedKind = getAttrListKind(kind);
3453   while (attrs->getKind() != parsedKind) {
3454     attrs = attrs->getNext();
3455     assert(attrs && "no matching attribute in expected location!");
3456   }
3457 
3458   TL.setAttrNameLoc(attrs->getLoc());
3459   if (TL.hasAttrExprOperand()) {
3460     assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
3461     TL.setAttrExprOperand(attrs->getArgAsExpr(0));
3462   } else if (TL.hasAttrEnumOperand()) {
3463     assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
3464            "unexpected attribute operand kind");
3465     if (attrs->isArgIdent(0))
3466       TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
3467     else
3468       TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
3469   }
3470 
3471   // FIXME: preserve this information to here.
3472   if (TL.hasAttrOperand())
3473     TL.setAttrOperandParensRange(SourceRange());
3474 }
3475 
3476 namespace {
3477   class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
3478     ASTContext &Context;
3479     const DeclSpec &DS;
3480 
3481   public:
TypeSpecLocFiller(ASTContext & Context,const DeclSpec & DS)3482     TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
3483       : Context(Context), DS(DS) {}
3484 
VisitAttributedTypeLoc(AttributedTypeLoc TL)3485     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3486       fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3487       Visit(TL.getModifiedLoc());
3488     }
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)3489     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3490       Visit(TL.getUnqualifiedLoc());
3491     }
VisitTypedefTypeLoc(TypedefTypeLoc TL)3492     void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3493       TL.setNameLoc(DS.getTypeSpecTypeLoc());
3494     }
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)3495     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3496       TL.setNameLoc(DS.getTypeSpecTypeLoc());
3497       // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3498       // addition field. What we have is good enough for dispay of location
3499       // of 'fixit' on interface name.
3500       TL.setNameEndLoc(DS.getLocEnd());
3501     }
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)3502     void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3503       // Handle the base type, which might not have been written explicitly.
3504       if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3505         TL.setHasBaseTypeAsWritten(false);
3506         TL.getBaseLoc().initialize(Context, SourceLocation());
3507       } else {
3508         TL.setHasBaseTypeAsWritten(true);
3509         Visit(TL.getBaseLoc());
3510       }
3511 
3512       // Protocol qualifiers.
3513       if (DS.getProtocolQualifiers()) {
3514         assert(TL.getNumProtocols() > 0);
3515         assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3516         TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3517         TL.setRAngleLoc(DS.getSourceRange().getEnd());
3518         for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3519           TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3520       } else {
3521         assert(TL.getNumProtocols() == 0);
3522         TL.setLAngleLoc(SourceLocation());
3523         TL.setRAngleLoc(SourceLocation());
3524       }
3525     }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)3526     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3527       TL.setStarLoc(SourceLocation());
3528       Visit(TL.getPointeeLoc());
3529     }
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)3530     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
3531       TypeSourceInfo *TInfo = nullptr;
3532       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3533 
3534       // If we got no declarator info from previous Sema routines,
3535       // just fill with the typespec loc.
3536       if (!TInfo) {
3537         TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
3538         return;
3539       }
3540 
3541       TypeLoc OldTL = TInfo->getTypeLoc();
3542       if (TInfo->getType()->getAs<ElaboratedType>()) {
3543         ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
3544         TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
3545             .castAs<TemplateSpecializationTypeLoc>();
3546         TL.copy(NamedTL);
3547       } else {
3548         TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
3549         assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
3550       }
3551 
3552     }
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)3553     void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3554       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3555       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3556       TL.setParensRange(DS.getTypeofParensRange());
3557     }
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)3558     void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3559       assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3560       TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3561       TL.setParensRange(DS.getTypeofParensRange());
3562       assert(DS.getRepAsType());
3563       TypeSourceInfo *TInfo = nullptr;
3564       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3565       TL.setUnderlyingTInfo(TInfo);
3566     }
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)3567     void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3568       // FIXME: This holds only because we only have one unary transform.
3569       assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3570       TL.setKWLoc(DS.getTypeSpecTypeLoc());
3571       TL.setParensRange(DS.getTypeofParensRange());
3572       assert(DS.getRepAsType());
3573       TypeSourceInfo *TInfo = nullptr;
3574       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3575       TL.setUnderlyingTInfo(TInfo);
3576     }
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)3577     void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3578       // By default, use the source location of the type specifier.
3579       TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3580       if (TL.needsExtraLocalData()) {
3581         // Set info for the written builtin specifiers.
3582         TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3583         // Try to have a meaningful source location.
3584         if (TL.getWrittenSignSpec() != TSS_unspecified)
3585           // Sign spec loc overrides the others (e.g., 'unsigned long').
3586           TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3587         else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3588           // Width spec loc overrides type spec loc (e.g., 'short int').
3589           TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3590       }
3591     }
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)3592     void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3593       ElaboratedTypeKeyword Keyword
3594         = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
3595       if (DS.getTypeSpecType() == TST_typename) {
3596         TypeSourceInfo *TInfo = nullptr;
3597         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3598         if (TInfo) {
3599           TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
3600           return;
3601         }
3602       }
3603       TL.setElaboratedKeywordLoc(Keyword != ETK_None
3604                                  ? DS.getTypeSpecTypeLoc()
3605                                  : SourceLocation());
3606       const CXXScopeSpec& SS = DS.getTypeSpecScope();
3607       TL.setQualifierLoc(SS.getWithLocInContext(Context));
3608       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3609     }
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)3610     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3611       assert(DS.getTypeSpecType() == TST_typename);
3612       TypeSourceInfo *TInfo = nullptr;
3613       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3614       assert(TInfo);
3615       TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
3616     }
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)3617     void VisitDependentTemplateSpecializationTypeLoc(
3618                                  DependentTemplateSpecializationTypeLoc TL) {
3619       assert(DS.getTypeSpecType() == TST_typename);
3620       TypeSourceInfo *TInfo = nullptr;
3621       Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3622       assert(TInfo);
3623       TL.copy(
3624           TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
3625     }
VisitTagTypeLoc(TagTypeLoc TL)3626     void VisitTagTypeLoc(TagTypeLoc TL) {
3627       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
3628     }
VisitAtomicTypeLoc(AtomicTypeLoc TL)3629     void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3630       // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
3631       // or an _Atomic qualifier.
3632       if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
3633         TL.setKWLoc(DS.getTypeSpecTypeLoc());
3634         TL.setParensRange(DS.getTypeofParensRange());
3635 
3636         TypeSourceInfo *TInfo = nullptr;
3637         Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3638         assert(TInfo);
3639         TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
3640       } else {
3641         TL.setKWLoc(DS.getAtomicSpecLoc());
3642         // No parens, to indicate this was spelled as an _Atomic qualifier.
3643         TL.setParensRange(SourceRange());
3644         Visit(TL.getValueLoc());
3645       }
3646     }
3647 
VisitTypeLoc(TypeLoc TL)3648     void VisitTypeLoc(TypeLoc TL) {
3649       // FIXME: add other typespec types and change this to an assert.
3650       TL.initialize(Context, DS.getTypeSpecTypeLoc());
3651     }
3652   };
3653 
3654   class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
3655     ASTContext &Context;
3656     const DeclaratorChunk &Chunk;
3657 
3658   public:
DeclaratorLocFiller(ASTContext & Context,const DeclaratorChunk & Chunk)3659     DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3660       : Context(Context), Chunk(Chunk) {}
3661 
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)3662     void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3663       llvm_unreachable("qualified type locs not expected here!");
3664     }
VisitDecayedTypeLoc(DecayedTypeLoc TL)3665     void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
3666       llvm_unreachable("decayed type locs not expected here!");
3667     }
3668 
VisitAttributedTypeLoc(AttributedTypeLoc TL)3669     void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3670       fillAttributedTypeLoc(TL, Chunk.getAttrs());
3671     }
VisitAdjustedTypeLoc(AdjustedTypeLoc TL)3672     void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
3673       // nothing
3674     }
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)3675     void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3676       assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3677       TL.setCaretLoc(Chunk.Loc);
3678     }
VisitPointerTypeLoc(PointerTypeLoc TL)3679     void VisitPointerTypeLoc(PointerTypeLoc TL) {
3680       assert(Chunk.Kind == DeclaratorChunk::Pointer);
3681       TL.setStarLoc(Chunk.Loc);
3682     }
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)3683     void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3684       assert(Chunk.Kind == DeclaratorChunk::Pointer);
3685       TL.setStarLoc(Chunk.Loc);
3686     }
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)3687     void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3688       assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3689       const CXXScopeSpec& SS = Chunk.Mem.Scope();
3690       NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3691 
3692       const Type* ClsTy = TL.getClass();
3693       QualType ClsQT = QualType(ClsTy, 0);
3694       TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3695       // Now copy source location info into the type loc component.
3696       TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3697       switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3698       case NestedNameSpecifier::Identifier:
3699         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3700         {
3701           DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
3702           DNTLoc.setElaboratedKeywordLoc(SourceLocation());
3703           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3704           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3705         }
3706         break;
3707 
3708       case NestedNameSpecifier::TypeSpec:
3709       case NestedNameSpecifier::TypeSpecWithTemplate:
3710         if (isa<ElaboratedType>(ClsTy)) {
3711           ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
3712           ETLoc.setElaboratedKeywordLoc(SourceLocation());
3713           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3714           TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3715           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3716         } else {
3717           ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3718         }
3719         break;
3720 
3721       case NestedNameSpecifier::Namespace:
3722       case NestedNameSpecifier::NamespaceAlias:
3723       case NestedNameSpecifier::Global:
3724       case NestedNameSpecifier::Super:
3725         llvm_unreachable("Nested-name-specifier must name a type");
3726       }
3727 
3728       // Finally fill in MemberPointerLocInfo fields.
3729       TL.setStarLoc(Chunk.Loc);
3730       TL.setClassTInfo(ClsTInfo);
3731     }
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)3732     void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3733       assert(Chunk.Kind == DeclaratorChunk::Reference);
3734       // 'Amp' is misleading: this might have been originally
3735       /// spelled with AmpAmp.
3736       TL.setAmpLoc(Chunk.Loc);
3737     }
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)3738     void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3739       assert(Chunk.Kind == DeclaratorChunk::Reference);
3740       assert(!Chunk.Ref.LValueRef);
3741       TL.setAmpAmpLoc(Chunk.Loc);
3742     }
VisitArrayTypeLoc(ArrayTypeLoc TL)3743     void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3744       assert(Chunk.Kind == DeclaratorChunk::Array);
3745       TL.setLBracketLoc(Chunk.Loc);
3746       TL.setRBracketLoc(Chunk.EndLoc);
3747       TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3748     }
VisitFunctionTypeLoc(FunctionTypeLoc TL)3749     void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3750       assert(Chunk.Kind == DeclaratorChunk::Function);
3751       TL.setLocalRangeBegin(Chunk.Loc);
3752       TL.setLocalRangeEnd(Chunk.EndLoc);
3753 
3754       const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3755       TL.setLParenLoc(FTI.getLParenLoc());
3756       TL.setRParenLoc(FTI.getRParenLoc());
3757       for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
3758         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
3759         TL.setParam(tpi++, Param);
3760       }
3761       // FIXME: exception specs
3762     }
VisitParenTypeLoc(ParenTypeLoc TL)3763     void VisitParenTypeLoc(ParenTypeLoc TL) {
3764       assert(Chunk.Kind == DeclaratorChunk::Paren);
3765       TL.setLParenLoc(Chunk.Loc);
3766       TL.setRParenLoc(Chunk.EndLoc);
3767     }
3768 
VisitTypeLoc(TypeLoc TL)3769     void VisitTypeLoc(TypeLoc TL) {
3770       llvm_unreachable("unsupported TypeLoc kind in declarator!");
3771     }
3772   };
3773 }
3774 
fillAtomicQualLoc(AtomicTypeLoc ATL,const DeclaratorChunk & Chunk)3775 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
3776   SourceLocation Loc;
3777   switch (Chunk.Kind) {
3778   case DeclaratorChunk::Function:
3779   case DeclaratorChunk::Array:
3780   case DeclaratorChunk::Paren:
3781     llvm_unreachable("cannot be _Atomic qualified");
3782 
3783   case DeclaratorChunk::Pointer:
3784     Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
3785     break;
3786 
3787   case DeclaratorChunk::BlockPointer:
3788   case DeclaratorChunk::Reference:
3789   case DeclaratorChunk::MemberPointer:
3790     // FIXME: Provide a source location for the _Atomic keyword.
3791     break;
3792   }
3793 
3794   ATL.setKWLoc(Loc);
3795   ATL.setParensRange(SourceRange());
3796 }
3797 
3798 /// \brief Create and instantiate a TypeSourceInfo with type source information.
3799 ///
3800 /// \param T QualType referring to the type as written in source code.
3801 ///
3802 /// \param ReturnTypeInfo For declarators whose return type does not show
3803 /// up in the normal place in the declaration specifiers (such as a C++
3804 /// conversion function), this pointer will refer to a type source information
3805 /// for that return type.
3806 TypeSourceInfo *
GetTypeSourceInfoForDeclarator(Declarator & D,QualType T,TypeSourceInfo * ReturnTypeInfo)3807 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3808                                      TypeSourceInfo *ReturnTypeInfo) {
3809   TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3810   UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3811 
3812   // Handle parameter packs whose type is a pack expansion.
3813   if (isa<PackExpansionType>(T)) {
3814     CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
3815     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3816   }
3817 
3818   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3819     // An AtomicTypeLoc might be produced by an atomic qualifier in this
3820     // declarator chunk.
3821     if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
3822       fillAtomicQualLoc(ATL, D.getTypeObject(i));
3823       CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
3824     }
3825 
3826     while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
3827       fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3828       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3829     }
3830 
3831     // FIXME: Ordering here?
3832     while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
3833       CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3834 
3835     DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3836     CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3837   }
3838 
3839   // If we have different source information for the return type, use
3840   // that.  This really only applies to C++ conversion functions.
3841   if (ReturnTypeInfo) {
3842     TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3843     assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3844     memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3845   } else {
3846     TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3847   }
3848 
3849   return TInfo;
3850 }
3851 
3852 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
CreateParsedType(QualType T,TypeSourceInfo * TInfo)3853 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3854   // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3855   // and Sema during declaration parsing. Try deallocating/caching them when
3856   // it's appropriate, instead of allocating them and keeping them around.
3857   LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3858                                                        TypeAlignment);
3859   new (LocT) LocInfoType(T, TInfo);
3860   assert(LocT->getTypeClass() != T->getTypeClass() &&
3861          "LocInfoType's TypeClass conflicts with an existing Type class");
3862   return ParsedType::make(QualType(LocT, 0));
3863 }
3864 
getAsStringInternal(std::string & Str,const PrintingPolicy & Policy) const3865 void LocInfoType::getAsStringInternal(std::string &Str,
3866                                       const PrintingPolicy &Policy) const {
3867   llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3868          " was used directly instead of getting the QualType through"
3869          " GetTypeFromParser");
3870 }
3871 
ActOnTypeName(Scope * S,Declarator & D)3872 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3873   // C99 6.7.6: Type names have no identifier.  This is already validated by
3874   // the parser.
3875   assert(D.getIdentifier() == nullptr &&
3876          "Type name should have no identifier!");
3877 
3878   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3879   QualType T = TInfo->getType();
3880   if (D.isInvalidType())
3881     return true;
3882 
3883   // Make sure there are no unused decl attributes on the declarator.
3884   // We don't want to do this for ObjC parameters because we're going
3885   // to apply them to the actual parameter declaration.
3886   // Likewise, we don't want to do this for alias declarations, because
3887   // we are actually going to build a declaration from this eventually.
3888   if (D.getContext() != Declarator::ObjCParameterContext &&
3889       D.getContext() != Declarator::AliasDeclContext &&
3890       D.getContext() != Declarator::AliasTemplateContext)
3891     checkUnusedDeclAttributes(D);
3892 
3893   if (getLangOpts().CPlusPlus) {
3894     // Check that there are no default arguments (C++ only).
3895     CheckExtraCXXDefaultArguments(D);
3896   }
3897 
3898   return CreateParsedType(T, TInfo);
3899 }
3900 
ActOnObjCInstanceType(SourceLocation Loc)3901 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3902   QualType T = Context.getObjCInstanceType();
3903   TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3904   return CreateParsedType(T, TInfo);
3905 }
3906 
3907 
3908 //===----------------------------------------------------------------------===//
3909 // Type Attribute Processing
3910 //===----------------------------------------------------------------------===//
3911 
3912 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3913 /// specified type.  The attribute contains 1 argument, the id of the address
3914 /// space for the type.
HandleAddressSpaceTypeAttribute(QualType & Type,const AttributeList & Attr,Sema & S)3915 static void HandleAddressSpaceTypeAttribute(QualType &Type,
3916                                             const AttributeList &Attr, Sema &S){
3917 
3918   // If this type is already address space qualified, reject it.
3919   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3920   // qualifiers for two or more different address spaces."
3921   if (Type.getAddressSpace()) {
3922     S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3923     Attr.setInvalid();
3924     return;
3925   }
3926 
3927   // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3928   // qualified by an address-space qualifier."
3929   if (Type->isFunctionType()) {
3930     S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3931     Attr.setInvalid();
3932     return;
3933   }
3934 
3935   unsigned ASIdx;
3936   if (Attr.getKind() == AttributeList::AT_AddressSpace) {
3937     // Check the attribute arguments.
3938     if (Attr.getNumArgs() != 1) {
3939       S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3940         << Attr.getName() << 1;
3941       Attr.setInvalid();
3942       return;
3943     }
3944     Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
3945     llvm::APSInt addrSpace(32);
3946     if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3947         !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3948       S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3949         << Attr.getName() << AANT_ArgumentIntegerConstant
3950         << ASArgExpr->getSourceRange();
3951       Attr.setInvalid();
3952       return;
3953     }
3954 
3955     // Bounds checking.
3956     if (addrSpace.isSigned()) {
3957       if (addrSpace.isNegative()) {
3958         S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3959           << ASArgExpr->getSourceRange();
3960         Attr.setInvalid();
3961         return;
3962       }
3963       addrSpace.setIsSigned(false);
3964     }
3965     llvm::APSInt max(addrSpace.getBitWidth());
3966     max = Qualifiers::MaxAddressSpace;
3967     if (addrSpace > max) {
3968       S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3969         << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
3970       Attr.setInvalid();
3971       return;
3972     }
3973     ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3974   } else {
3975     // The keyword-based type attributes imply which address space to use.
3976     switch (Attr.getKind()) {
3977     case AttributeList::AT_OpenCLGlobalAddressSpace:
3978       ASIdx = LangAS::opencl_global; break;
3979     case AttributeList::AT_OpenCLLocalAddressSpace:
3980       ASIdx = LangAS::opencl_local; break;
3981     case AttributeList::AT_OpenCLConstantAddressSpace:
3982       ASIdx = LangAS::opencl_constant; break;
3983     case AttributeList::AT_OpenCLGenericAddressSpace:
3984       ASIdx = LangAS::opencl_generic; break;
3985     default:
3986       assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
3987       ASIdx = 0; break;
3988     }
3989   }
3990 
3991   Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3992 }
3993 
3994 /// Does this type have a "direct" ownership qualifier?  That is,
3995 /// is it written like "__strong id", as opposed to something like
3996 /// "typeof(foo)", where that happens to be strong?
hasDirectOwnershipQualifier(QualType type)3997 static bool hasDirectOwnershipQualifier(QualType type) {
3998   // Fast path: no qualifier at all.
3999   assert(type.getQualifiers().hasObjCLifetime());
4000 
4001   while (true) {
4002     // __strong id
4003     if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
4004       if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
4005         return true;
4006 
4007       type = attr->getModifiedType();
4008 
4009     // X *__strong (...)
4010     } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
4011       type = paren->getInnerType();
4012 
4013     // That's it for things we want to complain about.  In particular,
4014     // we do not want to look through typedefs, typeof(expr),
4015     // typeof(type), or any other way that the type is somehow
4016     // abstracted.
4017     } else {
4018 
4019       return false;
4020     }
4021   }
4022 }
4023 
4024 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
4025 /// attribute on the specified type.
4026 ///
4027 /// Returns 'true' if the attribute was handled.
handleObjCOwnershipTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)4028 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
4029                                        AttributeList &attr,
4030                                        QualType &type) {
4031   bool NonObjCPointer = false;
4032 
4033   if (!type->isDependentType() && !type->isUndeducedType()) {
4034     if (const PointerType *ptr = type->getAs<PointerType>()) {
4035       QualType pointee = ptr->getPointeeType();
4036       if (pointee->isObjCRetainableType() || pointee->isPointerType())
4037         return false;
4038       // It is important not to lose the source info that there was an attribute
4039       // applied to non-objc pointer. We will create an attributed type but
4040       // its type will be the same as the original type.
4041       NonObjCPointer = true;
4042     } else if (!type->isObjCRetainableType()) {
4043       return false;
4044     }
4045 
4046     // Don't accept an ownership attribute in the declspec if it would
4047     // just be the return type of a block pointer.
4048     if (state.isProcessingDeclSpec()) {
4049       Declarator &D = state.getDeclarator();
4050       if (maybeMovePastReturnType(D, D.getNumTypeObjects()))
4051         return false;
4052     }
4053   }
4054 
4055   Sema &S = state.getSema();
4056   SourceLocation AttrLoc = attr.getLoc();
4057   if (AttrLoc.isMacroID())
4058     AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
4059 
4060   if (!attr.isArgIdent(0)) {
4061     S.Diag(AttrLoc, diag::err_attribute_argument_type)
4062       << attr.getName() << AANT_ArgumentString;
4063     attr.setInvalid();
4064     return true;
4065   }
4066 
4067   // Consume lifetime attributes without further comment outside of
4068   // ARC mode.
4069   if (!S.getLangOpts().ObjCAutoRefCount)
4070     return true;
4071 
4072   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4073   Qualifiers::ObjCLifetime lifetime;
4074   if (II->isStr("none"))
4075     lifetime = Qualifiers::OCL_ExplicitNone;
4076   else if (II->isStr("strong"))
4077     lifetime = Qualifiers::OCL_Strong;
4078   else if (II->isStr("weak"))
4079     lifetime = Qualifiers::OCL_Weak;
4080   else if (II->isStr("autoreleasing"))
4081     lifetime = Qualifiers::OCL_Autoreleasing;
4082   else {
4083     S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
4084       << attr.getName() << II;
4085     attr.setInvalid();
4086     return true;
4087   }
4088 
4089   SplitQualType underlyingType = type.split();
4090 
4091   // Check for redundant/conflicting ownership qualifiers.
4092   if (Qualifiers::ObjCLifetime previousLifetime
4093         = type.getQualifiers().getObjCLifetime()) {
4094     // If it's written directly, that's an error.
4095     if (hasDirectOwnershipQualifier(type)) {
4096       S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
4097         << type;
4098       return true;
4099     }
4100 
4101     // Otherwise, if the qualifiers actually conflict, pull sugar off
4102     // until we reach a type that is directly qualified.
4103     if (previousLifetime != lifetime) {
4104       // This should always terminate: the canonical type is
4105       // qualified, so some bit of sugar must be hiding it.
4106       while (!underlyingType.Quals.hasObjCLifetime()) {
4107         underlyingType = underlyingType.getSingleStepDesugaredType();
4108       }
4109       underlyingType.Quals.removeObjCLifetime();
4110     }
4111   }
4112 
4113   underlyingType.Quals.addObjCLifetime(lifetime);
4114 
4115   if (NonObjCPointer) {
4116     StringRef name = attr.getName()->getName();
4117     switch (lifetime) {
4118     case Qualifiers::OCL_None:
4119     case Qualifiers::OCL_ExplicitNone:
4120       break;
4121     case Qualifiers::OCL_Strong: name = "__strong"; break;
4122     case Qualifiers::OCL_Weak: name = "__weak"; break;
4123     case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
4124     }
4125     S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
4126       << TDS_ObjCObjOrBlock << type;
4127   }
4128 
4129   QualType origType = type;
4130   if (!NonObjCPointer)
4131     type = S.Context.getQualifiedType(underlyingType);
4132 
4133   // If we have a valid source location for the attribute, use an
4134   // AttributedType instead.
4135   if (AttrLoc.isValid())
4136     type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
4137                                        origType, type);
4138 
4139   // Forbid __weak if the runtime doesn't support it.
4140   if (lifetime == Qualifiers::OCL_Weak &&
4141       !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
4142 
4143     // Actually, delay this until we know what we're parsing.
4144     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
4145       S.DelayedDiagnostics.add(
4146           sema::DelayedDiagnostic::makeForbiddenType(
4147               S.getSourceManager().getExpansionLoc(AttrLoc),
4148               diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
4149     } else {
4150       S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
4151     }
4152 
4153     attr.setInvalid();
4154     return true;
4155   }
4156 
4157   // Forbid __weak for class objects marked as
4158   // objc_arc_weak_reference_unavailable
4159   if (lifetime == Qualifiers::OCL_Weak) {
4160     if (const ObjCObjectPointerType *ObjT =
4161           type->getAs<ObjCObjectPointerType>()) {
4162       if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
4163         if (Class->isArcWeakrefUnavailable()) {
4164             S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
4165             S.Diag(ObjT->getInterfaceDecl()->getLocation(),
4166                    diag::note_class_declared);
4167         }
4168       }
4169     }
4170   }
4171 
4172   return true;
4173 }
4174 
4175 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
4176 /// attribute on the specified type.  Returns true to indicate that
4177 /// the attribute was handled, false to indicate that the type does
4178 /// not permit the attribute.
handleObjCGCTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)4179 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
4180                                  AttributeList &attr,
4181                                  QualType &type) {
4182   Sema &S = state.getSema();
4183 
4184   // Delay if this isn't some kind of pointer.
4185   if (!type->isPointerType() &&
4186       !type->isObjCObjectPointerType() &&
4187       !type->isBlockPointerType())
4188     return false;
4189 
4190   if (type.getObjCGCAttr() != Qualifiers::GCNone) {
4191     S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
4192     attr.setInvalid();
4193     return true;
4194   }
4195 
4196   // Check the attribute arguments.
4197   if (!attr.isArgIdent(0)) {
4198     S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
4199       << attr.getName() << AANT_ArgumentString;
4200     attr.setInvalid();
4201     return true;
4202   }
4203   Qualifiers::GC GCAttr;
4204   if (attr.getNumArgs() > 1) {
4205     S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4206       << attr.getName() << 1;
4207     attr.setInvalid();
4208     return true;
4209   }
4210 
4211   IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4212   if (II->isStr("weak"))
4213     GCAttr = Qualifiers::Weak;
4214   else if (II->isStr("strong"))
4215     GCAttr = Qualifiers::Strong;
4216   else {
4217     S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
4218       << attr.getName() << II;
4219     attr.setInvalid();
4220     return true;
4221   }
4222 
4223   QualType origType = type;
4224   type = S.Context.getObjCGCQualType(origType, GCAttr);
4225 
4226   // Make an attributed type to preserve the source information.
4227   if (attr.getLoc().isValid())
4228     type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
4229                                        origType, type);
4230 
4231   return true;
4232 }
4233 
4234 namespace {
4235   /// A helper class to unwrap a type down to a function for the
4236   /// purposes of applying attributes there.
4237   ///
4238   /// Use:
4239   ///   FunctionTypeUnwrapper unwrapped(SemaRef, T);
4240   ///   if (unwrapped.isFunctionType()) {
4241   ///     const FunctionType *fn = unwrapped.get();
4242   ///     // change fn somehow
4243   ///     T = unwrapped.wrap(fn);
4244   ///   }
4245   struct FunctionTypeUnwrapper {
4246     enum WrapKind {
4247       Desugar,
4248       Parens,
4249       Pointer,
4250       BlockPointer,
4251       Reference,
4252       MemberPointer
4253     };
4254 
4255     QualType Original;
4256     const FunctionType *Fn;
4257     SmallVector<unsigned char /*WrapKind*/, 8> Stack;
4258 
FunctionTypeUnwrapper__anon7ba70c020411::FunctionTypeUnwrapper4259     FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
4260       while (true) {
4261         const Type *Ty = T.getTypePtr();
4262         if (isa<FunctionType>(Ty)) {
4263           Fn = cast<FunctionType>(Ty);
4264           return;
4265         } else if (isa<ParenType>(Ty)) {
4266           T = cast<ParenType>(Ty)->getInnerType();
4267           Stack.push_back(Parens);
4268         } else if (isa<PointerType>(Ty)) {
4269           T = cast<PointerType>(Ty)->getPointeeType();
4270           Stack.push_back(Pointer);
4271         } else if (isa<BlockPointerType>(Ty)) {
4272           T = cast<BlockPointerType>(Ty)->getPointeeType();
4273           Stack.push_back(BlockPointer);
4274         } else if (isa<MemberPointerType>(Ty)) {
4275           T = cast<MemberPointerType>(Ty)->getPointeeType();
4276           Stack.push_back(MemberPointer);
4277         } else if (isa<ReferenceType>(Ty)) {
4278           T = cast<ReferenceType>(Ty)->getPointeeType();
4279           Stack.push_back(Reference);
4280         } else {
4281           const Type *DTy = Ty->getUnqualifiedDesugaredType();
4282           if (Ty == DTy) {
4283             Fn = nullptr;
4284             return;
4285           }
4286 
4287           T = QualType(DTy, 0);
4288           Stack.push_back(Desugar);
4289         }
4290       }
4291     }
4292 
isFunctionType__anon7ba70c020411::FunctionTypeUnwrapper4293     bool isFunctionType() const { return (Fn != nullptr); }
get__anon7ba70c020411::FunctionTypeUnwrapper4294     const FunctionType *get() const { return Fn; }
4295 
wrap__anon7ba70c020411::FunctionTypeUnwrapper4296     QualType wrap(Sema &S, const FunctionType *New) {
4297       // If T wasn't modified from the unwrapped type, do nothing.
4298       if (New == get()) return Original;
4299 
4300       Fn = New;
4301       return wrap(S.Context, Original, 0);
4302     }
4303 
4304   private:
wrap__anon7ba70c020411::FunctionTypeUnwrapper4305     QualType wrap(ASTContext &C, QualType Old, unsigned I) {
4306       if (I == Stack.size())
4307         return C.getQualifiedType(Fn, Old.getQualifiers());
4308 
4309       // Build up the inner type, applying the qualifiers from the old
4310       // type to the new type.
4311       SplitQualType SplitOld = Old.split();
4312 
4313       // As a special case, tail-recurse if there are no qualifiers.
4314       if (SplitOld.Quals.empty())
4315         return wrap(C, SplitOld.Ty, I);
4316       return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
4317     }
4318 
wrap__anon7ba70c020411::FunctionTypeUnwrapper4319     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
4320       if (I == Stack.size()) return QualType(Fn, 0);
4321 
4322       switch (static_cast<WrapKind>(Stack[I++])) {
4323       case Desugar:
4324         // This is the point at which we potentially lose source
4325         // information.
4326         return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4327 
4328       case Parens: {
4329         QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4330         return C.getParenType(New);
4331       }
4332 
4333       case Pointer: {
4334         QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4335         return C.getPointerType(New);
4336       }
4337 
4338       case BlockPointer: {
4339         QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4340         return C.getBlockPointerType(New);
4341       }
4342 
4343       case MemberPointer: {
4344         const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4345         QualType New = wrap(C, OldMPT->getPointeeType(), I);
4346         return C.getMemberPointerType(New, OldMPT->getClass());
4347       }
4348 
4349       case Reference: {
4350         const ReferenceType *OldRef = cast<ReferenceType>(Old);
4351         QualType New = wrap(C, OldRef->getPointeeType(), I);
4352         if (isa<LValueReferenceType>(OldRef))
4353           return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4354         else
4355           return C.getRValueReferenceType(New);
4356       }
4357       }
4358 
4359       llvm_unreachable("unknown wrapping kind");
4360     }
4361   };
4362 }
4363 
handleMSPointerTypeQualifierAttr(TypeProcessingState & State,AttributeList & Attr,QualType & Type)4364 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
4365                                              AttributeList &Attr,
4366                                              QualType &Type) {
4367   Sema &S = State.getSema();
4368 
4369   AttributeList::Kind Kind = Attr.getKind();
4370   QualType Desugared = Type;
4371   const AttributedType *AT = dyn_cast<AttributedType>(Type);
4372   while (AT) {
4373     AttributedType::Kind CurAttrKind = AT->getAttrKind();
4374 
4375     // You cannot specify duplicate type attributes, so if the attribute has
4376     // already been applied, flag it.
4377     if (getAttrListKind(CurAttrKind) == Kind) {
4378       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
4379         << Attr.getName();
4380       return true;
4381     }
4382 
4383     // You cannot have both __sptr and __uptr on the same type, nor can you
4384     // have __ptr32 and __ptr64.
4385     if ((CurAttrKind == AttributedType::attr_ptr32 &&
4386          Kind == AttributeList::AT_Ptr64) ||
4387         (CurAttrKind == AttributedType::attr_ptr64 &&
4388          Kind == AttributeList::AT_Ptr32)) {
4389       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4390         << "'__ptr32'" << "'__ptr64'";
4391       return true;
4392     } else if ((CurAttrKind == AttributedType::attr_sptr &&
4393                 Kind == AttributeList::AT_UPtr) ||
4394                (CurAttrKind == AttributedType::attr_uptr &&
4395                 Kind == AttributeList::AT_SPtr)) {
4396       S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4397         << "'__sptr'" << "'__uptr'";
4398       return true;
4399     }
4400 
4401     Desugared = AT->getEquivalentType();
4402     AT = dyn_cast<AttributedType>(Desugared);
4403   }
4404 
4405   // Pointer type qualifiers can only operate on pointer types, but not
4406   // pointer-to-member types.
4407   if (!isa<PointerType>(Desugared)) {
4408     S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
4409                           diag::err_attribute_no_member_pointers :
4410                           diag::err_attribute_pointers_only) << Attr.getName();
4411     return true;
4412   }
4413 
4414   AttributedType::Kind TAK;
4415   switch (Kind) {
4416   default: llvm_unreachable("Unknown attribute kind");
4417   case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
4418   case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
4419   case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
4420   case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
4421   }
4422 
4423   Type = S.Context.getAttributedType(TAK, Type, Type);
4424   return false;
4425 }
4426 
getCCTypeAttrKind(AttributeList & Attr)4427 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
4428   assert(!Attr.isInvalid());
4429   switch (Attr.getKind()) {
4430   default:
4431     llvm_unreachable("not a calling convention attribute");
4432   case AttributeList::AT_CDecl:
4433     return AttributedType::attr_cdecl;
4434   case AttributeList::AT_FastCall:
4435     return AttributedType::attr_fastcall;
4436   case AttributeList::AT_StdCall:
4437     return AttributedType::attr_stdcall;
4438   case AttributeList::AT_ThisCall:
4439     return AttributedType::attr_thiscall;
4440   case AttributeList::AT_Pascal:
4441     return AttributedType::attr_pascal;
4442   case AttributeList::AT_VectorCall:
4443     return AttributedType::attr_vectorcall;
4444   case AttributeList::AT_Pcs: {
4445     // The attribute may have had a fixit applied where we treated an
4446     // identifier as a string literal.  The contents of the string are valid,
4447     // but the form may not be.
4448     StringRef Str;
4449     if (Attr.isArgExpr(0))
4450       Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
4451     else
4452       Str = Attr.getArgAsIdent(0)->Ident->getName();
4453     return llvm::StringSwitch<AttributedType::Kind>(Str)
4454         .Case("aapcs", AttributedType::attr_pcs)
4455         .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
4456   }
4457   case AttributeList::AT_PnaclCall:
4458     return AttributedType::attr_pnaclcall;
4459   case AttributeList::AT_IntelOclBicc:
4460     return AttributedType::attr_inteloclbicc;
4461   case AttributeList::AT_MSABI:
4462     return AttributedType::attr_ms_abi;
4463   case AttributeList::AT_SysVABI:
4464     return AttributedType::attr_sysv_abi;
4465   }
4466   llvm_unreachable("unexpected attribute kind!");
4467 }
4468 
4469 /// Process an individual function attribute.  Returns true to
4470 /// indicate that the attribute was handled, false if it wasn't.
handleFunctionTypeAttr(TypeProcessingState & state,AttributeList & attr,QualType & type)4471 static bool handleFunctionTypeAttr(TypeProcessingState &state,
4472                                    AttributeList &attr,
4473                                    QualType &type) {
4474   Sema &S = state.getSema();
4475 
4476   FunctionTypeUnwrapper unwrapped(S, type);
4477 
4478   if (attr.getKind() == AttributeList::AT_NoReturn) {
4479     if (S.CheckNoReturnAttr(attr))
4480       return true;
4481 
4482     // Delay if this is not a function type.
4483     if (!unwrapped.isFunctionType())
4484       return false;
4485 
4486     // Otherwise we can process right away.
4487     FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
4488     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4489     return true;
4490   }
4491 
4492   // ns_returns_retained is not always a type attribute, but if we got
4493   // here, we're treating it as one right now.
4494   if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
4495     assert(S.getLangOpts().ObjCAutoRefCount &&
4496            "ns_returns_retained treated as type attribute in non-ARC");
4497     if (attr.getNumArgs()) return true;
4498 
4499     // Delay if this is not a function type.
4500     if (!unwrapped.isFunctionType())
4501       return false;
4502 
4503     FunctionType::ExtInfo EI
4504       = unwrapped.get()->getExtInfo().withProducesResult(true);
4505     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4506     return true;
4507   }
4508 
4509   if (attr.getKind() == AttributeList::AT_Regparm) {
4510     unsigned value;
4511     if (S.CheckRegparmAttr(attr, value))
4512       return true;
4513 
4514     // Delay if this is not a function type.
4515     if (!unwrapped.isFunctionType())
4516       return false;
4517 
4518     // Diagnose regparm with fastcall.
4519     const FunctionType *fn = unwrapped.get();
4520     CallingConv CC = fn->getCallConv();
4521     if (CC == CC_X86FastCall) {
4522       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4523         << FunctionType::getNameForCallConv(CC)
4524         << "regparm";
4525       attr.setInvalid();
4526       return true;
4527     }
4528 
4529     FunctionType::ExtInfo EI =
4530       unwrapped.get()->getExtInfo().withRegParm(value);
4531     type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4532     return true;
4533   }
4534 
4535   // Delay if the type didn't work out to a function.
4536   if (!unwrapped.isFunctionType()) return false;
4537 
4538   // Otherwise, a calling convention.
4539   CallingConv CC;
4540   if (S.CheckCallingConvAttr(attr, CC))
4541     return true;
4542 
4543   const FunctionType *fn = unwrapped.get();
4544   CallingConv CCOld = fn->getCallConv();
4545   AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
4546 
4547   if (CCOld != CC) {
4548     // Error out on when there's already an attribute on the type
4549     // and the CCs don't match.
4550     const AttributedType *AT = S.getCallingConvAttributedType(type);
4551     if (AT && AT->getAttrKind() != CCAttrKind) {
4552       S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4553         << FunctionType::getNameForCallConv(CC)
4554         << FunctionType::getNameForCallConv(CCOld);
4555       attr.setInvalid();
4556       return true;
4557     }
4558   }
4559 
4560   // Diagnose use of callee-cleanup calling convention on variadic functions.
4561   if (!supportsVariadicCall(CC)) {
4562     const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
4563     if (FnP && FnP->isVariadic()) {
4564       unsigned DiagID = diag::err_cconv_varargs;
4565       // stdcall and fastcall are ignored with a warning for GCC and MS
4566       // compatibility.
4567       if (CC == CC_X86StdCall || CC == CC_X86FastCall)
4568         DiagID = diag::warn_cconv_varargs;
4569 
4570       S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
4571       attr.setInvalid();
4572       return true;
4573     }
4574   }
4575 
4576   // Also diagnose fastcall with regparm.
4577   if (CC == CC_X86FastCall && fn->getHasRegParm()) {
4578     S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4579         << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
4580     attr.setInvalid();
4581     return true;
4582   }
4583 
4584   // Modify the CC from the wrapped function type, wrap it all back, and then
4585   // wrap the whole thing in an AttributedType as written.  The modified type
4586   // might have a different CC if we ignored the attribute.
4587   FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
4588   QualType Equivalent =
4589       unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4590   type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
4591   return true;
4592 }
4593 
hasExplicitCallingConv(QualType & T)4594 bool Sema::hasExplicitCallingConv(QualType &T) {
4595   QualType R = T.IgnoreParens();
4596   while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
4597     if (AT->isCallingConv())
4598       return true;
4599     R = AT->getModifiedType().IgnoreParens();
4600   }
4601   return false;
4602 }
4603 
adjustMemberFunctionCC(QualType & T,bool IsStatic)4604 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) {
4605   FunctionTypeUnwrapper Unwrapped(*this, T);
4606   const FunctionType *FT = Unwrapped.get();
4607   bool IsVariadic = (isa<FunctionProtoType>(FT) &&
4608                      cast<FunctionProtoType>(FT)->isVariadic());
4609 
4610   // Only adjust types with the default convention.  For example, on Windows we
4611   // should adjust a __cdecl type to __thiscall for instance methods, and a
4612   // __thiscall type to __cdecl for static methods.
4613   CallingConv CurCC = FT->getCallConv();
4614   CallingConv FromCC =
4615       Context.getDefaultCallingConvention(IsVariadic, IsStatic);
4616   CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
4617   if (CurCC != FromCC || FromCC == ToCC)
4618     return;
4619 
4620   if (hasExplicitCallingConv(T))
4621     return;
4622 
4623   FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
4624   QualType Wrapped = Unwrapped.wrap(*this, FT);
4625   T = Context.getAdjustedType(T, Wrapped);
4626 }
4627 
4628 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
4629 /// and float scalars, although arrays, pointers, and function return values are
4630 /// allowed in conjunction with this construct. Aggregates with this attribute
4631 /// are invalid, even if they are of the same size as a corresponding scalar.
4632 /// The raw attribute should contain precisely 1 argument, the vector size for
4633 /// the variable, measured in bytes. If curType and rawAttr are well formed,
4634 /// this routine will return a new vector type.
HandleVectorSizeAttr(QualType & CurType,const AttributeList & Attr,Sema & S)4635 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4636                                  Sema &S) {
4637   // Check the attribute arguments.
4638   if (Attr.getNumArgs() != 1) {
4639     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4640       << Attr.getName() << 1;
4641     Attr.setInvalid();
4642     return;
4643   }
4644   Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4645   llvm::APSInt vecSize(32);
4646   if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4647       !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
4648     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4649       << Attr.getName() << AANT_ArgumentIntegerConstant
4650       << sizeExpr->getSourceRange();
4651     Attr.setInvalid();
4652     return;
4653   }
4654   // The base type must be integer (not Boolean or enumeration) or float, and
4655   // can't already be a vector.
4656   if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
4657       (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
4658     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4659     Attr.setInvalid();
4660     return;
4661   }
4662   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4663   // vecSize is specified in bytes - convert to bits.
4664   unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4665 
4666   // the vector size needs to be an integral multiple of the type size.
4667   if (vectorSize % typeSize) {
4668     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4669       << sizeExpr->getSourceRange();
4670     Attr.setInvalid();
4671     return;
4672   }
4673   if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
4674     S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
4675       << sizeExpr->getSourceRange();
4676     Attr.setInvalid();
4677     return;
4678   }
4679   if (vectorSize == 0) {
4680     S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4681       << sizeExpr->getSourceRange();
4682     Attr.setInvalid();
4683     return;
4684   }
4685 
4686   // Success! Instantiate the vector type, the number of elements is > 0, and
4687   // not required to be a power of 2, unlike GCC.
4688   CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
4689                                     VectorType::GenericVector);
4690 }
4691 
4692 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4693 /// a type.
HandleExtVectorTypeAttr(QualType & CurType,const AttributeList & Attr,Sema & S)4694 static void HandleExtVectorTypeAttr(QualType &CurType,
4695                                     const AttributeList &Attr,
4696                                     Sema &S) {
4697   // check the attribute arguments.
4698   if (Attr.getNumArgs() != 1) {
4699     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4700       << Attr.getName() << 1;
4701     return;
4702   }
4703 
4704   Expr *sizeExpr;
4705 
4706   // Special case where the argument is a template id.
4707   if (Attr.isArgIdent(0)) {
4708     CXXScopeSpec SS;
4709     SourceLocation TemplateKWLoc;
4710     UnqualifiedId id;
4711     id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
4712 
4713     ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4714                                           id, false, false);
4715     if (Size.isInvalid())
4716       return;
4717 
4718     sizeExpr = Size.get();
4719   } else {
4720     sizeExpr = Attr.getArgAsExpr(0);
4721   }
4722 
4723   // Create the vector type.
4724   QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4725   if (!T.isNull())
4726     CurType = T;
4727 }
4728 
isPermittedNeonBaseType(QualType & Ty,VectorType::VectorKind VecKind,Sema & S)4729 static bool isPermittedNeonBaseType(QualType &Ty,
4730                                     VectorType::VectorKind VecKind, Sema &S) {
4731   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
4732   if (!BTy)
4733     return false;
4734 
4735   llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4736 
4737   // Signed poly is mathematically wrong, but has been baked into some ABIs by
4738   // now.
4739   bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
4740                         Triple.getArch() == llvm::Triple::aarch64_be;
4741   if (VecKind == VectorType::NeonPolyVector) {
4742     if (IsPolyUnsigned) {
4743       // AArch64 polynomial vectors are unsigned and support poly64.
4744       return BTy->getKind() == BuiltinType::UChar ||
4745              BTy->getKind() == BuiltinType::UShort ||
4746              BTy->getKind() == BuiltinType::ULong ||
4747              BTy->getKind() == BuiltinType::ULongLong;
4748     } else {
4749       // AArch32 polynomial vector are signed.
4750       return BTy->getKind() == BuiltinType::SChar ||
4751              BTy->getKind() == BuiltinType::Short;
4752     }
4753   }
4754 
4755   // Non-polynomial vector types: the usual suspects are allowed, as well as
4756   // float64_t on AArch64.
4757   bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
4758                  Triple.getArch() == llvm::Triple::aarch64_be;
4759 
4760   if (Is64Bit && BTy->getKind() == BuiltinType::Double)
4761     return true;
4762 
4763   return BTy->getKind() == BuiltinType::SChar ||
4764          BTy->getKind() == BuiltinType::UChar ||
4765          BTy->getKind() == BuiltinType::Short ||
4766          BTy->getKind() == BuiltinType::UShort ||
4767          BTy->getKind() == BuiltinType::Int ||
4768          BTy->getKind() == BuiltinType::UInt ||
4769          BTy->getKind() == BuiltinType::Long ||
4770          BTy->getKind() == BuiltinType::ULong ||
4771          BTy->getKind() == BuiltinType::LongLong ||
4772          BTy->getKind() == BuiltinType::ULongLong ||
4773          BTy->getKind() == BuiltinType::Float ||
4774          BTy->getKind() == BuiltinType::Half;
4775 }
4776 
4777 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4778 /// "neon_polyvector_type" attributes are used to create vector types that
4779 /// are mangled according to ARM's ABI.  Otherwise, these types are identical
4780 /// to those created with the "vector_size" attribute.  Unlike "vector_size"
4781 /// the argument to these Neon attributes is the number of vector elements,
4782 /// not the vector size in bytes.  The vector width and element type must
4783 /// match one of the standard Neon vector types.
HandleNeonVectorTypeAttr(QualType & CurType,const AttributeList & Attr,Sema & S,VectorType::VectorKind VecKind)4784 static void HandleNeonVectorTypeAttr(QualType& CurType,
4785                                      const AttributeList &Attr, Sema &S,
4786                                      VectorType::VectorKind VecKind) {
4787   // Target must have NEON
4788   if (!S.Context.getTargetInfo().hasFeature("neon")) {
4789     S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
4790     Attr.setInvalid();
4791     return;
4792   }
4793   // Check the attribute arguments.
4794   if (Attr.getNumArgs() != 1) {
4795     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4796       << Attr.getName() << 1;
4797     Attr.setInvalid();
4798     return;
4799   }
4800   // The number of elements must be an ICE.
4801   Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4802   llvm::APSInt numEltsInt(32);
4803   if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4804       !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4805     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4806       << Attr.getName() << AANT_ArgumentIntegerConstant
4807       << numEltsExpr->getSourceRange();
4808     Attr.setInvalid();
4809     return;
4810   }
4811   // Only certain element types are supported for Neon vectors.
4812   if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
4813     S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4814     Attr.setInvalid();
4815     return;
4816   }
4817 
4818   // The total size of the vector must be 64 or 128 bits.
4819   unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4820   unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4821   unsigned vecSize = typeSize * numElts;
4822   if (vecSize != 64 && vecSize != 128) {
4823     S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4824     Attr.setInvalid();
4825     return;
4826   }
4827 
4828   CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4829 }
4830 
processTypeAttrs(TypeProcessingState & state,QualType & type,TypeAttrLocation TAL,AttributeList * attrs)4831 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
4832                              TypeAttrLocation TAL, AttributeList *attrs) {
4833   // Scan through and apply attributes to this type where it makes sense.  Some
4834   // attributes (such as __address_space__, __vector_size__, etc) apply to the
4835   // type, but others can be present in the type specifiers even though they
4836   // apply to the decl.  Here we apply type attributes and ignore the rest.
4837 
4838   AttributeList *next;
4839   do {
4840     AttributeList &attr = *attrs;
4841     next = attr.getNext();
4842 
4843     // Skip attributes that were marked to be invalid.
4844     if (attr.isInvalid())
4845       continue;
4846 
4847     if (attr.isCXX11Attribute()) {
4848       // [[gnu::...]] attributes are treated as declaration attributes, so may
4849       // not appertain to a DeclaratorChunk, even if we handle them as type
4850       // attributes.
4851       if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4852         if (TAL == TAL_DeclChunk) {
4853           state.getSema().Diag(attr.getLoc(),
4854                                diag::warn_cxx11_gnu_attribute_on_type)
4855               << attr.getName();
4856           continue;
4857         }
4858       } else if (TAL != TAL_DeclChunk) {
4859         // Otherwise, only consider type processing for a C++11 attribute if
4860         // it's actually been applied to a type.
4861         continue;
4862       }
4863     }
4864 
4865     // If this is an attribute we can handle, do so now,
4866     // otherwise, add it to the FnAttrs list for rechaining.
4867     switch (attr.getKind()) {
4868     default:
4869       // A C++11 attribute on a declarator chunk must appertain to a type.
4870       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
4871         state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
4872           << attr.getName();
4873         attr.setUsedAsTypeAttr();
4874       }
4875       break;
4876 
4877     case AttributeList::UnknownAttribute:
4878       if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4879         state.getSema().Diag(attr.getLoc(),
4880                              diag::warn_unknown_attribute_ignored)
4881           << attr.getName();
4882       break;
4883 
4884     case AttributeList::IgnoredAttribute:
4885       break;
4886 
4887     case AttributeList::AT_MayAlias:
4888       // FIXME: This attribute needs to actually be handled, but if we ignore
4889       // it it breaks large amounts of Linux software.
4890       attr.setUsedAsTypeAttr();
4891       break;
4892     case AttributeList::AT_OpenCLPrivateAddressSpace:
4893     case AttributeList::AT_OpenCLGlobalAddressSpace:
4894     case AttributeList::AT_OpenCLLocalAddressSpace:
4895     case AttributeList::AT_OpenCLConstantAddressSpace:
4896     case AttributeList::AT_OpenCLGenericAddressSpace:
4897     case AttributeList::AT_AddressSpace:
4898       HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
4899       attr.setUsedAsTypeAttr();
4900       break;
4901     OBJC_POINTER_TYPE_ATTRS_CASELIST:
4902       if (!handleObjCPointerTypeAttr(state, attr, type))
4903         distributeObjCPointerTypeAttr(state, attr, type);
4904       attr.setUsedAsTypeAttr();
4905       break;
4906     case AttributeList::AT_VectorSize:
4907       HandleVectorSizeAttr(type, attr, state.getSema());
4908       attr.setUsedAsTypeAttr();
4909       break;
4910     case AttributeList::AT_ExtVectorType:
4911       HandleExtVectorTypeAttr(type, attr, state.getSema());
4912       attr.setUsedAsTypeAttr();
4913       break;
4914     case AttributeList::AT_NeonVectorType:
4915       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4916                                VectorType::NeonVector);
4917       attr.setUsedAsTypeAttr();
4918       break;
4919     case AttributeList::AT_NeonPolyVectorType:
4920       HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4921                                VectorType::NeonPolyVector);
4922       attr.setUsedAsTypeAttr();
4923       break;
4924     case AttributeList::AT_OpenCLImageAccess:
4925       // FIXME: there should be some type checking happening here, I would
4926       // imagine, but the original handler's checking was entirely superfluous.
4927       attr.setUsedAsTypeAttr();
4928       break;
4929 
4930     MS_TYPE_ATTRS_CASELIST:
4931       if (!handleMSPointerTypeQualifierAttr(state, attr, type))
4932         attr.setUsedAsTypeAttr();
4933       break;
4934 
4935     case AttributeList::AT_NSReturnsRetained:
4936       if (!state.getSema().getLangOpts().ObjCAutoRefCount)
4937         break;
4938       // fallthrough into the function attrs
4939 
4940     FUNCTION_TYPE_ATTRS_CASELIST:
4941       attr.setUsedAsTypeAttr();
4942 
4943       // Never process function type attributes as part of the
4944       // declaration-specifiers.
4945       if (TAL == TAL_DeclSpec)
4946         distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4947 
4948       // Otherwise, handle the possible delays.
4949       else if (!handleFunctionTypeAttr(state, attr, type))
4950         distributeFunctionTypeAttr(state, attr, type);
4951       break;
4952     }
4953   } while ((attrs = next));
4954 }
4955 
4956 /// \brief Ensure that the type of the given expression is complete.
4957 ///
4958 /// This routine checks whether the expression \p E has a complete type. If the
4959 /// expression refers to an instantiable construct, that instantiation is
4960 /// performed as needed to complete its type. Furthermore
4961 /// Sema::RequireCompleteType is called for the expression's type (or in the
4962 /// case of a reference type, the referred-to type).
4963 ///
4964 /// \param E The expression whose type is required to be complete.
4965 /// \param Diagnoser The object that will emit a diagnostic if the type is
4966 /// incomplete.
4967 ///
4968 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4969 /// otherwise.
RequireCompleteExprType(Expr * E,TypeDiagnoser & Diagnoser)4970 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
4971   QualType T = E->getType();
4972 
4973   // Fast path the case where the type is already complete.
4974   if (!T->isIncompleteType())
4975     // FIXME: The definition might not be visible.
4976     return false;
4977 
4978   // Incomplete array types may be completed by the initializer attached to
4979   // their definitions. For static data members of class templates and for
4980   // variable templates, we need to instantiate the definition to get this
4981   // initializer and complete the type.
4982   if (T->isIncompleteArrayType()) {
4983     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4984       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4985         if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
4986           SourceLocation PointOfInstantiation = E->getExprLoc();
4987 
4988           if (MemberSpecializationInfo *MSInfo =
4989                   Var->getMemberSpecializationInfo()) {
4990             // If we don't already have a point of instantiation, this is it.
4991             if (MSInfo->getPointOfInstantiation().isInvalid()) {
4992               MSInfo->setPointOfInstantiation(PointOfInstantiation);
4993 
4994               // This is a modification of an existing AST node. Notify
4995               // listeners.
4996               if (ASTMutationListener *L = getASTMutationListener())
4997                 L->StaticDataMemberInstantiated(Var);
4998             }
4999           } else {
5000             VarTemplateSpecializationDecl *VarSpec =
5001                 cast<VarTemplateSpecializationDecl>(Var);
5002             if (VarSpec->getPointOfInstantiation().isInvalid())
5003               VarSpec->setPointOfInstantiation(PointOfInstantiation);
5004           }
5005 
5006           InstantiateVariableDefinition(PointOfInstantiation, Var);
5007 
5008           // Update the type to the newly instantiated definition's type both
5009           // here and within the expression.
5010           if (VarDecl *Def = Var->getDefinition()) {
5011             DRE->setDecl(Def);
5012             T = Def->getType();
5013             DRE->setType(T);
5014             E->setType(T);
5015           }
5016 
5017           // We still go on to try to complete the type independently, as it
5018           // may also require instantiations or diagnostics if it remains
5019           // incomplete.
5020         }
5021       }
5022     }
5023   }
5024 
5025   // FIXME: Are there other cases which require instantiating something other
5026   // than the type to complete the type of an expression?
5027 
5028   // Look through reference types and complete the referred type.
5029   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5030     T = Ref->getPointeeType();
5031 
5032   return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
5033 }
5034 
5035 namespace {
5036   struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
5037     unsigned DiagID;
5038 
TypeDiagnoserDiag__anon7ba70c020511::TypeDiagnoserDiag5039     TypeDiagnoserDiag(unsigned DiagID)
5040       : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
5041 
diagnose__anon7ba70c020511::TypeDiagnoserDiag5042     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5043       if (Suppressed) return;
5044       S.Diag(Loc, DiagID) << T;
5045     }
5046   };
5047 }
5048 
RequireCompleteExprType(Expr * E,unsigned DiagID)5049 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
5050   TypeDiagnoserDiag Diagnoser(DiagID);
5051   return RequireCompleteExprType(E, Diagnoser);
5052 }
5053 
5054 /// @brief Ensure that the type T is a complete type.
5055 ///
5056 /// This routine checks whether the type @p T is complete in any
5057 /// context where a complete type is required. If @p T is a complete
5058 /// type, returns false. If @p T is a class template specialization,
5059 /// this routine then attempts to perform class template
5060 /// instantiation. If instantiation fails, or if @p T is incomplete
5061 /// and cannot be completed, issues the diagnostic @p diag (giving it
5062 /// the type @p T) and returns true.
5063 ///
5064 /// @param Loc  The location in the source that the incomplete type
5065 /// diagnostic should refer to.
5066 ///
5067 /// @param T  The type that this routine is examining for completeness.
5068 ///
5069 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
5070 /// @c false otherwise.
RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)5071 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5072                                TypeDiagnoser &Diagnoser) {
5073   if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
5074     return true;
5075   if (const TagType *Tag = T->getAs<TagType>()) {
5076     if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
5077       Tag->getDecl()->setCompleteDefinitionRequired();
5078       Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
5079     }
5080   }
5081   return false;
5082 }
5083 
5084 /// \brief Determine whether there is any declaration of \p D that was ever a
5085 ///        definition (perhaps before module merging) and is currently visible.
5086 /// \param D The definition of the entity.
5087 /// \param Suggested Filled in with the declaration that should be made visible
5088 ///        in order to provide a definition of this entity.
hasVisibleDefinition(Sema & S,NamedDecl * D,NamedDecl ** Suggested)5089 static bool hasVisibleDefinition(Sema &S, NamedDecl *D, NamedDecl **Suggested) {
5090   // Easy case: if we don't have modules, all declarations are visible.
5091   if (!S.getLangOpts().Modules)
5092     return true;
5093 
5094   // If this definition was instantiated from a template, map back to the
5095   // pattern from which it was instantiated.
5096   if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5097     if (auto *Pattern = RD->getTemplateInstantiationPattern())
5098       RD = Pattern;
5099     D = RD->getDefinition();
5100   } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
5101     while (auto *NewED = ED->getInstantiatedFromMemberEnum())
5102       ED = NewED;
5103     if (ED->isFixed()) {
5104       // If the enum has a fixed underlying type, any declaration of it will do.
5105       *Suggested = nullptr;
5106       for (auto *Redecl : ED->redecls()) {
5107         if (LookupResult::isVisible(S, Redecl))
5108           return true;
5109         if (Redecl->isThisDeclarationADefinition() ||
5110             (Redecl->isCanonicalDecl() && !*Suggested))
5111           *Suggested = Redecl;
5112       }
5113       return false;
5114     }
5115     D = ED->getDefinition();
5116   }
5117   assert(D && "missing definition for pattern of instantiated definition");
5118 
5119   // FIXME: If we merged any other decl into D, and that declaration is visible,
5120   // then we should consider a definition to be visible.
5121   *Suggested = D;
5122   return LookupResult::isVisible(S, D);
5123 }
5124 
5125 /// Locks in the inheritance model for the given class and all of its bases.
assignInheritanceModel(Sema & S,CXXRecordDecl * RD)5126 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
5127   RD = RD->getMostRecentDecl();
5128   if (!RD->hasAttr<MSInheritanceAttr>()) {
5129     MSInheritanceAttr::Spelling IM;
5130 
5131     switch (S.MSPointerToMemberRepresentationMethod) {
5132     case LangOptions::PPTMK_BestCase:
5133       IM = RD->calculateInheritanceModel();
5134       break;
5135     case LangOptions::PPTMK_FullGeneralitySingleInheritance:
5136       IM = MSInheritanceAttr::Keyword_single_inheritance;
5137       break;
5138     case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
5139       IM = MSInheritanceAttr::Keyword_multiple_inheritance;
5140       break;
5141     case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
5142       IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
5143       break;
5144     }
5145 
5146     RD->addAttr(MSInheritanceAttr::CreateImplicit(
5147         S.getASTContext(), IM,
5148         /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
5149             LangOptions::PPTMK_BestCase,
5150         S.ImplicitMSInheritanceAttrLoc.isValid()
5151             ? S.ImplicitMSInheritanceAttrLoc
5152             : RD->getSourceRange()));
5153   }
5154 }
5155 
5156 /// \brief The implementation of RequireCompleteType
RequireCompleteTypeImpl(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)5157 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
5158                                    TypeDiagnoser &Diagnoser) {
5159   // FIXME: Add this assertion to make sure we always get instantiation points.
5160   //  assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
5161   // FIXME: Add this assertion to help us flush out problems with
5162   // checking for dependent types and type-dependent expressions.
5163   //
5164   //  assert(!T->isDependentType() &&
5165   //         "Can't ask whether a dependent type is complete");
5166 
5167   // If we have a complete type, we're done.
5168   NamedDecl *Def = nullptr;
5169   if (!T->isIncompleteType(&Def)) {
5170     // If we know about the definition but it is not visible, complain.
5171     NamedDecl *SuggestedDef = nullptr;
5172     if (!Diagnoser.Suppressed && Def &&
5173         !hasVisibleDefinition(*this, Def, &SuggestedDef)) {
5174       // Suppress this error outside of a SFINAE context if we've already
5175       // emitted the error once for this type. There's no usefulness in
5176       // repeating the diagnostic.
5177       // FIXME: Add a Fix-It that imports the corresponding module or includes
5178       // the header.
5179       Module *Owner = SuggestedDef->getOwningModule();
5180       Diag(Loc, diag::err_module_private_definition)
5181         << T << Owner->getFullModuleName();
5182       Diag(SuggestedDef->getLocation(), diag::note_previous_definition);
5183 
5184       // Try to recover by implicitly importing this module.
5185       createImplicitModuleImportForErrorRecovery(Loc, Owner);
5186     }
5187 
5188     // We lock in the inheritance model once somebody has asked us to ensure
5189     // that a pointer-to-member type is complete.
5190     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5191       if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
5192         if (!MPTy->getClass()->isDependentType()) {
5193           RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0);
5194           assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
5195         }
5196       }
5197     }
5198 
5199     return false;
5200   }
5201 
5202   const TagType *Tag = T->getAs<TagType>();
5203   const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
5204 
5205   // If there's an unimported definition of this type in a module (for
5206   // instance, because we forward declared it, then imported the definition),
5207   // import that definition now.
5208   //
5209   // FIXME: What about other cases where an import extends a redeclaration
5210   // chain for a declaration that can be accessed through a mechanism other
5211   // than name lookup (eg, referenced in a template, or a variable whose type
5212   // could be completed by the module)?
5213   if (Tag || IFace) {
5214     NamedDecl *D =
5215         Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
5216 
5217     // Avoid diagnosing invalid decls as incomplete.
5218     if (D->isInvalidDecl())
5219       return true;
5220 
5221     // Give the external AST source a chance to complete the type.
5222     if (auto *Source = Context.getExternalSource()) {
5223       if (Tag)
5224         Source->CompleteType(Tag->getDecl());
5225       else
5226         Source->CompleteType(IFace->getDecl());
5227 
5228       // If the external source completed the type, go through the motions
5229       // again to ensure we're allowed to use the completed type.
5230       if (!T->isIncompleteType())
5231         return RequireCompleteTypeImpl(Loc, T, Diagnoser);
5232     }
5233   }
5234 
5235   // If we have a class template specialization or a class member of a
5236   // class template specialization, or an array with known size of such,
5237   // try to instantiate it.
5238   QualType MaybeTemplate = T;
5239   while (const ConstantArrayType *Array
5240            = Context.getAsConstantArrayType(MaybeTemplate))
5241     MaybeTemplate = Array->getElementType();
5242   if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
5243     if (ClassTemplateSpecializationDecl *ClassTemplateSpec
5244           = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
5245       if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
5246         return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
5247                                                       TSK_ImplicitInstantiation,
5248                                             /*Complain=*/!Diagnoser.Suppressed);
5249     } else if (CXXRecordDecl *Rec
5250                  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
5251       CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
5252       if (!Rec->isBeingDefined() && Pattern) {
5253         MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
5254         assert(MSI && "Missing member specialization information?");
5255         // This record was instantiated from a class within a template.
5256         if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5257           return InstantiateClass(Loc, Rec, Pattern,
5258                                   getTemplateInstantiationArgs(Rec),
5259                                   TSK_ImplicitInstantiation,
5260                                   /*Complain=*/!Diagnoser.Suppressed);
5261       }
5262     }
5263   }
5264 
5265   if (Diagnoser.Suppressed)
5266     return true;
5267 
5268   // We have an incomplete type. Produce a diagnostic.
5269   if (Ident___float128 &&
5270       T == Context.getTypeDeclType(Context.getFloat128StubType())) {
5271     Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
5272     return true;
5273   }
5274 
5275   Diagnoser.diagnose(*this, Loc, T);
5276 
5277   // If the type was a forward declaration of a class/struct/union
5278   // type, produce a note.
5279   if (Tag && !Tag->getDecl()->isInvalidDecl())
5280     Diag(Tag->getDecl()->getLocation(),
5281          Tag->isBeingDefined() ? diag::note_type_being_defined
5282                                : diag::note_forward_declaration)
5283       << QualType(Tag, 0);
5284 
5285   // If the Objective-C class was a forward declaration, produce a note.
5286   if (IFace && !IFace->getDecl()->isInvalidDecl())
5287     Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
5288 
5289   // If we have external information that we can use to suggest a fix,
5290   // produce a note.
5291   if (ExternalSource)
5292     ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
5293 
5294   return true;
5295 }
5296 
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)5297 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5298                                unsigned DiagID) {
5299   TypeDiagnoserDiag Diagnoser(DiagID);
5300   return RequireCompleteType(Loc, T, Diagnoser);
5301 }
5302 
5303 /// \brief Get diagnostic %select index for tag kind for
5304 /// literal type diagnostic message.
5305 /// WARNING: Indexes apply to particular diagnostics only!
5306 ///
5307 /// \returns diagnostic %select index.
getLiteralDiagFromTagKind(TagTypeKind Tag)5308 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
5309   switch (Tag) {
5310   case TTK_Struct: return 0;
5311   case TTK_Interface: return 1;
5312   case TTK_Class:  return 2;
5313   default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
5314   }
5315 }
5316 
5317 /// @brief Ensure that the type T is a literal type.
5318 ///
5319 /// This routine checks whether the type @p T is a literal type. If @p T is an
5320 /// incomplete type, an attempt is made to complete it. If @p T is a literal
5321 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
5322 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
5323 /// it the type @p T), along with notes explaining why the type is not a
5324 /// literal type, and returns true.
5325 ///
5326 /// @param Loc  The location in the source that the non-literal type
5327 /// diagnostic should refer to.
5328 ///
5329 /// @param T  The type that this routine is examining for literalness.
5330 ///
5331 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
5332 ///
5333 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
5334 /// @c false otherwise.
RequireLiteralType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)5335 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
5336                               TypeDiagnoser &Diagnoser) {
5337   assert(!T->isDependentType() && "type should not be dependent");
5338 
5339   QualType ElemType = Context.getBaseElementType(T);
5340   RequireCompleteType(Loc, ElemType, 0);
5341 
5342   if (T->isLiteralType(Context))
5343     return false;
5344 
5345   if (Diagnoser.Suppressed)
5346     return true;
5347 
5348   Diagnoser.diagnose(*this, Loc, T);
5349 
5350   if (T->isVariableArrayType())
5351     return true;
5352 
5353   const RecordType *RT = ElemType->getAs<RecordType>();
5354   if (!RT)
5355     return true;
5356 
5357   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5358 
5359   // A partially-defined class type can't be a literal type, because a literal
5360   // class type must have a trivial destructor (which can't be checked until
5361   // the class definition is complete).
5362   if (!RD->isCompleteDefinition()) {
5363     RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
5364     return true;
5365   }
5366 
5367   // If the class has virtual base classes, then it's not an aggregate, and
5368   // cannot have any constexpr constructors or a trivial default constructor,
5369   // so is non-literal. This is better to diagnose than the resulting absence
5370   // of constexpr constructors.
5371   if (RD->getNumVBases()) {
5372     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
5373       << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
5374     for (const auto &I : RD->vbases())
5375       Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
5376           << I.getSourceRange();
5377   } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
5378              !RD->hasTrivialDefaultConstructor()) {
5379     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
5380   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
5381     for (const auto &I : RD->bases()) {
5382       if (!I.getType()->isLiteralType(Context)) {
5383         Diag(I.getLocStart(),
5384              diag::note_non_literal_base_class)
5385           << RD << I.getType() << I.getSourceRange();
5386         return true;
5387       }
5388     }
5389     for (const auto *I : RD->fields()) {
5390       if (!I->getType()->isLiteralType(Context) ||
5391           I->getType().isVolatileQualified()) {
5392         Diag(I->getLocation(), diag::note_non_literal_field)
5393           << RD << I << I->getType()
5394           << I->getType().isVolatileQualified();
5395         return true;
5396       }
5397     }
5398   } else if (!RD->hasTrivialDestructor()) {
5399     // All fields and bases are of literal types, so have trivial destructors.
5400     // If this class's destructor is non-trivial it must be user-declared.
5401     CXXDestructorDecl *Dtor = RD->getDestructor();
5402     assert(Dtor && "class has literal fields and bases but no dtor?");
5403     if (!Dtor)
5404       return true;
5405 
5406     Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
5407          diag::note_non_literal_user_provided_dtor :
5408          diag::note_non_literal_nontrivial_dtor) << RD;
5409     if (!Dtor->isUserProvided())
5410       SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
5411   }
5412 
5413   return true;
5414 }
5415 
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID)5416 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
5417   TypeDiagnoserDiag Diagnoser(DiagID);
5418   return RequireLiteralType(Loc, T, Diagnoser);
5419 }
5420 
5421 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
5422 /// and qualified by the nested-name-specifier contained in SS.
getElaboratedType(ElaboratedTypeKeyword Keyword,const CXXScopeSpec & SS,QualType T)5423 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
5424                                  const CXXScopeSpec &SS, QualType T) {
5425   if (T.isNull())
5426     return T;
5427   NestedNameSpecifier *NNS;
5428   if (SS.isValid())
5429     NNS = SS.getScopeRep();
5430   else {
5431     if (Keyword == ETK_None)
5432       return T;
5433     NNS = nullptr;
5434   }
5435   return Context.getElaboratedType(Keyword, NNS, T);
5436 }
5437 
BuildTypeofExprType(Expr * E,SourceLocation Loc)5438 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
5439   ExprResult ER = CheckPlaceholderExpr(E);
5440   if (ER.isInvalid()) return QualType();
5441   E = ER.get();
5442 
5443   if (!E->isTypeDependent()) {
5444     QualType T = E->getType();
5445     if (const TagType *TT = T->getAs<TagType>())
5446       DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
5447   }
5448   return Context.getTypeOfExprType(E);
5449 }
5450 
5451 /// getDecltypeForExpr - Given an expr, will return the decltype for
5452 /// that expression, according to the rules in C++11
5453 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
getDecltypeForExpr(Sema & S,Expr * E)5454 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
5455   if (E->isTypeDependent())
5456     return S.Context.DependentTy;
5457 
5458   // C++11 [dcl.type.simple]p4:
5459   //   The type denoted by decltype(e) is defined as follows:
5460   //
5461   //     - if e is an unparenthesized id-expression or an unparenthesized class
5462   //       member access (5.2.5), decltype(e) is the type of the entity named
5463   //       by e. If there is no such entity, or if e names a set of overloaded
5464   //       functions, the program is ill-formed;
5465   //
5466   // We apply the same rules for Objective-C ivar and property references.
5467   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5468     if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
5469       return VD->getType();
5470   } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5471     if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
5472       return FD->getType();
5473   } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
5474     return IR->getDecl()->getType();
5475   } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
5476     if (PR->isExplicitProperty())
5477       return PR->getExplicitProperty()->getType();
5478   } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
5479     return PE->getType();
5480   }
5481 
5482   // C++11 [expr.lambda.prim]p18:
5483   //   Every occurrence of decltype((x)) where x is a possibly
5484   //   parenthesized id-expression that names an entity of automatic
5485   //   storage duration is treated as if x were transformed into an
5486   //   access to a corresponding data member of the closure type that
5487   //   would have been declared if x were an odr-use of the denoted
5488   //   entity.
5489   using namespace sema;
5490   if (S.getCurLambda()) {
5491     if (isa<ParenExpr>(E)) {
5492       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5493         if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5494           QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
5495           if (!T.isNull())
5496             return S.Context.getLValueReferenceType(T);
5497         }
5498       }
5499     }
5500   }
5501 
5502 
5503   // C++11 [dcl.type.simple]p4:
5504   //   [...]
5505   QualType T = E->getType();
5506   switch (E->getValueKind()) {
5507   //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5508   //       type of e;
5509   case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
5510   //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5511   //       type of e;
5512   case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
5513   //  - otherwise, decltype(e) is the type of e.
5514   case VK_RValue: break;
5515   }
5516 
5517   return T;
5518 }
5519 
BuildDecltypeType(Expr * E,SourceLocation Loc,bool AsUnevaluated)5520 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
5521                                  bool AsUnevaluated) {
5522   ExprResult ER = CheckPlaceholderExpr(E);
5523   if (ER.isInvalid()) return QualType();
5524   E = ER.get();
5525 
5526   if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
5527       E->HasSideEffects(Context, false)) {
5528     // The expression operand for decltype is in an unevaluated expression
5529     // context, so side effects could result in unintended consequences.
5530     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
5531   }
5532 
5533   return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
5534 }
5535 
BuildUnaryTransformType(QualType BaseType,UnaryTransformType::UTTKind UKind,SourceLocation Loc)5536 QualType Sema::BuildUnaryTransformType(QualType BaseType,
5537                                        UnaryTransformType::UTTKind UKind,
5538                                        SourceLocation Loc) {
5539   switch (UKind) {
5540   case UnaryTransformType::EnumUnderlyingType:
5541     if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
5542       Diag(Loc, diag::err_only_enums_have_underlying_types);
5543       return QualType();
5544     } else {
5545       QualType Underlying = BaseType;
5546       if (!BaseType->isDependentType()) {
5547         // The enum could be incomplete if we're parsing its definition or
5548         // recovering from an error.
5549         NamedDecl *FwdDecl = nullptr;
5550         if (BaseType->isIncompleteType(&FwdDecl)) {
5551           Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
5552           Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
5553           return QualType();
5554         }
5555 
5556         EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
5557         assert(ED && "EnumType has no EnumDecl");
5558 
5559         DiagnoseUseOfDecl(ED, Loc);
5560 
5561         Underlying = ED->getIntegerType();
5562         assert(!Underlying.isNull());
5563       }
5564       return Context.getUnaryTransformType(BaseType, Underlying,
5565                                         UnaryTransformType::EnumUnderlyingType);
5566     }
5567   }
5568   llvm_unreachable("unknown unary transform type");
5569 }
5570 
BuildAtomicType(QualType T,SourceLocation Loc)5571 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
5572   if (!T->isDependentType()) {
5573     // FIXME: It isn't entirely clear whether incomplete atomic types
5574     // are allowed or not; for simplicity, ban them for the moment.
5575     if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
5576       return QualType();
5577 
5578     int DisallowedKind = -1;
5579     if (T->isArrayType())
5580       DisallowedKind = 1;
5581     else if (T->isFunctionType())
5582       DisallowedKind = 2;
5583     else if (T->isReferenceType())
5584       DisallowedKind = 3;
5585     else if (T->isAtomicType())
5586       DisallowedKind = 4;
5587     else if (T.hasQualifiers())
5588       DisallowedKind = 5;
5589     else if (!T.isTriviallyCopyableType(Context))
5590       // Some other non-trivially-copyable type (probably a C++ class)
5591       DisallowedKind = 6;
5592 
5593     if (DisallowedKind != -1) {
5594       Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
5595       return QualType();
5596     }
5597 
5598     // FIXME: Do we need any handling for ARC here?
5599   }
5600 
5601   // Build the pointer type.
5602   return Context.getAtomicType(T);
5603 }
5604