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