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