blob: 35816a42f33e9388db09c9ff37ebb646d744c9f5 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36f255c2011-06-03 14:28:43 +000016#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Steve Naroff980e5082007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor2943aed2009-03-03 04:44:36 +000019#include "clang/AST/DeclTemplate.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/Expr.h"
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +000021#include "clang/AST/TypeLoc.h"
John McCall51bd8032009-10-18 01:05:36 +000022#include "clang/AST/TypeLocVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Basic/OpenCL.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000024#include "clang/Basic/PartialDiagnostic.h"
Charles Davisd18f9f92010-08-16 04:01:50 +000025#include "clang/Basic/TargetInfo.h"
John McCall2792fa52011-03-08 04:17:03 +000026#include "clang/Lex/Preprocessor.h"
Eli Friedmanbc1029b2012-04-05 22:47:34 +000027#include "clang/Parse/ParseDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregord07cc362012-01-02 17:18:37 +000030#include "clang/Sema/Lookup.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/ScopeInfo.h"
32#include "clang/Sema/Template.h"
Sebastian Redl4994d2d2009-07-04 11:39:00 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor87c12c42009-11-04 16:49:01 +000034#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Chris Lattner5db2bb12009-10-25 18:21:37 +000037/// isOmittedBlockReturnType - Return true if this declarator is missing a
Chad Rosier91cbbbf2012-06-26 21:41:40 +000038/// return type because this is a omitted return type on a block literal.
Sebastian Redl8ce35b02009-10-25 21:45:37 +000039static bool isOmittedBlockReturnType(const Declarator &D) {
Chris Lattner5db2bb12009-10-25 18:21:37 +000040 if (D.getContext() != Declarator::BlockLiteralContext ||
Sebastian Redl8ce35b02009-10-25 21:45:37 +000041 D.getDeclSpec().hasTypeSpecifier())
Chris Lattner5db2bb12009-10-25 18:21:37 +000042 return false;
Chad Rosier91cbbbf2012-06-26 21:41:40 +000043
Chris Lattner5db2bb12009-10-25 18:21:37 +000044 if (D.getNumTypeObjects() == 0)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000045 return true; // ^{ ... }
Chad Rosier91cbbbf2012-06-26 21:41:40 +000046
Chris Lattner5db2bb12009-10-25 18:21:37 +000047 if (D.getNumTypeObjects() == 1 &&
48 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000049 return true; // ^(int X, float Y) { ... }
Chad Rosier91cbbbf2012-06-26 21:41:40 +000050
Chris Lattner5db2bb12009-10-25 18:21:37 +000051 return false;
52}
53
John McCall2792fa52011-03-08 04:17:03 +000054/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
55/// doesn't apply to the given type.
56static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
57 QualType type) {
Chandler Carruth108f7562011-07-26 05:40:03 +000058 bool useExpansionLoc = false;
John McCall2792fa52011-03-08 04:17:03 +000059
60 unsigned diagID = 0;
61 switch (attr.getKind()) {
Sean Hunt8e083e72012-06-19 23:57:03 +000062 case AttributeList::AT_ObjCGC:
John McCall2792fa52011-03-08 04:17:03 +000063 diagID = diag::warn_pointer_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000064 useExpansionLoc = true;
John McCall2792fa52011-03-08 04:17:03 +000065 break;
66
Sean Hunt8e083e72012-06-19 23:57:03 +000067 case AttributeList::AT_ObjCOwnership:
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000068 diagID = diag::warn_objc_object_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000069 useExpansionLoc = true;
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000070 break;
71
John McCall2792fa52011-03-08 04:17:03 +000072 default:
73 // Assume everything else was a function attribute.
74 diagID = diag::warn_function_attribute_wrong_type;
75 break;
76 }
77
78 SourceLocation loc = attr.getLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +000079 StringRef name = attr.getName()->getName();
John McCall2792fa52011-03-08 04:17:03 +000080
81 // The GC attributes are usually written with macros; special-case them.
Chandler Carruth108f7562011-07-26 05:40:03 +000082 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
John McCall834e3f62011-03-08 07:59:04 +000083 if (attr.getParameterName()->isStr("strong")) {
84 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
85 } else if (attr.getParameterName()->isStr("weak")) {
86 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
John McCall2792fa52011-03-08 04:17:03 +000087 }
88 }
89
90 S.Diag(loc, diagID) << name << type;
91}
92
John McCall711c52b2011-01-05 12:14:39 +000093// objc_gc applies to Objective-C pointers or, otherwise, to the
94// smallest available pointer type (i.e. 'void*' in 'void**').
95#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
Sean Hunt8e083e72012-06-19 23:57:03 +000096 case AttributeList::AT_ObjCGC: \
97 case AttributeList::AT_ObjCOwnership
John McCall04a67a62010-02-05 21:31:56 +000098
John McCall711c52b2011-01-05 12:14:39 +000099// Function type attributes.
100#define FUNCTION_TYPE_ATTRS_CASELIST \
Sean Hunt8e083e72012-06-19 23:57:03 +0000101 case AttributeList::AT_NoReturn: \
102 case AttributeList::AT_CDecl: \
103 case AttributeList::AT_FastCall: \
104 case AttributeList::AT_StdCall: \
105 case AttributeList::AT_ThisCall: \
106 case AttributeList::AT_Pascal: \
107 case AttributeList::AT_Regparm: \
Derek Schuff263366f2012-10-16 22:30:41 +0000108 case AttributeList::AT_Pcs: \
Guy Benyei38980082012-12-25 08:53:55 +0000109 case AttributeList::AT_PnaclCall: \
110 case AttributeList::AT_IntelOclBicc \
John McCall04a67a62010-02-05 21:31:56 +0000111
John McCall711c52b2011-01-05 12:14:39 +0000112namespace {
113 /// An object which stores processing state for the entire
114 /// GetTypeForDeclarator process.
115 class TypeProcessingState {
116 Sema &sema;
117
118 /// The declarator being processed.
119 Declarator &declarator;
120
121 /// The index of the declarator chunk we're currently processing.
122 /// May be the total number of valid chunks, indicating the
123 /// DeclSpec.
124 unsigned chunkIndex;
125
126 /// Whether there are non-trivial modifications to the decl spec.
127 bool trivial;
128
John McCall7ea21932011-03-26 01:39:56 +0000129 /// Whether we saved the attributes in the decl spec.
130 bool hasSavedAttrs;
131
John McCall711c52b2011-01-05 12:14:39 +0000132 /// The original set of attributes on the DeclSpec.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<AttributeList*, 2> savedAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000134
135 /// A list of attributes to diagnose the uselessness of when the
136 /// processing is complete.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000137 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000138
139 public:
140 TypeProcessingState(Sema &sema, Declarator &declarator)
141 : sema(sema), declarator(declarator),
142 chunkIndex(declarator.getNumTypeObjects()),
John McCall7ea21932011-03-26 01:39:56 +0000143 trivial(true), hasSavedAttrs(false) {}
John McCall711c52b2011-01-05 12:14:39 +0000144
145 Sema &getSema() const {
146 return sema;
Abramo Bagnarae215f722010-04-30 13:10:51 +0000147 }
John McCall711c52b2011-01-05 12:14:39 +0000148
149 Declarator &getDeclarator() const {
150 return declarator;
151 }
152
153 unsigned getCurrentChunkIndex() const {
154 return chunkIndex;
155 }
156
157 void setCurrentChunkIndex(unsigned idx) {
158 assert(idx <= declarator.getNumTypeObjects());
159 chunkIndex = idx;
160 }
161
162 AttributeList *&getCurrentAttrListRef() const {
163 assert(chunkIndex <= declarator.getNumTypeObjects());
164 if (chunkIndex == declarator.getNumTypeObjects())
165 return getMutableDeclSpec().getAttributes().getListRef();
166 return declarator.getTypeObject(chunkIndex).getAttrListRef();
167 }
168
169 /// Save the current set of attributes on the DeclSpec.
170 void saveDeclSpecAttrs() {
171 // Don't try to save them multiple times.
John McCall7ea21932011-03-26 01:39:56 +0000172 if (hasSavedAttrs) return;
John McCall711c52b2011-01-05 12:14:39 +0000173
174 DeclSpec &spec = getMutableDeclSpec();
175 for (AttributeList *attr = spec.getAttributes().getList(); attr;
176 attr = attr->getNext())
177 savedAttrs.push_back(attr);
178 trivial &= savedAttrs.empty();
John McCall7ea21932011-03-26 01:39:56 +0000179 hasSavedAttrs = true;
John McCall711c52b2011-01-05 12:14:39 +0000180 }
181
182 /// Record that we had nowhere to put the given type attribute.
183 /// We will diagnose such attributes later.
184 void addIgnoredTypeAttr(AttributeList &attr) {
185 ignoredTypeAttrs.push_back(&attr);
186 }
187
188 /// Diagnose all the ignored type attributes, given that the
189 /// declarator worked out to the given type.
190 void diagnoseIgnoredTypeAttrs(QualType type) const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000191 for (SmallVectorImpl<AttributeList*>::const_iterator
John McCall711c52b2011-01-05 12:14:39 +0000192 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
John McCall2792fa52011-03-08 04:17:03 +0000193 i != e; ++i)
194 diagnoseBadTypeAttribute(getSema(), **i, type);
John McCall711c52b2011-01-05 12:14:39 +0000195 }
196
197 ~TypeProcessingState() {
198 if (trivial) return;
199
200 restoreDeclSpecAttrs();
201 }
202
203 private:
204 DeclSpec &getMutableDeclSpec() const {
205 return const_cast<DeclSpec&>(declarator.getDeclSpec());
206 }
207
208 void restoreDeclSpecAttrs() {
John McCall7ea21932011-03-26 01:39:56 +0000209 assert(hasSavedAttrs);
210
211 if (savedAttrs.empty()) {
212 getMutableDeclSpec().getAttributes().set(0);
213 return;
214 }
215
John McCall711c52b2011-01-05 12:14:39 +0000216 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
217 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
218 savedAttrs[i]->setNext(savedAttrs[i+1]);
219 savedAttrs.back()->setNext(0);
220 }
221 };
222
223 /// Basically std::pair except that we really want to avoid an
224 /// implicit operator= for safety concerns. It's also a minor
225 /// link-time optimization for this to be a private type.
226 struct AttrAndList {
227 /// The attribute.
228 AttributeList &first;
229
230 /// The head of the list the attribute is currently in.
231 AttributeList *&second;
232
233 AttrAndList(AttributeList &attr, AttributeList *&head)
234 : first(attr), second(head) {}
235 };
John McCall04a67a62010-02-05 21:31:56 +0000236}
237
John McCall711c52b2011-01-05 12:14:39 +0000238namespace llvm {
239 template <> struct isPodLike<AttrAndList> {
240 static const bool value = true;
241 };
242}
243
244static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
245 attr.setNext(head);
246 head = &attr;
247}
248
249static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
250 if (head == &attr) {
251 head = attr.getNext();
252 return;
John McCall04a67a62010-02-05 21:31:56 +0000253 }
John McCall711c52b2011-01-05 12:14:39 +0000254
255 AttributeList *cur = head;
256 while (true) {
257 assert(cur && cur->getNext() && "ran out of attrs?");
258 if (cur->getNext() == &attr) {
259 cur->setNext(attr.getNext());
260 return;
261 }
262 cur = cur->getNext();
263 }
264}
265
266static void moveAttrFromListToList(AttributeList &attr,
267 AttributeList *&fromList,
268 AttributeList *&toList) {
269 spliceAttrOutOfList(attr, fromList);
270 spliceAttrIntoList(attr, toList);
271}
272
Richard Smithf7a05272013-01-14 07:53:01 +0000273/// The location of a type attribute.
274enum TypeAttrLocation {
275 /// The attribute is in the decl-specifier-seq.
276 TAL_DeclSpec,
277 /// The attribute is part of a DeclaratorChunk.
278 TAL_DeclChunk,
279 /// The attribute is immediately after the declaration's name.
280 TAL_DeclName
281};
282
John McCall711c52b2011-01-05 12:14:39 +0000283static void processTypeAttrs(TypeProcessingState &state,
Richard Smithf7a05272013-01-14 07:53:01 +0000284 QualType &type, TypeAttrLocation TAL,
John McCall711c52b2011-01-05 12:14:39 +0000285 AttributeList *attrs);
286
287static bool handleFunctionTypeAttr(TypeProcessingState &state,
288 AttributeList &attr,
289 QualType &type);
290
291static bool handleObjCGCTypeAttr(TypeProcessingState &state,
292 AttributeList &attr, QualType &type);
293
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000294static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +0000295 AttributeList &attr, QualType &type);
296
John McCall711c52b2011-01-05 12:14:39 +0000297static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
298 AttributeList &attr, QualType &type) {
Sean Hunt8e083e72012-06-19 23:57:03 +0000299 if (attr.getKind() == AttributeList::AT_ObjCGC)
John McCallf85e1932011-06-15 23:02:42 +0000300 return handleObjCGCTypeAttr(state, attr, type);
Sean Hunt8e083e72012-06-19 23:57:03 +0000301 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000302 return handleObjCOwnershipTypeAttr(state, attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000303}
304
305/// Given that an objc_gc attribute was written somewhere on a
306/// declaration *other* than on the declarator itself (for which, use
307/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
308/// didn't apply in whatever position it was written in, try to move
309/// it to a more appropriate position.
310static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
311 AttributeList &attr,
312 QualType type) {
313 Declarator &declarator = state.getDeclarator();
314 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
315 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
316 switch (chunk.Kind) {
317 case DeclaratorChunk::Pointer:
318 case DeclaratorChunk::BlockPointer:
319 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
320 chunk.getAttrListRef());
321 return;
322
323 case DeclaratorChunk::Paren:
324 case DeclaratorChunk::Array:
325 continue;
326
327 // Don't walk through these.
328 case DeclaratorChunk::Reference:
329 case DeclaratorChunk::Function:
330 case DeclaratorChunk::MemberPointer:
331 goto error;
332 }
333 }
334 error:
John McCall2792fa52011-03-08 04:17:03 +0000335
336 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000337}
338
339/// Distribute an objc_gc type attribute that was written on the
340/// declarator.
341static void
342distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
343 AttributeList &attr,
344 QualType &declSpecType) {
345 Declarator &declarator = state.getDeclarator();
346
347 // objc_gc goes on the innermost pointer to something that's not a
348 // pointer.
349 unsigned innermost = -1U;
350 bool considerDeclSpec = true;
351 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
352 DeclaratorChunk &chunk = declarator.getTypeObject(i);
353 switch (chunk.Kind) {
354 case DeclaratorChunk::Pointer:
355 case DeclaratorChunk::BlockPointer:
356 innermost = i;
John McCallae278a32011-01-12 00:34:59 +0000357 continue;
John McCall711c52b2011-01-05 12:14:39 +0000358
359 case DeclaratorChunk::Reference:
360 case DeclaratorChunk::MemberPointer:
361 case DeclaratorChunk::Paren:
362 case DeclaratorChunk::Array:
363 continue;
364
365 case DeclaratorChunk::Function:
366 considerDeclSpec = false;
367 goto done;
368 }
369 }
370 done:
371
372 // That might actually be the decl spec if we weren't blocked by
373 // anything in the declarator.
374 if (considerDeclSpec) {
John McCall7ea21932011-03-26 01:39:56 +0000375 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
376 // Splice the attribute into the decl spec. Prevents the
377 // attribute from being applied multiple times and gives
378 // the source-location-filler something to work with.
379 state.saveDeclSpecAttrs();
380 moveAttrFromListToList(attr, declarator.getAttrListRef(),
381 declarator.getMutableDeclSpec().getAttributes().getListRef());
John McCall711c52b2011-01-05 12:14:39 +0000382 return;
John McCall7ea21932011-03-26 01:39:56 +0000383 }
John McCall711c52b2011-01-05 12:14:39 +0000384 }
385
386 // Otherwise, if we found an appropriate chunk, splice the attribute
387 // into it.
388 if (innermost != -1U) {
389 moveAttrFromListToList(attr, declarator.getAttrListRef(),
390 declarator.getTypeObject(innermost).getAttrListRef());
391 return;
392 }
393
394 // Otherwise, diagnose when we're done building the type.
395 spliceAttrOutOfList(attr, declarator.getAttrListRef());
396 state.addIgnoredTypeAttr(attr);
397}
398
399/// A function type attribute was written somewhere in a declaration
400/// *other* than on the declarator itself or in the decl spec. Given
401/// that it didn't apply in whatever position it was written in, try
402/// to move it to a more appropriate position.
403static void distributeFunctionTypeAttr(TypeProcessingState &state,
404 AttributeList &attr,
405 QualType type) {
406 Declarator &declarator = state.getDeclarator();
407
408 // Try to push the attribute from the return type of a function to
409 // the function itself.
410 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
411 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
412 switch (chunk.Kind) {
413 case DeclaratorChunk::Function:
414 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
415 chunk.getAttrListRef());
416 return;
417
418 case DeclaratorChunk::Paren:
419 case DeclaratorChunk::Pointer:
420 case DeclaratorChunk::BlockPointer:
421 case DeclaratorChunk::Array:
422 case DeclaratorChunk::Reference:
423 case DeclaratorChunk::MemberPointer:
424 continue;
425 }
426 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000427
John McCall2792fa52011-03-08 04:17:03 +0000428 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000429}
430
431/// Try to distribute a function type attribute to the innermost
432/// function chunk or type. Returns true if the attribute was
433/// distributed, false if no location was found.
434static bool
435distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
436 AttributeList &attr,
437 AttributeList *&attrList,
438 QualType &declSpecType) {
439 Declarator &declarator = state.getDeclarator();
440
441 // Put it on the innermost function chunk, if there is one.
442 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
443 DeclaratorChunk &chunk = declarator.getTypeObject(i);
444 if (chunk.Kind != DeclaratorChunk::Function) continue;
445
446 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
447 return true;
448 }
449
John McCallf85e1932011-06-15 23:02:42 +0000450 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
451 spliceAttrOutOfList(attr, attrList);
452 return true;
453 }
454
455 return false;
John McCall711c52b2011-01-05 12:14:39 +0000456}
457
458/// A function type attribute was written in the decl spec. Try to
459/// apply it somewhere.
460static void
461distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
462 AttributeList &attr,
463 QualType &declSpecType) {
464 state.saveDeclSpecAttrs();
465
Richard Smith5c521662013-01-15 02:48:13 +0000466 // C++11 attributes before the decl specifiers actually appertain to
467 // the declarators. Move them straight there. We don't support the
468 // 'put them wherever you like' semantics we allow for GNU attributes.
469 if (attr.isCXX11Attribute()) {
470 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
471 state.getDeclarator().getAttrListRef());
472 return;
473 }
474
John McCall711c52b2011-01-05 12:14:39 +0000475 // Try to distribute to the innermost.
476 if (distributeFunctionTypeAttrToInnermost(state, attr,
477 state.getCurrentAttrListRef(),
478 declSpecType))
479 return;
480
481 // If that failed, diagnose the bad attribute when the declarator is
482 // fully built.
483 state.addIgnoredTypeAttr(attr);
484}
485
486/// A function type attribute was written on the declarator. Try to
487/// apply it somewhere.
488static void
489distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
490 AttributeList &attr,
491 QualType &declSpecType) {
492 Declarator &declarator = state.getDeclarator();
493
494 // Try to distribute to the innermost.
495 if (distributeFunctionTypeAttrToInnermost(state, attr,
496 declarator.getAttrListRef(),
497 declSpecType))
498 return;
499
500 // If that failed, diagnose the bad attribute when the declarator is
501 // fully built.
502 spliceAttrOutOfList(attr, declarator.getAttrListRef());
503 state.addIgnoredTypeAttr(attr);
504}
505
506/// \brief Given that there are attributes written on the declarator
507/// itself, try to distribute any type attributes to the appropriate
508/// declarator chunk.
509///
510/// These are attributes like the following:
511/// int f ATTR;
512/// int (f ATTR)();
513/// but not necessarily this:
514/// int f() ATTR;
515static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
516 QualType &declSpecType) {
517 // Collect all the type attributes from the declarator itself.
518 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
519 AttributeList *attr = state.getDeclarator().getAttributes();
520 AttributeList *next;
521 do {
522 next = attr->getNext();
523
Richard Smith5c521662013-01-15 02:48:13 +0000524 // Do not distribute C++11 attributes. They have strict rules for what
525 // they appertain to.
526 if (attr->isCXX11Attribute())
527 continue;
528
John McCall711c52b2011-01-05 12:14:39 +0000529 switch (attr->getKind()) {
530 OBJC_POINTER_TYPE_ATTRS_CASELIST:
531 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
532 break;
533
Sean Hunt8e083e72012-06-19 23:57:03 +0000534 case AttributeList::AT_NSReturnsRetained:
David Blaikie4e4d0842012-03-11 07:00:24 +0000535 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000536 break;
537 // fallthrough
538
John McCall711c52b2011-01-05 12:14:39 +0000539 FUNCTION_TYPE_ATTRS_CASELIST:
540 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
541 break;
542
543 default:
544 break;
545 }
546 } while ((attr = next));
547}
548
549/// Add a synthetic '()' to a block-literal declarator if it is
550/// required, given the return type.
551static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
552 QualType declSpecType) {
553 Declarator &declarator = state.getDeclarator();
554
555 // First, check whether the declarator would produce a function,
556 // i.e. whether the innermost semantic chunk is a function.
557 if (declarator.isFunctionDeclarator()) {
558 // If so, make that declarator a prototyped declarator.
559 declarator.getFunctionTypeInfo().hasPrototype = true;
560 return;
561 }
562
John McCallda263792011-02-08 01:59:10 +0000563 // If there are any type objects, the type as written won't name a
564 // function, regardless of the decl spec type. This is because a
565 // block signature declarator is always an abstract-declarator, and
566 // abstract-declarators can't just be parentheses chunks. Therefore
567 // we need to build a function chunk unless there are no type
568 // objects and the decl spec type is a function.
John McCall711c52b2011-01-05 12:14:39 +0000569 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
570 return;
571
John McCallda263792011-02-08 01:59:10 +0000572 // Note that there *are* cases with invalid declarators where
573 // declarators consist solely of parentheses. In general, these
574 // occur only in failed efforts to make function declarators, so
575 // faking up the function chunk is still the right thing to do.
John McCall711c52b2011-01-05 12:14:39 +0000576
577 // Otherwise, we need to fake up a function declarator.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000578 SourceLocation loc = declarator.getLocStart();
John McCall711c52b2011-01-05 12:14:39 +0000579
580 // ...and *prepend* it to the declarator.
Abramo Bagnara59c0a812012-10-04 21:42:10 +0000581 SourceLocation NoLoc;
John McCall711c52b2011-01-05 12:14:39 +0000582 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
Abramo Bagnara59c0a812012-10-04 21:42:10 +0000583 /*HasProto=*/true,
584 /*IsAmbiguous=*/false,
585 /*LParenLoc=*/NoLoc,
586 /*ArgInfo=*/0,
587 /*NumArgs=*/0,
588 /*EllipsisLoc=*/NoLoc,
589 /*RParenLoc=*/NoLoc,
590 /*TypeQuals=*/0,
591 /*RefQualifierIsLvalueRef=*/true,
592 /*RefQualifierLoc=*/NoLoc,
593 /*ConstQualifierLoc=*/NoLoc,
594 /*VolatileQualifierLoc=*/NoLoc,
595 /*MutableLoc=*/NoLoc,
596 EST_None,
597 /*ESpecLoc=*/NoLoc,
598 /*Exceptions=*/0,
599 /*ExceptionRanges=*/0,
600 /*NumExceptions=*/0,
601 /*NoexceptExpr=*/0,
602 loc, loc, declarator));
John McCall711c52b2011-01-05 12:14:39 +0000603
604 // For consistency, make sure the state still has us as processing
605 // the decl spec.
606 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
607 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
John McCall04a67a62010-02-05 21:31:56 +0000608}
609
Douglas Gregor930d8b52009-01-30 22:09:00 +0000610/// \brief Convert the specified declspec to the appropriate type
611/// object.
James Dennett1dfbd922012-06-14 21:40:34 +0000612/// \param state Specifies the declarator containing the declaration specifier
613/// to be converted, along with other associated processing state.
Chris Lattner5153ee62009-04-25 08:47:54 +0000614/// \returns The type described by the declaration specifiers. This function
615/// never returns null.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000616static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
618 // checking.
John McCall711c52b2011-01-05 12:14:39 +0000619
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000620 Sema &S = state.getSema();
John McCall711c52b2011-01-05 12:14:39 +0000621 Declarator &declarator = state.getDeclarator();
622 const DeclSpec &DS = declarator.getDeclSpec();
623 SourceLocation DeclLoc = declarator.getIdentifierLoc();
Chris Lattner5db2bb12009-10-25 18:21:37 +0000624 if (DeclLoc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000625 DeclLoc = DS.getLocStart();
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000626
John McCall711c52b2011-01-05 12:14:39 +0000627 ASTContext &Context = S.Context;
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattner5db2bb12009-10-25 18:21:37 +0000629 QualType Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 switch (DS.getTypeSpecType()) {
Chris Lattner96b77fc2008-04-02 06:50:17 +0000631 case DeclSpec::TST_void:
632 Result = Context.VoidTy;
633 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 case DeclSpec::TST_char:
635 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000636 Result = Context.CharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000638 Result = Context.SignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 else {
640 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
641 "Unknown TSS value");
Chris Lattnerfab5b452008-02-20 23:53:49 +0000642 Result = Context.UnsignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 }
Chris Lattner958858e2008-02-20 21:40:32 +0000644 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000645 case DeclSpec::TST_wchar:
646 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
647 Result = Context.WCharTy;
648 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
John McCall711c52b2011-01-05 12:14:39 +0000649 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000650 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000651 Result = Context.getSignedWCharType();
652 } else {
653 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
654 "Unknown TSS value");
John McCall711c52b2011-01-05 12:14:39 +0000655 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000656 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000657 Result = Context.getUnsignedWCharType();
658 }
659 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000660 case DeclSpec::TST_char16:
661 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
662 "Unknown TSS value");
663 Result = Context.Char16Ty;
664 break;
665 case DeclSpec::TST_char32:
666 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
667 "Unknown TSS value");
668 Result = Context.Char32Ty;
669 break;
Chris Lattnerd658b562008-04-05 06:32:51 +0000670 case DeclSpec::TST_unspecified:
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000671 // "<proto1,proto2>" is an objc qualified ID with a missing id.
Chris Lattner097e9162008-10-20 02:01:50 +0000672 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000673 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
Roman Divacky31ba6132012-09-06 15:59:27 +0000674 (ObjCProtocolDecl*const*)PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000675 DS.getNumProtocolQualifiers());
676 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000677 break;
678 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000679
Chris Lattner5db2bb12009-10-25 18:21:37 +0000680 // If this is a missing declspec in a block literal return context, then it
681 // is inferred from the return statements inside the block.
Eli Friedmanf88c4002012-01-04 04:41:38 +0000682 // The declspec is always missing in a lambda expr context; it is either
683 // specified with a trailing return type or inferred.
684 if (declarator.getContext() == Declarator::LambdaExprContext ||
685 isOmittedBlockReturnType(declarator)) {
Chris Lattner5db2bb12009-10-25 18:21:37 +0000686 Result = Context.DependentTy;
687 break;
688 }
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Chris Lattnerd658b562008-04-05 06:32:51 +0000690 // Unspecified typespec defaults to int in C90. However, the C90 grammar
691 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
692 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
693 // Note that the one exception to this is function definitions, which are
694 // allowed to be completely missing a declspec. This is handled in the
695 // parser already though by it pretending to have seen an 'int' in this
696 // case.
David Blaikie4e4d0842012-03-11 07:00:24 +0000697 if (S.getLangOpts().ImplicitInt) {
Chris Lattner35d276f2009-02-27 18:53:28 +0000698 // In C89 mode, we only warn if there is a completely missing declspec
699 // when one is not allowed.
Chris Lattner3f84ad22009-04-22 05:27:59 +0000700 if (DS.isEmpty()) {
John McCall711c52b2011-01-05 12:14:39 +0000701 S.Diag(DeclLoc, diag::ext_missing_declspec)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000702 << DS.getSourceRange()
Daniel Dunbar96a00142012-03-09 18:35:03 +0000703 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
Chris Lattner3f84ad22009-04-22 05:27:59 +0000704 }
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000705 } else if (!DS.hasTypeSpecifier()) {
Chris Lattnerd658b562008-04-05 06:32:51 +0000706 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
707 // "At least one type specifier shall be given in the declaration
708 // specifiers in each declaration, and in the specifier-qualifier list in
709 // each struct declaration and type name."
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000710 // FIXME: Does Microsoft really have the implicit int extension in C++?
David Blaikie4e4d0842012-03-11 07:00:24 +0000711 if (S.getLangOpts().CPlusPlus &&
712 !S.getLangOpts().MicrosoftExt) {
John McCall711c52b2011-01-05 12:14:39 +0000713 S.Diag(DeclLoc, diag::err_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000714 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattnerb78d8332009-06-26 04:45:06 +0000716 // When this occurs in C++ code, often something is very broken with the
717 // value being declared, poison it as invalid so we don't get chains of
718 // errors.
John McCall711c52b2011-01-05 12:14:39 +0000719 declarator.setInvalidType(true);
Chris Lattnerb78d8332009-06-26 04:45:06 +0000720 } else {
John McCall711c52b2011-01-05 12:14:39 +0000721 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000722 << DS.getSourceRange();
Chris Lattnerb78d8332009-06-26 04:45:06 +0000723 }
Chris Lattnerd658b562008-04-05 06:32:51 +0000724 }
Mike Stump1eb44332009-09-09 15:08:12 +0000725
726 // FALL THROUGH.
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000727 case DeclSpec::TST_int: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
729 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000730 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
731 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
732 case DeclSpec::TSW_long: Result = Context.LongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000733 case DeclSpec::TSW_longlong:
734 Result = Context.LongLongTy;
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000735
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000736 // 'long long' is a C99 or C++11 feature.
737 if (!S.getLangOpts().C99) {
738 if (S.getLangOpts().CPlusPlus)
739 S.Diag(DS.getTypeSpecWidthLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000740 S.getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000741 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
742 else
743 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
744 }
Chris Lattner311157f2009-10-25 18:25:04 +0000745 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 }
747 } else {
748 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000749 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
750 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
751 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000752 case DeclSpec::TSW_longlong:
753 Result = Context.UnsignedLongLongTy;
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000754
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000755 // 'long long' is a C99 or C++11 feature.
756 if (!S.getLangOpts().C99) {
757 if (S.getLangOpts().CPlusPlus)
758 S.Diag(DS.getTypeSpecWidthLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000759 S.getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000760 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
761 else
762 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
763 }
Chris Lattner311157f2009-10-25 18:25:04 +0000764 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 }
766 }
Chris Lattner958858e2008-02-20 21:40:32 +0000767 break;
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000768 }
Richard Smith5a5a9712012-04-04 06:24:32 +0000769 case DeclSpec::TST_int128:
Richard Smith84268902012-11-29 05:41:51 +0000770 if (!S.PP.getTargetInfo().hasInt128Type())
771 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
Richard Smith5a5a9712012-04-04 06:24:32 +0000772 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
773 Result = Context.UnsignedInt128Ty;
774 else
775 Result = Context.Int128Ty;
776 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000777 case DeclSpec::TST_half: Result = Context.HalfTy; break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000778 case DeclSpec::TST_float: Result = Context.FloatTy; break;
Chris Lattner958858e2008-02-20 21:40:32 +0000779 case DeclSpec::TST_double:
780 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000781 Result = Context.LongDoubleTy;
Chris Lattner958858e2008-02-20 21:40:32 +0000782 else
Chris Lattnerfab5b452008-02-20 23:53:49 +0000783 Result = Context.DoubleTy;
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000784
David Blaikie4e4d0842012-03-11 07:00:24 +0000785 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000786 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
787 declarator.setInvalidType(true);
788 }
Chris Lattner958858e2008-02-20 21:40:32 +0000789 break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000790 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
Reid Spencer5f016e22007-07-11 17:01:13 +0000791 case DeclSpec::TST_decimal32: // _Decimal32
792 case DeclSpec::TST_decimal64: // _Decimal64
793 case DeclSpec::TST_decimal128: // _Decimal128
John McCall711c52b2011-01-05 12:14:39 +0000794 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
Chris Lattner8f12f652009-05-13 05:02:08 +0000795 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000796 declarator.setInvalidType(true);
Chris Lattner8f12f652009-05-13 05:02:08 +0000797 break;
Chris Lattner99dc9142008-04-13 18:59:07 +0000798 case DeclSpec::TST_class:
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 case DeclSpec::TST_enum:
800 case DeclSpec::TST_union:
Joao Matos6666ed42012-08-31 18:45:21 +0000801 case DeclSpec::TST_struct:
802 case DeclSpec::TST_interface: {
John McCallb3d87482010-08-24 05:47:05 +0000803 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
John McCall6e247262009-10-10 05:48:19 +0000804 if (!D) {
805 // This can happen in C++ with ambiguous lookups.
806 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000807 declarator.setInvalidType(true);
John McCall6e247262009-10-10 05:48:19 +0000808 break;
809 }
810
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000811 // If the type is deprecated or unavailable, diagnose it.
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000812 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000813
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000815 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000816
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 // TypeQuals handled by caller.
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000818 Result = Context.getTypeDeclType(D);
John McCall2191b202009-09-05 06:31:47 +0000819
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000820 // In both C and C++, make an ElaboratedType.
821 ElaboratedTypeKeyword Keyword
822 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
823 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000824 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000825 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000826 case DeclSpec::TST_typename: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000827 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
828 DS.getTypeSpecSign() == 0 &&
829 "Can't handle qualifiers on typedef names yet!");
John McCall711c52b2011-01-05 12:14:39 +0000830 Result = S.GetTypeFromParser(DS.getRepAsType());
John McCall27940d22010-07-30 05:17:22 +0000831 if (Result.isNull())
John McCall711c52b2011-01-05 12:14:39 +0000832 declarator.setInvalidType(true);
John McCall27940d22010-07-30 05:17:22 +0000833 else if (DeclSpec::ProtocolQualifierListTy PQ
834 = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000835 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
836 // Silently drop any existing protocol qualifiers.
837 // TODO: determine whether that's the right thing to do.
838 if (ObjT->getNumProtocols())
839 Result = ObjT->getBaseType();
840
841 if (DS.getNumProtocolQualifiers())
842 Result = Context.getObjCObjectType(Result,
Roman Divacky31ba6132012-09-06 15:59:27 +0000843 (ObjCProtocolDecl*const*) PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000844 DS.getNumProtocolQualifiers());
845 } else if (Result->isObjCIdType()) {
Chris Lattnerae4da612008-07-26 01:53:50 +0000846 // id<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000847 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
Roman Divacky31ba6132012-09-06 15:59:27 +0000848 (ObjCProtocolDecl*const*) PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000849 DS.getNumProtocolQualifiers());
850 Result = Context.getObjCObjectPointerType(Result);
851 } else if (Result->isObjCClassType()) {
Steve Naroff4262a072009-02-23 18:53:24 +0000852 // Class<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000853 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
Roman Divacky31ba6132012-09-06 15:59:27 +0000854 (ObjCProtocolDecl*const*) PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000855 DS.getNumProtocolQualifiers());
856 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000857 } else {
John McCall711c52b2011-01-05 12:14:39 +0000858 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000859 << DS.getSourceRange();
John McCall711c52b2011-01-05 12:14:39 +0000860 declarator.setInvalidType(true);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000861 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 // TypeQuals handled by caller.
Chris Lattner958858e2008-02-20 21:40:32 +0000865 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 }
Chris Lattner958858e2008-02-20 21:40:32 +0000867 case DeclSpec::TST_typeofType:
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000868 // FIXME: Preserve type source info.
John McCall711c52b2011-01-05 12:14:39 +0000869 Result = S.GetTypeFromParser(DS.getRepAsType());
Chris Lattner958858e2008-02-20 21:40:32 +0000870 assert(!Result.isNull() && "Didn't get a type for typeof?");
Fariborz Jahanian730e1752010-10-06 17:00:02 +0000871 if (!Result->isDependentType())
872 if (const TagType *TT = Result->getAs<TagType>())
John McCall711c52b2011-01-05 12:14:39 +0000873 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
Steve Naroffd1861fd2007-07-31 12:34:36 +0000874 // TypeQuals handled by caller.
Chris Lattnerfab5b452008-02-20 23:53:49 +0000875 Result = Context.getTypeOfType(Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000876 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000877 case DeclSpec::TST_typeofExpr: {
John McCallb3d87482010-08-24 05:47:05 +0000878 Expr *E = DS.getRepAsExpr();
Steve Naroffd1861fd2007-07-31 12:34:36 +0000879 assert(E && "Didn't get an expression for typeof?");
880 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000881 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +0000882 if (Result.isNull()) {
883 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000884 declarator.setInvalidType(true);
Douglas Gregor4b52e252009-12-21 23:17:24 +0000885 }
Chris Lattner958858e2008-02-20 21:40:32 +0000886 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000887 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000888 case DeclSpec::TST_decltype: {
John McCallb3d87482010-08-24 05:47:05 +0000889 Expr *E = DS.getRepAsExpr();
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000890 assert(E && "Didn't get an expression for decltype?");
891 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000892 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
Anders Carlssonaf017e62009-06-29 22:58:55 +0000893 if (Result.isNull()) {
894 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000895 declarator.setInvalidType(true);
Anders Carlssonaf017e62009-06-29 22:58:55 +0000896 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000897 break;
898 }
Sean Huntca63c202011-05-24 22:41:36 +0000899 case DeclSpec::TST_underlyingType:
Sean Huntdb5d44b2011-05-19 05:37:45 +0000900 Result = S.GetTypeFromParser(DS.getRepAsType());
901 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
Sean Huntca63c202011-05-24 22:41:36 +0000902 Result = S.BuildUnaryTransformType(Result,
903 UnaryTransformType::EnumUnderlyingType,
904 DS.getTypeSpecTypeLoc());
905 if (Result.isNull()) {
906 Result = Context.IntTy;
907 declarator.setInvalidType(true);
Sean Huntdb5d44b2011-05-19 05:37:45 +0000908 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000909 break;
Sean Huntdb5d44b2011-05-19 05:37:45 +0000910
Anders Carlssone89d1592009-06-26 18:41:36 +0000911 case DeclSpec::TST_auto: {
912 // TypeQuals handled by caller.
Richard Smith34b41d92011-02-20 03:19:35 +0000913 Result = Context.getAutoType(QualType());
Anders Carlssone89d1592009-06-26 18:41:36 +0000914 break;
915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
John McCalla5fc4722011-04-09 22:50:59 +0000917 case DeclSpec::TST_unknown_anytype:
918 Result = Context.UnknownAnyTy;
919 break;
920
Eli Friedmanb001de72011-10-06 23:00:33 +0000921 case DeclSpec::TST_atomic:
922 Result = S.GetTypeFromParser(DS.getRepAsType());
923 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
924 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
925 if (Result.isNull()) {
926 Result = Context.IntTy;
927 declarator.setInvalidType(true);
928 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000929 break;
Eli Friedmanb001de72011-10-06 23:00:33 +0000930
Guy Benyeib13621d2012-12-18 14:38:23 +0000931 case DeclSpec::TST_image1d_t:
932 Result = Context.OCLImage1dTy;
933 break;
934
935 case DeclSpec::TST_image1d_array_t:
936 Result = Context.OCLImage1dArrayTy;
937 break;
938
939 case DeclSpec::TST_image1d_buffer_t:
940 Result = Context.OCLImage1dBufferTy;
941 break;
942
943 case DeclSpec::TST_image2d_t:
944 Result = Context.OCLImage2dTy;
945 break;
946
947 case DeclSpec::TST_image2d_array_t:
948 Result = Context.OCLImage2dArrayTy;
949 break;
950
951 case DeclSpec::TST_image3d_t:
952 Result = Context.OCLImage3dTy;
953 break;
954
Douglas Gregor809070a2009-02-18 17:45:20 +0000955 case DeclSpec::TST_error:
Chris Lattner5153ee62009-04-25 08:47:54 +0000956 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000957 declarator.setInvalidType(true);
Chris Lattner5153ee62009-04-25 08:47:54 +0000958 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner958858e2008-02-20 21:40:32 +0000961 // Handle complex types.
Douglas Gregorf244cd72009-02-14 21:06:05 +0000962 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000963 if (S.getLangOpts().Freestanding)
John McCall711c52b2011-01-05 12:14:39 +0000964 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
Chris Lattnerfab5b452008-02-20 23:53:49 +0000965 Result = Context.getComplexType(Result);
John Thompson82287d12010-02-05 00:12:22 +0000966 } else if (DS.isTypeAltiVecVector()) {
967 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
968 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
Bob Wilsone86d78c2010-11-10 21:56:12 +0000969 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000970 if (DS.isTypeAltiVecPixel())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000971 VecKind = VectorType::AltiVecPixel;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000972 else if (DS.isTypeAltiVecBool())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000973 VecKind = VectorType::AltiVecBool;
974 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
Douglas Gregorf244cd72009-02-14 21:06:05 +0000975 }
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Argyrios Kyrtzidis47423bd2010-09-23 09:40:31 +0000977 // FIXME: Imaginary.
978 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
John McCall711c52b2011-01-05 12:14:39 +0000979 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
John McCall711c52b2011-01-05 12:14:39 +0000981 // Before we process any type attributes, synthesize a block literal
982 // function declarator if necessary.
983 if (declarator.getContext() == Declarator::BlockLiteralContext)
984 maybeSynthesizeBlockSignature(state, Result);
985
986 // Apply any type attributes from the decl spec. This may cause the
987 // list of type attributes to be temporarily saved while the type
988 // attributes are pushed around.
989 if (AttributeList *attrs = DS.getAttributes().getList())
Richard Smithf7a05272013-01-14 07:53:01 +0000990 processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner96b77fc2008-04-02 06:50:17 +0000992 // Apply const/volatile/restrict qualifiers to T.
993 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
994
995 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
996 // or incomplete types shall not be restrict-qualified." C++ also allows
997 // restrict-qualified references.
John McCall0953e762009-09-24 19:53:00 +0000998 if (TypeQuals & DeclSpec::TQ_restrict) {
Fariborz Jahanian2b5ff1a2009-12-07 18:08:58 +0000999 if (Result->isAnyPointerType() || Result->isReferenceType()) {
1000 QualType EltTy;
1001 if (Result->isObjCObjectPointerType())
1002 EltTy = Result;
1003 else
1004 EltTy = Result->isPointerType() ?
1005 Result->getAs<PointerType>()->getPointeeType() :
1006 Result->getAs<ReferenceType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Douglas Gregorbad0e652009-03-24 20:32:41 +00001008 // If we have a pointer or reference, the pointee must have an object
Chris Lattnerbdcd6372008-04-02 17:35:06 +00001009 // incomplete type.
1010 if (!EltTy->isIncompleteOrObjectType()) {
John McCall711c52b2011-01-05 12:14:39 +00001011 S.Diag(DS.getRestrictSpecLoc(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001012 diag::err_typecheck_invalid_restrict_invalid_pointee)
Chris Lattnerd1625842008-11-24 06:25:27 +00001013 << EltTy << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +00001014 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattnerbdcd6372008-04-02 17:35:06 +00001015 }
1016 } else {
John McCall711c52b2011-01-05 12:14:39 +00001017 S.Diag(DS.getRestrictSpecLoc(),
1018 diag::err_typecheck_invalid_restrict_not_pointer)
Chris Lattnerd1625842008-11-24 06:25:27 +00001019 << Result << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +00001020 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattner96b77fc2008-04-02 06:50:17 +00001021 }
Chris Lattner96b77fc2008-04-02 06:50:17 +00001022 }
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Chris Lattner96b77fc2008-04-02 06:50:17 +00001024 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
1025 // of a function type includes any type qualifiers, the behavior is
1026 // undefined."
1027 if (Result->isFunctionType() && TypeQuals) {
1028 // Get some location to point at, either the C or V location.
1029 SourceLocation Loc;
John McCall0953e762009-09-24 19:53:00 +00001030 if (TypeQuals & DeclSpec::TQ_const)
Chris Lattner96b77fc2008-04-02 06:50:17 +00001031 Loc = DS.getConstSpecLoc();
John McCall0953e762009-09-24 19:53:00 +00001032 else if (TypeQuals & DeclSpec::TQ_volatile)
Chris Lattner96b77fc2008-04-02 06:50:17 +00001033 Loc = DS.getVolatileSpecLoc();
John McCall0953e762009-09-24 19:53:00 +00001034 else {
1035 assert((TypeQuals & DeclSpec::TQ_restrict) &&
1036 "Has CVR quals but not C, V, or R?");
1037 Loc = DS.getRestrictSpecLoc();
Chris Lattner96b77fc2008-04-02 06:50:17 +00001038 }
John McCall711c52b2011-01-05 12:14:39 +00001039 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
Chris Lattnerd1625842008-11-24 06:25:27 +00001040 << Result << DS.getSourceRange();
Chris Lattner96b77fc2008-04-02 06:50:17 +00001041 }
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +00001043 // C++ [dcl.ref]p1:
1044 // Cv-qualified references are ill-formed except when the
1045 // cv-qualifiers are introduced through the use of a typedef
1046 // (7.1.3) or of a template type argument (14.3), in which
1047 // case the cv-qualifiers are ignored.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001048 // FIXME: Shouldn't we be checking SCS_typedef here?
1049 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +00001050 TypeQuals && Result->isReferenceType()) {
John McCall0953e762009-09-24 19:53:00 +00001051 TypeQuals &= ~DeclSpec::TQ_const;
1052 TypeQuals &= ~DeclSpec::TQ_volatile;
Mike Stump1eb44332009-09-09 15:08:12 +00001053 }
1054
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001055 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1056 // than once in the same specifier-list or qualifier-list, either directly
1057 // or via one or more typedefs."
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001058 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001059 && TypeQuals & Result.getCVRQualifiers()) {
1060 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001061 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001062 << "const";
1063 }
1064
1065 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001066 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001067 << "volatile";
1068 }
1069
1070 // C90 doesn't have restrict, so it doesn't force us to produce a warning
1071 // in this case.
1072 }
1073
John McCall0953e762009-09-24 19:53:00 +00001074 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
1075 Result = Context.getQualifiedType(Result, Quals);
Chris Lattner96b77fc2008-04-02 06:50:17 +00001076 }
John McCall0953e762009-09-24 19:53:00 +00001077
Chris Lattnerf1d705c2008-02-21 01:07:18 +00001078 return Result;
1079}
1080
Douglas Gregorcd281c32009-02-28 00:25:32 +00001081static std::string getPrintableNameForEntity(DeclarationName Entity) {
1082 if (Entity)
1083 return Entity.getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Douglas Gregorcd281c32009-02-28 00:25:32 +00001085 return "type name";
1086}
1087
John McCall28654742010-06-05 06:41:15 +00001088QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1089 Qualifiers Qs) {
1090 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1091 // object or incomplete types shall not be restrict-qualified."
1092 if (Qs.hasRestrict()) {
1093 unsigned DiagID = 0;
1094 QualType ProblemTy;
1095
1096 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
1097 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
1098 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
1099 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1100 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
1101 }
1102 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1103 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1104 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1105 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1106 }
1107 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1108 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1109 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1110 ProblemTy = T->getAs<PointerType>()->getPointeeType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001111 }
John McCall28654742010-06-05 06:41:15 +00001112 } else if (!Ty->isDependentType()) {
1113 // FIXME: this deserves a proper diagnostic
1114 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1115 ProblemTy = T;
1116 }
1117
1118 if (DiagID) {
1119 Diag(Loc, DiagID) << ProblemTy;
1120 Qs.removeRestrict();
1121 }
1122 }
1123
1124 return Context.getQualifiedType(T, Qs);
1125}
1126
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001127/// \brief Build a paren type including \p T.
1128QualType Sema::BuildParenType(QualType T) {
1129 return Context.getParenType(T);
1130}
1131
John McCallf85e1932011-06-15 23:02:42 +00001132/// Given that we're building a pointer or reference to the given
1133static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1134 SourceLocation loc,
1135 bool isReference) {
1136 // Bail out if retention is unrequired or already specified.
1137 if (!type->isObjCLifetimeType() ||
1138 type.getObjCLifetime() != Qualifiers::OCL_None)
1139 return type;
1140
1141 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1142
1143 // If the object type is const-qualified, we can safely use
1144 // __unsafe_unretained. This is safe (because there are no read
1145 // barriers), and it'll be safe to coerce anything but __weak* to
1146 // the resulting type.
1147 if (type.isConstQualified()) {
1148 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1149
1150 // Otherwise, check whether the static type does not require
1151 // retaining. This currently only triggers for Class (possibly
1152 // protocol-qualifed, and arrays thereof).
1153 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1154 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1155
Eli Friedmanef331b72012-01-20 01:26:23 +00001156 // If we are in an unevaluated context, like sizeof, skip adding a
1157 // qualification.
David Blaikie71f55f72012-08-06 22:47:24 +00001158 } else if (S.isUnevaluatedContext()) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001159 return type;
Argyrios Kyrtzidis5b76f372011-09-20 23:49:22 +00001160
John McCalle8c904f2012-01-26 20:04:03 +00001161 // If that failed, give an error and recover using __strong. __strong
1162 // is the option most likely to prevent spurious second-order diagnostics,
1163 // like when binding a reference to a field.
John McCallf85e1932011-06-15 23:02:42 +00001164 } else {
1165 // These types can show up in private ivars in system headers, so
1166 // we need this to not be an error in those cases. Instead we
1167 // want to delay.
1168 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001169 S.DelayedDiagnostics.add(
1170 sema::DelayedDiagnostic::makeForbiddenType(loc,
1171 diag::err_arc_indirect_no_ownership, type, isReference));
John McCallf85e1932011-06-15 23:02:42 +00001172 } else {
Eli Friedmanef331b72012-01-20 01:26:23 +00001173 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
John McCallf85e1932011-06-15 23:02:42 +00001174 }
John McCalle8c904f2012-01-26 20:04:03 +00001175 implicitLifetime = Qualifiers::OCL_Strong;
John McCallf85e1932011-06-15 23:02:42 +00001176 }
1177 assert(implicitLifetime && "didn't infer any lifetime!");
1178
1179 Qualifiers qs;
1180 qs.addObjCLifetime(implicitLifetime);
1181 return S.Context.getQualifiedType(type, qs);
1182}
1183
Douglas Gregorcd281c32009-02-28 00:25:32 +00001184/// \brief Build a pointer type.
1185///
1186/// \param T The type to which we'll be building a pointer.
1187///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001188/// \param Loc The location of the entity whose type involves this
1189/// pointer type or, if there is no such entity, the location of the
1190/// type that will have pointer type.
1191///
1192/// \param Entity The name of the entity that involves the pointer
1193/// type, if known.
1194///
1195/// \returns A suitable pointer type, if there are no
1196/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001197QualType Sema::BuildPointerType(QualType T,
Douglas Gregorcd281c32009-02-28 00:25:32 +00001198 SourceLocation Loc, DeclarationName Entity) {
1199 if (T->isReferenceType()) {
1200 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1201 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001202 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001203 return QualType();
1204 }
1205
John McCallc12c5bb2010-05-15 11:32:37 +00001206 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
Douglas Gregor92e986e2010-04-22 16:44:27 +00001207
John McCallf85e1932011-06-15 23:02:42 +00001208 // In ARC, it is forbidden to build pointers to unqualified pointers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001209 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001210 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1211
Douglas Gregorcd281c32009-02-28 00:25:32 +00001212 // Build the pointer type.
John McCall28654742010-06-05 06:41:15 +00001213 return Context.getPointerType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001214}
1215
1216/// \brief Build a reference type.
1217///
1218/// \param T The type to which we'll be building a reference.
1219///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001220/// \param Loc The location of the entity whose type involves this
1221/// reference type or, if there is no such entity, the location of the
1222/// type that will have reference type.
1223///
1224/// \param Entity The name of the entity that involves the reference
1225/// type, if known.
1226///
1227/// \returns A suitable reference type, if there are no
1228/// errors. Otherwise, returns a NULL type.
John McCall54e14c42009-10-22 22:37:11 +00001229QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
John McCall28654742010-06-05 06:41:15 +00001230 SourceLocation Loc,
John McCall54e14c42009-10-22 22:37:11 +00001231 DeclarationName Entity) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001232 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
Douglas Gregor9625e442011-05-21 22:16:50 +00001233 "Unresolved overloaded function type");
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001234
Douglas Gregor69d83162011-01-20 16:08:06 +00001235 // C++0x [dcl.ref]p6:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001236 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1237 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1238 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1239 // the type "lvalue reference to T", while an attempt to create the type
Douglas Gregor69d83162011-01-20 16:08:06 +00001240 // "rvalue reference to cv TR" creates the type TR.
John McCall54e14c42009-10-22 22:37:11 +00001241 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1242
John McCall54e14c42009-10-22 22:37:11 +00001243 // C++ [dcl.ref]p4: There shall be no references to references.
1244 //
1245 // According to C++ DR 106, references to references are only
1246 // diagnosed when they are written directly (e.g., "int & &"),
1247 // but not when they happen via a typedef:
1248 //
1249 // typedef int& intref;
1250 // typedef intref& intref2;
1251 //
1252 // Parser::ParseDeclaratorInternal diagnoses the case where
1253 // references are written directly; here, we handle the
Douglas Gregor69d83162011-01-20 16:08:06 +00001254 // collapsing of references-to-references as described in C++0x.
1255 // DR 106 and 540 introduce reference-collapsing into C++98/03.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001256
1257 // C++ [dcl.ref]p1:
Eli Friedman33a31382009-08-05 19:21:58 +00001258 // A declarator that specifies the type "reference to cv void"
Douglas Gregorcd281c32009-02-28 00:25:32 +00001259 // is ill-formed.
1260 if (T->isVoidType()) {
1261 Diag(Loc, diag::err_reference_to_void);
1262 return QualType();
1263 }
1264
John McCallf85e1932011-06-15 23:02:42 +00001265 // In ARC, it is forbidden to build references to unqualified pointers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001266 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001267 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1268
Douglas Gregorcd281c32009-02-28 00:25:32 +00001269 // Handle restrict on references.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001270 if (LValueRef)
John McCall28654742010-06-05 06:41:15 +00001271 return Context.getLValueReferenceType(T, SpelledAsLValue);
1272 return Context.getRValueReferenceType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001273}
1274
Chris Lattnere1eed382011-06-14 06:38:10 +00001275/// Check whether the specified array size makes the array type a VLA. If so,
1276/// return true, if not, return the size of the array in SizeVal.
Richard Smith282e7e62012-02-04 09:53:13 +00001277static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1278 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1279 // (like gnu99, but not c99) accept any evaluatable value as an extension.
Douglas Gregorab41fe92012-05-04 22:38:52 +00001280 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1281 public:
1282 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001283
Douglas Gregorab41fe92012-05-04 22:38:52 +00001284 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1285 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001286
Douglas Gregorab41fe92012-05-04 22:38:52 +00001287 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) {
1288 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1289 }
1290 } Diagnoser;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001291
Douglas Gregorab41fe92012-05-04 22:38:52 +00001292 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1293 S.LangOpts.GNUMode).isInvalid();
Chris Lattnere1eed382011-06-14 06:38:10 +00001294}
1295
1296
Douglas Gregorcd281c32009-02-28 00:25:32 +00001297/// \brief Build an array type.
1298///
1299/// \param T The type of each element in the array.
1300///
1301/// \param ASM C99 array size modifier (e.g., '*', 'static').
Mike Stump1eb44332009-09-09 15:08:12 +00001302///
1303/// \param ArraySize Expression describing the size of the array.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001304///
James Dennettefce31f2012-06-22 08:10:18 +00001305/// \param Brackets The range from the opening '[' to the closing ']'.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001306///
1307/// \param Entity The name of the entity that involves the array
1308/// type, if known.
1309///
1310/// \returns A suitable array type, if there are no errors. Otherwise,
1311/// returns a NULL type.
1312QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1313 Expr *ArraySize, unsigned Quals,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001314 SourceRange Brackets, DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001315
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001316 SourceLocation Loc = Brackets.getBegin();
David Blaikie4e4d0842012-03-11 07:00:24 +00001317 if (getLangOpts().CPlusPlus) {
Douglas Gregor138bb232010-04-27 19:38:14 +00001318 // C++ [dcl.array]p1:
1319 // T is called the array element type; this type shall not be a reference
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001320 // type, the (possibly cv-qualified) type void, a function type or an
Douglas Gregor138bb232010-04-27 19:38:14 +00001321 // abstract class type.
1322 //
Richard Smithbb351512012-07-07 23:00:31 +00001323 // C++ [dcl.array]p3:
1324 // When several "array of" specifications are adjacent, [...] only the
1325 // first of the constant expressions that specify the bounds of the arrays
1326 // may be omitted.
1327 //
Douglas Gregor138bb232010-04-27 19:38:14 +00001328 // Note: function types are handled in the common path with C.
1329 if (T->isReferenceType()) {
1330 Diag(Loc, diag::err_illegal_decl_array_of_references)
1331 << getPrintableNameForEntity(Entity) << T;
1332 return QualType();
1333 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001334
Richard Smithbb351512012-07-07 23:00:31 +00001335 if (T->isVoidType() || T->isIncompleteArrayType()) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001336 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1337 return QualType();
1338 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001339
1340 if (RequireNonAbstractType(Brackets.getBegin(), T,
Douglas Gregor138bb232010-04-27 19:38:14 +00001341 diag::err_array_of_abstract_type))
1342 return QualType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001343
Sebastian Redl923d56d2009-11-05 15:52:31 +00001344 } else {
Douglas Gregor138bb232010-04-27 19:38:14 +00001345 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1346 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
Sebastian Redl923d56d2009-11-05 15:52:31 +00001347 if (RequireCompleteType(Loc, T,
1348 diag::err_illegal_decl_array_incomplete_type))
1349 return QualType();
1350 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001351
1352 if (T->isFunctionType()) {
1353 Diag(Loc, diag::err_illegal_decl_array_of_functions)
John McCallac406052009-10-30 00:37:20 +00001354 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001355 return QualType();
1356 }
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Richard Smith34b41d92011-02-20 03:19:35 +00001358 if (T->getContainedAutoType()) {
1359 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1360 << getPrintableNameForEntity(Entity) << T;
Anders Carlssone7cf07d2009-06-26 19:33:28 +00001361 return QualType();
1362 }
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Ted Kremenek6217b802009-07-29 21:53:49 +00001364 if (const RecordType *EltTy = T->getAs<RecordType>()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001365 // If the element type is a struct or union that contains a variadic
1366 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1367 if (EltTy->getDecl()->hasFlexibleArrayMember())
1368 Diag(Loc, diag::ext_flexible_array_in_array) << T;
John McCallc12c5bb2010-05-15 11:32:37 +00001369 } else if (T->isObjCObjectType()) {
Chris Lattnerc7c11b12009-04-27 01:55:56 +00001370 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1371 return QualType();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001372 }
Mike Stump1eb44332009-09-09 15:08:12 +00001373
John McCall806054d2012-01-11 00:14:46 +00001374 // Do placeholder conversions on the array size expression.
1375 if (ArraySize && ArraySize->hasPlaceholderType()) {
1376 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1377 if (Result.isInvalid()) return QualType();
1378 ArraySize = Result.take();
1379 }
1380
John McCall5e3c67b2010-12-15 04:42:30 +00001381 // Do lvalue-to-rvalue conversions on the array size expression.
John Wiegley429bb272011-04-08 18:41:53 +00001382 if (ArraySize && !ArraySize->isRValue()) {
1383 ExprResult Result = DefaultLvalueConversion(ArraySize);
1384 if (Result.isInvalid())
1385 return QualType();
1386
1387 ArraySize = Result.take();
1388 }
John McCall5e3c67b2010-12-15 04:42:30 +00001389
Douglas Gregorcd281c32009-02-28 00:25:32 +00001390 // C99 6.7.5.2p1: The size expression shall have integer type.
Richard Smith282e7e62012-02-04 09:53:13 +00001391 // C++11 allows contextual conversions to such types.
Richard Smith80ad52f2013-01-02 11:42:31 +00001392 if (!getLangOpts().CPlusPlus11 &&
Richard Smith282e7e62012-02-04 09:53:13 +00001393 ArraySize && !ArraySize->isTypeDependent() &&
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001394 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001395 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1396 << ArraySize->getType() << ArraySize->getSourceRange();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001397 return QualType();
1398 }
Richard Smith282e7e62012-02-04 09:53:13 +00001399
Douglas Gregor2767ce22010-08-18 00:39:00 +00001400 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
Douglas Gregorcd281c32009-02-28 00:25:32 +00001401 if (!ArraySize) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001402 if (ASM == ArrayType::Star)
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001403 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001404 else
1405 T = Context.getIncompleteArrayType(T, ASM, Quals);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00001406 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001407 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
Richard Smith282e7e62012-02-04 09:53:13 +00001408 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1409 !T->isConstantSizeType()) ||
1410 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1411 // Even in C++11, don't allow contextual conversions in the array bound
1412 // of a VLA.
Richard Smith80ad52f2013-01-02 11:42:31 +00001413 if (getLangOpts().CPlusPlus11 &&
Richard Smith282e7e62012-02-04 09:53:13 +00001414 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1415 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1416 << ArraySize->getType() << ArraySize->getSourceRange();
1417 return QualType();
1418 }
1419
Chris Lattnere1eed382011-06-14 06:38:10 +00001420 // C99: an array with an element type that has a non-constant-size is a VLA.
Chris Lattnere1eed382011-06-14 06:38:10 +00001421 // C99: an array with a non-ICE size is a VLA. We accept any expression
1422 // that we can fold to a non-zero positive value as an extension.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001423 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001424 } else {
1425 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1426 // have a value greater than zero.
Sebastian Redl923d56d2009-11-05 15:52:31 +00001427 if (ConstVal.isSigned() && ConstVal.isNegative()) {
Chandler Carruthb2b5cc02011-01-04 04:44:35 +00001428 if (Entity)
1429 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1430 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1431 else
1432 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1433 << ArraySize->getSourceRange();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001434 return QualType();
1435 }
1436 if (ConstVal == 0) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001437 // GCC accepts zero sized static arrays. We allow them when
1438 // we're not in a SFINAE context.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001439 Diag(ArraySize->getLocStart(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001440 isSFINAEContext()? diag::err_typecheck_zero_array_size
1441 : diag::ext_typecheck_zero_array_size)
Sebastian Redl923d56d2009-11-05 15:52:31 +00001442 << ArraySize->getSourceRange();
Peter Collingbourne20cdbeb2011-10-16 21:17:32 +00001443
1444 if (ASM == ArrayType::Static) {
1445 Diag(ArraySize->getLocStart(),
1446 diag::warn_typecheck_zero_static_array_size)
1447 << ArraySize->getSourceRange();
1448 ASM = ArrayType::Normal;
1449 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001450 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
Douglas Gregor2767ce22010-08-18 00:39:00 +00001451 !T->isIncompleteType()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001452 // Is the array too large?
Douglas Gregor2767ce22010-08-18 00:39:00 +00001453 unsigned ActiveSizeBits
1454 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1455 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1456 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1457 << ConstVal.toString(10)
1458 << ArraySize->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001459 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001460
John McCall46a617a2009-10-16 00:14:28 +00001461 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001462 }
Joey Gouly617bb312013-01-17 17:35:00 +00001463
1464 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1465 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1466 Diag(Loc, diag::err_opencl_vla);
1467 return QualType();
1468 }
David Chisnallaf407762010-01-11 23:08:08 +00001469 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001470 if (!getLangOpts().C99) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001471 if (T->isVariableArrayType()) {
1472 // Prohibit the use of non-POD types in VLAs.
John McCallf85e1932011-06-15 23:02:42 +00001473 QualType BaseT = Context.getBaseElementType(T);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001474 if (!T->isDependentType() &&
Douglas Gregor3c7236e2013-01-08 00:01:45 +00001475 !BaseT.isPODType(Context) &&
1476 !BaseT->isObjCLifetimeType()) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001477 Diag(Loc, diag::err_vla_non_pod)
John McCallf85e1932011-06-15 23:02:42 +00001478 << BaseT;
Douglas Gregor0fddb972010-05-22 16:17:30 +00001479 return QualType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001480 }
Douglas Gregora481ec42010-05-23 19:57:01 +00001481 // Prohibit the use of VLAs during template argument deduction.
1482 else if (isSFINAEContext()) {
1483 Diag(Loc, diag::err_vla_in_sfinae);
1484 return QualType();
1485 }
Douglas Gregor0fddb972010-05-22 16:17:30 +00001486 // Just extwarn about VLAs.
1487 else
1488 Diag(Loc, diag::ext_vla);
1489 } else if (ASM != ArrayType::Normal || Quals != 0)
Richard Smithd7c56e12011-12-29 21:57:33 +00001490 Diag(Loc,
David Blaikie4e4d0842012-03-11 07:00:24 +00001491 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
Richard Smithd7c56e12011-12-29 21:57:33 +00001492 : diag::ext_c99_array_usage) << ASM;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001493 }
1494
1495 return T;
1496}
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001497
1498/// \brief Build an ext-vector type.
1499///
1500/// Run the required checks for the extended vector type.
John McCall9ae2f072010-08-23 23:25:46 +00001501QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001502 SourceLocation AttrLoc) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001503 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1504 // in conjunction with complex types (pointers, arrays, functions, etc.).
Mike Stump1eb44332009-09-09 15:08:12 +00001505 if (!T->isDependentType() &&
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001506 !T->isIntegerType() && !T->isRealFloatingType()) {
1507 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1508 return QualType();
1509 }
1510
John McCall9ae2f072010-08-23 23:25:46 +00001511 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001512 llvm::APSInt vecSize(32);
John McCall9ae2f072010-08-23 23:25:46 +00001513 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001514 Diag(AttrLoc, diag::err_attribute_argument_not_int)
John McCall9ae2f072010-08-23 23:25:46 +00001515 << "ext_vector_type" << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001516 return QualType();
1517 }
Mike Stump1eb44332009-09-09 15:08:12 +00001518
1519 // unlike gcc's vector_size attribute, the size is specified as the
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001520 // number of elements, not the number of bytes.
Mike Stump1eb44332009-09-09 15:08:12 +00001521 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1522
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001523 if (vectorSize == 0) {
1524 Diag(AttrLoc, diag::err_attribute_zero_size)
John McCall9ae2f072010-08-23 23:25:46 +00001525 << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001526 return QualType();
1527 }
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Douglas Gregor4ac01402011-06-15 16:02:29 +00001529 return Context.getExtVectorType(T, vectorSize);
Mike Stump1eb44332009-09-09 15:08:12 +00001530 }
1531
John McCall9ae2f072010-08-23 23:25:46 +00001532 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001533}
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Douglas Gregor724651c2009-02-28 01:04:19 +00001535/// \brief Build a function type.
1536///
1537/// This routine checks the function type according to C++ rules and
1538/// under the assumption that the result type and parameter types have
1539/// just been instantiated from a template. It therefore duplicates
Douglas Gregor2943aed2009-03-03 04:44:36 +00001540/// some of the behavior of GetTypeForDeclarator, but in a much
Douglas Gregor724651c2009-02-28 01:04:19 +00001541/// simpler form that is only suitable for this narrow use case.
1542///
1543/// \param T The return type of the function.
1544///
1545/// \param ParamTypes The parameter types of the function. This array
1546/// will be modified to account for adjustments to the types of the
1547/// function parameters.
1548///
1549/// \param NumParamTypes The number of parameter types in ParamTypes.
1550///
1551/// \param Variadic Whether this is a variadic function type.
1552///
Richard Smitheefb3d52012-02-10 09:58:53 +00001553/// \param HasTrailingReturn Whether this function has a trailing return type.
1554///
Douglas Gregor724651c2009-02-28 01:04:19 +00001555/// \param Quals The cvr-qualifiers to be applied to the function type.
1556///
1557/// \param Loc The location of the entity whose type involves this
1558/// function type or, if there is no such entity, the location of the
1559/// type that will have function type.
1560///
1561/// \param Entity The name of the entity that involves the function
1562/// type, if known.
1563///
1564/// \returns A suitable function type, if there are no
1565/// errors. Otherwise, returns a NULL type.
1566QualType Sema::BuildFunctionType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001567 QualType *ParamTypes,
Douglas Gregor724651c2009-02-28 01:04:19 +00001568 unsigned NumParamTypes,
Richard Smitheefb3d52012-02-10 09:58:53 +00001569 bool Variadic, bool HasTrailingReturn,
1570 unsigned Quals,
Douglas Gregorc938c162011-01-26 05:01:58 +00001571 RefQualifierKind RefQualifier,
Eli Friedmanfa869542010-08-05 02:54:05 +00001572 SourceLocation Loc, DeclarationName Entity,
John McCalle23cf432010-12-14 08:05:40 +00001573 FunctionType::ExtInfo Info) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001574 if (T->isArrayType() || T->isFunctionType()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001575 Diag(Loc, diag::err_func_returning_array_function)
Douglas Gregor58408bc2010-01-11 18:46:21 +00001576 << T->isFunctionType() << T;
Douglas Gregor724651c2009-02-28 01:04:19 +00001577 return QualType();
1578 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001579
1580 // Functions cannot return half FP.
1581 if (T->isHalfType()) {
1582 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1583 FixItHint::CreateInsertion(Loc, "*");
1584 return QualType();
1585 }
1586
Douglas Gregor724651c2009-02-28 01:04:19 +00001587 bool Invalid = false;
1588 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001589 // FIXME: Loc is too inprecise here, should use proper locations for args.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00001590 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001591 if (ParamType->isVoidType()) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001592 Diag(Loc, diag::err_param_with_void_type);
1593 Invalid = true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001594 } else if (ParamType->isHalfType()) {
1595 // Disallow half FP arguments.
1596 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1597 FixItHint::CreateInsertion(Loc, "*");
1598 Invalid = true;
Douglas Gregor724651c2009-02-28 01:04:19 +00001599 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001600
John McCall54e14c42009-10-22 22:37:11 +00001601 ParamTypes[Idx] = ParamType;
Douglas Gregor724651c2009-02-28 01:04:19 +00001602 }
1603
1604 if (Invalid)
1605 return QualType();
1606
John McCalle23cf432010-12-14 08:05:40 +00001607 FunctionProtoType::ExtProtoInfo EPI;
1608 EPI.Variadic = Variadic;
Richard Smitheefb3d52012-02-10 09:58:53 +00001609 EPI.HasTrailingReturn = HasTrailingReturn;
John McCalle23cf432010-12-14 08:05:40 +00001610 EPI.TypeQuals = Quals;
Douglas Gregorc938c162011-01-26 05:01:58 +00001611 EPI.RefQualifier = RefQualifier;
John McCalle23cf432010-12-14 08:05:40 +00001612 EPI.ExtInfo = Info;
1613
1614 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
Douglas Gregor724651c2009-02-28 01:04:19 +00001615}
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Douglas Gregor949bf692009-06-09 22:17:39 +00001617/// \brief Build a member pointer type \c T Class::*.
1618///
1619/// \param T the type to which the member pointer refers.
1620/// \param Class the class type into which the member pointer points.
Douglas Gregor949bf692009-06-09 22:17:39 +00001621/// \param Loc the location where this type begins
1622/// \param Entity the name of the entity that will have this member pointer type
1623///
1624/// \returns a member pointer type, if successful, or a NULL type if there was
1625/// an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001626QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
John McCall28654742010-06-05 06:41:15 +00001627 SourceLocation Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +00001628 DeclarationName Entity) {
1629 // Verify that we're not building a pointer to pointer to function with
1630 // exception specification.
1631 if (CheckDistantExceptionSpec(T)) {
1632 Diag(Loc, diag::err_distant_exception_spec);
1633
1634 // FIXME: If we're doing this as part of template instantiation,
1635 // we should return immediately.
1636
1637 // Build the type anyway, but use the canonical type so that the
1638 // exception specifiers are stripped off.
1639 T = Context.getCanonicalType(T);
1640 }
1641
Sebastian Redl73780122010-06-09 21:19:43 +00001642 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
Douglas Gregor949bf692009-06-09 22:17:39 +00001643 // with reference type, or "cv void."
1644 if (T->isReferenceType()) {
Anders Carlsson8d4655d2009-06-30 00:06:57 +00001645 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001646 << (Entity? Entity.getAsString() : "type name") << T;
Douglas Gregor949bf692009-06-09 22:17:39 +00001647 return QualType();
1648 }
1649
1650 if (T->isVoidType()) {
1651 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1652 << (Entity? Entity.getAsString() : "type name");
1653 return QualType();
1654 }
1655
Douglas Gregor949bf692009-06-09 22:17:39 +00001656 if (!Class->isDependentType() && !Class->isRecordType()) {
1657 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1658 return QualType();
1659 }
1660
Joao Matos679fc932012-09-04 17:18:12 +00001661 // In the Microsoft ABI, the class is allowed to be an incomplete
1662 // type. In such cases, the compiler makes a worst-case assumption.
1663 // We make no such assumption right now, so emit an error if the
1664 // class isn't a complete type.
1665 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
1666 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1667 return QualType();
1668
John McCall28654742010-06-05 06:41:15 +00001669 return Context.getMemberPointerType(T, Class.getTypePtr());
Douglas Gregor949bf692009-06-09 22:17:39 +00001670}
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Anders Carlsson9a917e42009-06-12 22:56:54 +00001672/// \brief Build a block pointer type.
1673///
1674/// \param T The type to which we'll be building a block pointer.
1675///
James Dennettefce31f2012-06-22 08:10:18 +00001676/// \param Loc The source location, used for diagnostics.
Anders Carlsson9a917e42009-06-12 22:56:54 +00001677///
Anders Carlsson9a917e42009-06-12 22:56:54 +00001678/// \param Entity The name of the entity that involves the block pointer
1679/// type, if known.
1680///
1681/// \returns A suitable block pointer type, if there are no
1682/// errors. Otherwise, returns a NULL type.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001683QualType Sema::BuildBlockPointerType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001684 SourceLocation Loc,
Anders Carlsson9a917e42009-06-12 22:56:54 +00001685 DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001686 if (!T->isFunctionType()) {
Anders Carlsson9a917e42009-06-12 22:56:54 +00001687 Diag(Loc, diag::err_nonfunction_block_type);
1688 return QualType();
1689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690
John McCall28654742010-06-05 06:41:15 +00001691 return Context.getBlockPointerType(T);
Anders Carlsson9a917e42009-06-12 22:56:54 +00001692}
1693
John McCallb3d87482010-08-24 05:47:05 +00001694QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1695 QualType QT = Ty.get();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001696 if (QT.isNull()) {
John McCalla93c9342009-12-07 02:54:59 +00001697 if (TInfo) *TInfo = 0;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001698 return QualType();
1699 }
1700
John McCalla93c9342009-12-07 02:54:59 +00001701 TypeSourceInfo *DI = 0;
John McCallf4c73712011-01-19 06:33:43 +00001702 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001703 QT = LIT->getType();
John McCalla93c9342009-12-07 02:54:59 +00001704 DI = LIT->getTypeSourceInfo();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
John McCalla93c9342009-12-07 02:54:59 +00001707 if (TInfo) *TInfo = DI;
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001708 return QT;
1709}
1710
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001711static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1712 Qualifiers::ObjCLifetime ownership,
1713 unsigned chunkIndex);
1714
John McCallf85e1932011-06-15 23:02:42 +00001715/// Given that this is the declaration of a parameter under ARC,
1716/// attempt to infer attributes and such for pointer-to-whatever
1717/// types.
1718static void inferARCWriteback(TypeProcessingState &state,
1719 QualType &declSpecType) {
1720 Sema &S = state.getSema();
1721 Declarator &declarator = state.getDeclarator();
1722
1723 // TODO: should we care about decl qualifiers?
1724
1725 // Check whether the declarator has the expected form. We walk
1726 // from the inside out in order to make the block logic work.
1727 unsigned outermostPointerIndex = 0;
1728 bool isBlockPointer = false;
1729 unsigned numPointers = 0;
1730 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1731 unsigned chunkIndex = i;
1732 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1733 switch (chunk.Kind) {
1734 case DeclaratorChunk::Paren:
1735 // Ignore parens.
1736 break;
1737
1738 case DeclaratorChunk::Reference:
1739 case DeclaratorChunk::Pointer:
1740 // Count the number of pointers. Treat references
1741 // interchangeably as pointers; if they're mis-ordered, normal
1742 // type building will discover that.
1743 outermostPointerIndex = chunkIndex;
1744 numPointers++;
1745 break;
1746
1747 case DeclaratorChunk::BlockPointer:
1748 // If we have a pointer to block pointer, that's an acceptable
1749 // indirect reference; anything else is not an application of
1750 // the rules.
1751 if (numPointers != 1) return;
1752 numPointers++;
1753 outermostPointerIndex = chunkIndex;
1754 isBlockPointer = true;
1755
1756 // We don't care about pointer structure in return values here.
1757 goto done;
1758
1759 case DeclaratorChunk::Array: // suppress if written (id[])?
1760 case DeclaratorChunk::Function:
1761 case DeclaratorChunk::MemberPointer:
1762 return;
1763 }
1764 }
1765 done:
1766
1767 // If we have *one* pointer, then we want to throw the qualifier on
1768 // the declaration-specifiers, which means that it needs to be a
1769 // retainable object type.
1770 if (numPointers == 1) {
1771 // If it's not a retainable object type, the rule doesn't apply.
1772 if (!declSpecType->isObjCRetainableType()) return;
1773
1774 // If it already has lifetime, don't do anything.
1775 if (declSpecType.getObjCLifetime()) return;
1776
1777 // Otherwise, modify the type in-place.
1778 Qualifiers qs;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001779
John McCallf85e1932011-06-15 23:02:42 +00001780 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1781 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1782 else
1783 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1784 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1785
1786 // If we have *two* pointers, then we want to throw the qualifier on
1787 // the outermost pointer.
1788 } else if (numPointers == 2) {
1789 // If we don't have a block pointer, we need to check whether the
1790 // declaration-specifiers gave us something that will turn into a
1791 // retainable object pointer after we slap the first pointer on it.
1792 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1793 return;
1794
1795 // Look for an explicit lifetime attribute there.
1796 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
Argyrios Kyrtzidis1c73dcb2011-07-01 22:23:03 +00001797 if (chunk.Kind != DeclaratorChunk::Pointer &&
1798 chunk.Kind != DeclaratorChunk::BlockPointer)
1799 return;
John McCallf85e1932011-06-15 23:02:42 +00001800 for (const AttributeList *attr = chunk.getAttrs(); attr;
1801 attr = attr->getNext())
Sean Hunt8e083e72012-06-19 23:57:03 +00001802 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
John McCallf85e1932011-06-15 23:02:42 +00001803 return;
1804
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001805 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1806 outermostPointerIndex);
John McCallf85e1932011-06-15 23:02:42 +00001807
1808 // Any other number of pointers/references does not trigger the rule.
1809 } else return;
1810
1811 // TODO: mark whether we did this inference?
1812}
1813
Chandler Carruthd067c072011-02-23 18:51:59 +00001814static void DiagnoseIgnoredQualifiers(unsigned Quals,
1815 SourceLocation ConstQualLoc,
1816 SourceLocation VolatileQualLoc,
1817 SourceLocation RestrictQualLoc,
1818 Sema& S) {
1819 std::string QualStr;
1820 unsigned NumQuals = 0;
1821 SourceLocation Loc;
1822
1823 FixItHint ConstFixIt;
1824 FixItHint VolatileFixIt;
1825 FixItHint RestrictFixIt;
1826
Hans Wennborga08fcb82011-06-03 17:37:26 +00001827 const SourceManager &SM = S.getSourceManager();
1828
Chandler Carruthd067c072011-02-23 18:51:59 +00001829 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1830 // find a range and grow it to encompass all the qualifiers, regardless of
1831 // the order in which they textually appear.
1832 if (Quals & Qualifiers::Const) {
1833 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
Chandler Carruthd067c072011-02-23 18:51:59 +00001834 QualStr = "const";
Hans Wennborga08fcb82011-06-03 17:37:26 +00001835 ++NumQuals;
1836 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1837 Loc = ConstQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001838 }
1839 if (Quals & Qualifiers::Volatile) {
1840 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001841 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
Chandler Carruthd067c072011-02-23 18:51:59 +00001842 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001843 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1844 Loc = VolatileQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001845 }
1846 if (Quals & Qualifiers::Restrict) {
1847 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001848 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
Chandler Carruthd067c072011-02-23 18:51:59 +00001849 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001850 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1851 Loc = RestrictQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001852 }
1853
1854 assert(NumQuals > 0 && "No known qualifiers?");
1855
1856 S.Diag(Loc, diag::warn_qual_return_type)
Hans Wennborga08fcb82011-06-03 17:37:26 +00001857 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
Chandler Carruthd067c072011-02-23 18:51:59 +00001858}
1859
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001860static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1861 TypeSourceInfo *&ReturnTypeInfo) {
1862 Sema &SemaRef = state.getSema();
1863 Declarator &D = state.getDeclarator();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001864 QualType T;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001865 ReturnTypeInfo = 0;
1866
1867 // The TagDecl owned by the DeclSpec.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001868 TagDecl *OwnedTagDecl = 0;
John McCall711c52b2011-01-05 12:14:39 +00001869
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001870 switch (D.getName().getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001871 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001872 case UnqualifiedId::IK_OperatorFunctionId:
Sebastian Redl8999fe12011-03-14 18:08:30 +00001873 case UnqualifiedId::IK_Identifier:
Sean Hunt0486d742009-11-28 04:44:28 +00001874 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001875 case UnqualifiedId::IK_TemplateId:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001876 T = ConvertDeclSpecToType(state);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001877
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001878 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001879 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Abramo Bagnara15987972011-03-08 22:33:38 +00001880 // Owned declaration is embedded in declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001881 OwnedTagDecl->setEmbeddedInDeclarator(true);
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001882 }
Douglas Gregor930d8b52009-01-30 22:09:00 +00001883 break;
1884
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001885 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001886 case UnqualifiedId::IK_ConstructorTemplateId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001887 case UnqualifiedId::IK_DestructorName:
Douglas Gregor930d8b52009-01-30 22:09:00 +00001888 // Constructors and destructors don't have return types. Use
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001889 // "void" instead.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001890 T = SemaRef.Context.VoidTy;
Rafael Espindolaa78a6402012-07-31 01:54:04 +00001891 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
Richard Smithf7a05272013-01-14 07:53:01 +00001892 processTypeAttrs(state, T, TAL_DeclSpec, attrs);
Douglas Gregor930d8b52009-01-30 22:09:00 +00001893 break;
Douglas Gregor48026d22010-01-11 18:40:55 +00001894
1895 case UnqualifiedId::IK_ConversionFunctionId:
1896 // The result type of a conversion function is the type that it
1897 // converts to.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001898 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001899 &ReturnTypeInfo);
Douglas Gregor48026d22010-01-11 18:40:55 +00001900 break;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001901 }
Douglas Gregordab60ad2010-10-01 18:44:50 +00001902
John McCall711c52b2011-01-05 12:14:39 +00001903 if (D.getAttributes())
1904 distributeTypeAttrsFromDeclarator(state, T);
1905
Richard Smithd37b3602012-02-10 11:05:11 +00001906 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1907 // In C++11, a function declarator using 'auto' must have a trailing return
Richard Smith8110f042011-02-22 01:22:29 +00001908 // type (this is checked later) and we can skip this. In other languages
1909 // using auto, we need to check regardless.
Richard Smith34b41d92011-02-20 03:19:35 +00001910 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Richard Smith80ad52f2013-01-02 11:42:31 +00001911 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001912 int Error = -1;
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001914 switch (D.getContext()) {
1915 case Declarator::KNRTypeListContext:
David Blaikieb219cfc2011-09-23 05:06:16 +00001916 llvm_unreachable("K&R type lists aren't allowed in C++");
Eli Friedmanf88c4002012-01-04 04:41:38 +00001917 case Declarator::LambdaExprContext:
1918 llvm_unreachable("Can't specify a type specifier in lambda grammar");
John McCallcdda47f2011-10-01 09:56:14 +00001919 case Declarator::ObjCParameterContext:
1920 case Declarator::ObjCResultContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001921 case Declarator::PrototypeContext:
1922 Error = 0; // Function prototype
1923 break;
1924 case Declarator::MemberContext:
Richard Smith7a614d82011-06-11 17:19:42 +00001925 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1926 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001927 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
David Blaikieeb2d1f12011-09-23 20:26:49 +00001928 case TTK_Enum: llvm_unreachable("unhandled tag kind");
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001929 case TTK_Struct: Error = 1; /* Struct member */ break;
1930 case TTK_Union: Error = 2; /* Union member */ break;
1931 case TTK_Class: Error = 3; /* Class member */ break;
Joao Matos6666ed42012-08-31 18:45:21 +00001932 case TTK_Interface: Error = 4; /* Interface member */ break;
Mike Stump1eb44332009-09-09 15:08:12 +00001933 }
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001934 break;
1935 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00001936 case Declarator::ObjCCatchContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001937 Error = 5; // Exception declaration
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001938 break;
1939 case Declarator::TemplateParamContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001940 Error = 6; // Template parameter
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001941 break;
1942 case Declarator::BlockLiteralContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001943 Error = 7; // Block literal
Richard Smith34b41d92011-02-20 03:19:35 +00001944 break;
1945 case Declarator::TemplateTypeArgContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001946 Error = 8; // Template type argument
Richard Smith34b41d92011-02-20 03:19:35 +00001947 break;
Richard Smith162e1c12011-04-15 14:24:37 +00001948 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001949 case Declarator::AliasTemplateContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001950 Error = 10; // Type alias
Richard Smith162e1c12011-04-15 14:24:37 +00001951 break;
Richard Smith7796eb52012-03-12 08:56:40 +00001952 case Declarator::TrailingReturnContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001953 Error = 11; // Function return type
Richard Smith7796eb52012-03-12 08:56:40 +00001954 break;
Richard Smith34b41d92011-02-20 03:19:35 +00001955 case Declarator::TypeNameContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001956 Error = 12; // Generic
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001957 break;
1958 case Declarator::FileContext:
1959 case Declarator::BlockContext:
1960 case Declarator::ForContext:
1961 case Declarator::ConditionContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001962 case Declarator::CXXNewContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001963 break;
1964 }
1965
Richard Smithddc83f92011-02-21 23:18:00 +00001966 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
Joao Matos6666ed42012-08-31 18:45:21 +00001967 Error = 9;
Richard Smithddc83f92011-02-21 23:18:00 +00001968
Richard Smith8110f042011-02-22 01:22:29 +00001969 // In Objective-C it is an error to use 'auto' on a function declarator.
1970 if (D.isFunctionDeclarator())
Joao Matos6666ed42012-08-31 18:45:21 +00001971 Error = 11;
Richard Smith8110f042011-02-22 01:22:29 +00001972
Richard Smithd37b3602012-02-10 11:05:11 +00001973 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
Richard Smithe7397c62011-02-22 00:36:53 +00001974 // contains a trailing return type. That is only legal at the outermost
1975 // level. Check all declarator chunks (outermost first) anyway, to give
1976 // better diagnostics.
Richard Smith80ad52f2013-01-02 11:42:31 +00001977 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
Richard Smithe7397c62011-02-22 00:36:53 +00001978 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1979 unsigned chunkIndex = e - i - 1;
1980 state.setCurrentChunkIndex(chunkIndex);
1981 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1982 if (DeclType.Kind == DeclaratorChunk::Function) {
1983 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Richard Smith54655be2012-06-12 01:51:59 +00001984 if (FTI.hasTrailingReturnType()) {
Richard Smithe7397c62011-02-22 00:36:53 +00001985 Error = -1;
1986 break;
1987 }
1988 }
1989 }
1990 }
1991
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001992 if (Error != -1) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001993 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1994 diag::err_auto_not_allowed)
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001995 << Error;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001996 T = SemaRef.Context.IntTy;
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001997 D.setInvalidType(true);
Richard Smith0aa86c02011-10-15 05:42:01 +00001998 } else
1999 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2000 diag::warn_cxx98_compat_auto_type_specifier);
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002001 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002002
David Blaikie4e4d0842012-03-11 07:00:24 +00002003 if (SemaRef.getLangOpts().CPlusPlus &&
John McCall5e1cdac2011-10-07 06:10:15 +00002004 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002005 // Check the contexts where C++ forbids the declaration of a new class
2006 // or enumeration in a type-specifier-seq.
2007 switch (D.getContext()) {
Richard Smith7796eb52012-03-12 08:56:40 +00002008 case Declarator::TrailingReturnContext:
2009 // Class and enumeration definitions are syntactically not allowed in
2010 // trailing return types.
2011 llvm_unreachable("parser should not have allowed this");
2012 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002013 case Declarator::FileContext:
2014 case Declarator::MemberContext:
2015 case Declarator::BlockContext:
2016 case Declarator::ForContext:
2017 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00002018 case Declarator::LambdaExprContext:
Richard Smithd37b3602012-02-10 11:05:11 +00002019 // C++11 [dcl.type]p3:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002020 // A type-specifier-seq shall not define a class or enumeration unless
2021 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2022 // the declaration of a template-declaration.
2023 case Declarator::AliasDeclContext:
2024 break;
2025 case Declarator::AliasTemplateContext:
2026 SemaRef.Diag(OwnedTagDecl->getLocation(),
2027 diag::err_type_defined_in_alias_template)
2028 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002029 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002030 break;
2031 case Declarator::TypeNameContext:
2032 case Declarator::TemplateParamContext:
2033 case Declarator::CXXNewContext:
2034 case Declarator::CXXCatchContext:
2035 case Declarator::ObjCCatchContext:
2036 case Declarator::TemplateTypeArgContext:
2037 SemaRef.Diag(OwnedTagDecl->getLocation(),
2038 diag::err_type_defined_in_type_specifier)
2039 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002040 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002041 break;
2042 case Declarator::PrototypeContext:
John McCallcdda47f2011-10-01 09:56:14 +00002043 case Declarator::ObjCParameterContext:
2044 case Declarator::ObjCResultContext:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002045 case Declarator::KNRTypeListContext:
2046 // C++ [dcl.fct]p6:
2047 // Types shall not be defined in return or parameter types.
2048 SemaRef.Diag(OwnedTagDecl->getLocation(),
2049 diag::err_type_defined_in_param_type)
2050 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002051 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002052 break;
2053 case Declarator::ConditionContext:
2054 // C++ 6.4p2:
2055 // The type-specifier-seq shall not contain typedef and shall not declare
2056 // a new class or enumeration.
2057 SemaRef.Diag(OwnedTagDecl->getLocation(),
2058 diag::err_type_defined_in_condition);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002059 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002060 break;
2061 }
2062 }
2063
2064 return T;
2065}
2066
Benjamin Kramera08c2fb2012-02-24 22:19:42 +00002067static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
Richard Smithd37b3602012-02-10 11:05:11 +00002068 std::string Quals =
2069 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2070
2071 switch (FnTy->getRefQualifier()) {
2072 case RQ_None:
2073 break;
2074
2075 case RQ_LValue:
2076 if (!Quals.empty())
2077 Quals += ' ';
2078 Quals += '&';
2079 break;
2080
2081 case RQ_RValue:
2082 if (!Quals.empty())
2083 Quals += ' ';
2084 Quals += "&&";
2085 break;
2086 }
2087
2088 return Quals;
2089}
2090
2091/// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
2092/// can be contained within the declarator chunk DeclType, and produce an
2093/// appropriate diagnostic if not.
2094static void checkQualifiedFunction(Sema &S, QualType T,
2095 DeclaratorChunk &DeclType) {
2096 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
2097 // cv-qualifier or a ref-qualifier can only appear at the topmost level
2098 // of a type.
2099 int DiagKind = -1;
2100 switch (DeclType.Kind) {
2101 case DeclaratorChunk::Paren:
2102 case DeclaratorChunk::MemberPointer:
2103 // These cases are permitted.
2104 return;
2105 case DeclaratorChunk::Array:
2106 case DeclaratorChunk::Function:
2107 // These cases don't allow function types at all; no need to diagnose the
2108 // qualifiers separately.
2109 return;
2110 case DeclaratorChunk::BlockPointer:
2111 DiagKind = 0;
2112 break;
2113 case DeclaratorChunk::Pointer:
2114 DiagKind = 1;
2115 break;
2116 case DeclaratorChunk::Reference:
2117 DiagKind = 2;
2118 break;
2119 }
2120
2121 assert(DiagKind != -1);
2122 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
2123 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
2124 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
2125}
2126
Richard Smithb9c62612012-07-30 21:30:52 +00002127/// Produce an approprioate diagnostic for an ambiguity between a function
2128/// declarator and a C++ direct-initializer.
2129static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2130 DeclaratorChunk &DeclType, QualType RT) {
2131 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2132 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2133
2134 // If the return type is void there is no ambiguity.
2135 if (RT->isVoidType())
2136 return;
2137
2138 // An initializer for a non-class type can have at most one argument.
2139 if (!RT->isRecordType() && FTI.NumArgs > 1)
2140 return;
2141
2142 // An initializer for a reference must have exactly one argument.
2143 if (RT->isReferenceType() && FTI.NumArgs != 1)
2144 return;
2145
2146 // Only warn if this declarator is declaring a function at block scope, and
2147 // doesn't have a storage class (such as 'extern') specified.
2148 if (!D.isFunctionDeclarator() ||
2149 D.getFunctionDefinitionKind() != FDK_Declaration ||
2150 !S.CurContext->isFunctionOrMethod() ||
2151 D.getDeclSpec().getStorageClassSpecAsWritten()
2152 != DeclSpec::SCS_unspecified)
2153 return;
2154
2155 // Inside a condition, a direct initializer is not permitted. We allow one to
2156 // be parsed in order to give better diagnostics in condition parsing.
2157 if (D.getContext() == Declarator::ConditionContext)
2158 return;
2159
2160 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2161
Richard Smithd64effc2012-07-30 21:42:05 +00002162 S.Diag(DeclType.Loc,
2163 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration
2164 : diag::warn_empty_parens_are_function_decl)
2165 << ParenRange;
Richard Smithb9c62612012-07-30 21:30:52 +00002166
Richard Smithd64effc2012-07-30 21:42:05 +00002167 // If the declaration looks like:
2168 // T var1,
2169 // f();
2170 // and name lookup finds a function named 'f', then the ',' was
2171 // probably intended to be a ';'.
2172 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2173 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2174 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2175 if (Comma.getFileID() != Name.getFileID() ||
2176 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2177 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2178 Sema::LookupOrdinaryName);
2179 if (S.LookupName(Result, S.getCurScope()))
2180 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2181 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2182 << D.getIdentifier();
2183 }
2184 }
2185
2186 if (FTI.NumArgs > 0) {
2187 // For a declaration with parameters, eg. "T var(T());", suggest adding parens
2188 // around the first parameter to turn the declaration into a variable
2189 // declaration.
Richard Smithb9c62612012-07-30 21:30:52 +00002190 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange();
2191 SourceLocation B = Range.getBegin();
2192 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd());
2193 // FIXME: Maybe we should suggest adding braces instead of parens
2194 // in C++11 for classes that don't have an initializer_list constructor.
2195 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2196 << FixItHint::CreateInsertion(B, "(")
2197 << FixItHint::CreateInsertion(E, ")");
Richard Smithd64effc2012-07-30 21:42:05 +00002198 } else {
2199 // For a declaration without parameters, eg. "T var();", suggest replacing the
2200 // parens with an initializer to turn the declaration into a variable
2201 // declaration.
Richard Smithb9c62612012-07-30 21:30:52 +00002202 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Richard Smithd64effc2012-07-30 21:42:05 +00002203
Richard Smithb9c62612012-07-30 21:30:52 +00002204 // Empty parens mean value-initialization, and no parens mean
2205 // default initialization. These are equivalent if the default
2206 // constructor is user-provided or if zero-initialization is a
2207 // no-op.
2208 if (RD && RD->hasDefinition() &&
2209 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2210 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2211 << FixItHint::CreateRemoval(ParenRange);
2212 else {
2213 std::string Init = S.getFixItZeroInitializerForType(RT);
Richard Smith80ad52f2013-01-02 11:42:31 +00002214 if (Init.empty() && S.LangOpts.CPlusPlus11)
Richard Smithb9c62612012-07-30 21:30:52 +00002215 Init = "{}";
2216 if (!Init.empty())
2217 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2218 << FixItHint::CreateReplacement(ParenRange, Init);
2219 }
2220 }
2221}
2222
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002223static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2224 QualType declSpecType,
2225 TypeSourceInfo *TInfo) {
2226
2227 QualType T = declSpecType;
2228 Declarator &D = state.getDeclarator();
2229 Sema &S = state.getSema();
2230 ASTContext &Context = S.Context;
David Blaikie4e4d0842012-03-11 07:00:24 +00002231 const LangOptions &LangOpts = S.getLangOpts();
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002232
Douglas Gregorcd281c32009-02-28 00:25:32 +00002233 // The name we're declaring, if any.
2234 DeclarationName Name;
2235 if (D.getIdentifier())
2236 Name = D.getIdentifier();
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Richard Smith162e1c12011-04-15 14:24:37 +00002238 // Does this declaration declare a typedef-name?
2239 bool IsTypedefName =
2240 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
Richard Smith3e4c6c42011-05-05 21:57:07 +00002241 D.getContext() == Declarator::AliasDeclContext ||
2242 D.getContext() == Declarator::AliasTemplateContext;
Richard Smith162e1c12011-04-15 14:24:37 +00002243
Richard Smithd37b3602012-02-10 11:05:11 +00002244 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2245 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2246 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2247 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2248
Mike Stump98eb8a72009-02-04 22:31:32 +00002249 // Walk the DeclTypeInfo, building the recursive type as we go.
2250 // DeclTypeInfos are ordered from the identifier out, which is
2251 // opposite of what we want :).
Sebastian Redl8ce35b02009-10-25 21:45:37 +00002252 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall711c52b2011-01-05 12:14:39 +00002253 unsigned chunkIndex = e - i - 1;
2254 state.setCurrentChunkIndex(chunkIndex);
2255 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
Richard Smithd37b3602012-02-10 11:05:11 +00002256 if (IsQualifiedFunction) {
2257 checkQualifiedFunction(S, T, DeclType);
2258 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
2259 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 switch (DeclType.Kind) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002261 case DeclaratorChunk::Paren:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002262 T = S.BuildParenType(T);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002263 break;
Steve Naroff5618bd42008-08-27 16:04:49 +00002264 case DeclaratorChunk::BlockPointer:
Chris Lattner9af55002009-03-27 04:18:06 +00002265 // If blocks are disabled, emit an error.
2266 if (!LangOpts.Blocks)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002267 S.Diag(DeclType.Loc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002269 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
John McCall28654742010-06-05 06:41:15 +00002270 if (DeclType.Cls.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002271 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
Steve Naroff5618bd42008-08-27 16:04:49 +00002272 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 case DeclaratorChunk::Pointer:
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002274 // Verify that we're not building a pointer to pointer to function with
2275 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002276 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2277 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002278 D.setInvalidType(true);
2279 // Build the type anyway.
2280 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002281 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00002282 T = Context.getObjCObjectPointerType(T);
John McCall28654742010-06-05 06:41:15 +00002283 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002284 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
Steve Naroff14108da2009-07-10 23:34:53 +00002285 break;
2286 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002287 T = S.BuildPointerType(T, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002288 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002289 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
John McCall711c52b2011-01-05 12:14:39 +00002290
Reid Spencer5f016e22007-07-11 17:01:13 +00002291 break;
John McCall0953e762009-09-24 19:53:00 +00002292 case DeclaratorChunk::Reference: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002293 // Verify that we're not building a reference to pointer to function with
2294 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002295 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2296 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002297 D.setInvalidType(true);
2298 // Build the type anyway.
2299 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002300 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002301
2302 Qualifiers Quals;
2303 if (DeclType.Ref.HasRestrict)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002304 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
Reid Spencer5f016e22007-07-11 17:01:13 +00002305 break;
John McCall0953e762009-09-24 19:53:00 +00002306 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 case DeclaratorChunk::Array: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002308 // Verify that we're not building an array of pointers to function with
2309 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002310 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2311 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002312 D.setInvalidType(true);
2313 // Build the type anyway.
2314 }
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002315 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
Chris Lattner94f81fd2007-08-28 16:54:00 +00002316 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00002317 ArrayType::ArraySizeModifier ASM;
2318 if (ATI.isStar)
2319 ASM = ArrayType::Star;
2320 else if (ATI.hasStatic)
2321 ASM = ArrayType::Static;
2322 else
2323 ASM = ArrayType::Normal;
John McCallc05a94b2011-03-23 23:43:04 +00002324 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002325 // FIXME: This check isn't quite right: it allows star in prototypes
2326 // for function definitions, and disallows some edge cases detailed
2327 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002328 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002329 ASM = ArrayType::Normal;
2330 D.setInvalidType(true);
2331 }
Hans Wennborg7f397c52012-08-15 07:42:30 +00002332
2333 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2334 // shall appear only in a declaration of a function parameter with an
2335 // array type, ...
2336 if (ASM == ArrayType::Static || ATI.TypeQuals) {
Matt Beaumont-Gay99570a52012-08-15 19:53:19 +00002337 if (!(D.isPrototypeContext() ||
2338 D.getContext() == Declarator::KNRTypeListContext)) {
Hans Wennborg7f397c52012-08-15 07:42:30 +00002339 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2340 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2341 // Remove the 'static' and the type qualifiers.
2342 if (ASM == ArrayType::Static)
2343 ASM = ArrayType::Normal;
2344 ATI.TypeQuals = 0;
2345 D.setInvalidType(true);
2346 }
2347
2348 // C99 6.7.5.2p1: ... and then only in the outermost array type
2349 // derivation.
2350 unsigned x = chunkIndex;
2351 while (x != 0) {
2352 // Walk outwards along the declarator chunks.
2353 x--;
2354 const DeclaratorChunk &DC = D.getTypeObject(x);
2355 switch (DC.Kind) {
2356 case DeclaratorChunk::Paren:
2357 continue;
2358 case DeclaratorChunk::Array:
2359 case DeclaratorChunk::Pointer:
2360 case DeclaratorChunk::Reference:
2361 case DeclaratorChunk::MemberPointer:
2362 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2363 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2364 if (ASM == ArrayType::Static)
2365 ASM = ArrayType::Normal;
2366 ATI.TypeQuals = 0;
2367 D.setInvalidType(true);
2368 break;
2369 case DeclaratorChunk::Function:
2370 case DeclaratorChunk::BlockPointer:
2371 // These are invalid anyway, so just ignore.
2372 break;
2373 }
2374 }
2375 }
2376
Eli Friedman8ac2c662011-11-11 02:00:42 +00002377 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002378 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 break;
2380 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002381 case DeclaratorChunk::Function: {
Reid Spencer5f016e22007-07-11 17:01:13 +00002382 // If the function declarator has a prototype (i.e. it is not () and
2383 // does not have a K&R-style identifier list), then the arguments are part
2384 // of the type, otherwise the argument list is ().
2385 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Richard Smithd37b3602012-02-10 11:05:11 +00002386 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
Sebastian Redl3cc97262009-05-31 11:47:27 +00002387
Richard Smithe7397c62011-02-22 00:36:53 +00002388 // Check for auto functions and trailing return type and adjust the
2389 // return type accordingly.
2390 if (!D.isInvalidType()) {
2391 // trailing-return-type is only required if we're declaring a function,
2392 // and not, for instance, a pointer to a function.
2393 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Richard Smith54655be2012-06-12 01:51:59 +00002394 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002395 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002396 diag::err_auto_missing_trailing_return);
2397 T = Context.IntTy;
2398 D.setInvalidType(true);
Richard Smith54655be2012-06-12 01:51:59 +00002399 } else if (FTI.hasTrailingReturnType()) {
Richard Smithe7397c62011-02-22 00:36:53 +00002400 // T must be exactly 'auto' at this point. See CWG issue 681.
2401 if (isa<ParenType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002402 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002403 diag::err_trailing_return_in_parens)
2404 << T << D.getDeclSpec().getSourceRange();
2405 D.setInvalidType(true);
Eli Friedmanf88c4002012-01-04 04:41:38 +00002406 } else if (D.getContext() != Declarator::LambdaExprContext &&
2407 (T.hasQualifiers() || !isa<AutoType>(T))) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002408 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002409 diag::err_trailing_return_without_auto)
2410 << T << D.getDeclSpec().getSourceRange();
2411 D.setInvalidType(true);
2412 }
Richard Smith54655be2012-06-12 01:51:59 +00002413 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2414 if (T.isNull()) {
2415 // An error occurred parsing the trailing return type.
2416 T = Context.IntTy;
2417 D.setInvalidType(true);
2418 }
Richard Smithe7397c62011-02-22 00:36:53 +00002419 }
2420 }
2421
Chris Lattnercd881292007-12-19 05:31:29 +00002422 // C99 6.7.5.3p1: The return type may not be a function or array type.
Douglas Gregor58408bc2010-01-11 18:46:21 +00002423 // For conversion functions, we'll diagnose this particular error later.
Douglas Gregor48026d22010-01-11 18:40:55 +00002424 if ((T->isArrayType() || T->isFunctionType()) &&
2425 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002426 unsigned diagID = diag::err_func_returning_array_function;
Argyrios Kyrtzidisa4356ad2011-01-26 01:26:44 +00002427 // Last processing chunk in block context means this function chunk
2428 // represents the block.
2429 if (chunkIndex == 0 &&
2430 D.getContext() == Declarator::BlockLiteralContext)
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002431 diagID = diag::err_block_returning_array_function;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002432 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
Chris Lattnercd881292007-12-19 05:31:29 +00002433 T = Context.IntTy;
2434 D.setInvalidType(true);
2435 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002436
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002437 // Do not allow returning half FP value.
2438 // FIXME: This really should be in BuildFunctionType.
2439 if (T->isHalfType()) {
2440 S.Diag(D.getIdentifierLoc(),
2441 diag::err_parameters_retval_cannot_have_fp16_type) << 1
2442 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
2443 D.setInvalidType(true);
2444 }
2445
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002446 // cv-qualifiers on return types are pointless except when the type is a
2447 // class type in C++.
Douglas Gregorfff95132011-03-01 17:04:42 +00002448 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
Rafael Espindola1e153942011-03-11 04:56:58 +00002449 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002450 (!LangOpts.CPlusPlus || !T->isDependentType())) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002451 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2452 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2453 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2454
2455 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2456
2457 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2458 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2459 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2460 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002461 S);
Chandler Carruthd067c072011-02-23 18:51:59 +00002462
2463 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002464 (!LangOpts.CPlusPlus ||
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002465 (!T->isDependentType() && !T->isRecordType()))) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002466
2467 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2468 D.getDeclSpec().getConstSpecLoc(),
2469 D.getDeclSpec().getVolatileSpecLoc(),
2470 D.getDeclSpec().getRestrictSpecLoc(),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002471 S);
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002472 }
Chandler Carruthd067c072011-02-23 18:51:59 +00002473
Douglas Gregor02dd7982013-01-17 23:36:45 +00002474 // Objective-C ARC ownership qualifiers are ignored on the function
2475 // return type (by type canonicalization). Complain if this attribute
2476 // was written here.
2477 if (T.getQualifiers().hasObjCLifetime()) {
2478 SourceLocation AttrLoc;
2479 if (chunkIndex + 1 < D.getNumTypeObjects()) {
2480 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2481 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
2482 Attr; Attr = Attr->getNext()) {
2483 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2484 AttrLoc = Attr->getLoc();
2485 break;
2486 }
2487 }
2488 }
2489 if (AttrLoc.isInvalid()) {
2490 for (const AttributeList *Attr
2491 = D.getDeclSpec().getAttributes().getList();
2492 Attr; Attr = Attr->getNext()) {
2493 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2494 AttrLoc = Attr->getLoc();
2495 break;
2496 }
2497 }
2498 }
2499
2500 if (AttrLoc.isValid()) {
2501 // The ownership attributes are almost always written via
2502 // the predefined
2503 // __strong/__weak/__autoreleasing/__unsafe_unretained.
2504 if (AttrLoc.isMacroID())
2505 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
2506
2507 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
2508 << T.getQualifiers().getObjCLifetime();
2509 }
2510 }
2511
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002512 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
Douglas Gregor402abb52009-05-28 23:31:59 +00002513 // C++ [dcl.fct]p6:
2514 // Types shall not be defined in return or parameter types.
John McCallb3d87482010-08-24 05:47:05 +00002515 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
John McCall5e1cdac2011-10-07 06:10:15 +00002516 if (Tag->isCompleteDefinition())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002517 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
Douglas Gregor402abb52009-05-28 23:31:59 +00002518 << Context.getTypeDeclType(Tag);
2519 }
2520
Sebastian Redl3cc97262009-05-31 11:47:27 +00002521 // Exception specs are not allowed in typedefs. Complain, but add it
2522 // anyway.
Richard Smith162e1c12011-04-15 14:24:37 +00002523 if (IsTypedefName && FTI.getExceptionSpecType())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002524 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
Richard Smith3e4c6c42011-05-05 21:57:07 +00002525 << (D.getContext() == Declarator::AliasDeclContext ||
2526 D.getContext() == Declarator::AliasTemplateContext);
Sebastian Redl3cc97262009-05-31 11:47:27 +00002527
Richard Smithb9c62612012-07-30 21:30:52 +00002528 // If we see "T var();" or "T var(T());" at block scope, it is probably
2529 // an attempt to initialize a variable, not a function declaration.
2530 if (FTI.isAmbiguous)
2531 warnAboutAmbiguousFunction(S, D, DeclType, T);
2532
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002533 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
John McCall28654742010-06-05 06:41:15 +00002534 // Simple void foo(), where the incoming T is the result type.
2535 T = Context.getFunctionNoProtoType(T);
2536 } else {
2537 // We allow a zero-parameter variadic function in C if the
2538 // function is marked with the "overloadable" attribute. Scan
2539 // for this attribute now.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002540 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002541 bool Overloadable = false;
2542 for (const AttributeList *Attrs = D.getAttributes();
2543 Attrs; Attrs = Attrs->getNext()) {
Sean Hunt8e083e72012-06-19 23:57:03 +00002544 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002545 Overloadable = true;
2546 break;
2547 }
2548 }
2549
2550 if (!Overloadable)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002551 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
Argyrios Kyrtzidisc6f73452008-10-16 17:31:08 +00002552 }
John McCall28654742010-06-05 06:41:15 +00002553
2554 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002555 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2556 // definition.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002557 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
John McCall28654742010-06-05 06:41:15 +00002558 D.setInvalidType(true);
2559 break;
2560 }
2561
John McCalle23cf432010-12-14 08:05:40 +00002562 FunctionProtoType::ExtProtoInfo EPI;
2563 EPI.Variadic = FTI.isVariadic;
Richard Smith54655be2012-06-12 01:51:59 +00002564 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
John McCalle23cf432010-12-14 08:05:40 +00002565 EPI.TypeQuals = FTI.TypeQuals;
Douglas Gregorc938c162011-01-26 05:01:58 +00002566 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2567 : FTI.RefQualifierIsLValueRef? RQ_LValue
2568 : RQ_RValue;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002569
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 // Otherwise, we have a function with an argument list that is
2571 // potentially variadic.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002572 SmallVector<QualType, 16> ArgTys;
John McCall28654742010-06-05 06:41:15 +00002573 ArgTys.reserve(FTI.NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Chris Lattner5f9e2722011-07-23 10:55:15 +00002575 SmallVector<bool, 16> ConsumedArguments;
John McCallf85e1932011-06-15 23:02:42 +00002576 ConsumedArguments.reserve(FTI.NumArgs);
2577 bool HasAnyConsumedArguments = false;
2578
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002580 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Chris Lattner8123a952008-04-10 02:22:51 +00002581 QualType ArgTy = Param->getType();
Chris Lattner78c75fb2007-07-21 05:30:18 +00002582 assert(!ArgTy.isNull() && "Couldn't parse type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002583
2584 // Adjust the parameter type.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002585 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
Douglas Gregor79e6bd32011-07-12 04:42:08 +00002586 "Unadjusted type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002587
Reid Spencer5f016e22007-07-11 17:01:13 +00002588 // Look for 'void'. void is allowed only as a single argument to a
2589 // function with no other parameters (C99 6.7.5.3p10). We record
Douglas Gregor72564e72009-02-26 23:50:07 +00002590 // int(void) as a FunctionProtoType with an empty argument list.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002591 if (ArgTy->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002592 // If this is something like 'float(int, void)', reject it. 'void'
2593 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2594 // have arguments of incomplete type.
2595 if (FTI.NumArgs != 1 || FTI.isVariadic) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002596 S.Diag(DeclType.Loc, diag::err_void_only_param);
Chris Lattner2ff54262007-07-21 05:18:12 +00002597 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002598 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002599 } else if (FTI.ArgInfo[i].Ident) {
2600 // Reject, but continue to parse 'int(void abc)'.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002601 S.Diag(FTI.ArgInfo[i].IdentLoc,
Chris Lattner4565d4e2007-07-21 05:26:43 +00002602 diag::err_param_with_void_type);
Chris Lattner2ff54262007-07-21 05:18:12 +00002603 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002604 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002605 } else {
2606 // Reject, but continue to parse 'float(const void)'.
John McCall0953e762009-09-24 19:53:00 +00002607 if (ArgTy.hasQualifiers())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002608 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Chris Lattner2ff54262007-07-21 05:18:12 +00002610 // Do not add 'void' to the ArgTys list.
2611 break;
2612 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002613 } else if (ArgTy->isHalfType()) {
2614 // Disallow half FP arguments.
2615 // FIXME: This really should be in BuildFunctionType.
2616 S.Diag(Param->getLocation(),
2617 diag::err_parameters_retval_cannot_have_fp16_type) << 0
2618 << FixItHint::CreateInsertion(Param->getLocation(), "*");
2619 D.setInvalidType();
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002620 } else if (!FTI.hasPrototype) {
2621 if (ArgTy->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00002622 ArgTy = Context.getPromotedIntegerType(ArgTy);
John McCalleecf5fa2011-03-09 04:22:44 +00002623 Param->setKNRPromoted(true);
John McCall183700f2009-09-21 23:43:11 +00002624 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
John McCalleecf5fa2011-03-09 04:22:44 +00002625 if (BTy->getKind() == BuiltinType::Float) {
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002626 ArgTy = Context.DoubleTy;
John McCalleecf5fa2011-03-09 04:22:44 +00002627 Param->setKNRPromoted(true);
2628 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002629 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 }
Fariborz Jahanian56a965c2010-09-08 21:36:35 +00002631
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002632 if (LangOpts.ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002633 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2634 ConsumedArguments.push_back(Consumed);
2635 HasAnyConsumedArguments |= Consumed;
2636 }
2637
John McCall54e14c42009-10-22 22:37:11 +00002638 ArgTys.push_back(ArgTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002640
John McCallf85e1932011-06-15 23:02:42 +00002641 if (HasAnyConsumedArguments)
2642 EPI.ConsumedArguments = ConsumedArguments.data();
2643
Chris Lattner5f9e2722011-07-23 10:55:15 +00002644 SmallVector<QualType, 4> Exceptions;
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002645 SmallVector<ParsedType, 2> DynamicExceptions;
2646 SmallVector<SourceRange, 2> DynamicExceptionRanges;
2647 Expr *NoexceptExpr = 0;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002648
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002649 if (FTI.getExceptionSpecType() == EST_Dynamic) {
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002650 // FIXME: It's rather inefficient to have to split into two vectors
2651 // here.
2652 unsigned N = FTI.NumExceptions;
2653 DynamicExceptions.reserve(N);
2654 DynamicExceptionRanges.reserve(N);
2655 for (unsigned I = 0; I != N; ++I) {
2656 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
2657 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
John McCalle23cf432010-12-14 08:05:40 +00002658 }
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002659 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002660 NoexceptExpr = FTI.NoexceptExpr;
2661 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002662
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002663 S.checkExceptionSpecification(FTI.getExceptionSpecType(),
2664 DynamicExceptions,
2665 DynamicExceptionRanges,
2666 NoexceptExpr,
2667 Exceptions,
2668 EPI);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002669
John McCalle23cf432010-12-14 08:05:40 +00002670 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002671 }
John McCall04a67a62010-02-05 21:31:56 +00002672
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 break;
2674 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002675 case DeclaratorChunk::MemberPointer:
2676 // The scope spec must refer to a class, or be dependent.
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002677 CXXScopeSpec &SS = DeclType.Mem.Scope();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002678 QualType ClsType;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002679 if (SS.isInvalid()) {
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00002680 // Avoid emitting extra errors if we already errored on the scope.
2681 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002682 } else if (S.isDependentScopeSpecifier(SS) ||
2683 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002684 NestedNameSpecifier *NNS
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002685 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002686 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2687 switch (NNS->getKind()) {
2688 case NestedNameSpecifier::Identifier:
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002689 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002690 NNS->getAsIdentifier());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002691 break;
2692
2693 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00002694 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor87c12c42009-11-04 16:49:01 +00002695 case NestedNameSpecifier::Global:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002696 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002697
Douglas Gregor87c12c42009-11-04 16:49:01 +00002698 case NestedNameSpecifier::TypeSpec:
2699 case NestedNameSpecifier::TypeSpecWithTemplate:
2700 ClsType = QualType(NNS->getAsType(), 0);
Abramo Bagnara91ce2c42011-03-10 10:18:27 +00002701 // Note: if the NNS has a prefix and ClsType is a nondependent
2702 // TemplateSpecializationType, then the NNS prefix is NOT included
2703 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2704 // NOTE: in particular, no wrap occurs if ClsType already is an
2705 // Elaborated, DependentName, or DependentTemplateSpecialization.
2706 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002707 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
Douglas Gregor87c12c42009-11-04 16:49:01 +00002708 break;
2709 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002710 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002711 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
Douglas Gregor949bf692009-06-09 22:17:39 +00002712 diag::err_illegal_decl_mempointer_in_nonclass)
2713 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2714 << DeclType.Mem.Scope().getRange();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002715 D.setInvalidType(true);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002716 }
2717
Douglas Gregor949bf692009-06-09 22:17:39 +00002718 if (!ClsType.isNull())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002719 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
Douglas Gregor949bf692009-06-09 22:17:39 +00002720 if (T.isNull()) {
2721 T = Context.IntTy;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002722 D.setInvalidType(true);
John McCall28654742010-06-05 06:41:15 +00002723 } else if (DeclType.Mem.TypeQuals) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002724 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002725 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002726 break;
2727 }
2728
Douglas Gregorcd281c32009-02-28 00:25:32 +00002729 if (T.isNull()) {
2730 D.setInvalidType(true);
2731 T = Context.IntTy;
2732 }
2733
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002734 // See if there are any attributes on this declarator chunk.
John McCall711c52b2011-01-05 12:14:39 +00002735 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
Richard Smithf7a05272013-01-14 07:53:01 +00002736 processTypeAttrs(state, T, TAL_DeclChunk, attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002738
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002739 if (LangOpts.CPlusPlus && T->isFunctionType()) {
John McCall183700f2009-09-21 23:43:11 +00002740 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
Chris Lattner778ed742009-10-25 17:36:50 +00002741 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002742
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002743 // C++ 8.3.5p4:
Douglas Gregor708f3b82010-10-14 22:03:51 +00002744 // A cv-qualifier-seq shall only be part of the function type
2745 // for a nonstatic member function, the function type to which a pointer
2746 // to member refers, or the top-level function type of a function typedef
2747 // declaration.
Douglas Gregor683a81f2011-01-31 16:09:46 +00002748 //
2749 // Core issue 547 also allows cv-qualifiers on function types that are
2750 // top-level template type arguments.
John McCall613ef3d2010-10-19 01:54:45 +00002751 bool FreeFunction;
2752 if (!D.getCXXScopeSpec().isSet()) {
Eli Friedman906a7e12012-01-06 03:05:34 +00002753 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
2754 D.getContext() != Declarator::LambdaExprContext) ||
John McCall613ef3d2010-10-19 01:54:45 +00002755 D.getDeclSpec().isFriendSpecified());
2756 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002757 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
John McCall613ef3d2010-10-19 01:54:45 +00002758 FreeFunction = (DC && !DC->isRecord());
2759 }
2760
Richard Smithd37b3602012-02-10 11:05:11 +00002761 // C++11 [dcl.fct]p6 (w/DR1417):
2762 // An attempt to specify a function type with a cv-qualifier-seq or a
2763 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
2764 // - the function type for a non-static member function,
2765 // - the function type to which a pointer to member refers,
2766 // - the top-level function type of a function typedef declaration or
2767 // alias-declaration,
2768 // - the type-id in the default argument of a type-parameter, or
2769 // - the type-id of a template-argument for a type-parameter
2770 if (IsQualifiedFunction &&
2771 !(!FreeFunction &&
2772 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
2773 !IsTypedefName &&
2774 D.getContext() != Declarator::TemplateTypeArgContext) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002775 SourceLocation Loc = D.getLocStart();
Richard Smithd37b3602012-02-10 11:05:11 +00002776 SourceRange RemovalRange;
2777 unsigned I;
2778 if (D.isFunctionDeclarator(I)) {
2779 SmallVector<SourceLocation, 4> RemovalLocs;
2780 const DeclaratorChunk &Chunk = D.getTypeObject(I);
2781 assert(Chunk.Kind == DeclaratorChunk::Function);
2782 if (Chunk.Fun.hasRefQualifier())
2783 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
2784 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
2785 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
2786 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
2787 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
2788 // FIXME: We do not track the location of the __restrict qualifier.
2789 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
2790 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
2791 if (!RemovalLocs.empty()) {
2792 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002793 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
Richard Smithd37b3602012-02-10 11:05:11 +00002794 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
2795 Loc = RemovalLocs.front();
Douglas Gregorc938c162011-01-26 05:01:58 +00002796 }
2797 }
Richard Smithd37b3602012-02-10 11:05:11 +00002798
2799 S.Diag(Loc, diag::err_invalid_qualified_function_type)
2800 << FreeFunction << D.isFunctionDeclarator() << T
2801 << getFunctionQualifiersAsString(FnTy)
2802 << FixItHint::CreateRemoval(RemovalRange);
2803
2804 // Strip the cv-qualifiers and ref-qualifiers from the type.
2805 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2806 EPI.TypeQuals = 0;
2807 EPI.RefQualifier = RQ_None;
2808
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002809 T = Context.getFunctionType(FnTy->getResultType(),
Richard Smithd37b3602012-02-10 11:05:11 +00002810 FnTy->arg_type_begin(),
2811 FnTy->getNumArgs(), EPI);
Richard Smithe9253222012-10-24 23:51:56 +00002812 // Rebuild any parens around the identifier in the function type.
2813 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2814 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
2815 break;
2816 T = S.BuildParenType(T);
2817 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002818 }
2819 }
Mike Stump1eb44332009-09-09 15:08:12 +00002820
John McCall711c52b2011-01-05 12:14:39 +00002821 // Apply any undistributed attributes from the declarator.
2822 if (!T.isNull())
2823 if (AttributeList *attrs = D.getAttributes())
Richard Smithf7a05272013-01-14 07:53:01 +00002824 processTypeAttrs(state, T, TAL_DeclName, attrs);
John McCall711c52b2011-01-05 12:14:39 +00002825
2826 // Diagnose any ignored type attributes.
2827 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2828
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002829 // C++0x [dcl.constexpr]p9:
2830 // A constexpr specifier used in an object declaration declares the object
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002831 // as const.
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002832 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
Sebastian Redl73780122010-06-09 21:19:43 +00002833 T.addConst();
2834 }
2835
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002836 // If there was an ellipsis in the declarator, the declaration declares a
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002837 // parameter pack whose type may be a pack expansion type.
2838 if (D.hasEllipsis() && !T.isNull()) {
2839 // C++0x [dcl.fct]p13:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002840 // A declarator-id or abstract-declarator containing an ellipsis shall
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002841 // only be used in a parameter-declaration. Such a parameter-declaration
2842 // is a parameter pack (14.5.3). [...]
2843 switch (D.getContext()) {
2844 case Declarator::PrototypeContext:
2845 // C++0x [dcl.fct]p13:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002846 // [...] When it is part of a parameter-declaration-clause, the
2847 // parameter pack is a function parameter pack (14.5.3). The type T
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002848 // of the declarator-id of the function parameter pack shall contain
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002849 // a template parameter pack; each template parameter pack in T is
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002850 // expanded by the function parameter pack.
2851 //
2852 // We represent function parameter packs as function parameters whose
2853 // type is a pack expansion.
2854 if (!T->containsUnexpandedParameterPack()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002855 S.Diag(D.getEllipsisLoc(),
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002856 diag::err_function_parameter_pack_without_parameter_packs)
2857 << T << D.getSourceRange();
2858 D.setEllipsisLoc(SourceLocation());
2859 } else {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002860 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002861 }
2862 break;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002863
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002864 case Declarator::TemplateParamContext:
2865 // C++0x [temp.param]p15:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002866 // If a template-parameter is a [...] is a parameter-declaration that
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002867 // declares a parameter pack (8.3.5), then the template-parameter is a
2868 // template parameter pack (14.5.3).
2869 //
2870 // Note: core issue 778 clarifies that, if there are any unexpanded
2871 // parameter packs in the type of the non-type template parameter, then
2872 // it expands those parameter packs.
2873 if (T->containsUnexpandedParameterPack())
Douglas Gregorcded4f62011-01-14 17:04:44 +00002874 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Richard Smithe5acd132011-10-14 20:31:37 +00002875 else
2876 S.Diag(D.getEllipsisLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00002877 LangOpts.CPlusPlus11
Richard Smithe5acd132011-10-14 20:31:37 +00002878 ? diag::warn_cxx98_compat_variadic_templates
2879 : diag::ext_variadic_templates);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002880 break;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002881
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002882 case Declarator::FileContext:
2883 case Declarator::KNRTypeListContext:
John McCallcdda47f2011-10-01 09:56:14 +00002884 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
2885 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002886 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002887 case Declarator::CXXNewContext:
Richard Smith162e1c12011-04-15 14:24:37 +00002888 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002889 case Declarator::AliasTemplateContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002890 case Declarator::MemberContext:
2891 case Declarator::BlockContext:
2892 case Declarator::ForContext:
2893 case Declarator::ConditionContext:
2894 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002895 case Declarator::ObjCCatchContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002896 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00002897 case Declarator::LambdaExprContext:
Richard Smith7796eb52012-03-12 08:56:40 +00002898 case Declarator::TrailingReturnContext:
Douglas Gregor683a81f2011-01-31 16:09:46 +00002899 case Declarator::TemplateTypeArgContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002900 // FIXME: We may want to allow parameter packs in block-literal contexts
2901 // in the future.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002902 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002903 D.setEllipsisLoc(SourceLocation());
2904 break;
2905 }
2906 }
Richard Smithe7397c62011-02-22 00:36:53 +00002907
John McCallbf1a0282010-06-04 23:28:52 +00002908 if (T.isNull())
2909 return Context.getNullTypeSourceInfo();
2910 else if (D.isInvalidType())
2911 return Context.getTrivialTypeSourceInfo(T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002912
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002913 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2914}
2915
2916/// GetTypeForDeclarator - Convert the type for the specified
2917/// declarator to Type instances.
2918///
2919/// The result of this call will never be null, but the associated
2920/// type may be a null type if there's an unrecoverable error.
2921TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2922 // Determine the type of the declarator. Not all forms of declarator
2923 // have a type.
2924
2925 TypeProcessingState state(*this, D);
2926
2927 TypeSourceInfo *ReturnTypeInfo = 0;
2928 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2929 if (T.isNull())
2930 return Context.getNullTypeSourceInfo();
2931
David Blaikie4e4d0842012-03-11 07:00:24 +00002932 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002933 inferARCWriteback(state, T);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002934
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002935 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002936}
2937
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002938static void transferARCOwnershipToDeclSpec(Sema &S,
2939 QualType &declSpecTy,
2940 Qualifiers::ObjCLifetime ownership) {
2941 if (declSpecTy->isObjCRetainableType() &&
2942 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2943 Qualifiers qs;
2944 qs.addObjCLifetime(ownership);
2945 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2946 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002947}
2948
2949static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2950 Qualifiers::ObjCLifetime ownership,
2951 unsigned chunkIndex) {
2952 Sema &S = state.getSema();
2953 Declarator &D = state.getDeclarator();
2954
2955 // Look for an explicit lifetime attribute.
2956 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2957 for (const AttributeList *attr = chunk.getAttrs(); attr;
2958 attr = attr->getNext())
Sean Hunt8e083e72012-06-19 23:57:03 +00002959 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002960 return;
2961
2962 const char *attrStr = 0;
2963 switch (ownership) {
David Blaikie30263482012-01-20 21:50:17 +00002964 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002965 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2966 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2967 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2968 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2969 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002970
2971 // If there wasn't one, add one (with an invalid source location
2972 // so that we don't make an AttributedType for it).
2973 AttributeList *attr = D.getAttributePool()
2974 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2975 /*scope*/ 0, SourceLocation(),
2976 &S.Context.Idents.get(attrStr), SourceLocation(),
Sean Hunt93f95f22012-06-18 16:13:52 +00002977 /*args*/ 0, 0, AttributeList::AS_GNU);
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002978 spliceAttrIntoList(*attr, chunk.getAttrListRef());
2979
2980 // TODO: mark whether we did this inference?
2981}
2982
Benjamin Kramer48d798c2012-06-02 10:20:41 +00002983/// \brief Used for transferring ownership in casts resulting in l-values.
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002984static void transferARCOwnership(TypeProcessingState &state,
2985 QualType &declSpecTy,
2986 Qualifiers::ObjCLifetime ownership) {
2987 Sema &S = state.getSema();
2988 Declarator &D = state.getDeclarator();
2989
2990 int inner = -1;
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002991 bool hasIndirection = false;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002992 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2993 DeclaratorChunk &chunk = D.getTypeObject(i);
2994 switch (chunk.Kind) {
2995 case DeclaratorChunk::Paren:
2996 // Ignore parens.
2997 break;
2998
2999 case DeclaratorChunk::Array:
3000 case DeclaratorChunk::Reference:
3001 case DeclaratorChunk::Pointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00003002 if (inner != -1)
3003 hasIndirection = true;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003004 inner = i;
3005 break;
3006
3007 case DeclaratorChunk::BlockPointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00003008 if (inner != -1)
3009 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3010 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003011
3012 case DeclaratorChunk::Function:
3013 case DeclaratorChunk::MemberPointer:
3014 return;
3015 }
3016 }
3017
3018 if (inner == -1)
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00003019 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003020
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003021 DeclaratorChunk &chunk = D.getTypeObject(inner);
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003022 if (chunk.Kind == DeclaratorChunk::Pointer) {
3023 if (declSpecTy->isObjCRetainableType())
3024 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00003025 if (declSpecTy->isObjCObjectType() && hasIndirection)
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003026 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3027 } else {
3028 assert(chunk.Kind == DeclaratorChunk::Array ||
3029 chunk.Kind == DeclaratorChunk::Reference);
3030 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3031 }
3032}
3033
3034TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3035 TypeProcessingState state(*this, D);
3036
3037 TypeSourceInfo *ReturnTypeInfo = 0;
3038 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3039 if (declSpecTy.isNull())
3040 return Context.getNullTypeSourceInfo();
3041
David Blaikie4e4d0842012-03-11 07:00:24 +00003042 if (getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003043 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3044 if (ownership != Qualifiers::OCL_None)
3045 transferARCOwnership(state, declSpecTy, ownership);
3046 }
3047
3048 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3049}
3050
John McCall14aa2172011-03-04 04:00:19 +00003051/// Map an AttributedType::Kind to an AttributeList::Kind.
3052static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3053 switch (kind) {
3054 case AttributedType::attr_address_space:
Sean Hunt8e083e72012-06-19 23:57:03 +00003055 return AttributeList::AT_AddressSpace;
John McCall14aa2172011-03-04 04:00:19 +00003056 case AttributedType::attr_regparm:
Sean Hunt8e083e72012-06-19 23:57:03 +00003057 return AttributeList::AT_Regparm;
John McCall14aa2172011-03-04 04:00:19 +00003058 case AttributedType::attr_vector_size:
Sean Hunt8e083e72012-06-19 23:57:03 +00003059 return AttributeList::AT_VectorSize;
John McCall14aa2172011-03-04 04:00:19 +00003060 case AttributedType::attr_neon_vector_type:
Sean Hunt8e083e72012-06-19 23:57:03 +00003061 return AttributeList::AT_NeonVectorType;
John McCall14aa2172011-03-04 04:00:19 +00003062 case AttributedType::attr_neon_polyvector_type:
Sean Hunt8e083e72012-06-19 23:57:03 +00003063 return AttributeList::AT_NeonPolyVectorType;
John McCall14aa2172011-03-04 04:00:19 +00003064 case AttributedType::attr_objc_gc:
Sean Hunt8e083e72012-06-19 23:57:03 +00003065 return AttributeList::AT_ObjCGC;
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003066 case AttributedType::attr_objc_ownership:
Sean Hunt8e083e72012-06-19 23:57:03 +00003067 return AttributeList::AT_ObjCOwnership;
John McCall14aa2172011-03-04 04:00:19 +00003068 case AttributedType::attr_noreturn:
Sean Hunt8e083e72012-06-19 23:57:03 +00003069 return AttributeList::AT_NoReturn;
John McCall14aa2172011-03-04 04:00:19 +00003070 case AttributedType::attr_cdecl:
Sean Hunt8e083e72012-06-19 23:57:03 +00003071 return AttributeList::AT_CDecl;
John McCall14aa2172011-03-04 04:00:19 +00003072 case AttributedType::attr_fastcall:
Sean Hunt8e083e72012-06-19 23:57:03 +00003073 return AttributeList::AT_FastCall;
John McCall14aa2172011-03-04 04:00:19 +00003074 case AttributedType::attr_stdcall:
Sean Hunt8e083e72012-06-19 23:57:03 +00003075 return AttributeList::AT_StdCall;
John McCall14aa2172011-03-04 04:00:19 +00003076 case AttributedType::attr_thiscall:
Sean Hunt8e083e72012-06-19 23:57:03 +00003077 return AttributeList::AT_ThisCall;
John McCall14aa2172011-03-04 04:00:19 +00003078 case AttributedType::attr_pascal:
Sean Hunt8e083e72012-06-19 23:57:03 +00003079 return AttributeList::AT_Pascal;
Anton Korobeynikov414d8962011-04-14 20:06:49 +00003080 case AttributedType::attr_pcs:
Sean Hunt8e083e72012-06-19 23:57:03 +00003081 return AttributeList::AT_Pcs;
Derek Schuff263366f2012-10-16 22:30:41 +00003082 case AttributedType::attr_pnaclcall:
3083 return AttributeList::AT_PnaclCall;
Guy Benyei38980082012-12-25 08:53:55 +00003084 case AttributedType::attr_inteloclbicc:
3085 return AttributeList::AT_IntelOclBicc;
John McCall14aa2172011-03-04 04:00:19 +00003086 }
3087 llvm_unreachable("unexpected attribute kind!");
John McCall14aa2172011-03-04 04:00:19 +00003088}
3089
3090static void fillAttributedTypeLoc(AttributedTypeLoc TL,
3091 const AttributeList *attrs) {
3092 AttributedType::Kind kind = TL.getAttrKind();
3093
3094 assert(attrs && "no type attributes in the expected location!");
3095 AttributeList::Kind parsedKind = getAttrListKind(kind);
3096 while (attrs->getKind() != parsedKind) {
3097 attrs = attrs->getNext();
3098 assert(attrs && "no matching attribute in expected location!");
3099 }
3100
3101 TL.setAttrNameLoc(attrs->getLoc());
3102 if (TL.hasAttrExprOperand())
3103 TL.setAttrExprOperand(attrs->getArg(0));
3104 else if (TL.hasAttrEnumOperand())
3105 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
3106
3107 // FIXME: preserve this information to here.
3108 if (TL.hasAttrOperand())
3109 TL.setAttrOperandParensRange(SourceRange());
3110}
3111
John McCall51bd8032009-10-18 01:05:36 +00003112namespace {
3113 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003114 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00003115 const DeclSpec &DS;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003116
John McCall51bd8032009-10-18 01:05:36 +00003117 public:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003118 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003119 : Context(Context), DS(DS) {}
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003120
John McCall14aa2172011-03-04 04:00:19 +00003121 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3122 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3123 Visit(TL.getModifiedLoc());
3124 }
John McCall51bd8032009-10-18 01:05:36 +00003125 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3126 Visit(TL.getUnqualifiedLoc());
3127 }
3128 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3129 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3130 }
3131 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3132 TL.setNameLoc(DS.getTypeSpecTypeLoc());
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00003133 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3134 // addition field. What we have is good enough for dispay of location
3135 // of 'fixit' on interface name.
3136 TL.setNameEndLoc(DS.getLocEnd());
John McCallc12c5bb2010-05-15 11:32:37 +00003137 }
3138 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3139 // Handle the base type, which might not have been written explicitly.
3140 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3141 TL.setHasBaseTypeAsWritten(false);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003142 TL.getBaseLoc().initialize(Context, SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00003143 } else {
3144 TL.setHasBaseTypeAsWritten(true);
3145 Visit(TL.getBaseLoc());
3146 }
Argyrios Kyrtzidiseb667592009-09-29 19:45:22 +00003147
John McCallc12c5bb2010-05-15 11:32:37 +00003148 // Protocol qualifiers.
John McCall54e14c42009-10-22 22:37:11 +00003149 if (DS.getProtocolQualifiers()) {
3150 assert(TL.getNumProtocols() > 0);
3151 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3152 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3153 TL.setRAngleLoc(DS.getSourceRange().getEnd());
3154 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3155 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3156 } else {
3157 assert(TL.getNumProtocols() == 0);
3158 TL.setLAngleLoc(SourceLocation());
3159 TL.setRAngleLoc(SourceLocation());
3160 }
3161 }
3162 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall54e14c42009-10-22 22:37:11 +00003163 TL.setStarLoc(SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00003164 Visit(TL.getPointeeLoc());
John McCall51bd8032009-10-18 01:05:36 +00003165 }
John McCall833ca992009-10-29 08:12:44 +00003166 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
John McCalla93c9342009-12-07 02:54:59 +00003167 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00003168 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall833ca992009-10-29 08:12:44 +00003169
3170 // If we got no declarator info from previous Sema routines,
3171 // just fill with the typespec loc.
John McCalla93c9342009-12-07 02:54:59 +00003172 if (!TInfo) {
Abramo Bagnara0daaf322011-03-16 20:16:18 +00003173 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
John McCall833ca992009-10-29 08:12:44 +00003174 return;
3175 }
3176
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003177 TypeLoc OldTL = TInfo->getTypeLoc();
3178 if (TInfo->getType()->getAs<ElaboratedType>()) {
3179 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
3180 TemplateSpecializationTypeLoc NamedTL =
3181 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
3182 TL.copy(NamedTL);
3183 }
3184 else
3185 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
John McCall833ca992009-10-29 08:12:44 +00003186 }
John McCallcfb708c2010-01-13 20:03:27 +00003187 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3188 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3189 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3190 TL.setParensRange(DS.getTypeofParensRange());
3191 }
3192 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3193 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3194 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3195 TL.setParensRange(DS.getTypeofParensRange());
John McCallb3d87482010-08-24 05:47:05 +00003196 assert(DS.getRepAsType());
John McCallcfb708c2010-01-13 20:03:27 +00003197 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00003198 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCallcfb708c2010-01-13 20:03:27 +00003199 TL.setUnderlyingTInfo(TInfo);
3200 }
Sean Huntca63c202011-05-24 22:41:36 +00003201 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3202 // FIXME: This holds only because we only have one unary transform.
3203 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3204 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3205 TL.setParensRange(DS.getTypeofParensRange());
3206 assert(DS.getRepAsType());
3207 TypeSourceInfo *TInfo = 0;
3208 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3209 TL.setUnderlyingTInfo(TInfo);
3210 }
Douglas Gregorddf889a2010-01-18 18:04:31 +00003211 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3212 // By default, use the source location of the type specifier.
3213 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3214 if (TL.needsExtraLocalData()) {
3215 // Set info for the written builtin specifiers.
3216 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3217 // Try to have a meaningful source location.
3218 if (TL.getWrittenSignSpec() != TSS_unspecified)
3219 // Sign spec loc overrides the others (e.g., 'unsigned long').
3220 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3221 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3222 // Width spec loc overrides type spec loc (e.g., 'short int').
3223 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3224 }
3225 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003226 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3227 ElaboratedTypeKeyword Keyword
3228 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00003229 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003230 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00003231 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003232 if (TInfo) {
3233 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
3234 return;
3235 }
3236 }
Abramo Bagnara38a42912012-02-06 19:09:27 +00003237 TL.setElaboratedKeywordLoc(Keyword != ETK_None
3238 ? DS.getTypeSpecTypeLoc()
3239 : SourceLocation());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003240 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor9e876872011-03-01 18:12:44 +00003241 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003242 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3243 }
3244 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00003245 assert(DS.getTypeSpecType() == TST_typename);
3246 TypeSourceInfo *TInfo = 0;
3247 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3248 assert(TInfo);
3249 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003250 }
John McCall33500952010-06-11 00:33:02 +00003251 void VisitDependentTemplateSpecializationTypeLoc(
3252 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00003253 assert(DS.getTypeSpecType() == TST_typename);
3254 TypeSourceInfo *TInfo = 0;
3255 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3256 assert(TInfo);
3257 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
3258 TInfo->getTypeLoc()));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00003259 }
3260 void VisitTagTypeLoc(TagTypeLoc TL) {
3261 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
John McCall33500952010-06-11 00:33:02 +00003262 }
Eli Friedmanb001de72011-10-06 23:00:33 +00003263 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3264 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3265 TL.setParensRange(DS.getTypeofParensRange());
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003266
Douglas Gregor43fe2452011-10-09 18:45:17 +00003267 TypeSourceInfo *TInfo = 0;
3268 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3269 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
Eli Friedmanb001de72011-10-06 23:00:33 +00003270 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003271
John McCall51bd8032009-10-18 01:05:36 +00003272 void VisitTypeLoc(TypeLoc TL) {
3273 // FIXME: add other typespec types and change this to an assert.
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003274 TL.initialize(Context, DS.getTypeSpecTypeLoc());
John McCall51bd8032009-10-18 01:05:36 +00003275 }
3276 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003277
John McCall51bd8032009-10-18 01:05:36 +00003278 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003279 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00003280 const DeclaratorChunk &Chunk;
3281
3282 public:
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003283 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3284 : Context(Context), Chunk(Chunk) {}
John McCall51bd8032009-10-18 01:05:36 +00003285
3286 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003287 llvm_unreachable("qualified type locs not expected here!");
John McCall51bd8032009-10-18 01:05:36 +00003288 }
3289
John McCallf85e1932011-06-15 23:02:42 +00003290 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3291 fillAttributedTypeLoc(TL, Chunk.getAttrs());
3292 }
John McCall51bd8032009-10-18 01:05:36 +00003293 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3294 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3295 TL.setCaretLoc(Chunk.Loc);
3296 }
3297 void VisitPointerTypeLoc(PointerTypeLoc TL) {
3298 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3299 TL.setStarLoc(Chunk.Loc);
3300 }
3301 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3302 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3303 TL.setStarLoc(Chunk.Loc);
3304 }
3305 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3306 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003307 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3308 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3309
3310 const Type* ClsTy = TL.getClass();
3311 QualType ClsQT = QualType(ClsTy, 0);
3312 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3313 // Now copy source location info into the type loc component.
3314 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3315 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3316 case NestedNameSpecifier::Identifier:
3317 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3318 {
Abramo Bagnarafd9c42e2011-03-06 22:48:24 +00003319 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
Abramo Bagnara38a42912012-02-06 19:09:27 +00003320 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003321 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3322 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3323 }
3324 break;
3325
3326 case NestedNameSpecifier::TypeSpec:
3327 case NestedNameSpecifier::TypeSpecWithTemplate:
3328 if (isa<ElaboratedType>(ClsTy)) {
3329 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
Abramo Bagnara38a42912012-02-06 19:09:27 +00003330 ETLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003331 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3332 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3333 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3334 } else {
3335 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3336 }
3337 break;
3338
3339 case NestedNameSpecifier::Namespace:
3340 case NestedNameSpecifier::NamespaceAlias:
3341 case NestedNameSpecifier::Global:
3342 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003343 }
3344
3345 // Finally fill in MemberPointerLocInfo fields.
John McCall51bd8032009-10-18 01:05:36 +00003346 TL.setStarLoc(Chunk.Loc);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003347 TL.setClassTInfo(ClsTInfo);
John McCall51bd8032009-10-18 01:05:36 +00003348 }
3349 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3350 assert(Chunk.Kind == DeclaratorChunk::Reference);
John McCall54e14c42009-10-22 22:37:11 +00003351 // 'Amp' is misleading: this might have been originally
3352 /// spelled with AmpAmp.
John McCall51bd8032009-10-18 01:05:36 +00003353 TL.setAmpLoc(Chunk.Loc);
3354 }
3355 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3356 assert(Chunk.Kind == DeclaratorChunk::Reference);
3357 assert(!Chunk.Ref.LValueRef);
3358 TL.setAmpAmpLoc(Chunk.Loc);
3359 }
3360 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3361 assert(Chunk.Kind == DeclaratorChunk::Array);
3362 TL.setLBracketLoc(Chunk.Loc);
3363 TL.setRBracketLoc(Chunk.EndLoc);
3364 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3365 }
3366 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3367 assert(Chunk.Kind == DeclaratorChunk::Function);
Abramo Bagnara796aa442011-03-12 11:17:06 +00003368 TL.setLocalRangeBegin(Chunk.Loc);
3369 TL.setLocalRangeEnd(Chunk.EndLoc);
John McCall51bd8032009-10-18 01:05:36 +00003370
3371 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
Abramo Bagnara59c0a812012-10-04 21:42:10 +00003372 TL.setLParenLoc(FTI.getLParenLoc());
3373 TL.setRParenLoc(FTI.getRParenLoc());
John McCall54e14c42009-10-22 22:37:11 +00003374 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00003375 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
John McCall54e14c42009-10-22 22:37:11 +00003376 TL.setArg(tpi++, Param);
John McCall51bd8032009-10-18 01:05:36 +00003377 }
3378 // FIXME: exception specs
3379 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003380 void VisitParenTypeLoc(ParenTypeLoc TL) {
3381 assert(Chunk.Kind == DeclaratorChunk::Paren);
3382 TL.setLParenLoc(Chunk.Loc);
3383 TL.setRParenLoc(Chunk.EndLoc);
3384 }
John McCall51bd8032009-10-18 01:05:36 +00003385
3386 void VisitTypeLoc(TypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003387 llvm_unreachable("unsupported TypeLoc kind in declarator!");
John McCall51bd8032009-10-18 01:05:36 +00003388 }
3389 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003390}
3391
John McCalla93c9342009-12-07 02:54:59 +00003392/// \brief Create and instantiate a TypeSourceInfo with type source information.
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003393///
3394/// \param T QualType referring to the type as written in source code.
Douglas Gregor05baacb2010-04-12 23:19:01 +00003395///
3396/// \param ReturnTypeInfo For declarators whose return type does not show
3397/// up in the normal place in the declaration specifiers (such as a C++
3398/// conversion function), this pointer will refer to a type source information
3399/// for that return type.
John McCalla93c9342009-12-07 02:54:59 +00003400TypeSourceInfo *
Douglas Gregor05baacb2010-04-12 23:19:01 +00003401Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3402 TypeSourceInfo *ReturnTypeInfo) {
John McCalla93c9342009-12-07 02:54:59 +00003403 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3404 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003405
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003406 // Handle parameter packs whose type is a pack expansion.
3407 if (isa<PackExpansionType>(T)) {
3408 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003409 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003410 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003411
Sebastian Redl8ce35b02009-10-25 21:45:37 +00003412 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall14aa2172011-03-04 04:00:19 +00003413 while (isa<AttributedTypeLoc>(CurrTL)) {
3414 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3415 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3416 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3417 }
3418
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003419 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
John McCall51bd8032009-10-18 01:05:36 +00003420 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003421 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003422
John McCallb3d87482010-08-24 05:47:05 +00003423 // If we have different source information for the return type, use
3424 // that. This really only applies to C++ conversion functions.
3425 if (ReturnTypeInfo) {
Douglas Gregor05baacb2010-04-12 23:19:01 +00003426 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3427 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3428 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
John McCallb3d87482010-08-24 05:47:05 +00003429 } else {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003430 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
Douglas Gregor05baacb2010-04-12 23:19:01 +00003431 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003432
John McCalla93c9342009-12-07 02:54:59 +00003433 return TInfo;
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003434}
3435
John McCalla93c9342009-12-07 02:54:59 +00003436/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
John McCallb3d87482010-08-24 05:47:05 +00003437ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003438 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3439 // and Sema during declaration parsing. Try deallocating/caching them when
3440 // it's appropriate, instead of allocating them and keeping them around.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003441 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
Douglas Gregoreb0eb492010-12-10 08:12:03 +00003442 TypeAlignment);
John McCalla93c9342009-12-07 02:54:59 +00003443 new (LocT) LocInfoType(T, TInfo);
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003444 assert(LocT->getTypeClass() != T->getTypeClass() &&
3445 "LocInfoType's TypeClass conflicts with an existing Type class");
John McCallb3d87482010-08-24 05:47:05 +00003446 return ParsedType::make(QualType(LocT, 0));
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003447}
3448
3449void LocInfoType::getAsStringInternal(std::string &Str,
3450 const PrintingPolicy &Policy) const {
David Blaikieb219cfc2011-09-23 05:06:16 +00003451 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
Argyrios Kyrtzidis35d44e52009-08-19 01:46:06 +00003452 " was used directly instead of getting the QualType through"
3453 " GetTypeFromParser");
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003454}
3455
John McCallf312b1e2010-08-26 23:41:50 +00003456TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003457 // C99 6.7.6: Type names have no identifier. This is already validated by
3458 // the parser.
3459 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
Mike Stump1eb44332009-09-09 15:08:12 +00003460
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003461 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00003462 QualType T = TInfo->getType();
Chris Lattner5153ee62009-04-25 08:47:54 +00003463 if (D.isInvalidType())
Douglas Gregor809070a2009-02-18 17:45:20 +00003464 return true;
Steve Naroff5912a352007-08-28 20:14:24 +00003465
John McCalle82247a2011-10-01 05:17:03 +00003466 // Make sure there are no unused decl attributes on the declarator.
John McCallcdda47f2011-10-01 09:56:14 +00003467 // We don't want to do this for ObjC parameters because we're going
3468 // to apply them to the actual parameter declaration.
3469 if (D.getContext() != Declarator::ObjCParameterContext)
3470 checkUnusedDeclAttributes(D);
John McCalle82247a2011-10-01 05:17:03 +00003471
David Blaikie4e4d0842012-03-11 07:00:24 +00003472 if (getLangOpts().CPlusPlus) {
Douglas Gregor402abb52009-05-28 23:31:59 +00003473 // Check that there are no default arguments (C++ only).
Douglas Gregor6d6eb572008-05-07 04:49:29 +00003474 CheckExtraCXXDefaultArguments(D);
Douglas Gregor402abb52009-05-28 23:31:59 +00003475 }
3476
John McCallb3d87482010-08-24 05:47:05 +00003477 return CreateParsedType(T, TInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00003478}
3479
Douglas Gregore97179c2011-09-08 01:46:34 +00003480ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3481 QualType T = Context.getObjCInstanceType();
3482 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3483 return CreateParsedType(T, TInfo);
3484}
3485
3486
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003487//===----------------------------------------------------------------------===//
3488// Type Attribute Processing
3489//===----------------------------------------------------------------------===//
3490
3491/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3492/// specified type. The attribute contains 1 argument, the id of the address
3493/// space for the type.
Mike Stump1eb44332009-09-09 15:08:12 +00003494static void HandleAddressSpaceTypeAttribute(QualType &Type,
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003495 const AttributeList &Attr, Sema &S){
John McCall0953e762009-09-24 19:53:00 +00003496
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003497 // If this type is already address space qualified, reject it.
Peter Collingbourne29e3ef82011-07-27 20:29:53 +00003498 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3499 // qualifiers for two or more different address spaces."
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003500 if (Type.getAddressSpace()) {
3501 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
Abramo Bagnarae215f722010-04-30 13:10:51 +00003502 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003503 return;
3504 }
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Peter Collingbourne020972d2011-07-27 20:30:05 +00003506 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3507 // qualified by an address-space qualifier."
3508 if (Type->isFunctionType()) {
3509 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3510 Attr.setInvalid();
3511 return;
3512 }
3513
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003514 // Check the attribute arguments.
3515 if (Attr.getNumArgs() != 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003516 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003517 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003518 return;
3519 }
3520 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3521 llvm::APSInt addrSpace(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003522 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3523 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003524 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3525 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003526 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003527 return;
3528 }
3529
John McCallefadb772009-07-28 06:52:18 +00003530 // Bounds checking.
3531 if (addrSpace.isSigned()) {
3532 if (addrSpace.isNegative()) {
3533 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3534 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003535 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003536 return;
3537 }
3538 addrSpace.setIsSigned(false);
3539 }
3540 llvm::APSInt max(addrSpace.getBitWidth());
John McCall0953e762009-09-24 19:53:00 +00003541 max = Qualifiers::MaxAddressSpace;
John McCallefadb772009-07-28 06:52:18 +00003542 if (addrSpace > max) {
3543 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
John McCall0953e762009-09-24 19:53:00 +00003544 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003545 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003546 return;
3547 }
3548
Mike Stump1eb44332009-09-09 15:08:12 +00003549 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003550 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003551}
3552
John McCalld85bf9d2012-02-08 00:46:41 +00003553/// Does this type have a "direct" ownership qualifier? That is,
3554/// is it written like "__strong id", as opposed to something like
3555/// "typeof(foo)", where that happens to be strong?
3556static bool hasDirectOwnershipQualifier(QualType type) {
3557 // Fast path: no qualifier at all.
3558 assert(type.getQualifiers().hasObjCLifetime());
3559
3560 while (true) {
3561 // __strong id
3562 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3563 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3564 return true;
3565
3566 type = attr->getModifiedType();
3567
3568 // X *__strong (...)
3569 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3570 type = paren->getInnerType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003571
John McCalld85bf9d2012-02-08 00:46:41 +00003572 // That's it for things we want to complain about. In particular,
3573 // we do not want to look through typedefs, typeof(expr),
3574 // typeof(type), or any other way that the type is somehow
3575 // abstracted.
3576 } else {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003577
John McCalld85bf9d2012-02-08 00:46:41 +00003578 return false;
3579 }
3580 }
3581}
3582
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003583/// handleObjCOwnershipTypeAttr - Process an objc_ownership
John McCallf85e1932011-06-15 23:02:42 +00003584/// attribute on the specified type.
3585///
3586/// Returns 'true' if the attribute was handled.
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003587static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +00003588 AttributeList &attr,
3589 QualType &type) {
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003590 bool NonObjCPointer = false;
3591
3592 if (!type->isDependentType()) {
3593 if (const PointerType *ptr = type->getAs<PointerType>()) {
3594 QualType pointee = ptr->getPointeeType();
3595 if (pointee->isObjCRetainableType() || pointee->isPointerType())
3596 return false;
3597 // It is important not to lose the source info that there was an attribute
3598 // applied to non-objc pointer. We will create an attributed type but
3599 // its type will be the same as the original type.
3600 NonObjCPointer = true;
3601 } else if (!type->isObjCRetainableType()) {
3602 return false;
3603 }
3604 }
John McCallf85e1932011-06-15 23:02:42 +00003605
3606 Sema &S = state.getSema();
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003607 SourceLocation AttrLoc = attr.getLoc();
3608 if (AttrLoc.isMacroID())
3609 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
John McCallf85e1932011-06-15 23:02:42 +00003610
John McCallf85e1932011-06-15 23:02:42 +00003611 if (!attr.getParameterName()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003612 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003613 << "objc_ownership" << 1;
John McCallf85e1932011-06-15 23:02:42 +00003614 attr.setInvalid();
3615 return true;
3616 }
3617
John McCalld85bf9d2012-02-08 00:46:41 +00003618 // Consume lifetime attributes without further comment outside of
3619 // ARC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003620 if (!S.getLangOpts().ObjCAutoRefCount)
John McCalld85bf9d2012-02-08 00:46:41 +00003621 return true;
3622
John McCallf85e1932011-06-15 23:02:42 +00003623 Qualifiers::ObjCLifetime lifetime;
3624 if (attr.getParameterName()->isStr("none"))
3625 lifetime = Qualifiers::OCL_ExplicitNone;
3626 else if (attr.getParameterName()->isStr("strong"))
3627 lifetime = Qualifiers::OCL_Strong;
3628 else if (attr.getParameterName()->isStr("weak"))
3629 lifetime = Qualifiers::OCL_Weak;
3630 else if (attr.getParameterName()->isStr("autoreleasing"))
3631 lifetime = Qualifiers::OCL_Autoreleasing;
3632 else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003633 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003634 << "objc_ownership" << attr.getParameterName();
John McCallf85e1932011-06-15 23:02:42 +00003635 attr.setInvalid();
3636 return true;
3637 }
3638
John McCalld85bf9d2012-02-08 00:46:41 +00003639 SplitQualType underlyingType = type.split();
3640
3641 // Check for redundant/conflicting ownership qualifiers.
3642 if (Qualifiers::ObjCLifetime previousLifetime
3643 = type.getQualifiers().getObjCLifetime()) {
3644 // If it's written directly, that's an error.
3645 if (hasDirectOwnershipQualifier(type)) {
3646 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3647 << type;
3648 return true;
3649 }
3650
3651 // Otherwise, if the qualifiers actually conflict, pull sugar off
3652 // until we reach a type that is directly qualified.
3653 if (previousLifetime != lifetime) {
3654 // This should always terminate: the canonical type is
3655 // qualified, so some bit of sugar must be hiding it.
3656 while (!underlyingType.Quals.hasObjCLifetime()) {
3657 underlyingType = underlyingType.getSingleStepDesugaredType();
3658 }
3659 underlyingType.Quals.removeObjCLifetime();
3660 }
3661 }
3662
3663 underlyingType.Quals.addObjCLifetime(lifetime);
John McCallf85e1932011-06-15 23:02:42 +00003664
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003665 if (NonObjCPointer) {
3666 StringRef name = attr.getName()->getName();
3667 switch (lifetime) {
3668 case Qualifiers::OCL_None:
3669 case Qualifiers::OCL_ExplicitNone:
3670 break;
3671 case Qualifiers::OCL_Strong: name = "__strong"; break;
3672 case Qualifiers::OCL_Weak: name = "__weak"; break;
3673 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3674 }
3675 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3676 << name << type;
3677 }
3678
John McCallf85e1932011-06-15 23:02:42 +00003679 QualType origType = type;
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003680 if (!NonObjCPointer)
John McCalld85bf9d2012-02-08 00:46:41 +00003681 type = S.Context.getQualifiedType(underlyingType);
John McCallf85e1932011-06-15 23:02:42 +00003682
3683 // If we have a valid source location for the attribute, use an
3684 // AttributedType instead.
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003685 if (AttrLoc.isValid())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003686 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
John McCallf85e1932011-06-15 23:02:42 +00003687 origType, type);
3688
John McCall9f084a32011-07-06 00:26:06 +00003689 // Forbid __weak if the runtime doesn't support it.
John McCallf85e1932011-06-15 23:02:42 +00003690 if (lifetime == Qualifiers::OCL_Weak &&
John McCall0a7dd782012-08-21 02:47:43 +00003691 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
John McCallf85e1932011-06-15 23:02:42 +00003692
3693 // Actually, delay this until we know what we're parsing.
3694 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3695 S.DelayedDiagnostics.add(
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003696 sema::DelayedDiagnostic::makeForbiddenType(
3697 S.getSourceManager().getExpansionLoc(AttrLoc),
John McCallf85e1932011-06-15 23:02:42 +00003698 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3699 } else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003700 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
John McCallf85e1932011-06-15 23:02:42 +00003701 }
3702
3703 attr.setInvalid();
3704 return true;
3705 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003706
3707 // Forbid __weak for class objects marked as
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003708 // objc_arc_weak_reference_unavailable
3709 if (lifetime == Qualifiers::OCL_Weak) {
3710 QualType T = type;
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003711 while (const PointerType *ptr = T->getAs<PointerType>())
3712 T = ptr->getPointeeType();
3713 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
Richard Smith4e90bc32012-08-23 04:53:18 +00003714 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
3715 if (Class->isArcWeakrefUnavailable()) {
3716 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
3717 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3718 diag::note_class_declared);
3719 }
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003720 }
3721 }
3722 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003723
John McCallf85e1932011-06-15 23:02:42 +00003724 return true;
3725}
3726
John McCall711c52b2011-01-05 12:14:39 +00003727/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3728/// attribute on the specified type. Returns true to indicate that
3729/// the attribute was handled, false to indicate that the type does
3730/// not permit the attribute.
3731static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3732 AttributeList &attr,
3733 QualType &type) {
3734 Sema &S = state.getSema();
3735
3736 // Delay if this isn't some kind of pointer.
3737 if (!type->isPointerType() &&
3738 !type->isObjCObjectPointerType() &&
3739 !type->isBlockPointerType())
3740 return false;
3741
3742 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3743 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3744 attr.setInvalid();
3745 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003746 }
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003748 // Check the attribute arguments.
John McCall711c52b2011-01-05 12:14:39 +00003749 if (!attr.getParameterName()) {
3750 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003751 << "objc_gc" << 1;
John McCall711c52b2011-01-05 12:14:39 +00003752 attr.setInvalid();
3753 return true;
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003754 }
John McCall0953e762009-09-24 19:53:00 +00003755 Qualifiers::GC GCAttr;
John McCall711c52b2011-01-05 12:14:39 +00003756 if (attr.getNumArgs() != 0) {
3757 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3758 attr.setInvalid();
3759 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003760 }
John McCall711c52b2011-01-05 12:14:39 +00003761 if (attr.getParameterName()->isStr("weak"))
John McCall0953e762009-09-24 19:53:00 +00003762 GCAttr = Qualifiers::Weak;
John McCall711c52b2011-01-05 12:14:39 +00003763 else if (attr.getParameterName()->isStr("strong"))
John McCall0953e762009-09-24 19:53:00 +00003764 GCAttr = Qualifiers::Strong;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003765 else {
John McCall711c52b2011-01-05 12:14:39 +00003766 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3767 << "objc_gc" << attr.getParameterName();
3768 attr.setInvalid();
3769 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003770 }
Mike Stump1eb44332009-09-09 15:08:12 +00003771
John McCall14aa2172011-03-04 04:00:19 +00003772 QualType origType = type;
3773 type = S.Context.getObjCGCQualType(origType, GCAttr);
3774
3775 // Make an attributed type to preserve the source information.
3776 if (attr.getLoc().isValid())
3777 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3778 origType, type);
3779
John McCall711c52b2011-01-05 12:14:39 +00003780 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003781}
3782
John McCalle6a365d2010-12-19 02:44:49 +00003783namespace {
3784 /// A helper class to unwrap a type down to a function for the
3785 /// purposes of applying attributes there.
3786 ///
3787 /// Use:
3788 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3789 /// if (unwrapped.isFunctionType()) {
3790 /// const FunctionType *fn = unwrapped.get();
3791 /// // change fn somehow
3792 /// T = unwrapped.wrap(fn);
3793 /// }
3794 struct FunctionTypeUnwrapper {
3795 enum WrapKind {
3796 Desugar,
3797 Parens,
3798 Pointer,
3799 BlockPointer,
3800 Reference,
3801 MemberPointer
3802 };
3803
3804 QualType Original;
3805 const FunctionType *Fn;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003806 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
John McCalle6a365d2010-12-19 02:44:49 +00003807
3808 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3809 while (true) {
3810 const Type *Ty = T.getTypePtr();
3811 if (isa<FunctionType>(Ty)) {
3812 Fn = cast<FunctionType>(Ty);
3813 return;
3814 } else if (isa<ParenType>(Ty)) {
3815 T = cast<ParenType>(Ty)->getInnerType();
3816 Stack.push_back(Parens);
3817 } else if (isa<PointerType>(Ty)) {
3818 T = cast<PointerType>(Ty)->getPointeeType();
3819 Stack.push_back(Pointer);
3820 } else if (isa<BlockPointerType>(Ty)) {
3821 T = cast<BlockPointerType>(Ty)->getPointeeType();
3822 Stack.push_back(BlockPointer);
3823 } else if (isa<MemberPointerType>(Ty)) {
3824 T = cast<MemberPointerType>(Ty)->getPointeeType();
3825 Stack.push_back(MemberPointer);
3826 } else if (isa<ReferenceType>(Ty)) {
3827 T = cast<ReferenceType>(Ty)->getPointeeType();
3828 Stack.push_back(Reference);
3829 } else {
3830 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3831 if (Ty == DTy) {
3832 Fn = 0;
3833 return;
3834 }
3835
3836 T = QualType(DTy, 0);
3837 Stack.push_back(Desugar);
3838 }
3839 }
3840 }
3841
3842 bool isFunctionType() const { return (Fn != 0); }
3843 const FunctionType *get() const { return Fn; }
3844
3845 QualType wrap(Sema &S, const FunctionType *New) {
3846 // If T wasn't modified from the unwrapped type, do nothing.
3847 if (New == get()) return Original;
3848
3849 Fn = New;
3850 return wrap(S.Context, Original, 0);
3851 }
3852
3853 private:
3854 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3855 if (I == Stack.size())
3856 return C.getQualifiedType(Fn, Old.getQualifiers());
3857
3858 // Build up the inner type, applying the qualifiers from the old
3859 // type to the new type.
3860 SplitQualType SplitOld = Old.split();
3861
3862 // As a special case, tail-recurse if there are no qualifiers.
John McCall200fa532012-02-08 00:46:36 +00003863 if (SplitOld.Quals.empty())
3864 return wrap(C, SplitOld.Ty, I);
3865 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
John McCalle6a365d2010-12-19 02:44:49 +00003866 }
3867
3868 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3869 if (I == Stack.size()) return QualType(Fn, 0);
3870
3871 switch (static_cast<WrapKind>(Stack[I++])) {
3872 case Desugar:
3873 // This is the point at which we potentially lose source
3874 // information.
3875 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3876
3877 case Parens: {
3878 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3879 return C.getParenType(New);
3880 }
3881
3882 case Pointer: {
3883 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3884 return C.getPointerType(New);
3885 }
3886
3887 case BlockPointer: {
3888 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3889 return C.getBlockPointerType(New);
3890 }
3891
3892 case MemberPointer: {
3893 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3894 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3895 return C.getMemberPointerType(New, OldMPT->getClass());
3896 }
3897
3898 case Reference: {
3899 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3900 QualType New = wrap(C, OldRef->getPointeeType(), I);
3901 if (isa<LValueReferenceType>(OldRef))
3902 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3903 else
3904 return C.getRValueReferenceType(New);
3905 }
3906 }
3907
3908 llvm_unreachable("unknown wrapping kind");
John McCalle6a365d2010-12-19 02:44:49 +00003909 }
3910 };
3911}
3912
John McCall711c52b2011-01-05 12:14:39 +00003913/// Process an individual function attribute. Returns true to
3914/// indicate that the attribute was handled, false if it wasn't.
3915static bool handleFunctionTypeAttr(TypeProcessingState &state,
3916 AttributeList &attr,
3917 QualType &type) {
3918 Sema &S = state.getSema();
John McCalle6a365d2010-12-19 02:44:49 +00003919
John McCall711c52b2011-01-05 12:14:39 +00003920 FunctionTypeUnwrapper unwrapped(S, type);
Mike Stump24556362009-07-25 21:26:53 +00003921
Sean Hunt8e083e72012-06-19 23:57:03 +00003922 if (attr.getKind() == AttributeList::AT_NoReturn) {
John McCall711c52b2011-01-05 12:14:39 +00003923 if (S.CheckNoReturnAttr(attr))
John McCall04a67a62010-02-05 21:31:56 +00003924 return true;
John McCalle6a365d2010-12-19 02:44:49 +00003925
John McCall711c52b2011-01-05 12:14:39 +00003926 // Delay if this is not a function type.
3927 if (!unwrapped.isFunctionType())
3928 return false;
3929
John McCall04a67a62010-02-05 21:31:56 +00003930 // Otherwise we can process right away.
John McCall711c52b2011-01-05 12:14:39 +00003931 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3932 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3933 return true;
John McCall04a67a62010-02-05 21:31:56 +00003934 }
Mike Stump24556362009-07-25 21:26:53 +00003935
John McCallf85e1932011-06-15 23:02:42 +00003936 // ns_returns_retained is not always a type attribute, but if we got
3937 // here, we're treating it as one right now.
Sean Hunt8e083e72012-06-19 23:57:03 +00003938 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003939 assert(S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003940 "ns_returns_retained treated as type attribute in non-ARC");
3941 if (attr.getNumArgs()) return true;
3942
3943 // Delay if this is not a function type.
3944 if (!unwrapped.isFunctionType())
3945 return false;
3946
3947 FunctionType::ExtInfo EI
3948 = unwrapped.get()->getExtInfo().withProducesResult(true);
3949 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3950 return true;
3951 }
3952
Sean Hunt8e083e72012-06-19 23:57:03 +00003953 if (attr.getKind() == AttributeList::AT_Regparm) {
John McCall711c52b2011-01-05 12:14:39 +00003954 unsigned value;
3955 if (S.CheckRegparmAttr(attr, value))
Rafael Espindola425ef722010-03-30 22:15:11 +00003956 return true;
3957
John McCall711c52b2011-01-05 12:14:39 +00003958 // Delay if this is not a function type.
3959 if (!unwrapped.isFunctionType())
Rafael Espindola425ef722010-03-30 22:15:11 +00003960 return false;
3961
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003962 // Diagnose regparm with fastcall.
3963 const FunctionType *fn = unwrapped.get();
3964 CallingConv CC = fn->getCallConv();
3965 if (CC == CC_X86FastCall) {
3966 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3967 << FunctionType::getNameForCallConv(CC)
3968 << "regparm";
3969 attr.setInvalid();
3970 return true;
3971 }
3972
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003973 FunctionType::ExtInfo EI =
John McCall711c52b2011-01-05 12:14:39 +00003974 unwrapped.get()->getExtInfo().withRegParm(value);
3975 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3976 return true;
Rafael Espindola425ef722010-03-30 22:15:11 +00003977 }
3978
Aaron Ballman82bfa192012-10-02 14:26:08 +00003979 // Delay if the type didn't work out to a function.
3980 if (!unwrapped.isFunctionType()) return false;
3981
John McCall04a67a62010-02-05 21:31:56 +00003982 // Otherwise, a calling convention.
John McCall711c52b2011-01-05 12:14:39 +00003983 CallingConv CC;
3984 if (S.CheckCallingConvAttr(attr, CC))
3985 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003986
John McCall711c52b2011-01-05 12:14:39 +00003987 const FunctionType *fn = unwrapped.get();
3988 CallingConv CCOld = fn->getCallConv();
Charles Davis064f7db2010-02-23 06:13:55 +00003989 if (S.Context.getCanonicalCallConv(CC) ==
Abramo Bagnarae215f722010-04-30 13:10:51 +00003990 S.Context.getCanonicalCallConv(CCOld)) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003991 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3992 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
John McCall711c52b2011-01-05 12:14:39 +00003993 return true;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003994 }
John McCall04a67a62010-02-05 21:31:56 +00003995
Roman Divacky8e68f1c2011-08-05 16:37:22 +00003996 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
John McCall04a67a62010-02-05 21:31:56 +00003997 // Should we diagnose reapplications of the same convention?
John McCall711c52b2011-01-05 12:14:39 +00003998 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
John McCall04a67a62010-02-05 21:31:56 +00003999 << FunctionType::getNameForCallConv(CC)
4000 << FunctionType::getNameForCallConv(CCOld);
John McCall711c52b2011-01-05 12:14:39 +00004001 attr.setInvalid();
4002 return true;
John McCall04a67a62010-02-05 21:31:56 +00004003 }
4004
4005 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
4006 if (CC == CC_X86FastCall) {
John McCall711c52b2011-01-05 12:14:39 +00004007 if (isa<FunctionNoProtoType>(fn)) {
4008 S.Diag(attr.getLoc(), diag::err_cconv_knr)
John McCall04a67a62010-02-05 21:31:56 +00004009 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00004010 attr.setInvalid();
4011 return true;
John McCall04a67a62010-02-05 21:31:56 +00004012 }
4013
John McCall711c52b2011-01-05 12:14:39 +00004014 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
John McCall04a67a62010-02-05 21:31:56 +00004015 if (FnP->isVariadic()) {
John McCall711c52b2011-01-05 12:14:39 +00004016 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
John McCall04a67a62010-02-05 21:31:56 +00004017 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00004018 attr.setInvalid();
4019 return true;
John McCall04a67a62010-02-05 21:31:56 +00004020 }
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00004021
4022 // Also diagnose fastcall with regparm.
Eli Friedmana49218e2011-04-09 08:18:08 +00004023 if (fn->getHasRegParm()) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00004024 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4025 << "regparm"
4026 << FunctionType::getNameForCallConv(CC);
4027 attr.setInvalid();
4028 return true;
4029 }
John McCall04a67a62010-02-05 21:31:56 +00004030 }
4031
John McCall711c52b2011-01-05 12:14:39 +00004032 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
4033 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4034 return true;
John McCallf82b4e82010-02-04 05:44:44 +00004035}
4036
Peter Collingbourne207f4d82011-03-18 22:38:29 +00004037/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
4038static void HandleOpenCLImageAccessAttribute(QualType& CurType,
4039 const AttributeList &Attr,
4040 Sema &S) {
4041 // Check the attribute arguments.
4042 if (Attr.getNumArgs() != 1) {
4043 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4044 Attr.setInvalid();
4045 return;
4046 }
4047 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4048 llvm::APSInt arg(32);
4049 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4050 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
4051 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4052 << "opencl_image_access" << sizeExpr->getSourceRange();
4053 Attr.setInvalid();
4054 return;
4055 }
4056 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
4057 switch (iarg) {
4058 case CLIA_read_only:
4059 case CLIA_write_only:
4060 case CLIA_read_write:
4061 // Implemented in a separate patch
4062 break;
4063 default:
4064 // Implemented in a separate patch
4065 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4066 << sizeExpr->getSourceRange();
4067 Attr.setInvalid();
4068 break;
4069 }
4070}
4071
John Thompson6e132aa2009-12-04 21:51:28 +00004072/// HandleVectorSizeAttribute - this attribute is only applicable to integral
4073/// and float scalars, although arrays, pointers, and function return values are
4074/// allowed in conjunction with this construct. Aggregates with this attribute
4075/// are invalid, even if they are of the same size as a corresponding scalar.
4076/// The raw attribute should contain precisely 1 argument, the vector size for
4077/// the variable, measured in bytes. If curType and rawAttr are well formed,
4078/// this routine will return a new vector type.
Chris Lattner788b0fd2010-06-23 06:00:24 +00004079static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4080 Sema &S) {
Bob Wilson56affbc2010-11-16 00:32:16 +00004081 // Check the attribute arguments.
John Thompson6e132aa2009-12-04 21:51:28 +00004082 if (Attr.getNumArgs() != 1) {
4083 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00004084 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004085 return;
4086 }
4087 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4088 llvm::APSInt vecSize(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00004089 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4090 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
John Thompson6e132aa2009-12-04 21:51:28 +00004091 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4092 << "vector_size" << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00004093 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004094 return;
4095 }
4096 // the base type must be integer or float, and can't already be a vector.
Douglas Gregorf6094622010-07-23 15:58:24 +00004097 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
John Thompson6e132aa2009-12-04 21:51:28 +00004098 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
Abramo Bagnarae215f722010-04-30 13:10:51 +00004099 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004100 return;
4101 }
4102 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4103 // vecSize is specified in bytes - convert to bits.
4104 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4105
4106 // the vector size needs to be an integral multiple of the type size.
4107 if (vectorSize % typeSize) {
4108 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4109 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00004110 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004111 return;
4112 }
4113 if (vectorSize == 0) {
4114 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4115 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00004116 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004117 return;
4118 }
4119
4120 // Success! Instantiate the vector type, the number of elements is > 0, and
4121 // not required to be a power of 2, unlike GCC.
Chris Lattner788b0fd2010-06-23 06:00:24 +00004122 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
Bob Wilsone86d78c2010-11-10 21:56:12 +00004123 VectorType::GenericVector);
John Thompson6e132aa2009-12-04 21:51:28 +00004124}
4125
Douglas Gregor4ac01402011-06-15 16:02:29 +00004126/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4127/// a type.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004128static void HandleExtVectorTypeAttr(QualType &CurType,
4129 const AttributeList &Attr,
Douglas Gregor4ac01402011-06-15 16:02:29 +00004130 Sema &S) {
4131 Expr *sizeExpr;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004132
Douglas Gregor4ac01402011-06-15 16:02:29 +00004133 // Special case where the argument is a template id.
4134 if (Attr.getParameterName()) {
4135 CXXScopeSpec SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004136 SourceLocation TemplateKWLoc;
Douglas Gregor4ac01402011-06-15 16:02:29 +00004137 UnqualifiedId id;
4138 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004139
4140 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4141 id, false, false);
Douglas Gregor4ac01402011-06-15 16:02:29 +00004142 if (Size.isInvalid())
4143 return;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004144
Douglas Gregor4ac01402011-06-15 16:02:29 +00004145 sizeExpr = Size.get();
4146 } else {
4147 // check the attribute arguments.
4148 if (Attr.getNumArgs() != 1) {
4149 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4150 return;
4151 }
4152 sizeExpr = Attr.getArg(0);
4153 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004154
Douglas Gregor4ac01402011-06-15 16:02:29 +00004155 // Create the vector type.
4156 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4157 if (!T.isNull())
4158 CurType = T;
4159}
4160
Bob Wilson4211bb62010-11-16 00:32:24 +00004161/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4162/// "neon_polyvector_type" attributes are used to create vector types that
4163/// are mangled according to ARM's ABI. Otherwise, these types are identical
4164/// to those created with the "vector_size" attribute. Unlike "vector_size"
4165/// the argument to these Neon attributes is the number of vector elements,
4166/// not the vector size in bytes. The vector width and element type must
4167/// match one of the standard Neon vector types.
4168static void HandleNeonVectorTypeAttr(QualType& CurType,
4169 const AttributeList &Attr, Sema &S,
4170 VectorType::VectorKind VecKind,
4171 const char *AttrName) {
4172 // Check the attribute arguments.
4173 if (Attr.getNumArgs() != 1) {
4174 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4175 Attr.setInvalid();
4176 return;
4177 }
4178 // The number of elements must be an ICE.
4179 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
4180 llvm::APSInt numEltsInt(32);
4181 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4182 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4183 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4184 << AttrName << numEltsExpr->getSourceRange();
4185 Attr.setInvalid();
4186 return;
4187 }
4188 // Only certain element types are supported for Neon vectors.
4189 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
4190 if (!BTy ||
4191 (VecKind == VectorType::NeonPolyVector &&
4192 BTy->getKind() != BuiltinType::SChar &&
4193 BTy->getKind() != BuiltinType::Short) ||
4194 (BTy->getKind() != BuiltinType::SChar &&
4195 BTy->getKind() != BuiltinType::UChar &&
4196 BTy->getKind() != BuiltinType::Short &&
4197 BTy->getKind() != BuiltinType::UShort &&
4198 BTy->getKind() != BuiltinType::Int &&
4199 BTy->getKind() != BuiltinType::UInt &&
4200 BTy->getKind() != BuiltinType::LongLong &&
4201 BTy->getKind() != BuiltinType::ULongLong &&
4202 BTy->getKind() != BuiltinType::Float)) {
4203 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
4204 Attr.setInvalid();
4205 return;
4206 }
4207 // The total size of the vector must be 64 or 128 bits.
4208 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4209 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4210 unsigned vecSize = typeSize * numElts;
4211 if (vecSize != 64 && vecSize != 128) {
4212 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4213 Attr.setInvalid();
4214 return;
4215 }
4216
4217 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4218}
4219
John McCall711c52b2011-01-05 12:14:39 +00004220static void processTypeAttrs(TypeProcessingState &state, QualType &type,
Richard Smithf7a05272013-01-14 07:53:01 +00004221 TypeAttrLocation TAL, AttributeList *attrs) {
Chris Lattner232e8822008-02-21 01:08:11 +00004222 // Scan through and apply attributes to this type where it makes sense. Some
4223 // attributes (such as __address_space__, __vector_size__, etc) apply to the
4224 // type, but others can be present in the type specifiers even though they
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00004225 // apply to the decl. Here we apply type attributes and ignore the rest.
John McCall711c52b2011-01-05 12:14:39 +00004226
4227 AttributeList *next;
4228 do {
4229 AttributeList &attr = *attrs;
4230 next = attr.getNext();
4231
Abramo Bagnarae215f722010-04-30 13:10:51 +00004232 // Skip attributes that were marked to be invalid.
John McCall711c52b2011-01-05 12:14:39 +00004233 if (attr.isInvalid())
Abramo Bagnarae215f722010-04-30 13:10:51 +00004234 continue;
4235
Richard Smithcd8ab512013-01-17 01:30:42 +00004236 if (attr.isCXX11Attribute()) {
4237 // [[gnu::...]] attributes are treated as declaration attributes, so may
4238 // not appertain to a DeclaratorChunk, even if we handle them as type
4239 // attributes.
4240 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4241 if (TAL == TAL_DeclChunk) {
4242 state.getSema().Diag(attr.getLoc(),
4243 diag::warn_cxx11_gnu_attribute_on_type)
4244 << attr.getName();
4245 continue;
4246 }
4247 } else if (TAL != TAL_DeclChunk) {
4248 // Otherwise, only consider type processing for a C++11 attribute if
4249 // it's actually been applied to a type.
4250 continue;
4251 }
Richard Smithf7a05272013-01-14 07:53:01 +00004252 }
4253
Abramo Bagnarab1f1b262010-04-30 09:13:03 +00004254 // If this is an attribute we can handle, do so now,
4255 // otherwise, add it to the FnAttrs list for rechaining.
John McCall711c52b2011-01-05 12:14:39 +00004256 switch (attr.getKind()) {
Richard Smithcd8ab512013-01-17 01:30:42 +00004257 default:
4258 // A C++11 attribute on a declarator chunk must appertain to a type.
4259 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4260 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
4261 << attr.getName()->getName();
4262 break;
4263
4264 case AttributeList::UnknownAttribute:
4265 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4266 state.getSema().Diag(attr.getLoc(),
4267 diag::warn_unknown_attribute_ignored)
4268 << attr.getName();
4269 break;
4270
4271 case AttributeList::IgnoredAttribute:
4272 break;
John McCall04a67a62010-02-05 21:31:56 +00004273
Sean Hunt8e083e72012-06-19 23:57:03 +00004274 case AttributeList::AT_MayAlias:
Chandler Carruth682eae22011-10-07 18:40:27 +00004275 // FIXME: This attribute needs to actually be handled, but if we ignore
4276 // it it breaks large amounts of Linux software.
4277 attr.setUsedAsTypeAttr();
4278 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004279 case AttributeList::AT_AddressSpace:
John McCall711c52b2011-01-05 12:14:39 +00004280 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004281 attr.setUsedAsTypeAttr();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00004282 break;
John McCall711c52b2011-01-05 12:14:39 +00004283 OBJC_POINTER_TYPE_ATTRS_CASELIST:
4284 if (!handleObjCPointerTypeAttr(state, attr, type))
4285 distributeObjCPointerTypeAttr(state, attr, type);
John McCalle82247a2011-10-01 05:17:03 +00004286 attr.setUsedAsTypeAttr();
Mike Stump24556362009-07-25 21:26:53 +00004287 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004288 case AttributeList::AT_VectorSize:
John McCall711c52b2011-01-05 12:14:39 +00004289 HandleVectorSizeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004290 attr.setUsedAsTypeAttr();
John McCall04a67a62010-02-05 21:31:56 +00004291 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004292 case AttributeList::AT_ExtVectorType:
Richard Smitha4fa9002013-01-13 02:11:23 +00004293 HandleExtVectorTypeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004294 attr.setUsedAsTypeAttr();
Douglas Gregor4ac01402011-06-15 16:02:29 +00004295 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004296 case AttributeList::AT_NeonVectorType:
John McCall711c52b2011-01-05 12:14:39 +00004297 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4298 VectorType::NeonVector, "neon_vector_type");
John McCalle82247a2011-10-01 05:17:03 +00004299 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00004300 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004301 case AttributeList::AT_NeonPolyVectorType:
John McCall711c52b2011-01-05 12:14:39 +00004302 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4303 VectorType::NeonPolyVector,
Bob Wilson4211bb62010-11-16 00:32:24 +00004304 "neon_polyvector_type");
John McCalle82247a2011-10-01 05:17:03 +00004305 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00004306 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004307 case AttributeList::AT_OpenCLImageAccess:
Peter Collingbourne207f4d82011-03-18 22:38:29 +00004308 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004309 attr.setUsedAsTypeAttr();
Peter Collingbourne207f4d82011-03-18 22:38:29 +00004310 break;
4311
Sean Hunt8e083e72012-06-19 23:57:03 +00004312 case AttributeList::AT_Win64:
4313 case AttributeList::AT_Ptr32:
4314 case AttributeList::AT_Ptr64:
John McCallc052dbb2012-05-22 21:28:12 +00004315 // FIXME: don't ignore these
4316 attr.setUsedAsTypeAttr();
4317 break;
4318
Sean Hunt8e083e72012-06-19 23:57:03 +00004319 case AttributeList::AT_NSReturnsRetained:
David Blaikie4e4d0842012-03-11 07:00:24 +00004320 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
Richard Smithcd8ab512013-01-17 01:30:42 +00004321 break;
John McCallf85e1932011-06-15 23:02:42 +00004322 // fallthrough into the function attrs
4323
John McCall711c52b2011-01-05 12:14:39 +00004324 FUNCTION_TYPE_ATTRS_CASELIST:
John McCalle82247a2011-10-01 05:17:03 +00004325 attr.setUsedAsTypeAttr();
4326
John McCall711c52b2011-01-05 12:14:39 +00004327 // Never process function type attributes as part of the
4328 // declaration-specifiers.
Richard Smithf7a05272013-01-14 07:53:01 +00004329 if (TAL == TAL_DeclSpec)
John McCall711c52b2011-01-05 12:14:39 +00004330 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4331
4332 // Otherwise, handle the possible delays.
4333 else if (!handleFunctionTypeAttr(state, attr, type))
4334 distributeFunctionTypeAttr(state, attr, type);
John Thompson6e132aa2009-12-04 21:51:28 +00004335 break;
Chris Lattner232e8822008-02-21 01:08:11 +00004336 }
John McCall711c52b2011-01-05 12:14:39 +00004337 } while ((attrs = next));
Chris Lattner232e8822008-02-21 01:08:11 +00004338}
4339
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004340/// \brief Ensure that the type of the given expression is complete.
4341///
4342/// This routine checks whether the expression \p E has a complete type. If the
4343/// expression refers to an instantiable construct, that instantiation is
4344/// performed as needed to complete its type. Furthermore
4345/// Sema::RequireCompleteType is called for the expression's type (or in the
4346/// case of a reference type, the referred-to type).
4347///
4348/// \param E The expression whose type is required to be complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004349/// \param Diagnoser The object that will emit a diagnostic if the type is
4350/// incomplete.
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004351///
4352/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4353/// otherwise.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004354bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004355 QualType T = E->getType();
4356
4357 // Fast path the case where the type is already complete.
4358 if (!T->isIncompleteType())
4359 return false;
4360
4361 // Incomplete array types may be completed by the initializer attached to
4362 // their definitions. For static data members of class templates we need to
4363 // instantiate the definition to get this initializer and complete the type.
4364 if (T->isIncompleteArrayType()) {
4365 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4366 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4367 if (Var->isStaticDataMember() &&
4368 Var->getInstantiatedFromStaticDataMember()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004369
Douglas Gregor36f255c2011-06-03 14:28:43 +00004370 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4371 assert(MSInfo && "Missing member specialization information?");
4372 if (MSInfo->getTemplateSpecializationKind()
4373 != TSK_ExplicitSpecialization) {
4374 // If we don't already have a point of instantiation, this is it.
4375 if (MSInfo->getPointOfInstantiation().isInvalid()) {
4376 MSInfo->setPointOfInstantiation(E->getLocStart());
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004377
4378 // This is a modification of an existing AST node. Notify
Douglas Gregor36f255c2011-06-03 14:28:43 +00004379 // listeners.
4380 if (ASTMutationListener *L = getASTMutationListener())
4381 L->StaticDataMemberInstantiated(Var);
4382 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004383
Douglas Gregor36f255c2011-06-03 14:28:43 +00004384 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004385
Douglas Gregor36f255c2011-06-03 14:28:43 +00004386 // Update the type to the newly instantiated definition's type both
4387 // here and within the expression.
4388 if (VarDecl *Def = Var->getDefinition()) {
4389 DRE->setDecl(Def);
4390 T = Def->getType();
4391 DRE->setType(T);
4392 E->setType(T);
4393 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00004394 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004395
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004396 // We still go on to try to complete the type independently, as it
4397 // may also require instantiations or diagnostics if it remains
4398 // incomplete.
4399 }
4400 }
4401 }
4402 }
4403
4404 // FIXME: Are there other cases which require instantiating something other
4405 // than the type to complete the type of an expression?
4406
4407 // Look through reference types and complete the referred type.
4408 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4409 T = Ref->getPointeeType();
4410
Douglas Gregord10099e2012-05-04 16:32:21 +00004411 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
4412}
4413
4414namespace {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004415 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +00004416 unsigned DiagID;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004417
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004418 TypeDiagnoserDiag(unsigned DiagID)
4419 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004420
Douglas Gregord10099e2012-05-04 16:32:21 +00004421 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
4422 if (Suppressed) return;
4423 S.Diag(Loc, DiagID) << T;
4424 }
4425 };
4426}
4427
4428bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004429 TypeDiagnoserDiag Diagnoser(DiagID);
Douglas Gregord10099e2012-05-04 16:32:21 +00004430 return RequireCompleteExprType(E, Diagnoser);
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004431}
4432
Mike Stump1eb44332009-09-09 15:08:12 +00004433/// @brief Ensure that the type T is a complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004434///
4435/// This routine checks whether the type @p T is complete in any
4436/// context where a complete type is required. If @p T is a complete
Douglas Gregor86447ec2009-03-09 16:13:40 +00004437/// type, returns false. If @p T is a class template specialization,
4438/// this routine then attempts to perform class template
4439/// instantiation. If instantiation fails, or if @p T is incomplete
4440/// and cannot be completed, issues the diagnostic @p diag (giving it
4441/// the type @p T) and returns true.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004442///
4443/// @param Loc The location in the source that the incomplete type
4444/// diagnostic should refer to.
4445///
4446/// @param T The type that this routine is examining for completeness.
4447///
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004448/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4449/// @c false otherwise.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004450bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004451 TypeDiagnoser &Diagnoser) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004452 // FIXME: Add this assertion to make sure we always get instantiation points.
4453 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004454 // FIXME: Add this assertion to help us flush out problems with
4455 // checking for dependent types and type-dependent expressions.
4456 //
Mike Stump1eb44332009-09-09 15:08:12 +00004457 // assert(!T->isDependentType() &&
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004458 // "Can't ask whether a dependent type is complete");
4459
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004460 // If we have a complete type, we're done.
Douglas Gregord07cc362012-01-02 17:18:37 +00004461 NamedDecl *Def = 0;
4462 if (!T->isIncompleteType(&Def)) {
4463 // If we know about the definition but it is not visible, complain.
Douglas Gregord10099e2012-05-04 16:32:21 +00004464 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) {
Douglas Gregord07cc362012-01-02 17:18:37 +00004465 // Suppress this error outside of a SFINAE context if we've already
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004466 // emitted the error once for this type. There's no usefulness in
Douglas Gregord07cc362012-01-02 17:18:37 +00004467 // repeating the diagnostic.
4468 // FIXME: Add a Fix-It that imports the corresponding module or includes
4469 // the header.
Douglas Gregorca2ab452013-01-12 01:29:50 +00004470 Module *Owner = Def->getOwningModule();
4471 Diag(Loc, diag::err_module_private_definition)
4472 << T << Owner->getFullModuleName();
4473 Diag(Def->getLocation(), diag::note_previous_definition);
4474
4475 if (!isSFINAEContext()) {
4476 // Recover by implicitly importing this module.
4477 createImplicitModuleImport(Loc, Owner);
Douglas Gregord07cc362012-01-02 17:18:37 +00004478 }
4479 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004480
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004481 return false;
Douglas Gregord07cc362012-01-02 17:18:37 +00004482 }
Eli Friedman3c0eb162008-05-27 03:33:27 +00004483
Sean Callananbd791192011-12-16 00:20:31 +00004484 const TagType *Tag = T->getAs<TagType>();
4485 const ObjCInterfaceType *IFace = 0;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004486
Sean Callananbd791192011-12-16 00:20:31 +00004487 if (Tag) {
4488 // Avoid diagnosing invalid decls as incomplete.
4489 if (Tag->getDecl()->isInvalidDecl())
4490 return true;
4491
4492 // Give the external AST source a chance to complete the type.
4493 if (Tag->getDecl()->hasExternalLexicalStorage()) {
4494 Context.getExternalSource()->CompleteType(Tag->getDecl());
4495 if (!Tag->isIncompleteType())
4496 return false;
4497 }
4498 }
4499 else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4500 // Avoid diagnosing invalid decls as incomplete.
4501 if (IFace->getDecl()->isInvalidDecl())
4502 return true;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004503
Sean Callananbd791192011-12-16 00:20:31 +00004504 // Give the external AST source a chance to complete the type.
4505 if (IFace->getDecl()->hasExternalLexicalStorage()) {
4506 Context.getExternalSource()->CompleteType(IFace->getDecl());
4507 if (!IFace->isIncompleteType())
4508 return false;
4509 }
4510 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004511
Douglas Gregord475b8d2009-03-25 21:17:03 +00004512 // If we have a class template specialization or a class member of a
Sebastian Redl923d56d2009-11-05 15:52:31 +00004513 // class template specialization, or an array with known size of such,
4514 // try to instantiate it.
4515 QualType MaybeTemplate = T;
Douglas Gregore656b832012-04-23 16:42:52 +00004516 while (const ConstantArrayType *Array
4517 = Context.getAsConstantArrayType(MaybeTemplate))
Sebastian Redl923d56d2009-11-05 15:52:31 +00004518 MaybeTemplate = Array->getElementType();
4519 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00004520 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004521 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004522 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4523 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00004524 TSK_ImplicitInstantiation,
Douglas Gregord10099e2012-05-04 16:32:21 +00004525 /*Complain=*/!Diagnoser.Suppressed);
Mike Stump1eb44332009-09-09 15:08:12 +00004526 } else if (CXXRecordDecl *Rec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004527 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
Richard Smith564f4c52012-03-22 03:35:28 +00004528 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
4529 if (!Rec->isBeingDefined() && Pattern) {
4530 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
4531 assert(MSI && "Missing member specialization information?");
Douglas Gregor357bbd02009-08-28 20:50:45 +00004532 // This record was instantiated from a class within a template.
Richard Smith564f4c52012-03-22 03:35:28 +00004533 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregorf6b11852009-10-08 15:14:33 +00004534 return InstantiateClass(Loc, Rec, Pattern,
4535 getTemplateInstantiationArgs(Rec),
4536 TSK_ImplicitInstantiation,
Douglas Gregord10099e2012-05-04 16:32:21 +00004537 /*Complain=*/!Diagnoser.Suppressed);
Douglas Gregord475b8d2009-03-25 21:17:03 +00004538 }
4539 }
4540 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00004541
Douglas Gregord10099e2012-05-04 16:32:21 +00004542 if (Diagnoser.Suppressed)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004543 return true;
Douglas Gregord10099e2012-05-04 16:32:21 +00004544
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004545 // We have an incomplete type. Produce a diagnostic.
Douglas Gregord10099e2012-05-04 16:32:21 +00004546 Diagnoser.diagnose(*this, Loc, T);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004547
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004548 // If the type was a forward declaration of a class/struct/union
Rafael Espindola01620702010-03-21 22:56:43 +00004549 // type, produce a note.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004550 if (Tag && !Tag->getDecl()->isInvalidDecl())
Mike Stump1eb44332009-09-09 15:08:12 +00004551 Diag(Tag->getDecl()->getLocation(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004552 Tag->isBeingDefined() ? diag::note_type_being_defined
4553 : diag::note_forward_declaration)
Douglas Gregorb3029962011-11-14 22:10:01 +00004554 << QualType(Tag, 0);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004555
Douglas Gregorb3029962011-11-14 22:10:01 +00004556 // If the Objective-C class was a forward declaration, produce a note.
4557 if (IFace && !IFace->getDecl()->isInvalidDecl())
4558 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004559
4560 return true;
4561}
Douglas Gregore6258932009-03-19 00:39:20 +00004562
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004563bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004564 unsigned DiagID) {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004565 TypeDiagnoserDiag Diagnoser(DiagID);
Douglas Gregord10099e2012-05-04 16:32:21 +00004566 return RequireCompleteType(Loc, T, Diagnoser);
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004567}
4568
Joao Matos6666ed42012-08-31 18:45:21 +00004569/// \brief Get diagnostic %select index for tag kind for
4570/// literal type diagnostic message.
4571/// WARNING: Indexes apply to particular diagnostics only!
4572///
4573/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +00004574static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +00004575 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +00004576 case TTK_Struct: return 0;
4577 case TTK_Interface: return 1;
4578 case TTK_Class: return 2;
4579 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +00004580 }
Joao Matos6666ed42012-08-31 18:45:21 +00004581}
4582
Richard Smith9f569cc2011-10-01 02:31:28 +00004583/// @brief Ensure that the type T is a literal type.
4584///
4585/// This routine checks whether the type @p T is a literal type. If @p T is an
4586/// incomplete type, an attempt is made to complete it. If @p T is a literal
4587/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4588/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4589/// it the type @p T), along with notes explaining why the type is not a
4590/// literal type, and returns true.
4591///
4592/// @param Loc The location in the source that the non-literal type
4593/// diagnostic should refer to.
4594///
4595/// @param T The type that this routine is examining for literalness.
4596///
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004597/// @param Diagnoser Emits a diagnostic if T is not a literal type.
Richard Smith9f569cc2011-10-01 02:31:28 +00004598///
Richard Smith9f569cc2011-10-01 02:31:28 +00004599/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4600/// @c false otherwise.
4601bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004602 TypeDiagnoser &Diagnoser) {
Richard Smith9f569cc2011-10-01 02:31:28 +00004603 assert(!T->isDependentType() && "type should not be dependent");
4604
Eli Friedmanee065392012-02-20 23:58:14 +00004605 QualType ElemType = Context.getBaseElementType(T);
4606 RequireCompleteType(Loc, ElemType, 0);
4607
Richard Smith86c3ae42012-02-13 03:54:03 +00004608 if (T->isLiteralType())
Richard Smith9f569cc2011-10-01 02:31:28 +00004609 return false;
4610
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004611 if (Diagnoser.Suppressed)
Richard Smith9f569cc2011-10-01 02:31:28 +00004612 return true;
4613
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004614 Diagnoser.diagnose(*this, Loc, T);
Richard Smith9f569cc2011-10-01 02:31:28 +00004615
4616 if (T->isVariableArrayType())
4617 return true;
4618
Eli Friedmanee065392012-02-20 23:58:14 +00004619 const RecordType *RT = ElemType->getAs<RecordType>();
Richard Smith9f569cc2011-10-01 02:31:28 +00004620 if (!RT)
4621 return true;
4622
4623 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4624
Richard Smithc799a6a2012-04-25 23:23:48 +00004625 // A partially-defined class type can't be a literal type, because a literal
4626 // class type must have a trivial destructor (which can't be checked until
4627 // the class definition is complete).
4628 if (!RD->isCompleteDefinition()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00004629 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
Eli Friedmanee065392012-02-20 23:58:14 +00004630 return true;
Richard Smithc799a6a2012-04-25 23:23:48 +00004631 }
Eli Friedmanee065392012-02-20 23:58:14 +00004632
Richard Smith9f569cc2011-10-01 02:31:28 +00004633 // If the class has virtual base classes, then it's not an aggregate, and
Richard Smith86c3ae42012-02-13 03:54:03 +00004634 // cannot have any constexpr constructors or a trivial default constructor,
4635 // so is non-literal. This is better to diagnose than the resulting absence
4636 // of constexpr constructors.
Richard Smith9f569cc2011-10-01 02:31:28 +00004637 if (RD->getNumVBases()) {
4638 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
Joao Matos6666ed42012-08-31 18:45:21 +00004639 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Richard Smith9f569cc2011-10-01 02:31:28 +00004640 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4641 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +00004642 Diag(I->getLocStart(),
Richard Smith9f569cc2011-10-01 02:31:28 +00004643 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith86c3ae42012-02-13 03:54:03 +00004644 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
4645 !RD->hasTrivialDefaultConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00004646 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
Richard Smith9f569cc2011-10-01 02:31:28 +00004647 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4648 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4649 E = RD->bases_end(); I != E; ++I) {
4650 if (!I->getType()->isLiteralType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004651 Diag(I->getLocStart(),
Richard Smith9f569cc2011-10-01 02:31:28 +00004652 diag::note_non_literal_base_class)
4653 << RD << I->getType() << I->getSourceRange();
4654 return true;
4655 }
4656 }
4657 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4658 E = RD->field_end(); I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00004659 if (!I->getType()->isLiteralType() ||
4660 I->getType().isVolatileQualified()) {
4661 Diag(I->getLocation(), diag::note_non_literal_field)
David Blaikie581deb32012-06-06 20:45:41 +00004662 << RD << *I << I->getType()
David Blaikie262bc182012-04-30 02:36:29 +00004663 << I->getType().isVolatileQualified();
Richard Smith9f569cc2011-10-01 02:31:28 +00004664 return true;
4665 }
4666 }
4667 } else if (!RD->hasTrivialDestructor()) {
4668 // All fields and bases are of literal types, so have trivial destructors.
4669 // If this class's destructor is non-trivial it must be user-declared.
4670 CXXDestructorDecl *Dtor = RD->getDestructor();
4671 assert(Dtor && "class has literal fields and bases but no dtor?");
4672 if (!Dtor)
4673 return true;
4674
4675 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4676 diag::note_non_literal_user_provided_dtor :
4677 diag::note_non_literal_nontrivial_dtor) << RD;
Richard Smithac713512012-12-08 02:53:02 +00004678 if (!Dtor->isUserProvided())
4679 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
Richard Smith9f569cc2011-10-01 02:31:28 +00004680 }
4681
4682 return true;
4683}
4684
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004685bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004686 TypeDiagnoserDiag Diagnoser(DiagID);
4687 return RequireLiteralType(Loc, T, Diagnoser);
4688}
4689
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004690/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4691/// and qualified by the nested-name-specifier contained in SS.
4692QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4693 const CXXScopeSpec &SS, QualType T) {
4694 if (T.isNull())
Douglas Gregore6258932009-03-19 00:39:20 +00004695 return T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004696 NestedNameSpecifier *NNS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00004697 if (SS.isValid())
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004698 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4699 else {
4700 if (Keyword == ETK_None)
4701 return T;
4702 NNS = 0;
4703 }
4704 return Context.getElaboratedType(Keyword, NNS, T);
Douglas Gregore6258932009-03-19 00:39:20 +00004705}
Anders Carlssonaf017e62009-06-29 22:58:55 +00004706
John McCall2a984ca2010-10-12 00:20:44 +00004707QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004708 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004709 if (ER.isInvalid()) return QualType();
4710 E = ER.take();
4711
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004712 if (!E->isTypeDependent()) {
4713 QualType T = E->getType();
Fariborz Jahanianaca7f7b2010-10-06 00:23:25 +00004714 if (const TagType *TT = T->getAs<TagType>())
4715 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004716 }
Anders Carlssonaf017e62009-06-29 22:58:55 +00004717 return Context.getTypeOfExprType(E);
4718}
4719
Douglas Gregorf8af9822012-02-12 18:42:33 +00004720/// getDecltypeForExpr - Given an expr, will return the decltype for
4721/// that expression, according to the rules in C++11
4722/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
4723static QualType getDecltypeForExpr(Sema &S, Expr *E) {
4724 if (E->isTypeDependent())
4725 return S.Context.DependentTy;
4726
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004727 // C++11 [dcl.type.simple]p4:
4728 // The type denoted by decltype(e) is defined as follows:
4729 //
4730 // - if e is an unparenthesized id-expression or an unparenthesized class
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004731 // member access (5.2.5), decltype(e) is the type of the entity named
4732 // by e. If there is no such entity, or if e names a set of overloaded
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004733 // functions, the program is ill-formed;
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004734 //
4735 // We apply the same rules for Objective-C ivar and property references.
Douglas Gregorf8af9822012-02-12 18:42:33 +00004736 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4737 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
4738 return VD->getType();
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004739 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Douglas Gregorf8af9822012-02-12 18:42:33 +00004740 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4741 return FD->getType();
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004742 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
4743 return IR->getDecl()->getType();
4744 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
4745 if (PR->isExplicitProperty())
4746 return PR->getExplicitProperty()->getType();
Douglas Gregorf8af9822012-02-12 18:42:33 +00004747 }
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004748
Douglas Gregorf8af9822012-02-12 18:42:33 +00004749 // C++11 [expr.lambda.prim]p18:
4750 // Every occurrence of decltype((x)) where x is a possibly
4751 // parenthesized id-expression that names an entity of automatic
4752 // storage duration is treated as if x were transformed into an
4753 // access to a corresponding data member of the closure type that
4754 // would have been declared if x were an odr-use of the denoted
4755 // entity.
4756 using namespace sema;
4757 if (S.getCurLambda()) {
4758 if (isa<ParenExpr>(E)) {
4759 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4760 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor68932842012-02-18 05:51:20 +00004761 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
4762 if (!T.isNull())
4763 return S.Context.getLValueReferenceType(T);
Douglas Gregorf8af9822012-02-12 18:42:33 +00004764 }
4765 }
4766 }
4767 }
4768
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004769
4770 // C++11 [dcl.type.simple]p4:
4771 // [...]
Douglas Gregorf8af9822012-02-12 18:42:33 +00004772 QualType T = E->getType();
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004773 switch (E->getValueKind()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004774 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004775 // type of e;
4776 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004777 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004778 // type of e;
4779 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
4780 // - otherwise, decltype(e) is the type of e.
4781 case VK_RValue: break;
4782 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004783
Douglas Gregorf8af9822012-02-12 18:42:33 +00004784 return T;
4785}
4786
John McCall2a984ca2010-10-12 00:20:44 +00004787QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004788 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004789 if (ER.isInvalid()) return QualType();
4790 E = ER.take();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004791
Douglas Gregorf8af9822012-02-12 18:42:33 +00004792 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
Anders Carlssonaf017e62009-06-29 22:58:55 +00004793}
Sean Huntca63c202011-05-24 22:41:36 +00004794
4795QualType Sema::BuildUnaryTransformType(QualType BaseType,
4796 UnaryTransformType::UTTKind UKind,
4797 SourceLocation Loc) {
4798 switch (UKind) {
4799 case UnaryTransformType::EnumUnderlyingType:
4800 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4801 Diag(Loc, diag::err_only_enums_have_underlying_types);
4802 return QualType();
4803 } else {
4804 QualType Underlying = BaseType;
4805 if (!BaseType->isDependentType()) {
4806 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4807 assert(ED && "EnumType has no EnumDecl");
4808 DiagnoseUseOfDecl(ED, Loc);
4809 Underlying = ED->getIntegerType();
4810 }
4811 assert(!Underlying.isNull());
4812 return Context.getUnaryTransformType(BaseType, Underlying,
4813 UnaryTransformType::EnumUnderlyingType);
4814 }
4815 }
4816 llvm_unreachable("unknown unary transform type");
4817}
Eli Friedmanb001de72011-10-06 23:00:33 +00004818
4819QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4820 if (!T->isDependentType()) {
Richard Smith83271182012-02-11 18:03:45 +00004821 // FIXME: It isn't entirely clear whether incomplete atomic types
4822 // are allowed or not; for simplicity, ban them for the moment.
Douglas Gregord10099e2012-05-04 16:32:21 +00004823 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
Richard Smith83271182012-02-11 18:03:45 +00004824 return QualType();
4825
Eli Friedmanb001de72011-10-06 23:00:33 +00004826 int DisallowedKind = -1;
Richard Smith83271182012-02-11 18:03:45 +00004827 if (T->isArrayType())
Eli Friedmanb001de72011-10-06 23:00:33 +00004828 DisallowedKind = 1;
4829 else if (T->isFunctionType())
4830 DisallowedKind = 2;
4831 else if (T->isReferenceType())
4832 DisallowedKind = 3;
4833 else if (T->isAtomicType())
4834 DisallowedKind = 4;
4835 else if (T.hasQualifiers())
4836 DisallowedKind = 5;
4837 else if (!T.isTriviallyCopyableType(Context))
4838 // Some other non-trivially-copyable type (probably a C++ class)
4839 DisallowedKind = 6;
4840
4841 if (DisallowedKind != -1) {
4842 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4843 return QualType();
4844 }
4845
4846 // FIXME: Do we need any handling for ARC here?
4847 }
4848
4849 // Build the pointer type.
4850 return Context.getAtomicType(T);
4851}