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