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