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