blob: 67ee9376e8b23577d964895ac880d0f864c0d161 [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"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
Peter Collingbourne207f4d82011-03-18 22:38:29 +000016#include "clang/Basic/OpenCL.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36f255c2011-06-03 14:28:43 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Steve Naroff980e5082007-10-01 19:00:59 +000020#include "clang/AST/DeclObjC.h"
Douglas Gregor2943aed2009-03-03 04:44:36 +000021#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +000022#include "clang/AST/TypeLoc.h"
John McCall51bd8032009-10-18 01:05:36 +000023#include "clang/AST/TypeLocVisitor.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000024#include "clang/AST/Expr.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000025#include "clang/Basic/PartialDiagnostic.h"
Charles Davisd18f9f92010-08-16 04:01:50 +000026#include "clang/Basic/TargetInfo.h"
John McCall2792fa52011-03-08 04:17:03 +000027#include "clang/Lex/Preprocessor.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"
Sebastian Redl4994d2d2009-07-04 11:39:00 +000031#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor87c12c42009-11-04 16:49:01 +000032#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Chris Lattner5db2bb12009-10-25 18:21:37 +000035/// isOmittedBlockReturnType - Return true if this declarator is missing a
36/// return type because this is a omitted return type on a block literal.
Sebastian Redl8ce35b02009-10-25 21:45:37 +000037static bool isOmittedBlockReturnType(const Declarator &D) {
Chris Lattner5db2bb12009-10-25 18:21:37 +000038 if (D.getContext() != Declarator::BlockLiteralContext ||
Sebastian Redl8ce35b02009-10-25 21:45:37 +000039 D.getDeclSpec().hasTypeSpecifier())
Chris Lattner5db2bb12009-10-25 18:21:37 +000040 return false;
41
42 if (D.getNumTypeObjects() == 0)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000043 return true; // ^{ ... }
Chris Lattner5db2bb12009-10-25 18:21:37 +000044
45 if (D.getNumTypeObjects() == 1 &&
46 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000047 return true; // ^(int X, float Y) { ... }
Chris Lattner5db2bb12009-10-25 18:21:37 +000048
49 return false;
50}
51
John McCall2792fa52011-03-08 04:17:03 +000052/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
53/// doesn't apply to the given type.
54static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
55 QualType type) {
Chandler Carruth108f7562011-07-26 05:40:03 +000056 bool useExpansionLoc = false;
John McCall2792fa52011-03-08 04:17:03 +000057
58 unsigned diagID = 0;
59 switch (attr.getKind()) {
60 case AttributeList::AT_objc_gc:
61 diagID = diag::warn_pointer_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000062 useExpansionLoc = true;
John McCall2792fa52011-03-08 04:17:03 +000063 break;
64
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000065 case AttributeList::AT_objc_ownership:
66 diagID = diag::warn_objc_object_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000067 useExpansionLoc = true;
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000068 break;
69
John McCall2792fa52011-03-08 04:17:03 +000070 default:
71 // Assume everything else was a function attribute.
72 diagID = diag::warn_function_attribute_wrong_type;
73 break;
74 }
75
76 SourceLocation loc = attr.getLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +000077 StringRef name = attr.getName()->getName();
John McCall2792fa52011-03-08 04:17:03 +000078
79 // The GC attributes are usually written with macros; special-case them.
Chandler Carruth108f7562011-07-26 05:40:03 +000080 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
John McCall834e3f62011-03-08 07:59:04 +000081 if (attr.getParameterName()->isStr("strong")) {
82 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
83 } else if (attr.getParameterName()->isStr("weak")) {
84 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
John McCall2792fa52011-03-08 04:17:03 +000085 }
86 }
87
88 S.Diag(loc, diagID) << name << type;
89}
90
John McCall711c52b2011-01-05 12:14:39 +000091// objc_gc applies to Objective-C pointers or, otherwise, to the
92// smallest available pointer type (i.e. 'void*' in 'void**').
93#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
John McCallf85e1932011-06-15 23:02:42 +000094 case AttributeList::AT_objc_gc: \
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +000095 case AttributeList::AT_objc_ownership
John McCall04a67a62010-02-05 21:31:56 +000096
John McCall711c52b2011-01-05 12:14:39 +000097// Function type attributes.
98#define FUNCTION_TYPE_ATTRS_CASELIST \
99 case AttributeList::AT_noreturn: \
100 case AttributeList::AT_cdecl: \
101 case AttributeList::AT_fastcall: \
102 case AttributeList::AT_stdcall: \
103 case AttributeList::AT_thiscall: \
104 case AttributeList::AT_pascal: \
Anton Korobeynikov414d8962011-04-14 20:06:49 +0000105 case AttributeList::AT_regparm: \
106 case AttributeList::AT_pcs \
John McCall04a67a62010-02-05 21:31:56 +0000107
John McCall711c52b2011-01-05 12:14:39 +0000108namespace {
109 /// An object which stores processing state for the entire
110 /// GetTypeForDeclarator process.
111 class TypeProcessingState {
112 Sema &sema;
113
114 /// The declarator being processed.
115 Declarator &declarator;
116
117 /// The index of the declarator chunk we're currently processing.
118 /// May be the total number of valid chunks, indicating the
119 /// DeclSpec.
120 unsigned chunkIndex;
121
122 /// Whether there are non-trivial modifications to the decl spec.
123 bool trivial;
124
John McCall7ea21932011-03-26 01:39:56 +0000125 /// Whether we saved the attributes in the decl spec.
126 bool hasSavedAttrs;
127
John McCall711c52b2011-01-05 12:14:39 +0000128 /// The original set of attributes on the DeclSpec.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<AttributeList*, 2> savedAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000130
131 /// A list of attributes to diagnose the uselessness of when the
132 /// processing is complete.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000134
135 public:
136 TypeProcessingState(Sema &sema, Declarator &declarator)
137 : sema(sema), declarator(declarator),
138 chunkIndex(declarator.getNumTypeObjects()),
John McCall7ea21932011-03-26 01:39:56 +0000139 trivial(true), hasSavedAttrs(false) {}
John McCall711c52b2011-01-05 12:14:39 +0000140
141 Sema &getSema() const {
142 return sema;
Abramo Bagnarae215f722010-04-30 13:10:51 +0000143 }
John McCall711c52b2011-01-05 12:14:39 +0000144
145 Declarator &getDeclarator() const {
146 return declarator;
147 }
148
149 unsigned getCurrentChunkIndex() const {
150 return chunkIndex;
151 }
152
153 void setCurrentChunkIndex(unsigned idx) {
154 assert(idx <= declarator.getNumTypeObjects());
155 chunkIndex = idx;
156 }
157
158 AttributeList *&getCurrentAttrListRef() const {
159 assert(chunkIndex <= declarator.getNumTypeObjects());
160 if (chunkIndex == declarator.getNumTypeObjects())
161 return getMutableDeclSpec().getAttributes().getListRef();
162 return declarator.getTypeObject(chunkIndex).getAttrListRef();
163 }
164
165 /// Save the current set of attributes on the DeclSpec.
166 void saveDeclSpecAttrs() {
167 // Don't try to save them multiple times.
John McCall7ea21932011-03-26 01:39:56 +0000168 if (hasSavedAttrs) return;
John McCall711c52b2011-01-05 12:14:39 +0000169
170 DeclSpec &spec = getMutableDeclSpec();
171 for (AttributeList *attr = spec.getAttributes().getList(); attr;
172 attr = attr->getNext())
173 savedAttrs.push_back(attr);
174 trivial &= savedAttrs.empty();
John McCall7ea21932011-03-26 01:39:56 +0000175 hasSavedAttrs = true;
John McCall711c52b2011-01-05 12:14:39 +0000176 }
177
178 /// Record that we had nowhere to put the given type attribute.
179 /// We will diagnose such attributes later.
180 void addIgnoredTypeAttr(AttributeList &attr) {
181 ignoredTypeAttrs.push_back(&attr);
182 }
183
184 /// Diagnose all the ignored type attributes, given that the
185 /// declarator worked out to the given type.
186 void diagnoseIgnoredTypeAttrs(QualType type) const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000187 for (SmallVectorImpl<AttributeList*>::const_iterator
John McCall711c52b2011-01-05 12:14:39 +0000188 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
John McCall2792fa52011-03-08 04:17:03 +0000189 i != e; ++i)
190 diagnoseBadTypeAttribute(getSema(), **i, type);
John McCall711c52b2011-01-05 12:14:39 +0000191 }
192
193 ~TypeProcessingState() {
194 if (trivial) return;
195
196 restoreDeclSpecAttrs();
197 }
198
199 private:
200 DeclSpec &getMutableDeclSpec() const {
201 return const_cast<DeclSpec&>(declarator.getDeclSpec());
202 }
203
204 void restoreDeclSpecAttrs() {
John McCall7ea21932011-03-26 01:39:56 +0000205 assert(hasSavedAttrs);
206
207 if (savedAttrs.empty()) {
208 getMutableDeclSpec().getAttributes().set(0);
209 return;
210 }
211
John McCall711c52b2011-01-05 12:14:39 +0000212 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
213 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
214 savedAttrs[i]->setNext(savedAttrs[i+1]);
215 savedAttrs.back()->setNext(0);
216 }
217 };
218
219 /// Basically std::pair except that we really want to avoid an
220 /// implicit operator= for safety concerns. It's also a minor
221 /// link-time optimization for this to be a private type.
222 struct AttrAndList {
223 /// The attribute.
224 AttributeList &first;
225
226 /// The head of the list the attribute is currently in.
227 AttributeList *&second;
228
229 AttrAndList(AttributeList &attr, AttributeList *&head)
230 : first(attr), second(head) {}
231 };
John McCall04a67a62010-02-05 21:31:56 +0000232}
233
John McCall711c52b2011-01-05 12:14:39 +0000234namespace llvm {
235 template <> struct isPodLike<AttrAndList> {
236 static const bool value = true;
237 };
238}
239
240static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
241 attr.setNext(head);
242 head = &attr;
243}
244
245static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
246 if (head == &attr) {
247 head = attr.getNext();
248 return;
John McCall04a67a62010-02-05 21:31:56 +0000249 }
John McCall711c52b2011-01-05 12:14:39 +0000250
251 AttributeList *cur = head;
252 while (true) {
253 assert(cur && cur->getNext() && "ran out of attrs?");
254 if (cur->getNext() == &attr) {
255 cur->setNext(attr.getNext());
256 return;
257 }
258 cur = cur->getNext();
259 }
260}
261
262static void moveAttrFromListToList(AttributeList &attr,
263 AttributeList *&fromList,
264 AttributeList *&toList) {
265 spliceAttrOutOfList(attr, fromList);
266 spliceAttrIntoList(attr, toList);
267}
268
269static void processTypeAttrs(TypeProcessingState &state,
270 QualType &type, bool isDeclSpec,
271 AttributeList *attrs);
272
273static bool handleFunctionTypeAttr(TypeProcessingState &state,
274 AttributeList &attr,
275 QualType &type);
276
277static bool handleObjCGCTypeAttr(TypeProcessingState &state,
278 AttributeList &attr, QualType &type);
279
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000280static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +0000281 AttributeList &attr, QualType &type);
282
John McCall711c52b2011-01-05 12:14:39 +0000283static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
284 AttributeList &attr, QualType &type) {
John McCallf85e1932011-06-15 23:02:42 +0000285 if (attr.getKind() == AttributeList::AT_objc_gc)
286 return handleObjCGCTypeAttr(state, attr, type);
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000287 assert(attr.getKind() == AttributeList::AT_objc_ownership);
288 return handleObjCOwnershipTypeAttr(state, attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000289}
290
291/// Given that an objc_gc attribute was written somewhere on a
292/// declaration *other* than on the declarator itself (for which, use
293/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
294/// didn't apply in whatever position it was written in, try to move
295/// it to a more appropriate position.
296static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
297 AttributeList &attr,
298 QualType type) {
299 Declarator &declarator = state.getDeclarator();
300 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
301 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
302 switch (chunk.Kind) {
303 case DeclaratorChunk::Pointer:
304 case DeclaratorChunk::BlockPointer:
305 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
306 chunk.getAttrListRef());
307 return;
308
309 case DeclaratorChunk::Paren:
310 case DeclaratorChunk::Array:
311 continue;
312
313 // Don't walk through these.
314 case DeclaratorChunk::Reference:
315 case DeclaratorChunk::Function:
316 case DeclaratorChunk::MemberPointer:
317 goto error;
318 }
319 }
320 error:
John McCall2792fa52011-03-08 04:17:03 +0000321
322 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000323}
324
325/// Distribute an objc_gc type attribute that was written on the
326/// declarator.
327static void
328distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
329 AttributeList &attr,
330 QualType &declSpecType) {
331 Declarator &declarator = state.getDeclarator();
332
333 // objc_gc goes on the innermost pointer to something that's not a
334 // pointer.
335 unsigned innermost = -1U;
336 bool considerDeclSpec = true;
337 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
338 DeclaratorChunk &chunk = declarator.getTypeObject(i);
339 switch (chunk.Kind) {
340 case DeclaratorChunk::Pointer:
341 case DeclaratorChunk::BlockPointer:
342 innermost = i;
John McCallae278a32011-01-12 00:34:59 +0000343 continue;
John McCall711c52b2011-01-05 12:14:39 +0000344
345 case DeclaratorChunk::Reference:
346 case DeclaratorChunk::MemberPointer:
347 case DeclaratorChunk::Paren:
348 case DeclaratorChunk::Array:
349 continue;
350
351 case DeclaratorChunk::Function:
352 considerDeclSpec = false;
353 goto done;
354 }
355 }
356 done:
357
358 // That might actually be the decl spec if we weren't blocked by
359 // anything in the declarator.
360 if (considerDeclSpec) {
John McCall7ea21932011-03-26 01:39:56 +0000361 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
362 // Splice the attribute into the decl spec. Prevents the
363 // attribute from being applied multiple times and gives
364 // the source-location-filler something to work with.
365 state.saveDeclSpecAttrs();
366 moveAttrFromListToList(attr, declarator.getAttrListRef(),
367 declarator.getMutableDeclSpec().getAttributes().getListRef());
John McCall711c52b2011-01-05 12:14:39 +0000368 return;
John McCall7ea21932011-03-26 01:39:56 +0000369 }
John McCall711c52b2011-01-05 12:14:39 +0000370 }
371
372 // Otherwise, if we found an appropriate chunk, splice the attribute
373 // into it.
374 if (innermost != -1U) {
375 moveAttrFromListToList(attr, declarator.getAttrListRef(),
376 declarator.getTypeObject(innermost).getAttrListRef());
377 return;
378 }
379
380 // Otherwise, diagnose when we're done building the type.
381 spliceAttrOutOfList(attr, declarator.getAttrListRef());
382 state.addIgnoredTypeAttr(attr);
383}
384
385/// A function type attribute was written somewhere in a declaration
386/// *other* than on the declarator itself or in the decl spec. Given
387/// that it didn't apply in whatever position it was written in, try
388/// to move it to a more appropriate position.
389static void distributeFunctionTypeAttr(TypeProcessingState &state,
390 AttributeList &attr,
391 QualType type) {
392 Declarator &declarator = state.getDeclarator();
393
394 // Try to push the attribute from the return type of a function to
395 // the function itself.
396 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
397 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
398 switch (chunk.Kind) {
399 case DeclaratorChunk::Function:
400 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
401 chunk.getAttrListRef());
402 return;
403
404 case DeclaratorChunk::Paren:
405 case DeclaratorChunk::Pointer:
406 case DeclaratorChunk::BlockPointer:
407 case DeclaratorChunk::Array:
408 case DeclaratorChunk::Reference:
409 case DeclaratorChunk::MemberPointer:
410 continue;
411 }
412 }
413
John McCall2792fa52011-03-08 04:17:03 +0000414 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000415}
416
417/// Try to distribute a function type attribute to the innermost
418/// function chunk or type. Returns true if the attribute was
419/// distributed, false if no location was found.
420static bool
421distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
422 AttributeList &attr,
423 AttributeList *&attrList,
424 QualType &declSpecType) {
425 Declarator &declarator = state.getDeclarator();
426
427 // Put it on the innermost function chunk, if there is one.
428 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
429 DeclaratorChunk &chunk = declarator.getTypeObject(i);
430 if (chunk.Kind != DeclaratorChunk::Function) continue;
431
432 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
433 return true;
434 }
435
John McCallf85e1932011-06-15 23:02:42 +0000436 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
437 spliceAttrOutOfList(attr, attrList);
438 return true;
439 }
440
441 return false;
John McCall711c52b2011-01-05 12:14:39 +0000442}
443
444/// A function type attribute was written in the decl spec. Try to
445/// apply it somewhere.
446static void
447distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
448 AttributeList &attr,
449 QualType &declSpecType) {
450 state.saveDeclSpecAttrs();
451
452 // Try to distribute to the innermost.
453 if (distributeFunctionTypeAttrToInnermost(state, attr,
454 state.getCurrentAttrListRef(),
455 declSpecType))
456 return;
457
458 // If that failed, diagnose the bad attribute when the declarator is
459 // fully built.
460 state.addIgnoredTypeAttr(attr);
461}
462
463/// A function type attribute was written on the declarator. Try to
464/// apply it somewhere.
465static void
466distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
467 AttributeList &attr,
468 QualType &declSpecType) {
469 Declarator &declarator = state.getDeclarator();
470
471 // Try to distribute to the innermost.
472 if (distributeFunctionTypeAttrToInnermost(state, attr,
473 declarator.getAttrListRef(),
474 declSpecType))
475 return;
476
477 // If that failed, diagnose the bad attribute when the declarator is
478 // fully built.
479 spliceAttrOutOfList(attr, declarator.getAttrListRef());
480 state.addIgnoredTypeAttr(attr);
481}
482
483/// \brief Given that there are attributes written on the declarator
484/// itself, try to distribute any type attributes to the appropriate
485/// declarator chunk.
486///
487/// These are attributes like the following:
488/// int f ATTR;
489/// int (f ATTR)();
490/// but not necessarily this:
491/// int f() ATTR;
492static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
493 QualType &declSpecType) {
494 // Collect all the type attributes from the declarator itself.
495 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
496 AttributeList *attr = state.getDeclarator().getAttributes();
497 AttributeList *next;
498 do {
499 next = attr->getNext();
500
501 switch (attr->getKind()) {
502 OBJC_POINTER_TYPE_ATTRS_CASELIST:
503 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
504 break;
505
John McCallf85e1932011-06-15 23:02:42 +0000506 case AttributeList::AT_ns_returns_retained:
507 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
508 break;
509 // fallthrough
510
John McCall711c52b2011-01-05 12:14:39 +0000511 FUNCTION_TYPE_ATTRS_CASELIST:
512 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
513 break;
514
515 default:
516 break;
517 }
518 } while ((attr = next));
519}
520
521/// Add a synthetic '()' to a block-literal declarator if it is
522/// required, given the return type.
523static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
524 QualType declSpecType) {
525 Declarator &declarator = state.getDeclarator();
526
527 // First, check whether the declarator would produce a function,
528 // i.e. whether the innermost semantic chunk is a function.
529 if (declarator.isFunctionDeclarator()) {
530 // If so, make that declarator a prototyped declarator.
531 declarator.getFunctionTypeInfo().hasPrototype = true;
532 return;
533 }
534
John McCallda263792011-02-08 01:59:10 +0000535 // If there are any type objects, the type as written won't name a
536 // function, regardless of the decl spec type. This is because a
537 // block signature declarator is always an abstract-declarator, and
538 // abstract-declarators can't just be parentheses chunks. Therefore
539 // we need to build a function chunk unless there are no type
540 // objects and the decl spec type is a function.
John McCall711c52b2011-01-05 12:14:39 +0000541 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
542 return;
543
John McCallda263792011-02-08 01:59:10 +0000544 // Note that there *are* cases with invalid declarators where
545 // declarators consist solely of parentheses. In general, these
546 // occur only in failed efforts to make function declarators, so
547 // faking up the function chunk is still the right thing to do.
John McCall711c52b2011-01-05 12:14:39 +0000548
549 // Otherwise, we need to fake up a function declarator.
550 SourceLocation loc = declarator.getSourceRange().getBegin();
551
552 // ...and *prepend* it to the declarator.
553 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
John McCall711c52b2011-01-05 12:14:39 +0000554 /*proto*/ true,
555 /*variadic*/ false, SourceLocation(),
556 /*args*/ 0, 0,
557 /*type quals*/ 0,
Douglas Gregor83f51722011-01-26 03:43:54 +0000558 /*ref-qualifier*/true, SourceLocation(),
Douglas Gregor43f51032011-10-19 06:04:55 +0000559 /*const qualifier*/SourceLocation(),
560 /*volatile qualifier*/SourceLocation(),
Douglas Gregor90ebed02011-07-13 21:47:47 +0000561 /*mutable qualifier*/SourceLocation(),
Sebastian Redl6e5d3192011-03-05 22:42:13 +0000562 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
John McCall711c52b2011-01-05 12:14:39 +0000563 /*parens*/ loc, loc,
564 declarator));
565
566 // For consistency, make sure the state still has us as processing
567 // the decl spec.
568 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
569 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
John McCall04a67a62010-02-05 21:31:56 +0000570}
571
Douglas Gregor930d8b52009-01-30 22:09:00 +0000572/// \brief Convert the specified declspec to the appropriate type
573/// object.
Chris Lattner5db2bb12009-10-25 18:21:37 +0000574/// \param D the declarator containing the declaration specifier.
Chris Lattner5153ee62009-04-25 08:47:54 +0000575/// \returns The type described by the declaration specifiers. This function
576/// never returns null.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000577static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
579 // checking.
John McCall711c52b2011-01-05 12:14:39 +0000580
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000581 Sema &S = state.getSema();
John McCall711c52b2011-01-05 12:14:39 +0000582 Declarator &declarator = state.getDeclarator();
583 const DeclSpec &DS = declarator.getDeclSpec();
584 SourceLocation DeclLoc = declarator.getIdentifierLoc();
Chris Lattner5db2bb12009-10-25 18:21:37 +0000585 if (DeclLoc.isInvalid())
586 DeclLoc = DS.getSourceRange().getBegin();
Chris Lattner1564e392009-10-25 18:07:27 +0000587
John McCall711c52b2011-01-05 12:14:39 +0000588 ASTContext &Context = S.Context;
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattner5db2bb12009-10-25 18:21:37 +0000590 QualType Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 switch (DS.getTypeSpecType()) {
Chris Lattner96b77fc2008-04-02 06:50:17 +0000592 case DeclSpec::TST_void:
593 Result = Context.VoidTy;
594 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 case DeclSpec::TST_char:
596 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000597 Result = Context.CharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000599 Result = Context.SignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 else {
601 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
602 "Unknown TSS value");
Chris Lattnerfab5b452008-02-20 23:53:49 +0000603 Result = Context.UnsignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 }
Chris Lattner958858e2008-02-20 21:40:32 +0000605 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000606 case DeclSpec::TST_wchar:
607 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
608 Result = Context.WCharTy;
609 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
John McCall711c52b2011-01-05 12:14:39 +0000610 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000611 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000612 Result = Context.getSignedWCharType();
613 } else {
614 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
615 "Unknown TSS value");
John McCall711c52b2011-01-05 12:14:39 +0000616 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000617 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000618 Result = Context.getUnsignedWCharType();
619 }
620 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000621 case DeclSpec::TST_char16:
622 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
623 "Unknown TSS value");
624 Result = Context.Char16Ty;
625 break;
626 case DeclSpec::TST_char32:
627 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
628 "Unknown TSS value");
629 Result = Context.Char32Ty;
630 break;
Chris Lattnerd658b562008-04-05 06:32:51 +0000631 case DeclSpec::TST_unspecified:
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000632 // "<proto1,proto2>" is an objc qualified ID with a missing id.
Chris Lattner097e9162008-10-20 02:01:50 +0000633 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000634 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
635 (ObjCProtocolDecl**)PQ,
636 DS.getNumProtocolQualifiers());
637 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000638 break;
639 }
Chris Lattner5db2bb12009-10-25 18:21:37 +0000640
641 // If this is a missing declspec in a block literal return context, then it
642 // is inferred from the return statements inside the block.
Eli Friedmanf88c4002012-01-04 04:41:38 +0000643 // The declspec is always missing in a lambda expr context; it is either
644 // specified with a trailing return type or inferred.
645 if (declarator.getContext() == Declarator::LambdaExprContext ||
646 isOmittedBlockReturnType(declarator)) {
Chris Lattner5db2bb12009-10-25 18:21:37 +0000647 Result = Context.DependentTy;
648 break;
649 }
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Chris Lattnerd658b562008-04-05 06:32:51 +0000651 // Unspecified typespec defaults to int in C90. However, the C90 grammar
652 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
653 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
654 // Note that the one exception to this is function definitions, which are
655 // allowed to be completely missing a declspec. This is handled in the
656 // parser already though by it pretending to have seen an 'int' in this
657 // case.
John McCall711c52b2011-01-05 12:14:39 +0000658 if (S.getLangOptions().ImplicitInt) {
Chris Lattner35d276f2009-02-27 18:53:28 +0000659 // In C89 mode, we only warn if there is a completely missing declspec
660 // when one is not allowed.
Chris Lattner3f84ad22009-04-22 05:27:59 +0000661 if (DS.isEmpty()) {
John McCall711c52b2011-01-05 12:14:39 +0000662 S.Diag(DeclLoc, diag::ext_missing_declspec)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000663 << DS.getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000664 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
Chris Lattner3f84ad22009-04-22 05:27:59 +0000665 }
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000666 } else if (!DS.hasTypeSpecifier()) {
Chris Lattnerd658b562008-04-05 06:32:51 +0000667 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
668 // "At least one type specifier shall be given in the declaration
669 // specifiers in each declaration, and in the specifier-qualifier list in
670 // each struct declaration and type name."
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000671 // FIXME: Does Microsoft really have the implicit int extension in C++?
John McCall711c52b2011-01-05 12:14:39 +0000672 if (S.getLangOptions().CPlusPlus &&
Francois Pichet62ec1f22011-09-17 17:15:52 +0000673 !S.getLangOptions().MicrosoftExt) {
John McCall711c52b2011-01-05 12:14:39 +0000674 S.Diag(DeclLoc, diag::err_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000675 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Chris Lattnerb78d8332009-06-26 04:45:06 +0000677 // When this occurs in C++ code, often something is very broken with the
678 // value being declared, poison it as invalid so we don't get chains of
679 // errors.
John McCall711c52b2011-01-05 12:14:39 +0000680 declarator.setInvalidType(true);
Chris Lattnerb78d8332009-06-26 04:45:06 +0000681 } else {
John McCall711c52b2011-01-05 12:14:39 +0000682 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000683 << DS.getSourceRange();
Chris Lattnerb78d8332009-06-26 04:45:06 +0000684 }
Chris Lattnerd658b562008-04-05 06:32:51 +0000685 }
Mike Stump1eb44332009-09-09 15:08:12 +0000686
687 // FALL THROUGH.
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000688 case DeclSpec::TST_int: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000689 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
690 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000691 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
692 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
693 case DeclSpec::TSW_long: Result = Context.LongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000694 case DeclSpec::TSW_longlong:
695 Result = Context.LongLongTy;
696
697 // long long is a C99 feature.
Richard Smithebaf0e62011-10-18 20:49:44 +0000698 if (!S.getLangOptions().C99)
699 S.Diag(DS.getTypeSpecWidthLoc(),
700 S.getLangOptions().CPlusPlus0x ?
701 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000702 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 }
704 } else {
705 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000706 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
707 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
708 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000709 case DeclSpec::TSW_longlong:
710 Result = Context.UnsignedLongLongTy;
711
712 // long long is a C99 feature.
Richard Smithebaf0e62011-10-18 20:49:44 +0000713 if (!S.getLangOptions().C99)
714 S.Diag(DS.getTypeSpecWidthLoc(),
715 S.getLangOptions().CPlusPlus0x ?
716 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Chris Lattner311157f2009-10-25 18:25:04 +0000717 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 }
719 }
Chris Lattner958858e2008-02-20 21:40:32 +0000720 break;
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000721 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000722 case DeclSpec::TST_half: Result = Context.HalfTy; break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000723 case DeclSpec::TST_float: Result = Context.FloatTy; break;
Chris Lattner958858e2008-02-20 21:40:32 +0000724 case DeclSpec::TST_double:
725 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000726 Result = Context.LongDoubleTy;
Chris Lattner958858e2008-02-20 21:40:32 +0000727 else
Chris Lattnerfab5b452008-02-20 23:53:49 +0000728 Result = Context.DoubleTy;
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000729
730 if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
731 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
732 declarator.setInvalidType(true);
733 }
Chris Lattner958858e2008-02-20 21:40:32 +0000734 break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000735 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 case DeclSpec::TST_decimal32: // _Decimal32
737 case DeclSpec::TST_decimal64: // _Decimal64
738 case DeclSpec::TST_decimal128: // _Decimal128
John McCall711c52b2011-01-05 12:14:39 +0000739 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
Chris Lattner8f12f652009-05-13 05:02:08 +0000740 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000741 declarator.setInvalidType(true);
Chris Lattner8f12f652009-05-13 05:02:08 +0000742 break;
Chris Lattner99dc9142008-04-13 18:59:07 +0000743 case DeclSpec::TST_class:
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 case DeclSpec::TST_enum:
745 case DeclSpec::TST_union:
746 case DeclSpec::TST_struct: {
John McCallb3d87482010-08-24 05:47:05 +0000747 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
John McCall6e247262009-10-10 05:48:19 +0000748 if (!D) {
749 // This can happen in C++ with ambiguous lookups.
750 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000751 declarator.setInvalidType(true);
John McCall6e247262009-10-10 05:48:19 +0000752 break;
753 }
754
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000755 // If the type is deprecated or unavailable, diagnose it.
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000756 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000757
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000759 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
760
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 // TypeQuals handled by caller.
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000762 Result = Context.getTypeDeclType(D);
John McCall2191b202009-09-05 06:31:47 +0000763
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000764 // In both C and C++, make an ElaboratedType.
765 ElaboratedTypeKeyword Keyword
766 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
767 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
768
Chris Lattner5153ee62009-04-25 08:47:54 +0000769 if (D->isInvalidDecl())
John McCall711c52b2011-01-05 12:14:39 +0000770 declarator.setInvalidType(true);
Chris Lattner958858e2008-02-20 21:40:32 +0000771 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000772 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000773 case DeclSpec::TST_typename: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
775 DS.getTypeSpecSign() == 0 &&
776 "Can't handle qualifiers on typedef names yet!");
John McCall711c52b2011-01-05 12:14:39 +0000777 Result = S.GetTypeFromParser(DS.getRepAsType());
John McCall27940d22010-07-30 05:17:22 +0000778 if (Result.isNull())
John McCall711c52b2011-01-05 12:14:39 +0000779 declarator.setInvalidType(true);
John McCall27940d22010-07-30 05:17:22 +0000780 else if (DeclSpec::ProtocolQualifierListTy PQ
781 = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000782 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
783 // Silently drop any existing protocol qualifiers.
784 // TODO: determine whether that's the right thing to do.
785 if (ObjT->getNumProtocols())
786 Result = ObjT->getBaseType();
787
788 if (DS.getNumProtocolQualifiers())
789 Result = Context.getObjCObjectType(Result,
790 (ObjCProtocolDecl**) PQ,
791 DS.getNumProtocolQualifiers());
792 } else if (Result->isObjCIdType()) {
Chris Lattnerae4da612008-07-26 01:53:50 +0000793 // id<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000794 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
795 (ObjCProtocolDecl**) PQ,
796 DS.getNumProtocolQualifiers());
797 Result = Context.getObjCObjectPointerType(Result);
798 } else if (Result->isObjCClassType()) {
Steve Naroff4262a072009-02-23 18:53:24 +0000799 // Class<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000800 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
801 (ObjCProtocolDecl**) PQ,
802 DS.getNumProtocolQualifiers());
803 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000804 } else {
John McCall711c52b2011-01-05 12:14:39 +0000805 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000806 << DS.getSourceRange();
John McCall711c52b2011-01-05 12:14:39 +0000807 declarator.setInvalidType(true);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000808 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000809 }
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 // TypeQuals handled by caller.
Chris Lattner958858e2008-02-20 21:40:32 +0000812 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 }
Chris Lattner958858e2008-02-20 21:40:32 +0000814 case DeclSpec::TST_typeofType:
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000815 // FIXME: Preserve type source info.
John McCall711c52b2011-01-05 12:14:39 +0000816 Result = S.GetTypeFromParser(DS.getRepAsType());
Chris Lattner958858e2008-02-20 21:40:32 +0000817 assert(!Result.isNull() && "Didn't get a type for typeof?");
Fariborz Jahanian730e1752010-10-06 17:00:02 +0000818 if (!Result->isDependentType())
819 if (const TagType *TT = Result->getAs<TagType>())
John McCall711c52b2011-01-05 12:14:39 +0000820 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
Steve Naroffd1861fd2007-07-31 12:34:36 +0000821 // TypeQuals handled by caller.
Chris Lattnerfab5b452008-02-20 23:53:49 +0000822 Result = Context.getTypeOfType(Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000823 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000824 case DeclSpec::TST_typeofExpr: {
John McCallb3d87482010-08-24 05:47:05 +0000825 Expr *E = DS.getRepAsExpr();
Steve Naroffd1861fd2007-07-31 12:34:36 +0000826 assert(E && "Didn't get an expression for typeof?");
827 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000828 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +0000829 if (Result.isNull()) {
830 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000831 declarator.setInvalidType(true);
Douglas Gregor4b52e252009-12-21 23:17:24 +0000832 }
Chris Lattner958858e2008-02-20 21:40:32 +0000833 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000834 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000835 case DeclSpec::TST_decltype: {
John McCallb3d87482010-08-24 05:47:05 +0000836 Expr *E = DS.getRepAsExpr();
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000837 assert(E && "Didn't get an expression for decltype?");
838 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000839 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
Anders Carlssonaf017e62009-06-29 22:58:55 +0000840 if (Result.isNull()) {
841 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000842 declarator.setInvalidType(true);
Anders Carlssonaf017e62009-06-29 22:58:55 +0000843 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000844 break;
845 }
Sean Huntca63c202011-05-24 22:41:36 +0000846 case DeclSpec::TST_underlyingType:
Sean Huntdb5d44b2011-05-19 05:37:45 +0000847 Result = S.GetTypeFromParser(DS.getRepAsType());
848 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
Sean Huntca63c202011-05-24 22:41:36 +0000849 Result = S.BuildUnaryTransformType(Result,
850 UnaryTransformType::EnumUnderlyingType,
851 DS.getTypeSpecTypeLoc());
852 if (Result.isNull()) {
853 Result = Context.IntTy;
854 declarator.setInvalidType(true);
Sean Huntdb5d44b2011-05-19 05:37:45 +0000855 }
856 break;
857
Anders Carlssone89d1592009-06-26 18:41:36 +0000858 case DeclSpec::TST_auto: {
859 // TypeQuals handled by caller.
Richard Smith34b41d92011-02-20 03:19:35 +0000860 Result = Context.getAutoType(QualType());
Anders Carlssone89d1592009-06-26 18:41:36 +0000861 break;
862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
John McCalla5fc4722011-04-09 22:50:59 +0000864 case DeclSpec::TST_unknown_anytype:
865 Result = Context.UnknownAnyTy;
866 break;
867
Eli Friedmanb001de72011-10-06 23:00:33 +0000868 case DeclSpec::TST_atomic:
869 Result = S.GetTypeFromParser(DS.getRepAsType());
870 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
871 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
872 if (Result.isNull()) {
873 Result = Context.IntTy;
874 declarator.setInvalidType(true);
875 }
876 break;
877
Douglas Gregor809070a2009-02-18 17:45:20 +0000878 case DeclSpec::TST_error:
Chris Lattner5153ee62009-04-25 08:47:54 +0000879 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000880 declarator.setInvalidType(true);
Chris Lattner5153ee62009-04-25 08:47:54 +0000881 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 }
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner958858e2008-02-20 21:40:32 +0000884 // Handle complex types.
Douglas Gregorf244cd72009-02-14 21:06:05 +0000885 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
John McCall711c52b2011-01-05 12:14:39 +0000886 if (S.getLangOptions().Freestanding)
887 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
Chris Lattnerfab5b452008-02-20 23:53:49 +0000888 Result = Context.getComplexType(Result);
John Thompson82287d12010-02-05 00:12:22 +0000889 } else if (DS.isTypeAltiVecVector()) {
890 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
891 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
Bob Wilsone86d78c2010-11-10 21:56:12 +0000892 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000893 if (DS.isTypeAltiVecPixel())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000894 VecKind = VectorType::AltiVecPixel;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000895 else if (DS.isTypeAltiVecBool())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000896 VecKind = VectorType::AltiVecBool;
897 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
Douglas Gregorf244cd72009-02-14 21:06:05 +0000898 }
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Argyrios Kyrtzidis47423bd2010-09-23 09:40:31 +0000900 // FIXME: Imaginary.
901 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
John McCall711c52b2011-01-05 12:14:39 +0000902 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
Mike Stump1eb44332009-09-09 15:08:12 +0000903
John McCall711c52b2011-01-05 12:14:39 +0000904 // Before we process any type attributes, synthesize a block literal
905 // function declarator if necessary.
906 if (declarator.getContext() == Declarator::BlockLiteralContext)
907 maybeSynthesizeBlockSignature(state, Result);
908
909 // Apply any type attributes from the decl spec. This may cause the
910 // list of type attributes to be temporarily saved while the type
911 // attributes are pushed around.
912 if (AttributeList *attrs = DS.getAttributes().getList())
913 processTypeAttrs(state, Result, true, attrs);
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Chris Lattner96b77fc2008-04-02 06:50:17 +0000915 // Apply const/volatile/restrict qualifiers to T.
916 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
917
918 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
919 // or incomplete types shall not be restrict-qualified." C++ also allows
920 // restrict-qualified references.
John McCall0953e762009-09-24 19:53:00 +0000921 if (TypeQuals & DeclSpec::TQ_restrict) {
Fariborz Jahanian2b5ff1a2009-12-07 18:08:58 +0000922 if (Result->isAnyPointerType() || Result->isReferenceType()) {
923 QualType EltTy;
924 if (Result->isObjCObjectPointerType())
925 EltTy = Result;
926 else
927 EltTy = Result->isPointerType() ?
928 Result->getAs<PointerType>()->getPointeeType() :
929 Result->getAs<ReferenceType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Douglas Gregorbad0e652009-03-24 20:32:41 +0000931 // If we have a pointer or reference, the pointee must have an object
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000932 // incomplete type.
933 if (!EltTy->isIncompleteOrObjectType()) {
John McCall711c52b2011-01-05 12:14:39 +0000934 S.Diag(DS.getRestrictSpecLoc(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000935 diag::err_typecheck_invalid_restrict_invalid_pointee)
Chris Lattnerd1625842008-11-24 06:25:27 +0000936 << EltTy << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000937 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattnerbdcd6372008-04-02 17:35:06 +0000938 }
939 } else {
John McCall711c52b2011-01-05 12:14:39 +0000940 S.Diag(DS.getRestrictSpecLoc(),
941 diag::err_typecheck_invalid_restrict_not_pointer)
Chris Lattnerd1625842008-11-24 06:25:27 +0000942 << Result << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +0000943 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattner96b77fc2008-04-02 06:50:17 +0000944 }
Chris Lattner96b77fc2008-04-02 06:50:17 +0000945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Chris Lattner96b77fc2008-04-02 06:50:17 +0000947 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
948 // of a function type includes any type qualifiers, the behavior is
949 // undefined."
950 if (Result->isFunctionType() && TypeQuals) {
951 // Get some location to point at, either the C or V location.
952 SourceLocation Loc;
John McCall0953e762009-09-24 19:53:00 +0000953 if (TypeQuals & DeclSpec::TQ_const)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000954 Loc = DS.getConstSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000955 else if (TypeQuals & DeclSpec::TQ_volatile)
Chris Lattner96b77fc2008-04-02 06:50:17 +0000956 Loc = DS.getVolatileSpecLoc();
John McCall0953e762009-09-24 19:53:00 +0000957 else {
958 assert((TypeQuals & DeclSpec::TQ_restrict) &&
959 "Has CVR quals but not C, V, or R?");
960 Loc = DS.getRestrictSpecLoc();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000961 }
John McCall711c52b2011-01-05 12:14:39 +0000962 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
Chris Lattnerd1625842008-11-24 06:25:27 +0000963 << Result << DS.getSourceRange();
Chris Lattner96b77fc2008-04-02 06:50:17 +0000964 }
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000966 // C++ [dcl.ref]p1:
967 // Cv-qualified references are ill-formed except when the
968 // cv-qualifiers are introduced through the use of a typedef
969 // (7.1.3) or of a template type argument (14.3), in which
970 // case the cv-qualifiers are ignored.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000971 // FIXME: Shouldn't we be checking SCS_typedef here?
972 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +0000973 TypeQuals && Result->isReferenceType()) {
John McCall0953e762009-09-24 19:53:00 +0000974 TypeQuals &= ~DeclSpec::TQ_const;
975 TypeQuals &= ~DeclSpec::TQ_volatile;
Mike Stump1eb44332009-09-09 15:08:12 +0000976 }
977
John McCall0953e762009-09-24 19:53:00 +0000978 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
979 Result = Context.getQualifiedType(Result, Quals);
Chris Lattner96b77fc2008-04-02 06:50:17 +0000980 }
John McCall0953e762009-09-24 19:53:00 +0000981
Chris Lattnerf1d705c2008-02-21 01:07:18 +0000982 return Result;
983}
984
Douglas Gregorcd281c32009-02-28 00:25:32 +0000985static std::string getPrintableNameForEntity(DeclarationName Entity) {
986 if (Entity)
987 return Entity.getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Douglas Gregorcd281c32009-02-28 00:25:32 +0000989 return "type name";
990}
991
John McCall28654742010-06-05 06:41:15 +0000992QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
993 Qualifiers Qs) {
994 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
995 // object or incomplete types shall not be restrict-qualified."
996 if (Qs.hasRestrict()) {
997 unsigned DiagID = 0;
998 QualType ProblemTy;
999
1000 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
1001 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
1002 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
1003 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1004 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
1005 }
1006 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1007 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1008 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1009 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1010 }
1011 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1012 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1013 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1014 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1015 }
1016 } else if (!Ty->isDependentType()) {
1017 // FIXME: this deserves a proper diagnostic
1018 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1019 ProblemTy = T;
1020 }
1021
1022 if (DiagID) {
1023 Diag(Loc, DiagID) << ProblemTy;
1024 Qs.removeRestrict();
1025 }
1026 }
1027
1028 return Context.getQualifiedType(T, Qs);
1029}
1030
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001031/// \brief Build a paren type including \p T.
1032QualType Sema::BuildParenType(QualType T) {
1033 return Context.getParenType(T);
1034}
1035
John McCallf85e1932011-06-15 23:02:42 +00001036/// Given that we're building a pointer or reference to the given
1037static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1038 SourceLocation loc,
1039 bool isReference) {
1040 // Bail out if retention is unrequired or already specified.
1041 if (!type->isObjCLifetimeType() ||
1042 type.getObjCLifetime() != Qualifiers::OCL_None)
1043 return type;
1044
1045 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1046
1047 // If the object type is const-qualified, we can safely use
1048 // __unsafe_unretained. This is safe (because there are no read
1049 // barriers), and it'll be safe to coerce anything but __weak* to
1050 // the resulting type.
1051 if (type.isConstQualified()) {
1052 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1053
1054 // Otherwise, check whether the static type does not require
1055 // retaining. This currently only triggers for Class (possibly
1056 // protocol-qualifed, and arrays thereof).
1057 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1058 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1059
Eli Friedmanef331b72012-01-20 01:26:23 +00001060 // If we are in an unevaluated context, like sizeof, skip adding a
1061 // qualification.
Eli Friedman78a54242012-01-21 04:44:06 +00001062 } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001063 return type;
Argyrios Kyrtzidis5b76f372011-09-20 23:49:22 +00001064
John McCalle8c904f2012-01-26 20:04:03 +00001065 // If that failed, give an error and recover using __strong. __strong
1066 // is the option most likely to prevent spurious second-order diagnostics,
1067 // like when binding a reference to a field.
John McCallf85e1932011-06-15 23:02:42 +00001068 } else {
1069 // These types can show up in private ivars in system headers, so
1070 // we need this to not be an error in those cases. Instead we
1071 // want to delay.
1072 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001073 S.DelayedDiagnostics.add(
1074 sema::DelayedDiagnostic::makeForbiddenType(loc,
1075 diag::err_arc_indirect_no_ownership, type, isReference));
John McCallf85e1932011-06-15 23:02:42 +00001076 } else {
Eli Friedmanef331b72012-01-20 01:26:23 +00001077 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
John McCallf85e1932011-06-15 23:02:42 +00001078 }
John McCalle8c904f2012-01-26 20:04:03 +00001079 implicitLifetime = Qualifiers::OCL_Strong;
John McCallf85e1932011-06-15 23:02:42 +00001080 }
1081 assert(implicitLifetime && "didn't infer any lifetime!");
1082
1083 Qualifiers qs;
1084 qs.addObjCLifetime(implicitLifetime);
1085 return S.Context.getQualifiedType(type, qs);
1086}
1087
Douglas Gregorcd281c32009-02-28 00:25:32 +00001088/// \brief Build a pointer type.
1089///
1090/// \param T The type to which we'll be building a pointer.
1091///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001092/// \param Loc The location of the entity whose type involves this
1093/// pointer type or, if there is no such entity, the location of the
1094/// type that will have pointer type.
1095///
1096/// \param Entity The name of the entity that involves the pointer
1097/// type, if known.
1098///
1099/// \returns A suitable pointer type, if there are no
1100/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001101QualType Sema::BuildPointerType(QualType T,
Douglas Gregorcd281c32009-02-28 00:25:32 +00001102 SourceLocation Loc, DeclarationName Entity) {
1103 if (T->isReferenceType()) {
1104 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1105 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001106 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001107 return QualType();
1108 }
1109
John McCallc12c5bb2010-05-15 11:32:37 +00001110 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
Douglas Gregor92e986e2010-04-22 16:44:27 +00001111
John McCallf85e1932011-06-15 23:02:42 +00001112 // In ARC, it is forbidden to build pointers to unqualified pointers.
1113 if (getLangOptions().ObjCAutoRefCount)
1114 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1115
Douglas Gregorcd281c32009-02-28 00:25:32 +00001116 // Build the pointer type.
John McCall28654742010-06-05 06:41:15 +00001117 return Context.getPointerType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001118}
1119
1120/// \brief Build a reference type.
1121///
1122/// \param T The type to which we'll be building a reference.
1123///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001124/// \param Loc The location of the entity whose type involves this
1125/// reference type or, if there is no such entity, the location of the
1126/// type that will have reference type.
1127///
1128/// \param Entity The name of the entity that involves the reference
1129/// type, if known.
1130///
1131/// \returns A suitable reference type, if there are no
1132/// errors. Otherwise, returns a NULL type.
John McCall54e14c42009-10-22 22:37:11 +00001133QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
John McCall28654742010-06-05 06:41:15 +00001134 SourceLocation Loc,
John McCall54e14c42009-10-22 22:37:11 +00001135 DeclarationName Entity) {
Douglas Gregor9625e442011-05-21 22:16:50 +00001136 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1137 "Unresolved overloaded function type");
1138
Douglas Gregor69d83162011-01-20 16:08:06 +00001139 // C++0x [dcl.ref]p6:
1140 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1141 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1142 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1143 // the type "lvalue reference to T", while an attempt to create the type
1144 // "rvalue reference to cv TR" creates the type TR.
John McCall54e14c42009-10-22 22:37:11 +00001145 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1146
John McCall54e14c42009-10-22 22:37:11 +00001147 // C++ [dcl.ref]p4: There shall be no references to references.
1148 //
1149 // According to C++ DR 106, references to references are only
1150 // diagnosed when they are written directly (e.g., "int & &"),
1151 // but not when they happen via a typedef:
1152 //
1153 // typedef int& intref;
1154 // typedef intref& intref2;
1155 //
1156 // Parser::ParseDeclaratorInternal diagnoses the case where
1157 // references are written directly; here, we handle the
Douglas Gregor69d83162011-01-20 16:08:06 +00001158 // collapsing of references-to-references as described in C++0x.
1159 // DR 106 and 540 introduce reference-collapsing into C++98/03.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001160
1161 // C++ [dcl.ref]p1:
Eli Friedman33a31382009-08-05 19:21:58 +00001162 // A declarator that specifies the type "reference to cv void"
Douglas Gregorcd281c32009-02-28 00:25:32 +00001163 // is ill-formed.
1164 if (T->isVoidType()) {
1165 Diag(Loc, diag::err_reference_to_void);
1166 return QualType();
1167 }
1168
John McCallf85e1932011-06-15 23:02:42 +00001169 // In ARC, it is forbidden to build references to unqualified pointers.
1170 if (getLangOptions().ObjCAutoRefCount)
1171 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1172
Douglas Gregorcd281c32009-02-28 00:25:32 +00001173 // Handle restrict on references.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001174 if (LValueRef)
John McCall28654742010-06-05 06:41:15 +00001175 return Context.getLValueReferenceType(T, SpelledAsLValue);
1176 return Context.getRValueReferenceType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001177}
1178
Chris Lattnere1eed382011-06-14 06:38:10 +00001179/// Check whether the specified array size makes the array type a VLA. If so,
1180/// return true, if not, return the size of the array in SizeVal.
Richard Smith282e7e62012-02-04 09:53:13 +00001181static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1182 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1183 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1184 return S.VerifyIntegerConstantExpression(
1185 ArraySize, &SizeVal, S.PDiag(), S.LangOpts.GNUMode,
1186 S.PDiag(diag::ext_vla_folded_to_constant)).isInvalid();
Chris Lattnere1eed382011-06-14 06:38:10 +00001187}
1188
1189
Douglas Gregorcd281c32009-02-28 00:25:32 +00001190/// \brief Build an array type.
1191///
1192/// \param T The type of each element in the array.
1193///
1194/// \param ASM C99 array size modifier (e.g., '*', 'static').
Mike Stump1eb44332009-09-09 15:08:12 +00001195///
1196/// \param ArraySize Expression describing the size of the array.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001197///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001198/// \param Loc The location of the entity whose type involves this
1199/// array type or, if there is no such entity, the location of the
1200/// type that will have array type.
1201///
1202/// \param Entity The name of the entity that involves the array
1203/// type, if known.
1204///
1205/// \returns A suitable array type, if there are no errors. Otherwise,
1206/// returns a NULL type.
1207QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1208 Expr *ArraySize, unsigned Quals,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001209 SourceRange Brackets, DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001210
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001211 SourceLocation Loc = Brackets.getBegin();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001212 if (getLangOptions().CPlusPlus) {
Douglas Gregor138bb232010-04-27 19:38:14 +00001213 // C++ [dcl.array]p1:
1214 // T is called the array element type; this type shall not be a reference
1215 // type, the (possibly cv-qualified) type void, a function type or an
1216 // abstract class type.
1217 //
1218 // Note: function types are handled in the common path with C.
1219 if (T->isReferenceType()) {
1220 Diag(Loc, diag::err_illegal_decl_array_of_references)
1221 << getPrintableNameForEntity(Entity) << T;
1222 return QualType();
1223 }
1224
Sebastian Redl923d56d2009-11-05 15:52:31 +00001225 if (T->isVoidType()) {
1226 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1227 return QualType();
1228 }
Douglas Gregor138bb232010-04-27 19:38:14 +00001229
1230 if (RequireNonAbstractType(Brackets.getBegin(), T,
1231 diag::err_array_of_abstract_type))
1232 return QualType();
1233
Sebastian Redl923d56d2009-11-05 15:52:31 +00001234 } else {
Douglas Gregor138bb232010-04-27 19:38:14 +00001235 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1236 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
Sebastian Redl923d56d2009-11-05 15:52:31 +00001237 if (RequireCompleteType(Loc, T,
1238 diag::err_illegal_decl_array_incomplete_type))
1239 return QualType();
1240 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001241
1242 if (T->isFunctionType()) {
1243 Diag(Loc, diag::err_illegal_decl_array_of_functions)
John McCallac406052009-10-30 00:37:20 +00001244 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001245 return QualType();
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Richard Smith34b41d92011-02-20 03:19:35 +00001248 if (T->getContainedAutoType()) {
1249 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1250 << getPrintableNameForEntity(Entity) << T;
Anders Carlssone7cf07d2009-06-26 19:33:28 +00001251 return QualType();
1252 }
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Ted Kremenek6217b802009-07-29 21:53:49 +00001254 if (const RecordType *EltTy = T->getAs<RecordType>()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001255 // If the element type is a struct or union that contains a variadic
1256 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1257 if (EltTy->getDecl()->hasFlexibleArrayMember())
1258 Diag(Loc, diag::ext_flexible_array_in_array) << T;
John McCallc12c5bb2010-05-15 11:32:37 +00001259 } else if (T->isObjCObjectType()) {
Chris Lattnerc7c11b12009-04-27 01:55:56 +00001260 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1261 return QualType();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001262 }
Mike Stump1eb44332009-09-09 15:08:12 +00001263
John McCall806054d2012-01-11 00:14:46 +00001264 // Do placeholder conversions on the array size expression.
1265 if (ArraySize && ArraySize->hasPlaceholderType()) {
1266 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1267 if (Result.isInvalid()) return QualType();
1268 ArraySize = Result.take();
1269 }
1270
John McCall5e3c67b2010-12-15 04:42:30 +00001271 // Do lvalue-to-rvalue conversions on the array size expression.
John Wiegley429bb272011-04-08 18:41:53 +00001272 if (ArraySize && !ArraySize->isRValue()) {
1273 ExprResult Result = DefaultLvalueConversion(ArraySize);
1274 if (Result.isInvalid())
1275 return QualType();
1276
1277 ArraySize = Result.take();
1278 }
John McCall5e3c67b2010-12-15 04:42:30 +00001279
Douglas Gregorcd281c32009-02-28 00:25:32 +00001280 // C99 6.7.5.2p1: The size expression shall have integer type.
Richard Smith282e7e62012-02-04 09:53:13 +00001281 // C++11 allows contextual conversions to such types.
1282 if (!getLangOptions().CPlusPlus0x &&
1283 ArraySize && !ArraySize->isTypeDependent() &&
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001284 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001285 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1286 << ArraySize->getType() << ArraySize->getSourceRange();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001287 return QualType();
1288 }
Richard Smith282e7e62012-02-04 09:53:13 +00001289
Douglas Gregor2767ce22010-08-18 00:39:00 +00001290 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
Douglas Gregorcd281c32009-02-28 00:25:32 +00001291 if (!ArraySize) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001292 if (ASM == ArrayType::Star)
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001293 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001294 else
1295 T = Context.getIncompleteArrayType(T, ASM, Quals);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00001296 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001297 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
Richard Smith282e7e62012-02-04 09:53:13 +00001298 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1299 !T->isConstantSizeType()) ||
1300 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1301 // Even in C++11, don't allow contextual conversions in the array bound
1302 // of a VLA.
1303 if (getLangOptions().CPlusPlus0x &&
1304 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1305 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1306 << ArraySize->getType() << ArraySize->getSourceRange();
1307 return QualType();
1308 }
1309
Chris Lattnere1eed382011-06-14 06:38:10 +00001310 // C99: an array with an element type that has a non-constant-size is a VLA.
Chris Lattnere1eed382011-06-14 06:38:10 +00001311 // C99: an array with a non-ICE size is a VLA. We accept any expression
1312 // that we can fold to a non-zero positive value as an extension.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001313 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001314 } else {
1315 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1316 // have a value greater than zero.
Sebastian Redl923d56d2009-11-05 15:52:31 +00001317 if (ConstVal.isSigned() && ConstVal.isNegative()) {
Chandler Carruthb2b5cc02011-01-04 04:44:35 +00001318 if (Entity)
1319 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1320 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1321 else
1322 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1323 << ArraySize->getSourceRange();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001324 return QualType();
1325 }
1326 if (ConstVal == 0) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001327 // GCC accepts zero sized static arrays. We allow them when
1328 // we're not in a SFINAE context.
1329 Diag(ArraySize->getLocStart(),
1330 isSFINAEContext()? diag::err_typecheck_zero_array_size
1331 : diag::ext_typecheck_zero_array_size)
Sebastian Redl923d56d2009-11-05 15:52:31 +00001332 << ArraySize->getSourceRange();
Peter Collingbourne20cdbeb2011-10-16 21:17:32 +00001333
1334 if (ASM == ArrayType::Static) {
1335 Diag(ArraySize->getLocStart(),
1336 diag::warn_typecheck_zero_static_array_size)
1337 << ArraySize->getSourceRange();
1338 ASM = ArrayType::Normal;
1339 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001340 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1341 !T->isIncompleteType()) {
1342 // Is the array too large?
1343 unsigned ActiveSizeBits
1344 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1345 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1346 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1347 << ConstVal.toString(10)
1348 << ArraySize->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001349 }
Douglas Gregor2767ce22010-08-18 00:39:00 +00001350
John McCall46a617a2009-10-16 00:14:28 +00001351 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001352 }
David Chisnallaf407762010-01-11 23:08:08 +00001353 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1354 if (!getLangOptions().C99) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001355 if (T->isVariableArrayType()) {
1356 // Prohibit the use of non-POD types in VLAs.
John McCallf85e1932011-06-15 23:02:42 +00001357 QualType BaseT = Context.getBaseElementType(T);
Douglas Gregor204ce172010-05-24 20:42:30 +00001358 if (!T->isDependentType() &&
John McCallf85e1932011-06-15 23:02:42 +00001359 !BaseT.isPODType(Context) &&
1360 !BaseT->isObjCLifetimeType()) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001361 Diag(Loc, diag::err_vla_non_pod)
John McCallf85e1932011-06-15 23:02:42 +00001362 << BaseT;
Douglas Gregor0fddb972010-05-22 16:17:30 +00001363 return QualType();
1364 }
Douglas Gregora481ec42010-05-23 19:57:01 +00001365 // Prohibit the use of VLAs during template argument deduction.
1366 else if (isSFINAEContext()) {
1367 Diag(Loc, diag::err_vla_in_sfinae);
1368 return QualType();
1369 }
Douglas Gregor0fddb972010-05-22 16:17:30 +00001370 // Just extwarn about VLAs.
1371 else
1372 Diag(Loc, diag::ext_vla);
1373 } else if (ASM != ArrayType::Normal || Quals != 0)
Richard Smithd7c56e12011-12-29 21:57:33 +00001374 Diag(Loc,
Douglas Gregor043cad22009-09-11 00:18:58 +00001375 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
Richard Smithd7c56e12011-12-29 21:57:33 +00001376 : diag::ext_c99_array_usage) << ASM;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001377 }
1378
1379 return T;
1380}
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001381
1382/// \brief Build an ext-vector type.
1383///
1384/// Run the required checks for the extended vector type.
John McCall9ae2f072010-08-23 23:25:46 +00001385QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001386 SourceLocation AttrLoc) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001387 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1388 // in conjunction with complex types (pointers, arrays, functions, etc.).
Mike Stump1eb44332009-09-09 15:08:12 +00001389 if (!T->isDependentType() &&
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001390 !T->isIntegerType() && !T->isRealFloatingType()) {
1391 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1392 return QualType();
1393 }
1394
John McCall9ae2f072010-08-23 23:25:46 +00001395 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001396 llvm::APSInt vecSize(32);
John McCall9ae2f072010-08-23 23:25:46 +00001397 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001398 Diag(AttrLoc, diag::err_attribute_argument_not_int)
John McCall9ae2f072010-08-23 23:25:46 +00001399 << "ext_vector_type" << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001400 return QualType();
1401 }
Mike Stump1eb44332009-09-09 15:08:12 +00001402
1403 // unlike gcc's vector_size attribute, the size is specified as the
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001404 // number of elements, not the number of bytes.
Mike Stump1eb44332009-09-09 15:08:12 +00001405 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1406
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001407 if (vectorSize == 0) {
1408 Diag(AttrLoc, diag::err_attribute_zero_size)
John McCall9ae2f072010-08-23 23:25:46 +00001409 << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001410 return QualType();
1411 }
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Douglas Gregor4ac01402011-06-15 16:02:29 +00001413 return Context.getExtVectorType(T, vectorSize);
Mike Stump1eb44332009-09-09 15:08:12 +00001414 }
1415
John McCall9ae2f072010-08-23 23:25:46 +00001416 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001417}
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Douglas Gregor724651c2009-02-28 01:04:19 +00001419/// \brief Build a function type.
1420///
1421/// This routine checks the function type according to C++ rules and
1422/// under the assumption that the result type and parameter types have
1423/// just been instantiated from a template. It therefore duplicates
Douglas Gregor2943aed2009-03-03 04:44:36 +00001424/// some of the behavior of GetTypeForDeclarator, but in a much
Douglas Gregor724651c2009-02-28 01:04:19 +00001425/// simpler form that is only suitable for this narrow use case.
1426///
1427/// \param T The return type of the function.
1428///
1429/// \param ParamTypes The parameter types of the function. This array
1430/// will be modified to account for adjustments to the types of the
1431/// function parameters.
1432///
1433/// \param NumParamTypes The number of parameter types in ParamTypes.
1434///
1435/// \param Variadic Whether this is a variadic function type.
1436///
1437/// \param Quals The cvr-qualifiers to be applied to the function type.
1438///
1439/// \param Loc The location of the entity whose type involves this
1440/// function type or, if there is no such entity, the location of the
1441/// type that will have function type.
1442///
1443/// \param Entity The name of the entity that involves the function
1444/// type, if known.
1445///
1446/// \returns A suitable function type, if there are no
1447/// errors. Otherwise, returns a NULL type.
1448QualType Sema::BuildFunctionType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001449 QualType *ParamTypes,
Douglas Gregor724651c2009-02-28 01:04:19 +00001450 unsigned NumParamTypes,
1451 bool Variadic, unsigned Quals,
Douglas Gregorc938c162011-01-26 05:01:58 +00001452 RefQualifierKind RefQualifier,
Eli Friedmanfa869542010-08-05 02:54:05 +00001453 SourceLocation Loc, DeclarationName Entity,
John McCalle23cf432010-12-14 08:05:40 +00001454 FunctionType::ExtInfo Info) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001455 if (T->isArrayType() || T->isFunctionType()) {
Douglas Gregor58408bc2010-01-11 18:46:21 +00001456 Diag(Loc, diag::err_func_returning_array_function)
1457 << T->isFunctionType() << T;
Douglas Gregor724651c2009-02-28 01:04:19 +00001458 return QualType();
1459 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001460
1461 // Functions cannot return half FP.
1462 if (T->isHalfType()) {
1463 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1464 FixItHint::CreateInsertion(Loc, "*");
1465 return QualType();
1466 }
1467
Douglas Gregor724651c2009-02-28 01:04:19 +00001468 bool Invalid = false;
1469 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001470 // FIXME: Loc is too inprecise here, should use proper locations for args.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00001471 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001472 if (ParamType->isVoidType()) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001473 Diag(Loc, diag::err_param_with_void_type);
1474 Invalid = true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001475 } else if (ParamType->isHalfType()) {
1476 // Disallow half FP arguments.
1477 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1478 FixItHint::CreateInsertion(Loc, "*");
1479 Invalid = true;
Douglas Gregor724651c2009-02-28 01:04:19 +00001480 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001481
John McCall54e14c42009-10-22 22:37:11 +00001482 ParamTypes[Idx] = ParamType;
Douglas Gregor724651c2009-02-28 01:04:19 +00001483 }
1484
1485 if (Invalid)
1486 return QualType();
1487
John McCalle23cf432010-12-14 08:05:40 +00001488 FunctionProtoType::ExtProtoInfo EPI;
1489 EPI.Variadic = Variadic;
1490 EPI.TypeQuals = Quals;
Douglas Gregorc938c162011-01-26 05:01:58 +00001491 EPI.RefQualifier = RefQualifier;
John McCalle23cf432010-12-14 08:05:40 +00001492 EPI.ExtInfo = Info;
1493
1494 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
Douglas Gregor724651c2009-02-28 01:04:19 +00001495}
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Douglas Gregor949bf692009-06-09 22:17:39 +00001497/// \brief Build a member pointer type \c T Class::*.
1498///
1499/// \param T the type to which the member pointer refers.
1500/// \param Class the class type into which the member pointer points.
John McCall0953e762009-09-24 19:53:00 +00001501/// \param CVR Qualifiers applied to the member pointer type
Douglas Gregor949bf692009-06-09 22:17:39 +00001502/// \param Loc the location where this type begins
1503/// \param Entity the name of the entity that will have this member pointer type
1504///
1505/// \returns a member pointer type, if successful, or a NULL type if there was
1506/// an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001507QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
John McCall28654742010-06-05 06:41:15 +00001508 SourceLocation Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +00001509 DeclarationName Entity) {
1510 // Verify that we're not building a pointer to pointer to function with
1511 // exception specification.
1512 if (CheckDistantExceptionSpec(T)) {
1513 Diag(Loc, diag::err_distant_exception_spec);
1514
1515 // FIXME: If we're doing this as part of template instantiation,
1516 // we should return immediately.
1517
1518 // Build the type anyway, but use the canonical type so that the
1519 // exception specifiers are stripped off.
1520 T = Context.getCanonicalType(T);
1521 }
1522
Sebastian Redl73780122010-06-09 21:19:43 +00001523 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
Douglas Gregor949bf692009-06-09 22:17:39 +00001524 // with reference type, or "cv void."
1525 if (T->isReferenceType()) {
Anders Carlsson8d4655d2009-06-30 00:06:57 +00001526 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001527 << (Entity? Entity.getAsString() : "type name") << T;
Douglas Gregor949bf692009-06-09 22:17:39 +00001528 return QualType();
1529 }
1530
1531 if (T->isVoidType()) {
1532 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1533 << (Entity? Entity.getAsString() : "type name");
1534 return QualType();
1535 }
1536
Douglas Gregor949bf692009-06-09 22:17:39 +00001537 if (!Class->isDependentType() && !Class->isRecordType()) {
1538 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1539 return QualType();
1540 }
1541
Charles Davisd18f9f92010-08-16 04:01:50 +00001542 // In the Microsoft ABI, the class is allowed to be an incomplete
1543 // type. In such cases, the compiler makes a worst-case assumption.
1544 // We make no such assumption right now, so emit an error if the
1545 // class isn't a complete type.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001546 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
Charles Davisd18f9f92010-08-16 04:01:50 +00001547 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1548 return QualType();
1549
John McCall28654742010-06-05 06:41:15 +00001550 return Context.getMemberPointerType(T, Class.getTypePtr());
Douglas Gregor949bf692009-06-09 22:17:39 +00001551}
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Anders Carlsson9a917e42009-06-12 22:56:54 +00001553/// \brief Build a block pointer type.
1554///
1555/// \param T The type to which we'll be building a block pointer.
1556///
John McCall0953e762009-09-24 19:53:00 +00001557/// \param CVR The cvr-qualifiers to be applied to the block pointer type.
Anders Carlsson9a917e42009-06-12 22:56:54 +00001558///
1559/// \param Loc The location of the entity whose type involves this
1560/// block pointer type or, if there is no such entity, the location of the
1561/// type that will have block pointer type.
1562///
1563/// \param Entity The name of the entity that involves the block pointer
1564/// type, if known.
1565///
1566/// \returns A suitable block pointer type, if there are no
1567/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001568QualType Sema::BuildBlockPointerType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001569 SourceLocation Loc,
Anders Carlsson9a917e42009-06-12 22:56:54 +00001570 DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001571 if (!T->isFunctionType()) {
Anders Carlsson9a917e42009-06-12 22:56:54 +00001572 Diag(Loc, diag::err_nonfunction_block_type);
1573 return QualType();
1574 }
Mike Stump1eb44332009-09-09 15:08:12 +00001575
John McCall28654742010-06-05 06:41:15 +00001576 return Context.getBlockPointerType(T);
Anders Carlsson9a917e42009-06-12 22:56:54 +00001577}
1578
John McCallb3d87482010-08-24 05:47:05 +00001579QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1580 QualType QT = Ty.get();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001581 if (QT.isNull()) {
John McCalla93c9342009-12-07 02:54:59 +00001582 if (TInfo) *TInfo = 0;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001583 return QualType();
1584 }
1585
John McCalla93c9342009-12-07 02:54:59 +00001586 TypeSourceInfo *DI = 0;
John McCallf4c73712011-01-19 06:33:43 +00001587 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001588 QT = LIT->getType();
John McCalla93c9342009-12-07 02:54:59 +00001589 DI = LIT->getTypeSourceInfo();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001590 }
Mike Stump1eb44332009-09-09 15:08:12 +00001591
John McCalla93c9342009-12-07 02:54:59 +00001592 if (TInfo) *TInfo = DI;
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001593 return QT;
1594}
1595
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001596static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1597 Qualifiers::ObjCLifetime ownership,
1598 unsigned chunkIndex);
1599
John McCallf85e1932011-06-15 23:02:42 +00001600/// Given that this is the declaration of a parameter under ARC,
1601/// attempt to infer attributes and such for pointer-to-whatever
1602/// types.
1603static void inferARCWriteback(TypeProcessingState &state,
1604 QualType &declSpecType) {
1605 Sema &S = state.getSema();
1606 Declarator &declarator = state.getDeclarator();
1607
1608 // TODO: should we care about decl qualifiers?
1609
1610 // Check whether the declarator has the expected form. We walk
1611 // from the inside out in order to make the block logic work.
1612 unsigned outermostPointerIndex = 0;
1613 bool isBlockPointer = false;
1614 unsigned numPointers = 0;
1615 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1616 unsigned chunkIndex = i;
1617 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1618 switch (chunk.Kind) {
1619 case DeclaratorChunk::Paren:
1620 // Ignore parens.
1621 break;
1622
1623 case DeclaratorChunk::Reference:
1624 case DeclaratorChunk::Pointer:
1625 // Count the number of pointers. Treat references
1626 // interchangeably as pointers; if they're mis-ordered, normal
1627 // type building will discover that.
1628 outermostPointerIndex = chunkIndex;
1629 numPointers++;
1630 break;
1631
1632 case DeclaratorChunk::BlockPointer:
1633 // If we have a pointer to block pointer, that's an acceptable
1634 // indirect reference; anything else is not an application of
1635 // the rules.
1636 if (numPointers != 1) return;
1637 numPointers++;
1638 outermostPointerIndex = chunkIndex;
1639 isBlockPointer = true;
1640
1641 // We don't care about pointer structure in return values here.
1642 goto done;
1643
1644 case DeclaratorChunk::Array: // suppress if written (id[])?
1645 case DeclaratorChunk::Function:
1646 case DeclaratorChunk::MemberPointer:
1647 return;
1648 }
1649 }
1650 done:
1651
1652 // If we have *one* pointer, then we want to throw the qualifier on
1653 // the declaration-specifiers, which means that it needs to be a
1654 // retainable object type.
1655 if (numPointers == 1) {
1656 // If it's not a retainable object type, the rule doesn't apply.
1657 if (!declSpecType->isObjCRetainableType()) return;
1658
1659 // If it already has lifetime, don't do anything.
1660 if (declSpecType.getObjCLifetime()) return;
1661
1662 // Otherwise, modify the type in-place.
1663 Qualifiers qs;
1664
1665 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1666 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1667 else
1668 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1669 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1670
1671 // If we have *two* pointers, then we want to throw the qualifier on
1672 // the outermost pointer.
1673 } else if (numPointers == 2) {
1674 // If we don't have a block pointer, we need to check whether the
1675 // declaration-specifiers gave us something that will turn into a
1676 // retainable object pointer after we slap the first pointer on it.
1677 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1678 return;
1679
1680 // Look for an explicit lifetime attribute there.
1681 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
Argyrios Kyrtzidis1c73dcb2011-07-01 22:23:03 +00001682 if (chunk.Kind != DeclaratorChunk::Pointer &&
1683 chunk.Kind != DeclaratorChunk::BlockPointer)
1684 return;
John McCallf85e1932011-06-15 23:02:42 +00001685 for (const AttributeList *attr = chunk.getAttrs(); attr;
1686 attr = attr->getNext())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001687 if (attr->getKind() == AttributeList::AT_objc_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001688 return;
1689
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001690 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1691 outermostPointerIndex);
John McCallf85e1932011-06-15 23:02:42 +00001692
1693 // Any other number of pointers/references does not trigger the rule.
1694 } else return;
1695
1696 // TODO: mark whether we did this inference?
1697}
1698
Chandler Carruthd067c072011-02-23 18:51:59 +00001699static void DiagnoseIgnoredQualifiers(unsigned Quals,
1700 SourceLocation ConstQualLoc,
1701 SourceLocation VolatileQualLoc,
1702 SourceLocation RestrictQualLoc,
1703 Sema& S) {
1704 std::string QualStr;
1705 unsigned NumQuals = 0;
1706 SourceLocation Loc;
1707
1708 FixItHint ConstFixIt;
1709 FixItHint VolatileFixIt;
1710 FixItHint RestrictFixIt;
1711
Hans Wennborga08fcb82011-06-03 17:37:26 +00001712 const SourceManager &SM = S.getSourceManager();
1713
Chandler Carruthd067c072011-02-23 18:51:59 +00001714 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1715 // find a range and grow it to encompass all the qualifiers, regardless of
1716 // the order in which they textually appear.
1717 if (Quals & Qualifiers::Const) {
1718 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
Chandler Carruthd067c072011-02-23 18:51:59 +00001719 QualStr = "const";
Hans Wennborga08fcb82011-06-03 17:37:26 +00001720 ++NumQuals;
1721 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1722 Loc = ConstQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001723 }
1724 if (Quals & Qualifiers::Volatile) {
1725 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001726 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
Chandler Carruthd067c072011-02-23 18:51:59 +00001727 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001728 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1729 Loc = VolatileQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001730 }
1731 if (Quals & Qualifiers::Restrict) {
1732 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001733 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
Chandler Carruthd067c072011-02-23 18:51:59 +00001734 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001735 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1736 Loc = RestrictQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001737 }
1738
1739 assert(NumQuals > 0 && "No known qualifiers?");
1740
1741 S.Diag(Loc, diag::warn_qual_return_type)
Hans Wennborga08fcb82011-06-03 17:37:26 +00001742 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
Chandler Carruthd067c072011-02-23 18:51:59 +00001743}
1744
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001745static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1746 TypeSourceInfo *&ReturnTypeInfo) {
1747 Sema &SemaRef = state.getSema();
1748 Declarator &D = state.getDeclarator();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001749 QualType T;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001750 ReturnTypeInfo = 0;
1751
1752 // The TagDecl owned by the DeclSpec.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001753 TagDecl *OwnedTagDecl = 0;
John McCall711c52b2011-01-05 12:14:39 +00001754
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001755 switch (D.getName().getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001756 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001757 case UnqualifiedId::IK_OperatorFunctionId:
Sebastian Redl8999fe12011-03-14 18:08:30 +00001758 case UnqualifiedId::IK_Identifier:
Sean Hunt0486d742009-11-28 04:44:28 +00001759 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001760 case UnqualifiedId::IK_TemplateId:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001761 T = ConvertDeclSpecToType(state);
Chris Lattner5db2bb12009-10-25 18:21:37 +00001762
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001763 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001764 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Abramo Bagnara15987972011-03-08 22:33:38 +00001765 // Owned declaration is embedded in declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001766 OwnedTagDecl->setEmbeddedInDeclarator(true);
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001767 }
Douglas Gregor930d8b52009-01-30 22:09:00 +00001768 break;
1769
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001770 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001771 case UnqualifiedId::IK_ConstructorTemplateId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001772 case UnqualifiedId::IK_DestructorName:
Douglas Gregor930d8b52009-01-30 22:09:00 +00001773 // Constructors and destructors don't have return types. Use
Douglas Gregor48026d22010-01-11 18:40:55 +00001774 // "void" instead.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001775 T = SemaRef.Context.VoidTy;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001776 break;
Douglas Gregor48026d22010-01-11 18:40:55 +00001777
1778 case UnqualifiedId::IK_ConversionFunctionId:
1779 // The result type of a conversion function is the type that it
1780 // converts to.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001781 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1782 &ReturnTypeInfo);
Douglas Gregor48026d22010-01-11 18:40:55 +00001783 break;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001784 }
Douglas Gregordab60ad2010-10-01 18:44:50 +00001785
John McCall711c52b2011-01-05 12:14:39 +00001786 if (D.getAttributes())
1787 distributeTypeAttrsFromDeclarator(state, T);
1788
Richard Smithe7397c62011-02-22 00:36:53 +00001789 // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
Richard Smith8110f042011-02-22 01:22:29 +00001790 // In C++0x, a function declarator using 'auto' must have a trailing return
1791 // type (this is checked later) and we can skip this. In other languages
1792 // using auto, we need to check regardless.
Richard Smith34b41d92011-02-20 03:19:35 +00001793 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001794 (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001795 int Error = -1;
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001797 switch (D.getContext()) {
1798 case Declarator::KNRTypeListContext:
David Blaikieb219cfc2011-09-23 05:06:16 +00001799 llvm_unreachable("K&R type lists aren't allowed in C++");
Eli Friedmanf88c4002012-01-04 04:41:38 +00001800 case Declarator::LambdaExprContext:
1801 llvm_unreachable("Can't specify a type specifier in lambda grammar");
John McCallcdda47f2011-10-01 09:56:14 +00001802 case Declarator::ObjCParameterContext:
1803 case Declarator::ObjCResultContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001804 case Declarator::PrototypeContext:
1805 Error = 0; // Function prototype
1806 break;
1807 case Declarator::MemberContext:
Richard Smith7a614d82011-06-11 17:19:42 +00001808 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1809 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001810 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
David Blaikieeb2d1f12011-09-23 20:26:49 +00001811 case TTK_Enum: llvm_unreachable("unhandled tag kind");
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001812 case TTK_Struct: Error = 1; /* Struct member */ break;
1813 case TTK_Union: Error = 2; /* Union member */ break;
1814 case TTK_Class: Error = 3; /* Class member */ break;
Mike Stump1eb44332009-09-09 15:08:12 +00001815 }
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001816 break;
1817 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00001818 case Declarator::ObjCCatchContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001819 Error = 4; // Exception declaration
1820 break;
1821 case Declarator::TemplateParamContext:
1822 Error = 5; // Template parameter
1823 break;
1824 case Declarator::BlockLiteralContext:
Richard Smith34b41d92011-02-20 03:19:35 +00001825 Error = 6; // Block literal
1826 break;
1827 case Declarator::TemplateTypeArgContext:
1828 Error = 7; // Template type argument
1829 break;
Richard Smith162e1c12011-04-15 14:24:37 +00001830 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001831 case Declarator::AliasTemplateContext:
Richard Smith162e1c12011-04-15 14:24:37 +00001832 Error = 9; // Type alias
1833 break;
Richard Smith34b41d92011-02-20 03:19:35 +00001834 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001835 Error = 11; // Generic
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001836 break;
1837 case Declarator::FileContext:
1838 case Declarator::BlockContext:
1839 case Declarator::ForContext:
1840 case Declarator::ConditionContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001841 case Declarator::CXXNewContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001842 break;
1843 }
1844
Richard Smithddc83f92011-02-21 23:18:00 +00001845 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1846 Error = 8;
1847
Richard Smith8110f042011-02-22 01:22:29 +00001848 // In Objective-C it is an error to use 'auto' on a function declarator.
1849 if (D.isFunctionDeclarator())
Richard Smith162e1c12011-04-15 14:24:37 +00001850 Error = 10;
Richard Smith8110f042011-02-22 01:22:29 +00001851
Richard Smithe7397c62011-02-22 00:36:53 +00001852 // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1853 // contains a trailing return type. That is only legal at the outermost
1854 // level. Check all declarator chunks (outermost first) anyway, to give
1855 // better diagnostics.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001856 if (SemaRef.getLangOptions().CPlusPlus0x && Error != -1) {
Richard Smithe7397c62011-02-22 00:36:53 +00001857 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1858 unsigned chunkIndex = e - i - 1;
1859 state.setCurrentChunkIndex(chunkIndex);
1860 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1861 if (DeclType.Kind == DeclaratorChunk::Function) {
1862 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1863 if (FTI.TrailingReturnType) {
1864 Error = -1;
1865 break;
1866 }
1867 }
1868 }
1869 }
1870
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001871 if (Error != -1) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001872 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1873 diag::err_auto_not_allowed)
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001874 << Error;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001875 T = SemaRef.Context.IntTy;
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001876 D.setInvalidType(true);
Richard Smith0aa86c02011-10-15 05:42:01 +00001877 } else
1878 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1879 diag::warn_cxx98_compat_auto_type_specifier);
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001880 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001881
1882 if (SemaRef.getLangOptions().CPlusPlus &&
John McCall5e1cdac2011-10-07 06:10:15 +00001883 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001884 // Check the contexts where C++ forbids the declaration of a new class
1885 // or enumeration in a type-specifier-seq.
1886 switch (D.getContext()) {
1887 case Declarator::FileContext:
1888 case Declarator::MemberContext:
1889 case Declarator::BlockContext:
1890 case Declarator::ForContext:
1891 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00001892 case Declarator::LambdaExprContext:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001893 // C++0x [dcl.type]p3:
1894 // A type-specifier-seq shall not define a class or enumeration unless
1895 // it appears in the type-id of an alias-declaration (7.1.3) that is not
1896 // the declaration of a template-declaration.
1897 case Declarator::AliasDeclContext:
1898 break;
1899 case Declarator::AliasTemplateContext:
1900 SemaRef.Diag(OwnedTagDecl->getLocation(),
1901 diag::err_type_defined_in_alias_template)
1902 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1903 break;
1904 case Declarator::TypeNameContext:
1905 case Declarator::TemplateParamContext:
1906 case Declarator::CXXNewContext:
1907 case Declarator::CXXCatchContext:
1908 case Declarator::ObjCCatchContext:
1909 case Declarator::TemplateTypeArgContext:
1910 SemaRef.Diag(OwnedTagDecl->getLocation(),
1911 diag::err_type_defined_in_type_specifier)
1912 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1913 break;
1914 case Declarator::PrototypeContext:
John McCallcdda47f2011-10-01 09:56:14 +00001915 case Declarator::ObjCParameterContext:
1916 case Declarator::ObjCResultContext:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001917 case Declarator::KNRTypeListContext:
1918 // C++ [dcl.fct]p6:
1919 // Types shall not be defined in return or parameter types.
1920 SemaRef.Diag(OwnedTagDecl->getLocation(),
1921 diag::err_type_defined_in_param_type)
1922 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1923 break;
1924 case Declarator::ConditionContext:
1925 // C++ 6.4p2:
1926 // The type-specifier-seq shall not contain typedef and shall not declare
1927 // a new class or enumeration.
1928 SemaRef.Diag(OwnedTagDecl->getLocation(),
1929 diag::err_type_defined_in_condition);
1930 break;
1931 }
1932 }
1933
1934 return T;
1935}
1936
1937static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
1938 QualType declSpecType,
1939 TypeSourceInfo *TInfo) {
1940
1941 QualType T = declSpecType;
1942 Declarator &D = state.getDeclarator();
1943 Sema &S = state.getSema();
1944 ASTContext &Context = S.Context;
1945 const LangOptions &LangOpts = S.getLangOptions();
1946
1947 bool ImplicitlyNoexcept = false;
1948 if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
1949 LangOpts.CPlusPlus0x) {
1950 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1951 /// In C++0x, deallocation functions (normal and array operator delete)
1952 /// are implicitly noexcept.
1953 if (OO == OO_Delete || OO == OO_Array_Delete)
1954 ImplicitlyNoexcept = true;
1955 }
Richard Smith34b41d92011-02-20 03:19:35 +00001956
Douglas Gregorcd281c32009-02-28 00:25:32 +00001957 // The name we're declaring, if any.
1958 DeclarationName Name;
1959 if (D.getIdentifier())
1960 Name = D.getIdentifier();
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Richard Smith162e1c12011-04-15 14:24:37 +00001962 // Does this declaration declare a typedef-name?
1963 bool IsTypedefName =
1964 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
Richard Smith3e4c6c42011-05-05 21:57:07 +00001965 D.getContext() == Declarator::AliasDeclContext ||
1966 D.getContext() == Declarator::AliasTemplateContext;
Richard Smith162e1c12011-04-15 14:24:37 +00001967
Mike Stump98eb8a72009-02-04 22:31:32 +00001968 // Walk the DeclTypeInfo, building the recursive type as we go.
1969 // DeclTypeInfos are ordered from the identifier out, which is
1970 // opposite of what we want :).
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001971 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall711c52b2011-01-05 12:14:39 +00001972 unsigned chunkIndex = e - i - 1;
1973 state.setCurrentChunkIndex(chunkIndex);
1974 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 switch (DeclType.Kind) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001976 case DeclaratorChunk::Paren:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001977 T = S.BuildParenType(T);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001978 break;
Steve Naroff5618bd42008-08-27 16:04:49 +00001979 case DeclaratorChunk::BlockPointer:
Chris Lattner9af55002009-03-27 04:18:06 +00001980 // If blocks are disabled, emit an error.
1981 if (!LangOpts.Blocks)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001982 S.Diag(DeclType.Loc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001984 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
John McCall28654742010-06-05 06:41:15 +00001985 if (DeclType.Cls.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001986 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
Steve Naroff5618bd42008-08-27 16:04:49 +00001987 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 case DeclaratorChunk::Pointer:
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001989 // Verify that we're not building a pointer to pointer to function with
1990 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001991 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1992 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00001993 D.setInvalidType(true);
1994 // Build the type anyway.
1995 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001996 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00001997 T = Context.getObjCObjectPointerType(T);
John McCall28654742010-06-05 06:41:15 +00001998 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001999 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
Steve Naroff14108da2009-07-10 23:34:53 +00002000 break;
2001 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002002 T = S.BuildPointerType(T, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002003 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002004 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
John McCall711c52b2011-01-05 12:14:39 +00002005
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 break;
John McCall0953e762009-09-24 19:53:00 +00002007 case DeclaratorChunk::Reference: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002008 // Verify that we're not building a reference to pointer to function with
2009 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002010 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2011 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002012 D.setInvalidType(true);
2013 // Build the type anyway.
2014 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002015 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002016
2017 Qualifiers Quals;
2018 if (DeclType.Ref.HasRestrict)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002019 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
Reid Spencer5f016e22007-07-11 17:01:13 +00002020 break;
John McCall0953e762009-09-24 19:53:00 +00002021 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 case DeclaratorChunk::Array: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002023 // Verify that we're not building an array of pointers to function with
2024 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002025 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2026 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002027 D.setInvalidType(true);
2028 // Build the type anyway.
2029 }
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002030 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
Chris Lattner94f81fd2007-08-28 16:54:00 +00002031 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00002032 ArrayType::ArraySizeModifier ASM;
2033 if (ATI.isStar)
2034 ASM = ArrayType::Star;
2035 else if (ATI.hasStatic)
2036 ASM = ArrayType::Static;
2037 else
2038 ASM = ArrayType::Normal;
John McCallc05a94b2011-03-23 23:43:04 +00002039 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002040 // FIXME: This check isn't quite right: it allows star in prototypes
2041 // for function definitions, and disallows some edge cases detailed
2042 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002043 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002044 ASM = ArrayType::Normal;
2045 D.setInvalidType(true);
2046 }
Eli Friedman8ac2c662011-11-11 02:00:42 +00002047 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002048 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 break;
2050 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002051 case DeclaratorChunk::Function: {
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 // If the function declarator has a prototype (i.e. it is not () and
2053 // does not have a K&R-style identifier list), then the arguments are part
2054 // of the type, otherwise the argument list is ().
2055 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Sebastian Redl3cc97262009-05-31 11:47:27 +00002056
Richard Smithe7397c62011-02-22 00:36:53 +00002057 // Check for auto functions and trailing return type and adjust the
2058 // return type accordingly.
2059 if (!D.isInvalidType()) {
2060 // trailing-return-type is only required if we're declaring a function,
2061 // and not, for instance, a pointer to a function.
2062 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2063 !FTI.TrailingReturnType && chunkIndex == 0) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002064 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002065 diag::err_auto_missing_trailing_return);
2066 T = Context.IntTy;
2067 D.setInvalidType(true);
2068 } else if (FTI.TrailingReturnType) {
2069 // T must be exactly 'auto' at this point. See CWG issue 681.
2070 if (isa<ParenType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002071 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002072 diag::err_trailing_return_in_parens)
2073 << T << D.getDeclSpec().getSourceRange();
2074 D.setInvalidType(true);
Eli Friedmanf88c4002012-01-04 04:41:38 +00002075 } else if (D.getContext() != Declarator::LambdaExprContext &&
2076 (T.hasQualifiers() || !isa<AutoType>(T))) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002077 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002078 diag::err_trailing_return_without_auto)
2079 << T << D.getDeclSpec().getSourceRange();
2080 D.setInvalidType(true);
2081 }
2082
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002083 T = S.GetTypeFromParser(
Richard Smithe7397c62011-02-22 00:36:53 +00002084 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002085 &TInfo);
Richard Smithe7397c62011-02-22 00:36:53 +00002086 }
2087 }
2088
Chris Lattnercd881292007-12-19 05:31:29 +00002089 // C99 6.7.5.3p1: The return type may not be a function or array type.
Douglas Gregor58408bc2010-01-11 18:46:21 +00002090 // For conversion functions, we'll diagnose this particular error later.
Douglas Gregor48026d22010-01-11 18:40:55 +00002091 if ((T->isArrayType() || T->isFunctionType()) &&
2092 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002093 unsigned diagID = diag::err_func_returning_array_function;
Argyrios Kyrtzidisa4356ad2011-01-26 01:26:44 +00002094 // Last processing chunk in block context means this function chunk
2095 // represents the block.
2096 if (chunkIndex == 0 &&
2097 D.getContext() == Declarator::BlockLiteralContext)
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002098 diagID = diag::err_block_returning_array_function;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002099 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
Chris Lattnercd881292007-12-19 05:31:29 +00002100 T = Context.IntTy;
2101 D.setInvalidType(true);
2102 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002103
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002104 // Do not allow returning half FP value.
2105 // FIXME: This really should be in BuildFunctionType.
2106 if (T->isHalfType()) {
2107 S.Diag(D.getIdentifierLoc(),
2108 diag::err_parameters_retval_cannot_have_fp16_type) << 1
2109 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
2110 D.setInvalidType(true);
2111 }
2112
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002113 // cv-qualifiers on return types are pointless except when the type is a
2114 // class type in C++.
Douglas Gregorfff95132011-03-01 17:04:42 +00002115 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
Rafael Espindola1e153942011-03-11 04:56:58 +00002116 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002117 (!LangOpts.CPlusPlus || !T->isDependentType())) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002118 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2119 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2120 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2121
2122 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2123
2124 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2125 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2126 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2127 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002128 S);
Chandler Carruthd067c072011-02-23 18:51:59 +00002129
2130 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002131 (!LangOpts.CPlusPlus ||
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002132 (!T->isDependentType() && !T->isRecordType()))) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002133
2134 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2135 D.getDeclSpec().getConstSpecLoc(),
2136 D.getDeclSpec().getVolatileSpecLoc(),
2137 D.getDeclSpec().getRestrictSpecLoc(),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002138 S);
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002139 }
Chandler Carruthd067c072011-02-23 18:51:59 +00002140
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002141 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
Douglas Gregor402abb52009-05-28 23:31:59 +00002142 // C++ [dcl.fct]p6:
2143 // Types shall not be defined in return or parameter types.
John McCallb3d87482010-08-24 05:47:05 +00002144 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
John McCall5e1cdac2011-10-07 06:10:15 +00002145 if (Tag->isCompleteDefinition())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002146 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
Douglas Gregor402abb52009-05-28 23:31:59 +00002147 << Context.getTypeDeclType(Tag);
2148 }
2149
Sebastian Redl3cc97262009-05-31 11:47:27 +00002150 // Exception specs are not allowed in typedefs. Complain, but add it
2151 // anyway.
Richard Smith162e1c12011-04-15 14:24:37 +00002152 if (IsTypedefName && FTI.getExceptionSpecType())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002153 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
Richard Smith3e4c6c42011-05-05 21:57:07 +00002154 << (D.getContext() == Declarator::AliasDeclContext ||
2155 D.getContext() == Declarator::AliasTemplateContext);
Sebastian Redl3cc97262009-05-31 11:47:27 +00002156
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002157 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
John McCall28654742010-06-05 06:41:15 +00002158 // Simple void foo(), where the incoming T is the result type.
2159 T = Context.getFunctionNoProtoType(T);
2160 } else {
2161 // We allow a zero-parameter variadic function in C if the
2162 // function is marked with the "overloadable" attribute. Scan
2163 // for this attribute now.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002164 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002165 bool Overloadable = false;
2166 for (const AttributeList *Attrs = D.getAttributes();
2167 Attrs; Attrs = Attrs->getNext()) {
2168 if (Attrs->getKind() == AttributeList::AT_overloadable) {
2169 Overloadable = true;
2170 break;
2171 }
2172 }
2173
2174 if (!Overloadable)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002175 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
Argyrios Kyrtzidisc6f73452008-10-16 17:31:08 +00002176 }
John McCall28654742010-06-05 06:41:15 +00002177
2178 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002179 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2180 // definition.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002181 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
John McCall28654742010-06-05 06:41:15 +00002182 D.setInvalidType(true);
2183 break;
2184 }
2185
John McCalle23cf432010-12-14 08:05:40 +00002186 FunctionProtoType::ExtProtoInfo EPI;
2187 EPI.Variadic = FTI.isVariadic;
2188 EPI.TypeQuals = FTI.TypeQuals;
Douglas Gregorc938c162011-01-26 05:01:58 +00002189 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2190 : FTI.RefQualifierIsLValueRef? RQ_LValue
2191 : RQ_RValue;
2192
Reid Spencer5f016e22007-07-11 17:01:13 +00002193 // Otherwise, we have a function with an argument list that is
2194 // potentially variadic.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002195 SmallVector<QualType, 16> ArgTys;
John McCall28654742010-06-05 06:41:15 +00002196 ArgTys.reserve(FTI.NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Chris Lattner5f9e2722011-07-23 10:55:15 +00002198 SmallVector<bool, 16> ConsumedArguments;
John McCallf85e1932011-06-15 23:02:42 +00002199 ConsumedArguments.reserve(FTI.NumArgs);
2200 bool HasAnyConsumedArguments = false;
2201
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002203 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Chris Lattner8123a952008-04-10 02:22:51 +00002204 QualType ArgTy = Param->getType();
Chris Lattner78c75fb2007-07-21 05:30:18 +00002205 assert(!ArgTy.isNull() && "Couldn't parse type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002206
2207 // Adjust the parameter type.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00002208 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2209 "Unadjusted type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002210
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 // Look for 'void'. void is allowed only as a single argument to a
2212 // function with no other parameters (C99 6.7.5.3p10). We record
Douglas Gregor72564e72009-02-26 23:50:07 +00002213 // int(void) as a FunctionProtoType with an empty argument list.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002214 if (ArgTy->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002215 // If this is something like 'float(int, void)', reject it. 'void'
2216 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2217 // have arguments of incomplete type.
2218 if (FTI.NumArgs != 1 || FTI.isVariadic) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002219 S.Diag(DeclType.Loc, diag::err_void_only_param);
Chris Lattner2ff54262007-07-21 05:18:12 +00002220 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002221 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002222 } else if (FTI.ArgInfo[i].Ident) {
2223 // Reject, but continue to parse 'int(void abc)'.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002224 S.Diag(FTI.ArgInfo[i].IdentLoc,
Chris Lattner4565d4e2007-07-21 05:26:43 +00002225 diag::err_param_with_void_type);
Chris Lattner2ff54262007-07-21 05:18:12 +00002226 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002227 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002228 } else {
2229 // Reject, but continue to parse 'float(const void)'.
John McCall0953e762009-09-24 19:53:00 +00002230 if (ArgTy.hasQualifiers())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002231 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
Mike Stump1eb44332009-09-09 15:08:12 +00002232
Chris Lattner2ff54262007-07-21 05:18:12 +00002233 // Do not add 'void' to the ArgTys list.
2234 break;
2235 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002236 } else if (ArgTy->isHalfType()) {
2237 // Disallow half FP arguments.
2238 // FIXME: This really should be in BuildFunctionType.
2239 S.Diag(Param->getLocation(),
2240 diag::err_parameters_retval_cannot_have_fp16_type) << 0
2241 << FixItHint::CreateInsertion(Param->getLocation(), "*");
2242 D.setInvalidType();
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002243 } else if (!FTI.hasPrototype) {
2244 if (ArgTy->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00002245 ArgTy = Context.getPromotedIntegerType(ArgTy);
John McCalleecf5fa2011-03-09 04:22:44 +00002246 Param->setKNRPromoted(true);
John McCall183700f2009-09-21 23:43:11 +00002247 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
John McCalleecf5fa2011-03-09 04:22:44 +00002248 if (BTy->getKind() == BuiltinType::Float) {
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002249 ArgTy = Context.DoubleTy;
John McCalleecf5fa2011-03-09 04:22:44 +00002250 Param->setKNRPromoted(true);
2251 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002252 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002253 }
Fariborz Jahanian56a965c2010-09-08 21:36:35 +00002254
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002255 if (LangOpts.ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002256 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2257 ConsumedArguments.push_back(Consumed);
2258 HasAnyConsumedArguments |= Consumed;
2259 }
2260
John McCall54e14c42009-10-22 22:37:11 +00002261 ArgTys.push_back(ArgTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00002262 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002263
John McCallf85e1932011-06-15 23:02:42 +00002264 if (HasAnyConsumedArguments)
2265 EPI.ConsumedArguments = ConsumedArguments.data();
2266
Chris Lattner5f9e2722011-07-23 10:55:15 +00002267 SmallVector<QualType, 4> Exceptions;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002268 EPI.ExceptionSpecType = FTI.getExceptionSpecType();
2269 if (FTI.getExceptionSpecType() == EST_Dynamic) {
John McCalle23cf432010-12-14 08:05:40 +00002270 Exceptions.reserve(FTI.NumExceptions);
2271 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
2272 // FIXME: Preserve type source info.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002273 QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty);
John McCalle23cf432010-12-14 08:05:40 +00002274 // Check that the type is valid for an exception spec, and
2275 // drop it if not.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002276 if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
John McCalle23cf432010-12-14 08:05:40 +00002277 Exceptions.push_back(ET);
2278 }
John McCall373920b2010-12-14 16:45:57 +00002279 EPI.NumExceptions = Exceptions.size();
John McCalle23cf432010-12-14 08:05:40 +00002280 EPI.Exceptions = Exceptions.data();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002281 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
Sebastian Redl60618fa2011-03-12 11:50:43 +00002282 // If an error occurred, there's no expression here.
2283 if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
2284 assert((NoexceptExpr->isTypeDependent() ||
2285 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
2286 Context.BoolTy) &&
2287 "Parser should have made sure that the expression is boolean");
Richard Smith282e7e62012-02-04 09:53:13 +00002288 if (!NoexceptExpr->isValueDependent())
2289 NoexceptExpr = S.VerifyIntegerConstantExpression(NoexceptExpr, 0,
2290 S.PDiag(diag::err_noexcept_needs_constant_expression),
2291 /*AllowFold*/ false).take();
2292 EPI.NoexceptExpr = NoexceptExpr;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002293 }
Sebastian Redl8999fe12011-03-14 18:08:30 +00002294 } else if (FTI.getExceptionSpecType() == EST_None &&
2295 ImplicitlyNoexcept && chunkIndex == 0) {
2296 // Only the outermost chunk is marked noexcept, of course.
2297 EPI.ExceptionSpecType = EST_BasicNoexcept;
Sebastian Redlef65f062009-05-29 18:02:33 +00002298 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002299
John McCalle23cf432010-12-14 08:05:40 +00002300 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002301 }
John McCall04a67a62010-02-05 21:31:56 +00002302
Reid Spencer5f016e22007-07-11 17:01:13 +00002303 break;
2304 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002305 case DeclaratorChunk::MemberPointer:
2306 // The scope spec must refer to a class, or be dependent.
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002307 CXXScopeSpec &SS = DeclType.Mem.Scope();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002308 QualType ClsType;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002309 if (SS.isInvalid()) {
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00002310 // Avoid emitting extra errors if we already errored on the scope.
2311 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002312 } else if (S.isDependentScopeSpecifier(SS) ||
2313 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002314 NestedNameSpecifier *NNS
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002315 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002316 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2317 switch (NNS->getKind()) {
2318 case NestedNameSpecifier::Identifier:
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002319 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002320 NNS->getAsIdentifier());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002321 break;
2322
2323 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00002324 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor87c12c42009-11-04 16:49:01 +00002325 case NestedNameSpecifier::Global:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002326 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002327
Douglas Gregor87c12c42009-11-04 16:49:01 +00002328 case NestedNameSpecifier::TypeSpec:
2329 case NestedNameSpecifier::TypeSpecWithTemplate:
2330 ClsType = QualType(NNS->getAsType(), 0);
Abramo Bagnara91ce2c42011-03-10 10:18:27 +00002331 // Note: if the NNS has a prefix and ClsType is a nondependent
2332 // TemplateSpecializationType, then the NNS prefix is NOT included
2333 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2334 // NOTE: in particular, no wrap occurs if ClsType already is an
2335 // Elaborated, DependentName, or DependentTemplateSpecialization.
2336 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002337 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
Douglas Gregor87c12c42009-11-04 16:49:01 +00002338 break;
2339 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002340 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002341 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
Douglas Gregor949bf692009-06-09 22:17:39 +00002342 diag::err_illegal_decl_mempointer_in_nonclass)
2343 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2344 << DeclType.Mem.Scope().getRange();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002345 D.setInvalidType(true);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002346 }
2347
Douglas Gregor949bf692009-06-09 22:17:39 +00002348 if (!ClsType.isNull())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002349 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
Douglas Gregor949bf692009-06-09 22:17:39 +00002350 if (T.isNull()) {
2351 T = Context.IntTy;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002352 D.setInvalidType(true);
John McCall28654742010-06-05 06:41:15 +00002353 } else if (DeclType.Mem.TypeQuals) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002354 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002355 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002356 break;
2357 }
2358
Douglas Gregorcd281c32009-02-28 00:25:32 +00002359 if (T.isNull()) {
2360 D.setInvalidType(true);
2361 T = Context.IntTy;
2362 }
2363
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002364 // See if there are any attributes on this declarator chunk.
John McCall711c52b2011-01-05 12:14:39 +00002365 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2366 processTypeAttrs(state, T, false, attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002368
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002369 if (LangOpts.CPlusPlus && T->isFunctionType()) {
John McCall183700f2009-09-21 23:43:11 +00002370 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
Chris Lattner778ed742009-10-25 17:36:50 +00002371 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002372
Douglas Gregor708f3b82010-10-14 22:03:51 +00002373 // C++ 8.3.5p4:
2374 // A cv-qualifier-seq shall only be part of the function type
2375 // for a nonstatic member function, the function type to which a pointer
2376 // to member refers, or the top-level function type of a function typedef
2377 // declaration.
Douglas Gregor683a81f2011-01-31 16:09:46 +00002378 //
2379 // Core issue 547 also allows cv-qualifiers on function types that are
2380 // top-level template type arguments.
John McCall613ef3d2010-10-19 01:54:45 +00002381 bool FreeFunction;
2382 if (!D.getCXXScopeSpec().isSet()) {
Eli Friedman906a7e12012-01-06 03:05:34 +00002383 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
2384 D.getContext() != Declarator::LambdaExprContext) ||
John McCall613ef3d2010-10-19 01:54:45 +00002385 D.getDeclSpec().isFriendSpecified());
2386 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002387 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
John McCall613ef3d2010-10-19 01:54:45 +00002388 FreeFunction = (DC && !DC->isRecord());
2389 }
2390
Richard Smith55dec862011-09-30 00:45:47 +00002391 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
2392 // function that is not a constructor declares that function to be const.
2393 if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002394 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
Richard Smith55dec862011-09-30 00:45:47 +00002395 D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
2396 D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
2397 !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
2398 // Rebuild function type adding a 'const' qualifier.
2399 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2400 EPI.TypeQuals |= DeclSpec::TQ_const;
2401 T = Context.getFunctionType(FnTy->getResultType(),
2402 FnTy->arg_type_begin(),
2403 FnTy->getNumArgs(), EPI);
2404 }
2405
Douglas Gregorc938c162011-01-26 05:01:58 +00002406 // C++0x [dcl.fct]p6:
2407 // A ref-qualifier shall only be part of the function type for a
2408 // non-static member function, the function type to which a pointer to
2409 // member refers, or the top-level function type of a function typedef
2410 // declaration.
2411 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
Douglas Gregor683a81f2011-01-31 16:09:46 +00002412 !(D.getContext() == Declarator::TemplateTypeArgContext &&
Richard Smith162e1c12011-04-15 14:24:37 +00002413 !D.isFunctionDeclarator()) && !IsTypedefName &&
Sebastian Redlc61bb202010-07-09 21:26:08 +00002414 (FreeFunction ||
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002415 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
Douglas Gregor683a81f2011-01-31 16:09:46 +00002416 if (D.getContext() == Declarator::TemplateTypeArgContext) {
2417 // Accept qualified function types as template type arguments as a GNU
2418 // extension. This is also the subject of C++ core issue 547.
2419 std::string Quals;
2420 if (FnTy->getTypeQuals() != 0)
2421 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2422
2423 switch (FnTy->getRefQualifier()) {
2424 case RQ_None:
2425 break;
2426
2427 case RQ_LValue:
2428 if (!Quals.empty())
2429 Quals += ' ';
2430 Quals += '&';
2431 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002432
Douglas Gregor683a81f2011-01-31 16:09:46 +00002433 case RQ_RValue:
2434 if (!Quals.empty())
2435 Quals += ' ';
2436 Quals += "&&";
2437 break;
Douglas Gregorc938c162011-01-26 05:01:58 +00002438 }
Douglas Gregor683a81f2011-01-31 16:09:46 +00002439
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002440 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002441 diag::ext_qualified_function_type_template_arg)
2442 << Quals;
2443 } else {
2444 if (FnTy->getTypeQuals() != 0) {
Douglas Gregor43f51032011-10-19 06:04:55 +00002445 if (D.isFunctionDeclarator()) {
2446 SourceRange Range = D.getIdentifierLoc();
2447 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2448 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2449 if (Chunk.Kind == DeclaratorChunk::Function &&
2450 Chunk.Fun.TypeQuals != 0) {
2451 switch (Chunk.Fun.TypeQuals) {
2452 case Qualifiers::Const:
2453 Range = Chunk.Fun.getConstQualifierLoc();
2454 break;
2455 case Qualifiers::Volatile:
2456 Range = Chunk.Fun.getVolatileQualifierLoc();
2457 break;
2458 case Qualifiers::Const | Qualifiers::Volatile: {
2459 SourceLocation CLoc = Chunk.Fun.getConstQualifierLoc();
2460 SourceLocation VLoc = Chunk.Fun.getVolatileQualifierLoc();
2461 if (S.getSourceManager()
2462 .isBeforeInTranslationUnit(CLoc, VLoc)) {
2463 Range = SourceRange(CLoc, VLoc);
2464 } else {
2465 Range = SourceRange(VLoc, CLoc);
2466 }
2467 }
2468 break;
2469 }
2470 break;
2471 }
2472 }
2473 S.Diag(Range.getBegin(), diag::err_invalid_qualified_function_type)
2474 << FixItHint::CreateRemoval(Range);
2475 } else
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002476 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002477 diag::err_invalid_qualified_typedef_function_type_use)
2478 << FreeFunction;
2479 }
2480
2481 if (FnTy->getRefQualifier()) {
2482 if (D.isFunctionDeclarator()) {
2483 SourceLocation Loc = D.getIdentifierLoc();
2484 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2485 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2486 if (Chunk.Kind == DeclaratorChunk::Function &&
2487 Chunk.Fun.hasRefQualifier()) {
2488 Loc = Chunk.Fun.getRefQualifierLoc();
2489 break;
2490 }
2491 }
2492
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002493 S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
Douglas Gregor683a81f2011-01-31 16:09:46 +00002494 << (FnTy->getRefQualifier() == RQ_LValue)
2495 << FixItHint::CreateRemoval(Loc);
2496 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002497 S.Diag(D.getIdentifierLoc(),
Douglas Gregor683a81f2011-01-31 16:09:46 +00002498 diag::err_invalid_ref_qualifier_typedef_function_type_use)
2499 << FreeFunction
2500 << (FnTy->getRefQualifier() == RQ_LValue);
2501 }
2502 }
2503
2504 // Strip the cv-qualifiers and ref-qualifiers from the type.
2505 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2506 EPI.TypeQuals = 0;
2507 EPI.RefQualifier = RQ_None;
2508
2509 T = Context.getFunctionType(FnTy->getResultType(),
2510 FnTy->arg_type_begin(),
2511 FnTy->getNumArgs(), EPI);
Douglas Gregorc938c162011-01-26 05:01:58 +00002512 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002513 }
2514 }
Mike Stump1eb44332009-09-09 15:08:12 +00002515
John McCall711c52b2011-01-05 12:14:39 +00002516 // Apply any undistributed attributes from the declarator.
2517 if (!T.isNull())
2518 if (AttributeList *attrs = D.getAttributes())
2519 processTypeAttrs(state, T, false, attrs);
2520
2521 // Diagnose any ignored type attributes.
2522 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2523
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002524 // C++0x [dcl.constexpr]p9:
2525 // A constexpr specifier used in an object declaration declares the object
2526 // as const.
2527 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
Sebastian Redl73780122010-06-09 21:19:43 +00002528 T.addConst();
2529 }
2530
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002531 // If there was an ellipsis in the declarator, the declaration declares a
2532 // parameter pack whose type may be a pack expansion type.
2533 if (D.hasEllipsis() && !T.isNull()) {
2534 // C++0x [dcl.fct]p13:
2535 // A declarator-id or abstract-declarator containing an ellipsis shall
2536 // only be used in a parameter-declaration. Such a parameter-declaration
2537 // is a parameter pack (14.5.3). [...]
2538 switch (D.getContext()) {
2539 case Declarator::PrototypeContext:
2540 // C++0x [dcl.fct]p13:
2541 // [...] When it is part of a parameter-declaration-clause, the
2542 // parameter pack is a function parameter pack (14.5.3). The type T
2543 // of the declarator-id of the function parameter pack shall contain
2544 // a template parameter pack; each template parameter pack in T is
2545 // expanded by the function parameter pack.
2546 //
2547 // We represent function parameter packs as function parameters whose
2548 // type is a pack expansion.
2549 if (!T->containsUnexpandedParameterPack()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002550 S.Diag(D.getEllipsisLoc(),
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002551 diag::err_function_parameter_pack_without_parameter_packs)
2552 << T << D.getSourceRange();
2553 D.setEllipsisLoc(SourceLocation());
2554 } else {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002555 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002556 }
2557 break;
2558
2559 case Declarator::TemplateParamContext:
2560 // C++0x [temp.param]p15:
2561 // If a template-parameter is a [...] is a parameter-declaration that
2562 // declares a parameter pack (8.3.5), then the template-parameter is a
2563 // template parameter pack (14.5.3).
2564 //
2565 // Note: core issue 778 clarifies that, if there are any unexpanded
2566 // parameter packs in the type of the non-type template parameter, then
2567 // it expands those parameter packs.
2568 if (T->containsUnexpandedParameterPack())
Douglas Gregorcded4f62011-01-14 17:04:44 +00002569 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Richard Smithe5acd132011-10-14 20:31:37 +00002570 else
2571 S.Diag(D.getEllipsisLoc(),
2572 LangOpts.CPlusPlus0x
2573 ? diag::warn_cxx98_compat_variadic_templates
2574 : diag::ext_variadic_templates);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002575 break;
2576
2577 case Declarator::FileContext:
2578 case Declarator::KNRTypeListContext:
John McCallcdda47f2011-10-01 09:56:14 +00002579 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
2580 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002581 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002582 case Declarator::CXXNewContext:
Richard Smith162e1c12011-04-15 14:24:37 +00002583 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002584 case Declarator::AliasTemplateContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002585 case Declarator::MemberContext:
2586 case Declarator::BlockContext:
2587 case Declarator::ForContext:
2588 case Declarator::ConditionContext:
2589 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002590 case Declarator::ObjCCatchContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002591 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00002592 case Declarator::LambdaExprContext:
Douglas Gregor683a81f2011-01-31 16:09:46 +00002593 case Declarator::TemplateTypeArgContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002594 // FIXME: We may want to allow parameter packs in block-literal contexts
2595 // in the future.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002596 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002597 D.setEllipsisLoc(SourceLocation());
2598 break;
2599 }
2600 }
Richard Smithe7397c62011-02-22 00:36:53 +00002601
John McCallbf1a0282010-06-04 23:28:52 +00002602 if (T.isNull())
2603 return Context.getNullTypeSourceInfo();
2604 else if (D.isInvalidType())
2605 return Context.getTrivialTypeSourceInfo(T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002606
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002607 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2608}
2609
2610/// GetTypeForDeclarator - Convert the type for the specified
2611/// declarator to Type instances.
2612///
2613/// The result of this call will never be null, but the associated
2614/// type may be a null type if there's an unrecoverable error.
2615TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2616 // Determine the type of the declarator. Not all forms of declarator
2617 // have a type.
2618
2619 TypeProcessingState state(*this, D);
2620
2621 TypeSourceInfo *ReturnTypeInfo = 0;
2622 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2623 if (T.isNull())
2624 return Context.getNullTypeSourceInfo();
2625
2626 if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
2627 inferARCWriteback(state, T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002628
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002629 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002630}
2631
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002632static void transferARCOwnershipToDeclSpec(Sema &S,
2633 QualType &declSpecTy,
2634 Qualifiers::ObjCLifetime ownership) {
2635 if (declSpecTy->isObjCRetainableType() &&
2636 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2637 Qualifiers qs;
2638 qs.addObjCLifetime(ownership);
2639 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2640 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002641}
2642
2643static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2644 Qualifiers::ObjCLifetime ownership,
2645 unsigned chunkIndex) {
2646 Sema &S = state.getSema();
2647 Declarator &D = state.getDeclarator();
2648
2649 // Look for an explicit lifetime attribute.
2650 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2651 for (const AttributeList *attr = chunk.getAttrs(); attr;
2652 attr = attr->getNext())
2653 if (attr->getKind() == AttributeList::AT_objc_ownership)
2654 return;
2655
2656 const char *attrStr = 0;
2657 switch (ownership) {
David Blaikie30263482012-01-20 21:50:17 +00002658 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002659 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2660 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2661 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2662 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2663 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002664
2665 // If there wasn't one, add one (with an invalid source location
2666 // so that we don't make an AttributedType for it).
2667 AttributeList *attr = D.getAttributePool()
2668 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2669 /*scope*/ 0, SourceLocation(),
2670 &S.Context.Idents.get(attrStr), SourceLocation(),
2671 /*args*/ 0, 0,
2672 /*declspec*/ false, /*C++0x*/ false);
2673 spliceAttrIntoList(*attr, chunk.getAttrListRef());
2674
2675 // TODO: mark whether we did this inference?
2676}
2677
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002678/// \brief Used for transfering ownership in casts resulting in l-values.
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002679static void transferARCOwnership(TypeProcessingState &state,
2680 QualType &declSpecTy,
2681 Qualifiers::ObjCLifetime ownership) {
2682 Sema &S = state.getSema();
2683 Declarator &D = state.getDeclarator();
2684
2685 int inner = -1;
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002686 bool hasIndirection = false;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002687 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2688 DeclaratorChunk &chunk = D.getTypeObject(i);
2689 switch (chunk.Kind) {
2690 case DeclaratorChunk::Paren:
2691 // Ignore parens.
2692 break;
2693
2694 case DeclaratorChunk::Array:
2695 case DeclaratorChunk::Reference:
2696 case DeclaratorChunk::Pointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002697 if (inner != -1)
2698 hasIndirection = true;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002699 inner = i;
2700 break;
2701
2702 case DeclaratorChunk::BlockPointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002703 if (inner != -1)
2704 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2705 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002706
2707 case DeclaratorChunk::Function:
2708 case DeclaratorChunk::MemberPointer:
2709 return;
2710 }
2711 }
2712
2713 if (inner == -1)
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002714 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002715
2716 DeclaratorChunk &chunk = D.getTypeObject(inner);
2717 if (chunk.Kind == DeclaratorChunk::Pointer) {
2718 if (declSpecTy->isObjCRetainableType())
2719 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002720 if (declSpecTy->isObjCObjectType() && hasIndirection)
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002721 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2722 } else {
2723 assert(chunk.Kind == DeclaratorChunk::Array ||
2724 chunk.Kind == DeclaratorChunk::Reference);
2725 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2726 }
2727}
2728
2729TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2730 TypeProcessingState state(*this, D);
2731
2732 TypeSourceInfo *ReturnTypeInfo = 0;
2733 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2734 if (declSpecTy.isNull())
2735 return Context.getNullTypeSourceInfo();
2736
2737 if (getLangOptions().ObjCAutoRefCount) {
2738 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2739 if (ownership != Qualifiers::OCL_None)
2740 transferARCOwnership(state, declSpecTy, ownership);
2741 }
2742
2743 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2744}
2745
John McCall14aa2172011-03-04 04:00:19 +00002746/// Map an AttributedType::Kind to an AttributeList::Kind.
2747static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2748 switch (kind) {
2749 case AttributedType::attr_address_space:
2750 return AttributeList::AT_address_space;
2751 case AttributedType::attr_regparm:
2752 return AttributeList::AT_regparm;
2753 case AttributedType::attr_vector_size:
2754 return AttributeList::AT_vector_size;
2755 case AttributedType::attr_neon_vector_type:
2756 return AttributeList::AT_neon_vector_type;
2757 case AttributedType::attr_neon_polyvector_type:
2758 return AttributeList::AT_neon_polyvector_type;
2759 case AttributedType::attr_objc_gc:
2760 return AttributeList::AT_objc_gc;
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00002761 case AttributedType::attr_objc_ownership:
2762 return AttributeList::AT_objc_ownership;
John McCall14aa2172011-03-04 04:00:19 +00002763 case AttributedType::attr_noreturn:
2764 return AttributeList::AT_noreturn;
2765 case AttributedType::attr_cdecl:
2766 return AttributeList::AT_cdecl;
2767 case AttributedType::attr_fastcall:
2768 return AttributeList::AT_fastcall;
2769 case AttributedType::attr_stdcall:
2770 return AttributeList::AT_stdcall;
2771 case AttributedType::attr_thiscall:
2772 return AttributeList::AT_thiscall;
2773 case AttributedType::attr_pascal:
2774 return AttributeList::AT_pascal;
Anton Korobeynikov414d8962011-04-14 20:06:49 +00002775 case AttributedType::attr_pcs:
2776 return AttributeList::AT_pcs;
John McCall14aa2172011-03-04 04:00:19 +00002777 }
2778 llvm_unreachable("unexpected attribute kind!");
John McCall14aa2172011-03-04 04:00:19 +00002779}
2780
2781static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2782 const AttributeList *attrs) {
2783 AttributedType::Kind kind = TL.getAttrKind();
2784
2785 assert(attrs && "no type attributes in the expected location!");
2786 AttributeList::Kind parsedKind = getAttrListKind(kind);
2787 while (attrs->getKind() != parsedKind) {
2788 attrs = attrs->getNext();
2789 assert(attrs && "no matching attribute in expected location!");
2790 }
2791
2792 TL.setAttrNameLoc(attrs->getLoc());
2793 if (TL.hasAttrExprOperand())
2794 TL.setAttrExprOperand(attrs->getArg(0));
2795 else if (TL.hasAttrEnumOperand())
2796 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2797
2798 // FIXME: preserve this information to here.
2799 if (TL.hasAttrOperand())
2800 TL.setAttrOperandParensRange(SourceRange());
2801}
2802
John McCall51bd8032009-10-18 01:05:36 +00002803namespace {
2804 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002805 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002806 const DeclSpec &DS;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002807
John McCall51bd8032009-10-18 01:05:36 +00002808 public:
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002809 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2810 : Context(Context), DS(DS) {}
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002811
John McCall14aa2172011-03-04 04:00:19 +00002812 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2813 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2814 Visit(TL.getModifiedLoc());
2815 }
John McCall51bd8032009-10-18 01:05:36 +00002816 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2817 Visit(TL.getUnqualifiedLoc());
2818 }
2819 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2820 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2821 }
2822 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2823 TL.setNameLoc(DS.getTypeSpecTypeLoc());
John McCallc12c5bb2010-05-15 11:32:37 +00002824 }
2825 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2826 // Handle the base type, which might not have been written explicitly.
2827 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2828 TL.setHasBaseTypeAsWritten(false);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002829 TL.getBaseLoc().initialize(Context, SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002830 } else {
2831 TL.setHasBaseTypeAsWritten(true);
2832 Visit(TL.getBaseLoc());
2833 }
Argyrios Kyrtzidiseb667592009-09-29 19:45:22 +00002834
John McCallc12c5bb2010-05-15 11:32:37 +00002835 // Protocol qualifiers.
John McCall54e14c42009-10-22 22:37:11 +00002836 if (DS.getProtocolQualifiers()) {
2837 assert(TL.getNumProtocols() > 0);
2838 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2839 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2840 TL.setRAngleLoc(DS.getSourceRange().getEnd());
2841 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2842 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2843 } else {
2844 assert(TL.getNumProtocols() == 0);
2845 TL.setLAngleLoc(SourceLocation());
2846 TL.setRAngleLoc(SourceLocation());
2847 }
2848 }
2849 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall54e14c42009-10-22 22:37:11 +00002850 TL.setStarLoc(SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00002851 Visit(TL.getPointeeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002852 }
John McCall833ca992009-10-29 08:12:44 +00002853 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
John McCalla93c9342009-12-07 02:54:59 +00002854 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002855 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall833ca992009-10-29 08:12:44 +00002856
2857 // If we got no declarator info from previous Sema routines,
2858 // just fill with the typespec loc.
John McCalla93c9342009-12-07 02:54:59 +00002859 if (!TInfo) {
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002860 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
John McCall833ca992009-10-29 08:12:44 +00002861 return;
2862 }
2863
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002864 TypeLoc OldTL = TInfo->getTypeLoc();
2865 if (TInfo->getType()->getAs<ElaboratedType>()) {
2866 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2867 TemplateSpecializationTypeLoc NamedTL =
2868 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2869 TL.copy(NamedTL);
2870 }
2871 else
2872 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
John McCall833ca992009-10-29 08:12:44 +00002873 }
John McCallcfb708c2010-01-13 20:03:27 +00002874 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2875 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2876 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2877 TL.setParensRange(DS.getTypeofParensRange());
2878 }
2879 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2880 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2881 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2882 TL.setParensRange(DS.getTypeofParensRange());
John McCallb3d87482010-08-24 05:47:05 +00002883 assert(DS.getRepAsType());
John McCallcfb708c2010-01-13 20:03:27 +00002884 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002885 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCallcfb708c2010-01-13 20:03:27 +00002886 TL.setUnderlyingTInfo(TInfo);
2887 }
Sean Huntca63c202011-05-24 22:41:36 +00002888 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2889 // FIXME: This holds only because we only have one unary transform.
2890 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2891 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2892 TL.setParensRange(DS.getTypeofParensRange());
2893 assert(DS.getRepAsType());
2894 TypeSourceInfo *TInfo = 0;
2895 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2896 TL.setUnderlyingTInfo(TInfo);
2897 }
Douglas Gregorddf889a2010-01-18 18:04:31 +00002898 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2899 // By default, use the source location of the type specifier.
2900 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2901 if (TL.needsExtraLocalData()) {
2902 // Set info for the written builtin specifiers.
2903 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2904 // Try to have a meaningful source location.
2905 if (TL.getWrittenSignSpec() != TSS_unspecified)
2906 // Sign spec loc overrides the others (e.g., 'unsigned long').
2907 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2908 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2909 // Width spec loc overrides type spec loc (e.g., 'short int').
2910 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2911 }
2912 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002913 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2914 ElaboratedTypeKeyword Keyword
2915 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00002916 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002917 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00002918 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002919 if (TInfo) {
2920 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2921 return;
2922 }
2923 }
Abramo Bagnara38a42912012-02-06 19:09:27 +00002924 TL.setElaboratedKeywordLoc(Keyword != ETK_None
2925 ? DS.getTypeSpecTypeLoc()
2926 : SourceLocation());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002927 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor9e876872011-03-01 18:12:44 +00002928 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002929 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2930 }
2931 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00002932 assert(DS.getTypeSpecType() == TST_typename);
2933 TypeSourceInfo *TInfo = 0;
2934 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2935 assert(TInfo);
2936 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002937 }
John McCall33500952010-06-11 00:33:02 +00002938 void VisitDependentTemplateSpecializationTypeLoc(
2939 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00002940 assert(DS.getTypeSpecType() == TST_typename);
2941 TypeSourceInfo *TInfo = 0;
2942 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2943 assert(TInfo);
2944 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2945 TInfo->getTypeLoc()));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00002946 }
2947 void VisitTagTypeLoc(TagTypeLoc TL) {
2948 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
John McCall33500952010-06-11 00:33:02 +00002949 }
Eli Friedmanb001de72011-10-06 23:00:33 +00002950 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
2951 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2952 TL.setParensRange(DS.getTypeofParensRange());
Douglas Gregor43fe2452011-10-09 18:45:17 +00002953
2954 TypeSourceInfo *TInfo = 0;
2955 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2956 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
Eli Friedmanb001de72011-10-06 23:00:33 +00002957 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002958
John McCall51bd8032009-10-18 01:05:36 +00002959 void VisitTypeLoc(TypeLoc TL) {
2960 // FIXME: add other typespec types and change this to an assert.
Douglas Gregorc21c7e92011-01-25 19:13:18 +00002961 TL.initialize(Context, DS.getTypeSpecTypeLoc());
John McCall51bd8032009-10-18 01:05:36 +00002962 }
2963 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00002964
John McCall51bd8032009-10-18 01:05:36 +00002965 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002966 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00002967 const DeclaratorChunk &Chunk;
2968
2969 public:
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002970 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2971 : Context(Context), Chunk(Chunk) {}
John McCall51bd8032009-10-18 01:05:36 +00002972
2973 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002974 llvm_unreachable("qualified type locs not expected here!");
John McCall51bd8032009-10-18 01:05:36 +00002975 }
2976
John McCallf85e1932011-06-15 23:02:42 +00002977 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2978 fillAttributedTypeLoc(TL, Chunk.getAttrs());
2979 }
John McCall51bd8032009-10-18 01:05:36 +00002980 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2981 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2982 TL.setCaretLoc(Chunk.Loc);
2983 }
2984 void VisitPointerTypeLoc(PointerTypeLoc TL) {
2985 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2986 TL.setStarLoc(Chunk.Loc);
2987 }
2988 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2989 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2990 TL.setStarLoc(Chunk.Loc);
2991 }
2992 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2993 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00002994 const CXXScopeSpec& SS = Chunk.Mem.Scope();
2995 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
2996
2997 const Type* ClsTy = TL.getClass();
2998 QualType ClsQT = QualType(ClsTy, 0);
2999 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3000 // Now copy source location info into the type loc component.
3001 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3002 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3003 case NestedNameSpecifier::Identifier:
3004 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3005 {
Abramo Bagnarafd9c42e2011-03-06 22:48:24 +00003006 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
Abramo Bagnara38a42912012-02-06 19:09:27 +00003007 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003008 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3009 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3010 }
3011 break;
3012
3013 case NestedNameSpecifier::TypeSpec:
3014 case NestedNameSpecifier::TypeSpecWithTemplate:
3015 if (isa<ElaboratedType>(ClsTy)) {
3016 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
Abramo Bagnara38a42912012-02-06 19:09:27 +00003017 ETLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003018 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3019 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3020 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3021 } else {
3022 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3023 }
3024 break;
3025
3026 case NestedNameSpecifier::Namespace:
3027 case NestedNameSpecifier::NamespaceAlias:
3028 case NestedNameSpecifier::Global:
3029 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003030 }
3031
3032 // Finally fill in MemberPointerLocInfo fields.
John McCall51bd8032009-10-18 01:05:36 +00003033 TL.setStarLoc(Chunk.Loc);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003034 TL.setClassTInfo(ClsTInfo);
John McCall51bd8032009-10-18 01:05:36 +00003035 }
3036 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3037 assert(Chunk.Kind == DeclaratorChunk::Reference);
John McCall54e14c42009-10-22 22:37:11 +00003038 // 'Amp' is misleading: this might have been originally
3039 /// spelled with AmpAmp.
John McCall51bd8032009-10-18 01:05:36 +00003040 TL.setAmpLoc(Chunk.Loc);
3041 }
3042 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3043 assert(Chunk.Kind == DeclaratorChunk::Reference);
3044 assert(!Chunk.Ref.LValueRef);
3045 TL.setAmpAmpLoc(Chunk.Loc);
3046 }
3047 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3048 assert(Chunk.Kind == DeclaratorChunk::Array);
3049 TL.setLBracketLoc(Chunk.Loc);
3050 TL.setRBracketLoc(Chunk.EndLoc);
3051 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3052 }
3053 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3054 assert(Chunk.Kind == DeclaratorChunk::Function);
Abramo Bagnara796aa442011-03-12 11:17:06 +00003055 TL.setLocalRangeBegin(Chunk.Loc);
3056 TL.setLocalRangeEnd(Chunk.EndLoc);
Douglas Gregordab60ad2010-10-01 18:44:50 +00003057 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
John McCall51bd8032009-10-18 01:05:36 +00003058
3059 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
John McCall54e14c42009-10-22 22:37:11 +00003060 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00003061 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
John McCall54e14c42009-10-22 22:37:11 +00003062 TL.setArg(tpi++, Param);
John McCall51bd8032009-10-18 01:05:36 +00003063 }
3064 // FIXME: exception specs
3065 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003066 void VisitParenTypeLoc(ParenTypeLoc TL) {
3067 assert(Chunk.Kind == DeclaratorChunk::Paren);
3068 TL.setLParenLoc(Chunk.Loc);
3069 TL.setRParenLoc(Chunk.EndLoc);
3070 }
John McCall51bd8032009-10-18 01:05:36 +00003071
3072 void VisitTypeLoc(TypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003073 llvm_unreachable("unsupported TypeLoc kind in declarator!");
John McCall51bd8032009-10-18 01:05:36 +00003074 }
3075 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003076}
3077
John McCalla93c9342009-12-07 02:54:59 +00003078/// \brief Create and instantiate a TypeSourceInfo with type source information.
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003079///
3080/// \param T QualType referring to the type as written in source code.
Douglas Gregor05baacb2010-04-12 23:19:01 +00003081///
3082/// \param ReturnTypeInfo For declarators whose return type does not show
3083/// up in the normal place in the declaration specifiers (such as a C++
3084/// conversion function), this pointer will refer to a type source information
3085/// for that return type.
John McCalla93c9342009-12-07 02:54:59 +00003086TypeSourceInfo *
Douglas Gregor05baacb2010-04-12 23:19:01 +00003087Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3088 TypeSourceInfo *ReturnTypeInfo) {
John McCalla93c9342009-12-07 02:54:59 +00003089 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3090 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003091
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003092 // Handle parameter packs whose type is a pack expansion.
3093 if (isa<PackExpansionType>(T)) {
3094 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
3095 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3096 }
3097
Sebastian Redl8ce35b02009-10-25 21:45:37 +00003098 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall14aa2172011-03-04 04:00:19 +00003099 while (isa<AttributedTypeLoc>(CurrTL)) {
3100 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3101 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3102 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3103 }
3104
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003105 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
John McCall51bd8032009-10-18 01:05:36 +00003106 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003107 }
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003108
John McCallb3d87482010-08-24 05:47:05 +00003109 // If we have different source information for the return type, use
3110 // that. This really only applies to C++ conversion functions.
3111 if (ReturnTypeInfo) {
Douglas Gregor05baacb2010-04-12 23:19:01 +00003112 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3113 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3114 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
John McCallb3d87482010-08-24 05:47:05 +00003115 } else {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003116 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
Douglas Gregor05baacb2010-04-12 23:19:01 +00003117 }
3118
John McCalla93c9342009-12-07 02:54:59 +00003119 return TInfo;
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003120}
3121
John McCalla93c9342009-12-07 02:54:59 +00003122/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
John McCallb3d87482010-08-24 05:47:05 +00003123ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003124 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3125 // and Sema during declaration parsing. Try deallocating/caching them when
3126 // it's appropriate, instead of allocating them and keeping them around.
Douglas Gregoreb0eb492010-12-10 08:12:03 +00003127 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3128 TypeAlignment);
John McCalla93c9342009-12-07 02:54:59 +00003129 new (LocT) LocInfoType(T, TInfo);
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003130 assert(LocT->getTypeClass() != T->getTypeClass() &&
3131 "LocInfoType's TypeClass conflicts with an existing Type class");
John McCallb3d87482010-08-24 05:47:05 +00003132 return ParsedType::make(QualType(LocT, 0));
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003133}
3134
3135void LocInfoType::getAsStringInternal(std::string &Str,
3136 const PrintingPolicy &Policy) const {
David Blaikieb219cfc2011-09-23 05:06:16 +00003137 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
Argyrios Kyrtzidis35d44e52009-08-19 01:46:06 +00003138 " was used directly instead of getting the QualType through"
3139 " GetTypeFromParser");
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003140}
3141
John McCallf312b1e2010-08-26 23:41:50 +00003142TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003143 // C99 6.7.6: Type names have no identifier. This is already validated by
3144 // the parser.
3145 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
Mike Stump1eb44332009-09-09 15:08:12 +00003146
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003147 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00003148 QualType T = TInfo->getType();
Chris Lattner5153ee62009-04-25 08:47:54 +00003149 if (D.isInvalidType())
Douglas Gregor809070a2009-02-18 17:45:20 +00003150 return true;
Steve Naroff5912a352007-08-28 20:14:24 +00003151
John McCalle82247a2011-10-01 05:17:03 +00003152 // Make sure there are no unused decl attributes on the declarator.
John McCallcdda47f2011-10-01 09:56:14 +00003153 // We don't want to do this for ObjC parameters because we're going
3154 // to apply them to the actual parameter declaration.
3155 if (D.getContext() != Declarator::ObjCParameterContext)
3156 checkUnusedDeclAttributes(D);
John McCalle82247a2011-10-01 05:17:03 +00003157
Douglas Gregor402abb52009-05-28 23:31:59 +00003158 if (getLangOptions().CPlusPlus) {
3159 // Check that there are no default arguments (C++ only).
Douglas Gregor6d6eb572008-05-07 04:49:29 +00003160 CheckExtraCXXDefaultArguments(D);
Douglas Gregor402abb52009-05-28 23:31:59 +00003161 }
3162
John McCallb3d87482010-08-24 05:47:05 +00003163 return CreateParsedType(T, TInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00003164}
3165
Douglas Gregore97179c2011-09-08 01:46:34 +00003166ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3167 QualType T = Context.getObjCInstanceType();
3168 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3169 return CreateParsedType(T, TInfo);
3170}
3171
3172
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003173//===----------------------------------------------------------------------===//
3174// Type Attribute Processing
3175//===----------------------------------------------------------------------===//
3176
3177/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3178/// specified type. The attribute contains 1 argument, the id of the address
3179/// space for the type.
Mike Stump1eb44332009-09-09 15:08:12 +00003180static void HandleAddressSpaceTypeAttribute(QualType &Type,
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003181 const AttributeList &Attr, Sema &S){
John McCall0953e762009-09-24 19:53:00 +00003182
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003183 // If this type is already address space qualified, reject it.
Peter Collingbourne29e3ef82011-07-27 20:29:53 +00003184 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3185 // qualifiers for two or more different address spaces."
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003186 if (Type.getAddressSpace()) {
3187 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
Abramo Bagnarae215f722010-04-30 13:10:51 +00003188 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003189 return;
3190 }
Mike Stump1eb44332009-09-09 15:08:12 +00003191
Peter Collingbourne020972d2011-07-27 20:30:05 +00003192 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3193 // qualified by an address-space qualifier."
3194 if (Type->isFunctionType()) {
3195 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3196 Attr.setInvalid();
3197 return;
3198 }
3199
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003200 // Check the attribute arguments.
3201 if (Attr.getNumArgs() != 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003202 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003203 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003204 return;
3205 }
3206 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3207 llvm::APSInt addrSpace(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003208 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3209 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003210 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3211 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003212 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003213 return;
3214 }
3215
John McCallefadb772009-07-28 06:52:18 +00003216 // Bounds checking.
3217 if (addrSpace.isSigned()) {
3218 if (addrSpace.isNegative()) {
3219 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3220 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003221 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003222 return;
3223 }
3224 addrSpace.setIsSigned(false);
3225 }
3226 llvm::APSInt max(addrSpace.getBitWidth());
John McCall0953e762009-09-24 19:53:00 +00003227 max = Qualifiers::MaxAddressSpace;
John McCallefadb772009-07-28 06:52:18 +00003228 if (addrSpace > max) {
3229 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
John McCall0953e762009-09-24 19:53:00 +00003230 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003231 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003232 return;
3233 }
3234
Mike Stump1eb44332009-09-09 15:08:12 +00003235 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003236 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003237}
3238
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003239/// handleObjCOwnershipTypeAttr - Process an objc_ownership
John McCallf85e1932011-06-15 23:02:42 +00003240/// attribute on the specified type.
3241///
3242/// Returns 'true' if the attribute was handled.
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003243static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +00003244 AttributeList &attr,
3245 QualType &type) {
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003246 bool NonObjCPointer = false;
3247
3248 if (!type->isDependentType()) {
3249 if (const PointerType *ptr = type->getAs<PointerType>()) {
3250 QualType pointee = ptr->getPointeeType();
3251 if (pointee->isObjCRetainableType() || pointee->isPointerType())
3252 return false;
3253 // It is important not to lose the source info that there was an attribute
3254 // applied to non-objc pointer. We will create an attributed type but
3255 // its type will be the same as the original type.
3256 NonObjCPointer = true;
3257 } else if (!type->isObjCRetainableType()) {
3258 return false;
3259 }
3260 }
John McCallf85e1932011-06-15 23:02:42 +00003261
3262 Sema &S = state.getSema();
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003263 SourceLocation AttrLoc = attr.getLoc();
3264 if (AttrLoc.isMacroID())
3265 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
John McCallf85e1932011-06-15 23:02:42 +00003266
3267 if (type.getQualifiers().getObjCLifetime()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003268 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
John McCallf85e1932011-06-15 23:02:42 +00003269 << type;
3270 return true;
3271 }
3272
3273 if (!attr.getParameterName()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003274 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003275 << "objc_ownership" << 1;
John McCallf85e1932011-06-15 23:02:42 +00003276 attr.setInvalid();
3277 return true;
3278 }
3279
3280 Qualifiers::ObjCLifetime lifetime;
3281 if (attr.getParameterName()->isStr("none"))
3282 lifetime = Qualifiers::OCL_ExplicitNone;
3283 else if (attr.getParameterName()->isStr("strong"))
3284 lifetime = Qualifiers::OCL_Strong;
3285 else if (attr.getParameterName()->isStr("weak"))
3286 lifetime = Qualifiers::OCL_Weak;
3287 else if (attr.getParameterName()->isStr("autoreleasing"))
3288 lifetime = Qualifiers::OCL_Autoreleasing;
3289 else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003290 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003291 << "objc_ownership" << attr.getParameterName();
John McCallf85e1932011-06-15 23:02:42 +00003292 attr.setInvalid();
3293 return true;
3294 }
3295
3296 // Consume lifetime attributes without further comment outside of
3297 // ARC mode.
3298 if (!S.getLangOptions().ObjCAutoRefCount)
3299 return true;
3300
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003301 if (NonObjCPointer) {
3302 StringRef name = attr.getName()->getName();
3303 switch (lifetime) {
3304 case Qualifiers::OCL_None:
3305 case Qualifiers::OCL_ExplicitNone:
3306 break;
3307 case Qualifiers::OCL_Strong: name = "__strong"; break;
3308 case Qualifiers::OCL_Weak: name = "__weak"; break;
3309 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3310 }
3311 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3312 << name << type;
3313 }
3314
John McCallf85e1932011-06-15 23:02:42 +00003315 Qualifiers qs;
3316 qs.setObjCLifetime(lifetime);
3317 QualType origType = type;
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003318 if (!NonObjCPointer)
3319 type = S.Context.getQualifiedType(type, qs);
John McCallf85e1932011-06-15 23:02:42 +00003320
3321 // If we have a valid source location for the attribute, use an
3322 // AttributedType instead.
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003323 if (AttrLoc.isValid())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003324 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
John McCallf85e1932011-06-15 23:02:42 +00003325 origType, type);
3326
John McCall9f084a32011-07-06 00:26:06 +00003327 // Forbid __weak if the runtime doesn't support it.
John McCallf85e1932011-06-15 23:02:42 +00003328 if (lifetime == Qualifiers::OCL_Weak &&
Argyrios Kyrtzidis5cad8222011-11-07 18:40:21 +00003329 !S.getLangOptions().ObjCRuntimeHasWeak && !NonObjCPointer) {
John McCallf85e1932011-06-15 23:02:42 +00003330
3331 // Actually, delay this until we know what we're parsing.
3332 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3333 S.DelayedDiagnostics.add(
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003334 sema::DelayedDiagnostic::makeForbiddenType(
3335 S.getSourceManager().getExpansionLoc(AttrLoc),
John McCallf85e1932011-06-15 23:02:42 +00003336 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3337 } else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003338 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
John McCallf85e1932011-06-15 23:02:42 +00003339 }
3340
3341 attr.setInvalid();
3342 return true;
3343 }
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003344
3345 // Forbid __weak for class objects marked as
3346 // objc_arc_weak_reference_unavailable
3347 if (lifetime == Qualifiers::OCL_Weak) {
3348 QualType T = type;
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003349 while (const PointerType *ptr = T->getAs<PointerType>())
3350 T = ptr->getPointeeType();
3351 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3352 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
Fariborz Jahanian7263fee2011-07-06 20:48:48 +00003353 if (Class->isArcWeakrefUnavailable()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003354 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003355 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3356 diag::note_class_declared);
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003357 }
3358 }
3359 }
3360
John McCallf85e1932011-06-15 23:02:42 +00003361 return true;
3362}
3363
John McCall711c52b2011-01-05 12:14:39 +00003364/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3365/// attribute on the specified type. Returns true to indicate that
3366/// the attribute was handled, false to indicate that the type does
3367/// not permit the attribute.
3368static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3369 AttributeList &attr,
3370 QualType &type) {
3371 Sema &S = state.getSema();
3372
3373 // Delay if this isn't some kind of pointer.
3374 if (!type->isPointerType() &&
3375 !type->isObjCObjectPointerType() &&
3376 !type->isBlockPointerType())
3377 return false;
3378
3379 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3380 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3381 attr.setInvalid();
3382 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003383 }
Mike Stump1eb44332009-09-09 15:08:12 +00003384
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003385 // Check the attribute arguments.
John McCall711c52b2011-01-05 12:14:39 +00003386 if (!attr.getParameterName()) {
3387 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003388 << "objc_gc" << 1;
John McCall711c52b2011-01-05 12:14:39 +00003389 attr.setInvalid();
3390 return true;
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003391 }
John McCall0953e762009-09-24 19:53:00 +00003392 Qualifiers::GC GCAttr;
John McCall711c52b2011-01-05 12:14:39 +00003393 if (attr.getNumArgs() != 0) {
3394 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3395 attr.setInvalid();
3396 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003397 }
John McCall711c52b2011-01-05 12:14:39 +00003398 if (attr.getParameterName()->isStr("weak"))
John McCall0953e762009-09-24 19:53:00 +00003399 GCAttr = Qualifiers::Weak;
John McCall711c52b2011-01-05 12:14:39 +00003400 else if (attr.getParameterName()->isStr("strong"))
John McCall0953e762009-09-24 19:53:00 +00003401 GCAttr = Qualifiers::Strong;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003402 else {
John McCall711c52b2011-01-05 12:14:39 +00003403 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3404 << "objc_gc" << attr.getParameterName();
3405 attr.setInvalid();
3406 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003407 }
Mike Stump1eb44332009-09-09 15:08:12 +00003408
John McCall14aa2172011-03-04 04:00:19 +00003409 QualType origType = type;
3410 type = S.Context.getObjCGCQualType(origType, GCAttr);
3411
3412 // Make an attributed type to preserve the source information.
3413 if (attr.getLoc().isValid())
3414 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3415 origType, type);
3416
John McCall711c52b2011-01-05 12:14:39 +00003417 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003418}
3419
John McCalle6a365d2010-12-19 02:44:49 +00003420namespace {
3421 /// A helper class to unwrap a type down to a function for the
3422 /// purposes of applying attributes there.
3423 ///
3424 /// Use:
3425 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3426 /// if (unwrapped.isFunctionType()) {
3427 /// const FunctionType *fn = unwrapped.get();
3428 /// // change fn somehow
3429 /// T = unwrapped.wrap(fn);
3430 /// }
3431 struct FunctionTypeUnwrapper {
3432 enum WrapKind {
3433 Desugar,
3434 Parens,
3435 Pointer,
3436 BlockPointer,
3437 Reference,
3438 MemberPointer
3439 };
3440
3441 QualType Original;
3442 const FunctionType *Fn;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003443 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
John McCalle6a365d2010-12-19 02:44:49 +00003444
3445 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3446 while (true) {
3447 const Type *Ty = T.getTypePtr();
3448 if (isa<FunctionType>(Ty)) {
3449 Fn = cast<FunctionType>(Ty);
3450 return;
3451 } else if (isa<ParenType>(Ty)) {
3452 T = cast<ParenType>(Ty)->getInnerType();
3453 Stack.push_back(Parens);
3454 } else if (isa<PointerType>(Ty)) {
3455 T = cast<PointerType>(Ty)->getPointeeType();
3456 Stack.push_back(Pointer);
3457 } else if (isa<BlockPointerType>(Ty)) {
3458 T = cast<BlockPointerType>(Ty)->getPointeeType();
3459 Stack.push_back(BlockPointer);
3460 } else if (isa<MemberPointerType>(Ty)) {
3461 T = cast<MemberPointerType>(Ty)->getPointeeType();
3462 Stack.push_back(MemberPointer);
3463 } else if (isa<ReferenceType>(Ty)) {
3464 T = cast<ReferenceType>(Ty)->getPointeeType();
3465 Stack.push_back(Reference);
3466 } else {
3467 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3468 if (Ty == DTy) {
3469 Fn = 0;
3470 return;
3471 }
3472
3473 T = QualType(DTy, 0);
3474 Stack.push_back(Desugar);
3475 }
3476 }
3477 }
3478
3479 bool isFunctionType() const { return (Fn != 0); }
3480 const FunctionType *get() const { return Fn; }
3481
3482 QualType wrap(Sema &S, const FunctionType *New) {
3483 // If T wasn't modified from the unwrapped type, do nothing.
3484 if (New == get()) return Original;
3485
3486 Fn = New;
3487 return wrap(S.Context, Original, 0);
3488 }
3489
3490 private:
3491 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3492 if (I == Stack.size())
3493 return C.getQualifiedType(Fn, Old.getQualifiers());
3494
3495 // Build up the inner type, applying the qualifiers from the old
3496 // type to the new type.
3497 SplitQualType SplitOld = Old.split();
3498
3499 // As a special case, tail-recurse if there are no qualifiers.
John McCall200fa532012-02-08 00:46:36 +00003500 if (SplitOld.Quals.empty())
3501 return wrap(C, SplitOld.Ty, I);
3502 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
John McCalle6a365d2010-12-19 02:44:49 +00003503 }
3504
3505 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3506 if (I == Stack.size()) return QualType(Fn, 0);
3507
3508 switch (static_cast<WrapKind>(Stack[I++])) {
3509 case Desugar:
3510 // This is the point at which we potentially lose source
3511 // information.
3512 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3513
3514 case Parens: {
3515 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3516 return C.getParenType(New);
3517 }
3518
3519 case Pointer: {
3520 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3521 return C.getPointerType(New);
3522 }
3523
3524 case BlockPointer: {
3525 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3526 return C.getBlockPointerType(New);
3527 }
3528
3529 case MemberPointer: {
3530 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3531 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3532 return C.getMemberPointerType(New, OldMPT->getClass());
3533 }
3534
3535 case Reference: {
3536 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3537 QualType New = wrap(C, OldRef->getPointeeType(), I);
3538 if (isa<LValueReferenceType>(OldRef))
3539 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3540 else
3541 return C.getRValueReferenceType(New);
3542 }
3543 }
3544
3545 llvm_unreachable("unknown wrapping kind");
John McCalle6a365d2010-12-19 02:44:49 +00003546 }
3547 };
3548}
3549
John McCall711c52b2011-01-05 12:14:39 +00003550/// Process an individual function attribute. Returns true to
3551/// indicate that the attribute was handled, false if it wasn't.
3552static bool handleFunctionTypeAttr(TypeProcessingState &state,
3553 AttributeList &attr,
3554 QualType &type) {
3555 Sema &S = state.getSema();
John McCalle6a365d2010-12-19 02:44:49 +00003556
John McCall711c52b2011-01-05 12:14:39 +00003557 FunctionTypeUnwrapper unwrapped(S, type);
Mike Stump24556362009-07-25 21:26:53 +00003558
John McCall711c52b2011-01-05 12:14:39 +00003559 if (attr.getKind() == AttributeList::AT_noreturn) {
3560 if (S.CheckNoReturnAttr(attr))
John McCall04a67a62010-02-05 21:31:56 +00003561 return true;
John McCalle6a365d2010-12-19 02:44:49 +00003562
John McCall711c52b2011-01-05 12:14:39 +00003563 // Delay if this is not a function type.
3564 if (!unwrapped.isFunctionType())
3565 return false;
3566
John McCall04a67a62010-02-05 21:31:56 +00003567 // Otherwise we can process right away.
John McCall711c52b2011-01-05 12:14:39 +00003568 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3569 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3570 return true;
John McCall04a67a62010-02-05 21:31:56 +00003571 }
Mike Stump24556362009-07-25 21:26:53 +00003572
John McCallf85e1932011-06-15 23:02:42 +00003573 // ns_returns_retained is not always a type attribute, but if we got
3574 // here, we're treating it as one right now.
3575 if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
3576 assert(S.getLangOptions().ObjCAutoRefCount &&
3577 "ns_returns_retained treated as type attribute in non-ARC");
3578 if (attr.getNumArgs()) return true;
3579
3580 // Delay if this is not a function type.
3581 if (!unwrapped.isFunctionType())
3582 return false;
3583
3584 FunctionType::ExtInfo EI
3585 = unwrapped.get()->getExtInfo().withProducesResult(true);
3586 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3587 return true;
3588 }
3589
John McCall711c52b2011-01-05 12:14:39 +00003590 if (attr.getKind() == AttributeList::AT_regparm) {
3591 unsigned value;
3592 if (S.CheckRegparmAttr(attr, value))
Rafael Espindola425ef722010-03-30 22:15:11 +00003593 return true;
3594
John McCall711c52b2011-01-05 12:14:39 +00003595 // Delay if this is not a function type.
3596 if (!unwrapped.isFunctionType())
Rafael Espindola425ef722010-03-30 22:15:11 +00003597 return false;
3598
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003599 // Diagnose regparm with fastcall.
3600 const FunctionType *fn = unwrapped.get();
3601 CallingConv CC = fn->getCallConv();
3602 if (CC == CC_X86FastCall) {
3603 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3604 << FunctionType::getNameForCallConv(CC)
3605 << "regparm";
3606 attr.setInvalid();
3607 return true;
3608 }
3609
John McCalle6a365d2010-12-19 02:44:49 +00003610 FunctionType::ExtInfo EI =
John McCall711c52b2011-01-05 12:14:39 +00003611 unwrapped.get()->getExtInfo().withRegParm(value);
3612 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3613 return true;
Rafael Espindola425ef722010-03-30 22:15:11 +00003614 }
3615
John McCall04a67a62010-02-05 21:31:56 +00003616 // Otherwise, a calling convention.
John McCall711c52b2011-01-05 12:14:39 +00003617 CallingConv CC;
3618 if (S.CheckCallingConvAttr(attr, CC))
3619 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003620
John McCall04a67a62010-02-05 21:31:56 +00003621 // Delay if the type didn't work out to a function.
John McCall711c52b2011-01-05 12:14:39 +00003622 if (!unwrapped.isFunctionType()) return false;
John McCall04a67a62010-02-05 21:31:56 +00003623
John McCall711c52b2011-01-05 12:14:39 +00003624 const FunctionType *fn = unwrapped.get();
3625 CallingConv CCOld = fn->getCallConv();
Charles Davis064f7db2010-02-23 06:13:55 +00003626 if (S.Context.getCanonicalCallConv(CC) ==
Abramo Bagnarae215f722010-04-30 13:10:51 +00003627 S.Context.getCanonicalCallConv(CCOld)) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003628 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3629 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
John McCall711c52b2011-01-05 12:14:39 +00003630 return true;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003631 }
John McCall04a67a62010-02-05 21:31:56 +00003632
Roman Divacky8e68f1c2011-08-05 16:37:22 +00003633 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
John McCall04a67a62010-02-05 21:31:56 +00003634 // Should we diagnose reapplications of the same convention?
John McCall711c52b2011-01-05 12:14:39 +00003635 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
John McCall04a67a62010-02-05 21:31:56 +00003636 << FunctionType::getNameForCallConv(CC)
3637 << FunctionType::getNameForCallConv(CCOld);
John McCall711c52b2011-01-05 12:14:39 +00003638 attr.setInvalid();
3639 return true;
John McCall04a67a62010-02-05 21:31:56 +00003640 }
3641
3642 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3643 if (CC == CC_X86FastCall) {
John McCall711c52b2011-01-05 12:14:39 +00003644 if (isa<FunctionNoProtoType>(fn)) {
3645 S.Diag(attr.getLoc(), diag::err_cconv_knr)
John McCall04a67a62010-02-05 21:31:56 +00003646 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003647 attr.setInvalid();
3648 return true;
John McCall04a67a62010-02-05 21:31:56 +00003649 }
3650
John McCall711c52b2011-01-05 12:14:39 +00003651 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
John McCall04a67a62010-02-05 21:31:56 +00003652 if (FnP->isVariadic()) {
John McCall711c52b2011-01-05 12:14:39 +00003653 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
John McCall04a67a62010-02-05 21:31:56 +00003654 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003655 attr.setInvalid();
3656 return true;
John McCall04a67a62010-02-05 21:31:56 +00003657 }
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003658
3659 // Also diagnose fastcall with regparm.
Eli Friedmana49218e2011-04-09 08:18:08 +00003660 if (fn->getHasRegParm()) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003661 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3662 << "regparm"
3663 << FunctionType::getNameForCallConv(CC);
3664 attr.setInvalid();
3665 return true;
3666 }
John McCall04a67a62010-02-05 21:31:56 +00003667 }
3668
John McCall711c52b2011-01-05 12:14:39 +00003669 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3670 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3671 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003672}
3673
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003674/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3675static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3676 const AttributeList &Attr,
3677 Sema &S) {
3678 // Check the attribute arguments.
3679 if (Attr.getNumArgs() != 1) {
3680 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3681 Attr.setInvalid();
3682 return;
3683 }
3684 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3685 llvm::APSInt arg(32);
3686 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3687 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3688 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3689 << "opencl_image_access" << sizeExpr->getSourceRange();
3690 Attr.setInvalid();
3691 return;
3692 }
3693 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3694 switch (iarg) {
3695 case CLIA_read_only:
3696 case CLIA_write_only:
3697 case CLIA_read_write:
3698 // Implemented in a separate patch
3699 break;
3700 default:
3701 // Implemented in a separate patch
3702 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3703 << sizeExpr->getSourceRange();
3704 Attr.setInvalid();
3705 break;
3706 }
3707}
3708
John Thompson6e132aa2009-12-04 21:51:28 +00003709/// HandleVectorSizeAttribute - this attribute is only applicable to integral
3710/// and float scalars, although arrays, pointers, and function return values are
3711/// allowed in conjunction with this construct. Aggregates with this attribute
3712/// are invalid, even if they are of the same size as a corresponding scalar.
3713/// The raw attribute should contain precisely 1 argument, the vector size for
3714/// the variable, measured in bytes. If curType and rawAttr are well formed,
3715/// this routine will return a new vector type.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003716static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3717 Sema &S) {
Bob Wilson56affbc2010-11-16 00:32:16 +00003718 // Check the attribute arguments.
John Thompson6e132aa2009-12-04 21:51:28 +00003719 if (Attr.getNumArgs() != 1) {
3720 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003721 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003722 return;
3723 }
3724 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3725 llvm::APSInt vecSize(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003726 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3727 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
John Thompson6e132aa2009-12-04 21:51:28 +00003728 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3729 << "vector_size" << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003730 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003731 return;
3732 }
3733 // the base type must be integer or float, and can't already be a vector.
Douglas Gregorf6094622010-07-23 15:58:24 +00003734 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
John Thompson6e132aa2009-12-04 21:51:28 +00003735 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003736 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003737 return;
3738 }
3739 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3740 // vecSize is specified in bytes - convert to bits.
3741 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3742
3743 // the vector size needs to be an integral multiple of the type size.
3744 if (vectorSize % typeSize) {
3745 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3746 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003747 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003748 return;
3749 }
3750 if (vectorSize == 0) {
3751 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3752 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003753 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00003754 return;
3755 }
3756
3757 // Success! Instantiate the vector type, the number of elements is > 0, and
3758 // not required to be a power of 2, unlike GCC.
Chris Lattner788b0fd2010-06-23 06:00:24 +00003759 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
Bob Wilsone86d78c2010-11-10 21:56:12 +00003760 VectorType::GenericVector);
John Thompson6e132aa2009-12-04 21:51:28 +00003761}
3762
Douglas Gregor4ac01402011-06-15 16:02:29 +00003763/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3764/// a type.
3765static void HandleExtVectorTypeAttr(QualType &CurType,
3766 const AttributeList &Attr,
3767 Sema &S) {
3768 Expr *sizeExpr;
3769
3770 // Special case where the argument is a template id.
3771 if (Attr.getParameterName()) {
3772 CXXScopeSpec SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003773 SourceLocation TemplateKWLoc;
Douglas Gregor4ac01402011-06-15 16:02:29 +00003774 UnqualifiedId id;
3775 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003776
3777 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
3778 id, false, false);
Douglas Gregor4ac01402011-06-15 16:02:29 +00003779 if (Size.isInvalid())
3780 return;
3781
3782 sizeExpr = Size.get();
3783 } else {
3784 // check the attribute arguments.
3785 if (Attr.getNumArgs() != 1) {
3786 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3787 return;
3788 }
3789 sizeExpr = Attr.getArg(0);
3790 }
3791
3792 // Create the vector type.
3793 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3794 if (!T.isNull())
3795 CurType = T;
3796}
3797
Bob Wilson4211bb62010-11-16 00:32:24 +00003798/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3799/// "neon_polyvector_type" attributes are used to create vector types that
3800/// are mangled according to ARM's ABI. Otherwise, these types are identical
3801/// to those created with the "vector_size" attribute. Unlike "vector_size"
3802/// the argument to these Neon attributes is the number of vector elements,
3803/// not the vector size in bytes. The vector width and element type must
3804/// match one of the standard Neon vector types.
3805static void HandleNeonVectorTypeAttr(QualType& CurType,
3806 const AttributeList &Attr, Sema &S,
3807 VectorType::VectorKind VecKind,
3808 const char *AttrName) {
3809 // Check the attribute arguments.
3810 if (Attr.getNumArgs() != 1) {
3811 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3812 Attr.setInvalid();
3813 return;
3814 }
3815 // The number of elements must be an ICE.
3816 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3817 llvm::APSInt numEltsInt(32);
3818 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3819 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3820 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3821 << AttrName << numEltsExpr->getSourceRange();
3822 Attr.setInvalid();
3823 return;
3824 }
3825 // Only certain element types are supported for Neon vectors.
3826 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3827 if (!BTy ||
3828 (VecKind == VectorType::NeonPolyVector &&
3829 BTy->getKind() != BuiltinType::SChar &&
3830 BTy->getKind() != BuiltinType::Short) ||
3831 (BTy->getKind() != BuiltinType::SChar &&
3832 BTy->getKind() != BuiltinType::UChar &&
3833 BTy->getKind() != BuiltinType::Short &&
3834 BTy->getKind() != BuiltinType::UShort &&
3835 BTy->getKind() != BuiltinType::Int &&
3836 BTy->getKind() != BuiltinType::UInt &&
3837 BTy->getKind() != BuiltinType::LongLong &&
3838 BTy->getKind() != BuiltinType::ULongLong &&
3839 BTy->getKind() != BuiltinType::Float)) {
3840 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3841 Attr.setInvalid();
3842 return;
3843 }
3844 // The total size of the vector must be 64 or 128 bits.
3845 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3846 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3847 unsigned vecSize = typeSize * numElts;
3848 if (vecSize != 64 && vecSize != 128) {
3849 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3850 Attr.setInvalid();
3851 return;
3852 }
3853
3854 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3855}
3856
John McCall711c52b2011-01-05 12:14:39 +00003857static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3858 bool isDeclSpec, AttributeList *attrs) {
Chris Lattner232e8822008-02-21 01:08:11 +00003859 // Scan through and apply attributes to this type where it makes sense. Some
3860 // attributes (such as __address_space__, __vector_size__, etc) apply to the
3861 // type, but others can be present in the type specifiers even though they
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00003862 // apply to the decl. Here we apply type attributes and ignore the rest.
John McCall711c52b2011-01-05 12:14:39 +00003863
3864 AttributeList *next;
3865 do {
3866 AttributeList &attr = *attrs;
3867 next = attr.getNext();
3868
Abramo Bagnarae215f722010-04-30 13:10:51 +00003869 // Skip attributes that were marked to be invalid.
John McCall711c52b2011-01-05 12:14:39 +00003870 if (attr.isInvalid())
Abramo Bagnarae215f722010-04-30 13:10:51 +00003871 continue;
3872
Abramo Bagnarab1f1b262010-04-30 09:13:03 +00003873 // If this is an attribute we can handle, do so now,
3874 // otherwise, add it to the FnAttrs list for rechaining.
John McCall711c52b2011-01-05 12:14:39 +00003875 switch (attr.getKind()) {
Chris Lattner232e8822008-02-21 01:08:11 +00003876 default: break;
John McCall04a67a62010-02-05 21:31:56 +00003877
Chandler Carruth682eae22011-10-07 18:40:27 +00003878 case AttributeList::AT_may_alias:
3879 // FIXME: This attribute needs to actually be handled, but if we ignore
3880 // it it breaks large amounts of Linux software.
3881 attr.setUsedAsTypeAttr();
3882 break;
Chris Lattner232e8822008-02-21 01:08:11 +00003883 case AttributeList::AT_address_space:
John McCall711c52b2011-01-05 12:14:39 +00003884 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003885 attr.setUsedAsTypeAttr();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003886 break;
John McCall711c52b2011-01-05 12:14:39 +00003887 OBJC_POINTER_TYPE_ATTRS_CASELIST:
3888 if (!handleObjCPointerTypeAttr(state, attr, type))
3889 distributeObjCPointerTypeAttr(state, attr, type);
John McCalle82247a2011-10-01 05:17:03 +00003890 attr.setUsedAsTypeAttr();
Mike Stump24556362009-07-25 21:26:53 +00003891 break;
John Thompson6e132aa2009-12-04 21:51:28 +00003892 case AttributeList::AT_vector_size:
John McCall711c52b2011-01-05 12:14:39 +00003893 HandleVectorSizeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003894 attr.setUsedAsTypeAttr();
John McCall04a67a62010-02-05 21:31:56 +00003895 break;
Douglas Gregor4ac01402011-06-15 16:02:29 +00003896 case AttributeList::AT_ext_vector_type:
3897 if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3898 != DeclSpec::SCS_typedef)
3899 HandleExtVectorTypeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003900 attr.setUsedAsTypeAttr();
Douglas Gregor4ac01402011-06-15 16:02:29 +00003901 break;
Bob Wilson4211bb62010-11-16 00:32:24 +00003902 case AttributeList::AT_neon_vector_type:
John McCall711c52b2011-01-05 12:14:39 +00003903 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3904 VectorType::NeonVector, "neon_vector_type");
John McCalle82247a2011-10-01 05:17:03 +00003905 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00003906 break;
3907 case AttributeList::AT_neon_polyvector_type:
John McCall711c52b2011-01-05 12:14:39 +00003908 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3909 VectorType::NeonPolyVector,
Bob Wilson4211bb62010-11-16 00:32:24 +00003910 "neon_polyvector_type");
John McCalle82247a2011-10-01 05:17:03 +00003911 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00003912 break;
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003913 case AttributeList::AT_opencl_image_access:
3914 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00003915 attr.setUsedAsTypeAttr();
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003916 break;
3917
John McCallf85e1932011-06-15 23:02:42 +00003918 case AttributeList::AT_ns_returns_retained:
3919 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
3920 break;
3921 // fallthrough into the function attrs
3922
John McCall711c52b2011-01-05 12:14:39 +00003923 FUNCTION_TYPE_ATTRS_CASELIST:
John McCalle82247a2011-10-01 05:17:03 +00003924 attr.setUsedAsTypeAttr();
3925
John McCall711c52b2011-01-05 12:14:39 +00003926 // Never process function type attributes as part of the
3927 // declaration-specifiers.
3928 if (isDeclSpec)
3929 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3930
3931 // Otherwise, handle the possible delays.
3932 else if (!handleFunctionTypeAttr(state, attr, type))
3933 distributeFunctionTypeAttr(state, attr, type);
John Thompson6e132aa2009-12-04 21:51:28 +00003934 break;
Chris Lattner232e8822008-02-21 01:08:11 +00003935 }
John McCall711c52b2011-01-05 12:14:39 +00003936 } while ((attrs = next));
Chris Lattner232e8822008-02-21 01:08:11 +00003937}
3938
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003939/// \brief Ensure that the type of the given expression is complete.
3940///
3941/// This routine checks whether the expression \p E has a complete type. If the
3942/// expression refers to an instantiable construct, that instantiation is
3943/// performed as needed to complete its type. Furthermore
3944/// Sema::RequireCompleteType is called for the expression's type (or in the
3945/// case of a reference type, the referred-to type).
3946///
3947/// \param E The expression whose type is required to be complete.
3948/// \param PD The partial diagnostic that will be printed out if the type cannot
3949/// be completed.
3950///
3951/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3952/// otherwise.
3953bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3954 std::pair<SourceLocation,
3955 PartialDiagnostic> Note) {
3956 QualType T = E->getType();
3957
3958 // Fast path the case where the type is already complete.
3959 if (!T->isIncompleteType())
3960 return false;
3961
3962 // Incomplete array types may be completed by the initializer attached to
3963 // their definitions. For static data members of class templates we need to
3964 // instantiate the definition to get this initializer and complete the type.
3965 if (T->isIncompleteArrayType()) {
3966 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3967 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3968 if (Var->isStaticDataMember() &&
3969 Var->getInstantiatedFromStaticDataMember()) {
Douglas Gregor36f255c2011-06-03 14:28:43 +00003970
3971 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3972 assert(MSInfo && "Missing member specialization information?");
3973 if (MSInfo->getTemplateSpecializationKind()
3974 != TSK_ExplicitSpecialization) {
3975 // If we don't already have a point of instantiation, this is it.
3976 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3977 MSInfo->setPointOfInstantiation(E->getLocStart());
3978
3979 // This is a modification of an existing AST node. Notify
3980 // listeners.
3981 if (ASTMutationListener *L = getASTMutationListener())
3982 L->StaticDataMemberInstantiated(Var);
3983 }
3984
3985 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
3986
3987 // Update the type to the newly instantiated definition's type both
3988 // here and within the expression.
3989 if (VarDecl *Def = Var->getDefinition()) {
3990 DRE->setDecl(Def);
3991 T = Def->getType();
3992 DRE->setType(T);
3993 E->setType(T);
3994 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003995 }
3996
Chandler Carruthe4d645c2011-05-27 01:33:31 +00003997 // We still go on to try to complete the type independently, as it
3998 // may also require instantiations or diagnostics if it remains
3999 // incomplete.
4000 }
4001 }
4002 }
4003 }
4004
4005 // FIXME: Are there other cases which require instantiating something other
4006 // than the type to complete the type of an expression?
4007
4008 // Look through reference types and complete the referred type.
4009 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4010 T = Ref->getPointeeType();
4011
4012 return RequireCompleteType(E->getExprLoc(), T, PD, Note);
4013}
4014
Mike Stump1eb44332009-09-09 15:08:12 +00004015/// @brief Ensure that the type T is a complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004016///
4017/// This routine checks whether the type @p T is complete in any
4018/// context where a complete type is required. If @p T is a complete
Douglas Gregor86447ec2009-03-09 16:13:40 +00004019/// type, returns false. If @p T is a class template specialization,
4020/// this routine then attempts to perform class template
4021/// instantiation. If instantiation fails, or if @p T is incomplete
4022/// and cannot be completed, issues the diagnostic @p diag (giving it
4023/// the type @p T) and returns true.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004024///
4025/// @param Loc The location in the source that the incomplete type
4026/// diagnostic should refer to.
4027///
4028/// @param T The type that this routine is examining for completeness.
4029///
Mike Stump1eb44332009-09-09 15:08:12 +00004030/// @param PD The partial diagnostic that will be printed out if T is not a
Anders Carlssonb7906612009-08-26 23:45:07 +00004031/// complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004032///
4033/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4034/// @c false otherwise.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004035bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004036 const PartialDiagnostic &PD,
4037 std::pair<SourceLocation,
4038 PartialDiagnostic> Note) {
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004039 unsigned diag = PD.getDiagID();
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Douglas Gregor573d9c32009-10-21 23:19:44 +00004041 // FIXME: Add this assertion to make sure we always get instantiation points.
4042 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004043 // FIXME: Add this assertion to help us flush out problems with
4044 // checking for dependent types and type-dependent expressions.
4045 //
Mike Stump1eb44332009-09-09 15:08:12 +00004046 // assert(!T->isDependentType() &&
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004047 // "Can't ask whether a dependent type is complete");
4048
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004049 // If we have a complete type, we're done.
Douglas Gregord07cc362012-01-02 17:18:37 +00004050 NamedDecl *Def = 0;
4051 if (!T->isIncompleteType(&Def)) {
4052 // If we know about the definition but it is not visible, complain.
4053 if (diag != 0 && Def && !LookupResult::isVisible(Def)) {
4054 // Suppress this error outside of a SFINAE context if we've already
4055 // emitted the error once for this type. There's no usefulness in
4056 // repeating the diagnostic.
4057 // FIXME: Add a Fix-It that imports the corresponding module or includes
4058 // the header.
4059 if (isSFINAEContext() || HiddenDefinitions.insert(Def)) {
4060 Diag(Loc, diag::err_module_private_definition) << T;
4061 Diag(Def->getLocation(), diag::note_previous_definition);
4062 }
4063 }
4064
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004065 return false;
Douglas Gregord07cc362012-01-02 17:18:37 +00004066 }
Eli Friedman3c0eb162008-05-27 03:33:27 +00004067
Sean Callananbd791192011-12-16 00:20:31 +00004068 const TagType *Tag = T->getAs<TagType>();
4069 const ObjCInterfaceType *IFace = 0;
4070
4071 if (Tag) {
4072 // Avoid diagnosing invalid decls as incomplete.
4073 if (Tag->getDecl()->isInvalidDecl())
4074 return true;
4075
4076 // Give the external AST source a chance to complete the type.
4077 if (Tag->getDecl()->hasExternalLexicalStorage()) {
4078 Context.getExternalSource()->CompleteType(Tag->getDecl());
4079 if (!Tag->isIncompleteType())
4080 return false;
4081 }
4082 }
4083 else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4084 // Avoid diagnosing invalid decls as incomplete.
4085 if (IFace->getDecl()->isInvalidDecl())
4086 return true;
4087
4088 // Give the external AST source a chance to complete the type.
4089 if (IFace->getDecl()->hasExternalLexicalStorage()) {
4090 Context.getExternalSource()->CompleteType(IFace->getDecl());
4091 if (!IFace->isIncompleteType())
4092 return false;
4093 }
4094 }
4095
Douglas Gregord475b8d2009-03-25 21:17:03 +00004096 // If we have a class template specialization or a class member of a
Sebastian Redl923d56d2009-11-05 15:52:31 +00004097 // class template specialization, or an array with known size of such,
4098 // try to instantiate it.
4099 QualType MaybeTemplate = T;
Douglas Gregor89c49f02009-11-09 22:08:55 +00004100 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
Sebastian Redl923d56d2009-11-05 15:52:31 +00004101 MaybeTemplate = Array->getElementType();
4102 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00004103 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004104 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004105 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4106 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00004107 TSK_ImplicitInstantiation,
Douglas Gregor5842ba92009-08-24 15:23:48 +00004108 /*Complain=*/diag != 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004109 } else if (CXXRecordDecl *Rec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004110 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
4111 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004112 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
4113 assert(MSInfo && "Missing member specialization information?");
Douglas Gregor357bbd02009-08-28 20:50:45 +00004114 // This record was instantiated from a class within a template.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004115 if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004116 != TSK_ExplicitSpecialization)
Douglas Gregorf6b11852009-10-08 15:14:33 +00004117 return InstantiateClass(Loc, Rec, Pattern,
4118 getTemplateInstantiationArgs(Rec),
4119 TSK_ImplicitInstantiation,
4120 /*Complain=*/diag != 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +00004121 }
4122 }
4123 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00004124
Douglas Gregor5842ba92009-08-24 15:23:48 +00004125 if (diag == 0)
4126 return true;
Douglas Gregorb3029962011-11-14 22:10:01 +00004127
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004128 // We have an incomplete type. Produce a diagnostic.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004129 Diag(Loc, PD) << T;
Douglas Gregorb3029962011-11-14 22:10:01 +00004130
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004131 // If we have a note, produce it.
4132 if (!Note.first.isInvalid())
4133 Diag(Note.first, Note.second);
4134
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004135 // If the type was a forward declaration of a class/struct/union
Rafael Espindola01620702010-03-21 22:56:43 +00004136 // type, produce a note.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004137 if (Tag && !Tag->getDecl()->isInvalidDecl())
Mike Stump1eb44332009-09-09 15:08:12 +00004138 Diag(Tag->getDecl()->getLocation(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004139 Tag->isBeingDefined() ? diag::note_type_being_defined
4140 : diag::note_forward_declaration)
Douglas Gregorb3029962011-11-14 22:10:01 +00004141 << QualType(Tag, 0);
4142
4143 // If the Objective-C class was a forward declaration, produce a note.
4144 if (IFace && !IFace->getDecl()->isInvalidDecl())
4145 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004146
4147 return true;
4148}
Douglas Gregore6258932009-03-19 00:39:20 +00004149
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004150bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4151 const PartialDiagnostic &PD) {
4152 return RequireCompleteType(Loc, T, PD,
4153 std::make_pair(SourceLocation(), PDiag(0)));
4154}
4155
4156bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4157 unsigned DiagID) {
4158 return RequireCompleteType(Loc, T, PDiag(DiagID),
4159 std::make_pair(SourceLocation(), PDiag(0)));
4160}
4161
Richard Smith9f569cc2011-10-01 02:31:28 +00004162/// @brief Ensure that the type T is a literal type.
4163///
4164/// This routine checks whether the type @p T is a literal type. If @p T is an
4165/// incomplete type, an attempt is made to complete it. If @p T is a literal
4166/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4167/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4168/// it the type @p T), along with notes explaining why the type is not a
4169/// literal type, and returns true.
4170///
4171/// @param Loc The location in the source that the non-literal type
4172/// diagnostic should refer to.
4173///
4174/// @param T The type that this routine is examining for literalness.
4175///
4176/// @param PD The partial diagnostic that will be printed out if T is not a
4177/// literal type.
4178///
4179/// @param AllowIncompleteType If true, an incomplete type will be considered
4180/// acceptable.
4181///
4182/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4183/// @c false otherwise.
4184bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
4185 const PartialDiagnostic &PD,
4186 bool AllowIncompleteType) {
4187 assert(!T->isDependentType() && "type should not be dependent");
4188
4189 bool Incomplete = RequireCompleteType(Loc, T, 0);
Richard Smith8398cbf2012-02-01 04:40:02 +00004190 if (T->isLiteralType() ||
4191 (AllowIncompleteType && Incomplete && !T->isVoidType()))
Richard Smith9f569cc2011-10-01 02:31:28 +00004192 return false;
4193
4194 if (PD.getDiagID() == 0)
4195 return true;
4196
4197 Diag(Loc, PD) << T;
4198
4199 if (T->isVariableArrayType())
4200 return true;
4201
4202 const RecordType *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>();
4203 if (!RT)
4204 return true;
4205
4206 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4207
4208 // If the class has virtual base classes, then it's not an aggregate, and
4209 // cannot have any constexpr constructors, so is non-literal. This is better
4210 // to diagnose than the resulting absence of constexpr constructors.
4211 if (RD->getNumVBases()) {
4212 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
4213 << RD->isStruct() << RD->getNumVBases();
4214 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4215 E = RD->vbases_end(); I != E; ++I)
4216 Diag(I->getSourceRange().getBegin(),
4217 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
4218 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor()) {
4219 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
4220
4221 switch (RD->getTemplateSpecializationKind()) {
4222 case TSK_Undeclared:
4223 case TSK_ExplicitSpecialization:
4224 break;
4225
4226 case TSK_ImplicitInstantiation:
4227 case TSK_ExplicitInstantiationDeclaration:
4228 case TSK_ExplicitInstantiationDefinition:
4229 // If the base template had constexpr constructors which were
4230 // instantiated as non-constexpr constructors, explain why.
4231 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4232 E = RD->ctor_end(); I != E; ++I) {
4233 if ((*I)->isCopyConstructor() || (*I)->isMoveConstructor())
4234 continue;
4235
4236 FunctionDecl *Base = (*I)->getInstantiatedFromMemberFunction();
4237 if (Base && Base->isConstexpr())
4238 CheckConstexprFunctionDecl(*I, CCK_NoteNonConstexprInstantiation);
4239 }
4240 }
4241 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4242 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4243 E = RD->bases_end(); I != E; ++I) {
4244 if (!I->getType()->isLiteralType()) {
4245 Diag(I->getSourceRange().getBegin(),
4246 diag::note_non_literal_base_class)
4247 << RD << I->getType() << I->getSourceRange();
4248 return true;
4249 }
4250 }
4251 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4252 E = RD->field_end(); I != E; ++I) {
4253 if (!(*I)->getType()->isLiteralType()) {
4254 Diag((*I)->getLocation(), diag::note_non_literal_field)
4255 << RD << (*I) << (*I)->getType();
4256 return true;
Richard Smith5fa6a042011-10-12 05:08:15 +00004257 } else if ((*I)->isMutable()) {
4258 Diag((*I)->getLocation(), diag::note_non_literal_mutable_field) << RD;
4259 return true;
Richard Smith9f569cc2011-10-01 02:31:28 +00004260 }
4261 }
4262 } else if (!RD->hasTrivialDestructor()) {
4263 // All fields and bases are of literal types, so have trivial destructors.
4264 // If this class's destructor is non-trivial it must be user-declared.
4265 CXXDestructorDecl *Dtor = RD->getDestructor();
4266 assert(Dtor && "class has literal fields and bases but no dtor?");
4267 if (!Dtor)
4268 return true;
4269
4270 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4271 diag::note_non_literal_user_provided_dtor :
4272 diag::note_non_literal_nontrivial_dtor) << RD;
4273 }
4274
4275 return true;
4276}
4277
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004278/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4279/// and qualified by the nested-name-specifier contained in SS.
4280QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4281 const CXXScopeSpec &SS, QualType T) {
4282 if (T.isNull())
Douglas Gregore6258932009-03-19 00:39:20 +00004283 return T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004284 NestedNameSpecifier *NNS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00004285 if (SS.isValid())
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004286 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4287 else {
4288 if (Keyword == ETK_None)
4289 return T;
4290 NNS = 0;
4291 }
4292 return Context.getElaboratedType(Keyword, NNS, T);
Douglas Gregore6258932009-03-19 00:39:20 +00004293}
Anders Carlssonaf017e62009-06-29 22:58:55 +00004294
John McCall2a984ca2010-10-12 00:20:44 +00004295QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004296 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004297 if (ER.isInvalid()) return QualType();
4298 E = ER.take();
4299
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004300 if (!E->isTypeDependent()) {
4301 QualType T = E->getType();
Fariborz Jahanianaca7f7b2010-10-06 00:23:25 +00004302 if (const TagType *TT = T->getAs<TagType>())
4303 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004304 }
Anders Carlssonaf017e62009-06-29 22:58:55 +00004305 return Context.getTypeOfExprType(E);
4306}
4307
John McCall2a984ca2010-10-12 00:20:44 +00004308QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004309 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004310 if (ER.isInvalid()) return QualType();
4311 E = ER.take();
Douglas Gregor4b52e252009-12-21 23:17:24 +00004312
Anders Carlssonaf017e62009-06-29 22:58:55 +00004313 return Context.getDecltypeType(E);
4314}
Sean Huntca63c202011-05-24 22:41:36 +00004315
4316QualType Sema::BuildUnaryTransformType(QualType BaseType,
4317 UnaryTransformType::UTTKind UKind,
4318 SourceLocation Loc) {
4319 switch (UKind) {
4320 case UnaryTransformType::EnumUnderlyingType:
4321 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4322 Diag(Loc, diag::err_only_enums_have_underlying_types);
4323 return QualType();
4324 } else {
4325 QualType Underlying = BaseType;
4326 if (!BaseType->isDependentType()) {
4327 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4328 assert(ED && "EnumType has no EnumDecl");
4329 DiagnoseUseOfDecl(ED, Loc);
4330 Underlying = ED->getIntegerType();
4331 }
4332 assert(!Underlying.isNull());
4333 return Context.getUnaryTransformType(BaseType, Underlying,
4334 UnaryTransformType::EnumUnderlyingType);
4335 }
4336 }
4337 llvm_unreachable("unknown unary transform type");
4338}
Eli Friedmanb001de72011-10-06 23:00:33 +00004339
4340QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4341 if (!T->isDependentType()) {
4342 int DisallowedKind = -1;
4343 if (T->isIncompleteType())
4344 // FIXME: It isn't entirely clear whether incomplete atomic types
4345 // are allowed or not; for simplicity, ban them for the moment.
4346 DisallowedKind = 0;
4347 else if (T->isArrayType())
4348 DisallowedKind = 1;
4349 else if (T->isFunctionType())
4350 DisallowedKind = 2;
4351 else if (T->isReferenceType())
4352 DisallowedKind = 3;
4353 else if (T->isAtomicType())
4354 DisallowedKind = 4;
4355 else if (T.hasQualifiers())
4356 DisallowedKind = 5;
4357 else if (!T.isTriviallyCopyableType(Context))
4358 // Some other non-trivially-copyable type (probably a C++ class)
4359 DisallowedKind = 6;
4360
4361 if (DisallowedKind != -1) {
4362 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4363 return QualType();
4364 }
4365
4366 // FIXME: Do we need any handling for ARC here?
4367 }
4368
4369 // Build the pointer type.
4370 return Context.getAtomicType(T);
4371}