blob: 15aa39b7e4e06a616c5b439dec93c5e8eed30839 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36f255c2011-06-03 14:28:43 +000016#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Steve Naroff980e5082007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor2943aed2009-03-03 04:44:36 +000019#include "clang/AST/DeclTemplate.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/Expr.h"
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +000021#include "clang/AST/TypeLoc.h"
John McCall51bd8032009-10-18 01:05:36 +000022#include "clang/AST/TypeLocVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Basic/OpenCL.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000024#include "clang/Basic/PartialDiagnostic.h"
Charles Davisd18f9f92010-08-16 04:01:50 +000025#include "clang/Basic/TargetInfo.h"
John McCall2792fa52011-03-08 04:17:03 +000026#include "clang/Lex/Preprocessor.h"
Eli Friedmanbc1029b2012-04-05 22:47:34 +000027#include "clang/Parse/ParseDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
John McCallf85e1932011-06-15 23:02:42 +000029#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregord07cc362012-01-02 17:18:37 +000030#include "clang/Sema/Lookup.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "clang/Sema/ScopeInfo.h"
32#include "clang/Sema/Template.h"
Sebastian Redl4994d2d2009-07-04 11:39:00 +000033#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor87c12c42009-11-04 16:49:01 +000034#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Chris Lattner5db2bb12009-10-25 18:21:37 +000037/// isOmittedBlockReturnType - Return true if this declarator is missing a
Chad Rosier91cbbbf2012-06-26 21:41:40 +000038/// return type because this is a omitted return type on a block literal.
Sebastian Redl8ce35b02009-10-25 21:45:37 +000039static bool isOmittedBlockReturnType(const Declarator &D) {
Chris Lattner5db2bb12009-10-25 18:21:37 +000040 if (D.getContext() != Declarator::BlockLiteralContext ||
Sebastian Redl8ce35b02009-10-25 21:45:37 +000041 D.getDeclSpec().hasTypeSpecifier())
Chris Lattner5db2bb12009-10-25 18:21:37 +000042 return false;
Chad Rosier91cbbbf2012-06-26 21:41:40 +000043
Chris Lattner5db2bb12009-10-25 18:21:37 +000044 if (D.getNumTypeObjects() == 0)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000045 return true; // ^{ ... }
Chad Rosier91cbbbf2012-06-26 21:41:40 +000046
Chris Lattner5db2bb12009-10-25 18:21:37 +000047 if (D.getNumTypeObjects() == 1 &&
48 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
Chris Lattnera64ef0a2009-10-25 22:09:09 +000049 return true; // ^(int X, float Y) { ... }
Chad Rosier91cbbbf2012-06-26 21:41:40 +000050
Chris Lattner5db2bb12009-10-25 18:21:37 +000051 return false;
52}
53
John McCall2792fa52011-03-08 04:17:03 +000054/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
55/// doesn't apply to the given type.
56static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
57 QualType type) {
Chandler Carruth108f7562011-07-26 05:40:03 +000058 bool useExpansionLoc = false;
John McCall2792fa52011-03-08 04:17:03 +000059
60 unsigned diagID = 0;
61 switch (attr.getKind()) {
Sean Hunt8e083e72012-06-19 23:57:03 +000062 case AttributeList::AT_ObjCGC:
John McCall2792fa52011-03-08 04:17:03 +000063 diagID = diag::warn_pointer_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000064 useExpansionLoc = true;
John McCall2792fa52011-03-08 04:17:03 +000065 break;
66
Sean Hunt8e083e72012-06-19 23:57:03 +000067 case AttributeList::AT_ObjCOwnership:
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000068 diagID = diag::warn_objc_object_attribute_wrong_type;
Chandler Carruth108f7562011-07-26 05:40:03 +000069 useExpansionLoc = true;
Argyrios Kyrtzidis05d48762011-07-01 22:23:09 +000070 break;
71
John McCall2792fa52011-03-08 04:17:03 +000072 default:
73 // Assume everything else was a function attribute.
74 diagID = diag::warn_function_attribute_wrong_type;
75 break;
76 }
77
78 SourceLocation loc = attr.getLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +000079 StringRef name = attr.getName()->getName();
John McCall2792fa52011-03-08 04:17:03 +000080
81 // The GC attributes are usually written with macros; special-case them.
Chandler Carruth108f7562011-07-26 05:40:03 +000082 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
John McCall834e3f62011-03-08 07:59:04 +000083 if (attr.getParameterName()->isStr("strong")) {
84 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
85 } else if (attr.getParameterName()->isStr("weak")) {
86 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
John McCall2792fa52011-03-08 04:17:03 +000087 }
88 }
89
90 S.Diag(loc, diagID) << name << type;
91}
92
John McCall711c52b2011-01-05 12:14:39 +000093// objc_gc applies to Objective-C pointers or, otherwise, to the
94// smallest available pointer type (i.e. 'void*' in 'void**').
95#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
Sean Hunt8e083e72012-06-19 23:57:03 +000096 case AttributeList::AT_ObjCGC: \
97 case AttributeList::AT_ObjCOwnership
John McCall04a67a62010-02-05 21:31:56 +000098
John McCall711c52b2011-01-05 12:14:39 +000099// Function type attributes.
100#define FUNCTION_TYPE_ATTRS_CASELIST \
Sean Hunt8e083e72012-06-19 23:57:03 +0000101 case AttributeList::AT_NoReturn: \
102 case AttributeList::AT_CDecl: \
103 case AttributeList::AT_FastCall: \
104 case AttributeList::AT_StdCall: \
105 case AttributeList::AT_ThisCall: \
106 case AttributeList::AT_Pascal: \
107 case AttributeList::AT_Regparm: \
Derek Schuff263366f2012-10-16 22:30:41 +0000108 case AttributeList::AT_Pcs: \
Guy Benyei38980082012-12-25 08:53:55 +0000109 case AttributeList::AT_PnaclCall: \
110 case AttributeList::AT_IntelOclBicc \
John McCall04a67a62010-02-05 21:31:56 +0000111
John McCall711c52b2011-01-05 12:14:39 +0000112namespace {
113 /// An object which stores processing state for the entire
114 /// GetTypeForDeclarator process.
115 class TypeProcessingState {
116 Sema &sema;
117
118 /// The declarator being processed.
119 Declarator &declarator;
120
121 /// The index of the declarator chunk we're currently processing.
122 /// May be the total number of valid chunks, indicating the
123 /// DeclSpec.
124 unsigned chunkIndex;
125
126 /// Whether there are non-trivial modifications to the decl spec.
127 bool trivial;
128
John McCall7ea21932011-03-26 01:39:56 +0000129 /// Whether we saved the attributes in the decl spec.
130 bool hasSavedAttrs;
131
John McCall711c52b2011-01-05 12:14:39 +0000132 /// The original set of attributes on the DeclSpec.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<AttributeList*, 2> savedAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000134
135 /// A list of attributes to diagnose the uselessness of when the
136 /// processing is complete.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000137 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
John McCall711c52b2011-01-05 12:14:39 +0000138
139 public:
140 TypeProcessingState(Sema &sema, Declarator &declarator)
141 : sema(sema), declarator(declarator),
142 chunkIndex(declarator.getNumTypeObjects()),
John McCall7ea21932011-03-26 01:39:56 +0000143 trivial(true), hasSavedAttrs(false) {}
John McCall711c52b2011-01-05 12:14:39 +0000144
145 Sema &getSema() const {
146 return sema;
Abramo Bagnarae215f722010-04-30 13:10:51 +0000147 }
John McCall711c52b2011-01-05 12:14:39 +0000148
149 Declarator &getDeclarator() const {
150 return declarator;
151 }
152
153 unsigned getCurrentChunkIndex() const {
154 return chunkIndex;
155 }
156
157 void setCurrentChunkIndex(unsigned idx) {
158 assert(idx <= declarator.getNumTypeObjects());
159 chunkIndex = idx;
160 }
161
162 AttributeList *&getCurrentAttrListRef() const {
163 assert(chunkIndex <= declarator.getNumTypeObjects());
164 if (chunkIndex == declarator.getNumTypeObjects())
165 return getMutableDeclSpec().getAttributes().getListRef();
166 return declarator.getTypeObject(chunkIndex).getAttrListRef();
167 }
168
169 /// Save the current set of attributes on the DeclSpec.
170 void saveDeclSpecAttrs() {
171 // Don't try to save them multiple times.
John McCall7ea21932011-03-26 01:39:56 +0000172 if (hasSavedAttrs) return;
John McCall711c52b2011-01-05 12:14:39 +0000173
174 DeclSpec &spec = getMutableDeclSpec();
175 for (AttributeList *attr = spec.getAttributes().getList(); attr;
176 attr = attr->getNext())
177 savedAttrs.push_back(attr);
178 trivial &= savedAttrs.empty();
John McCall7ea21932011-03-26 01:39:56 +0000179 hasSavedAttrs = true;
John McCall711c52b2011-01-05 12:14:39 +0000180 }
181
182 /// Record that we had nowhere to put the given type attribute.
183 /// We will diagnose such attributes later.
184 void addIgnoredTypeAttr(AttributeList &attr) {
185 ignoredTypeAttrs.push_back(&attr);
186 }
187
188 /// Diagnose all the ignored type attributes, given that the
189 /// declarator worked out to the given type.
190 void diagnoseIgnoredTypeAttrs(QualType type) const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000191 for (SmallVectorImpl<AttributeList*>::const_iterator
John McCall711c52b2011-01-05 12:14:39 +0000192 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
John McCall2792fa52011-03-08 04:17:03 +0000193 i != e; ++i)
194 diagnoseBadTypeAttribute(getSema(), **i, type);
John McCall711c52b2011-01-05 12:14:39 +0000195 }
196
197 ~TypeProcessingState() {
198 if (trivial) return;
199
200 restoreDeclSpecAttrs();
201 }
202
203 private:
204 DeclSpec &getMutableDeclSpec() const {
205 return const_cast<DeclSpec&>(declarator.getDeclSpec());
206 }
207
208 void restoreDeclSpecAttrs() {
John McCall7ea21932011-03-26 01:39:56 +0000209 assert(hasSavedAttrs);
210
211 if (savedAttrs.empty()) {
212 getMutableDeclSpec().getAttributes().set(0);
213 return;
214 }
215
John McCall711c52b2011-01-05 12:14:39 +0000216 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
217 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
218 savedAttrs[i]->setNext(savedAttrs[i+1]);
219 savedAttrs.back()->setNext(0);
220 }
221 };
222
223 /// Basically std::pair except that we really want to avoid an
224 /// implicit operator= for safety concerns. It's also a minor
225 /// link-time optimization for this to be a private type.
226 struct AttrAndList {
227 /// The attribute.
228 AttributeList &first;
229
230 /// The head of the list the attribute is currently in.
231 AttributeList *&second;
232
233 AttrAndList(AttributeList &attr, AttributeList *&head)
234 : first(attr), second(head) {}
235 };
John McCall04a67a62010-02-05 21:31:56 +0000236}
237
John McCall711c52b2011-01-05 12:14:39 +0000238namespace llvm {
239 template <> struct isPodLike<AttrAndList> {
240 static const bool value = true;
241 };
242}
243
244static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
245 attr.setNext(head);
246 head = &attr;
247}
248
249static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
250 if (head == &attr) {
251 head = attr.getNext();
252 return;
John McCall04a67a62010-02-05 21:31:56 +0000253 }
John McCall711c52b2011-01-05 12:14:39 +0000254
255 AttributeList *cur = head;
256 while (true) {
257 assert(cur && cur->getNext() && "ran out of attrs?");
258 if (cur->getNext() == &attr) {
259 cur->setNext(attr.getNext());
260 return;
261 }
262 cur = cur->getNext();
263 }
264}
265
266static void moveAttrFromListToList(AttributeList &attr,
267 AttributeList *&fromList,
268 AttributeList *&toList) {
269 spliceAttrOutOfList(attr, fromList);
270 spliceAttrIntoList(attr, toList);
271}
272
Richard Smithf7a05272013-01-14 07:53:01 +0000273/// The location of a type attribute.
274enum TypeAttrLocation {
275 /// The attribute is in the decl-specifier-seq.
276 TAL_DeclSpec,
277 /// The attribute is part of a DeclaratorChunk.
278 TAL_DeclChunk,
279 /// The attribute is immediately after the declaration's name.
280 TAL_DeclName
281};
282
John McCall711c52b2011-01-05 12:14:39 +0000283static void processTypeAttrs(TypeProcessingState &state,
Richard Smithf7a05272013-01-14 07:53:01 +0000284 QualType &type, TypeAttrLocation TAL,
John McCall711c52b2011-01-05 12:14:39 +0000285 AttributeList *attrs);
286
287static bool handleFunctionTypeAttr(TypeProcessingState &state,
288 AttributeList &attr,
289 QualType &type);
290
291static bool handleObjCGCTypeAttr(TypeProcessingState &state,
292 AttributeList &attr, QualType &type);
293
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000294static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +0000295 AttributeList &attr, QualType &type);
296
John McCall711c52b2011-01-05 12:14:39 +0000297static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
298 AttributeList &attr, QualType &type) {
Sean Hunt8e083e72012-06-19 23:57:03 +0000299 if (attr.getKind() == AttributeList::AT_ObjCGC)
John McCallf85e1932011-06-15 23:02:42 +0000300 return handleObjCGCTypeAttr(state, attr, type);
Sean Hunt8e083e72012-06-19 23:57:03 +0000301 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000302 return handleObjCOwnershipTypeAttr(state, attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000303}
304
305/// Given that an objc_gc attribute was written somewhere on a
306/// declaration *other* than on the declarator itself (for which, use
307/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
308/// didn't apply in whatever position it was written in, try to move
309/// it to a more appropriate position.
310static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
311 AttributeList &attr,
312 QualType type) {
313 Declarator &declarator = state.getDeclarator();
314 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
315 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
316 switch (chunk.Kind) {
317 case DeclaratorChunk::Pointer:
318 case DeclaratorChunk::BlockPointer:
319 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
320 chunk.getAttrListRef());
321 return;
322
323 case DeclaratorChunk::Paren:
324 case DeclaratorChunk::Array:
325 continue;
326
327 // Don't walk through these.
328 case DeclaratorChunk::Reference:
329 case DeclaratorChunk::Function:
330 case DeclaratorChunk::MemberPointer:
331 goto error;
332 }
333 }
334 error:
John McCall2792fa52011-03-08 04:17:03 +0000335
336 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000337}
338
339/// Distribute an objc_gc type attribute that was written on the
340/// declarator.
341static void
342distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
343 AttributeList &attr,
344 QualType &declSpecType) {
345 Declarator &declarator = state.getDeclarator();
346
347 // objc_gc goes on the innermost pointer to something that's not a
348 // pointer.
349 unsigned innermost = -1U;
350 bool considerDeclSpec = true;
351 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
352 DeclaratorChunk &chunk = declarator.getTypeObject(i);
353 switch (chunk.Kind) {
354 case DeclaratorChunk::Pointer:
355 case DeclaratorChunk::BlockPointer:
356 innermost = i;
John McCallae278a32011-01-12 00:34:59 +0000357 continue;
John McCall711c52b2011-01-05 12:14:39 +0000358
359 case DeclaratorChunk::Reference:
360 case DeclaratorChunk::MemberPointer:
361 case DeclaratorChunk::Paren:
362 case DeclaratorChunk::Array:
363 continue;
364
365 case DeclaratorChunk::Function:
366 considerDeclSpec = false;
367 goto done;
368 }
369 }
370 done:
371
372 // That might actually be the decl spec if we weren't blocked by
373 // anything in the declarator.
374 if (considerDeclSpec) {
John McCall7ea21932011-03-26 01:39:56 +0000375 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
376 // Splice the attribute into the decl spec. Prevents the
377 // attribute from being applied multiple times and gives
378 // the source-location-filler something to work with.
379 state.saveDeclSpecAttrs();
380 moveAttrFromListToList(attr, declarator.getAttrListRef(),
381 declarator.getMutableDeclSpec().getAttributes().getListRef());
John McCall711c52b2011-01-05 12:14:39 +0000382 return;
John McCall7ea21932011-03-26 01:39:56 +0000383 }
John McCall711c52b2011-01-05 12:14:39 +0000384 }
385
386 // Otherwise, if we found an appropriate chunk, splice the attribute
387 // into it.
388 if (innermost != -1U) {
389 moveAttrFromListToList(attr, declarator.getAttrListRef(),
390 declarator.getTypeObject(innermost).getAttrListRef());
391 return;
392 }
393
394 // Otherwise, diagnose when we're done building the type.
395 spliceAttrOutOfList(attr, declarator.getAttrListRef());
396 state.addIgnoredTypeAttr(attr);
397}
398
399/// A function type attribute was written somewhere in a declaration
400/// *other* than on the declarator itself or in the decl spec. Given
401/// that it didn't apply in whatever position it was written in, try
402/// to move it to a more appropriate position.
403static void distributeFunctionTypeAttr(TypeProcessingState &state,
404 AttributeList &attr,
405 QualType type) {
406 Declarator &declarator = state.getDeclarator();
407
408 // Try to push the attribute from the return type of a function to
409 // the function itself.
410 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
411 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
412 switch (chunk.Kind) {
413 case DeclaratorChunk::Function:
414 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
415 chunk.getAttrListRef());
416 return;
417
418 case DeclaratorChunk::Paren:
419 case DeclaratorChunk::Pointer:
420 case DeclaratorChunk::BlockPointer:
421 case DeclaratorChunk::Array:
422 case DeclaratorChunk::Reference:
423 case DeclaratorChunk::MemberPointer:
424 continue;
425 }
426 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000427
John McCall2792fa52011-03-08 04:17:03 +0000428 diagnoseBadTypeAttribute(state.getSema(), attr, type);
John McCall711c52b2011-01-05 12:14:39 +0000429}
430
431/// Try to distribute a function type attribute to the innermost
432/// function chunk or type. Returns true if the attribute was
433/// distributed, false if no location was found.
434static bool
435distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
436 AttributeList &attr,
437 AttributeList *&attrList,
438 QualType &declSpecType) {
439 Declarator &declarator = state.getDeclarator();
440
441 // Put it on the innermost function chunk, if there is one.
442 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
443 DeclaratorChunk &chunk = declarator.getTypeObject(i);
444 if (chunk.Kind != DeclaratorChunk::Function) continue;
445
446 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
447 return true;
448 }
449
John McCallf85e1932011-06-15 23:02:42 +0000450 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
451 spliceAttrOutOfList(attr, attrList);
452 return true;
453 }
454
455 return false;
John McCall711c52b2011-01-05 12:14:39 +0000456}
457
458/// A function type attribute was written in the decl spec. Try to
459/// apply it somewhere.
460static void
461distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
462 AttributeList &attr,
463 QualType &declSpecType) {
464 state.saveDeclSpecAttrs();
465
Richard Smith5c521662013-01-15 02:48:13 +0000466 // C++11 attributes before the decl specifiers actually appertain to
467 // the declarators. Move them straight there. We don't support the
468 // 'put them wherever you like' semantics we allow for GNU attributes.
469 if (attr.isCXX11Attribute()) {
470 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
471 state.getDeclarator().getAttrListRef());
472 return;
473 }
474
John McCall711c52b2011-01-05 12:14:39 +0000475 // Try to distribute to the innermost.
476 if (distributeFunctionTypeAttrToInnermost(state, attr,
477 state.getCurrentAttrListRef(),
478 declSpecType))
479 return;
480
481 // If that failed, diagnose the bad attribute when the declarator is
482 // fully built.
483 state.addIgnoredTypeAttr(attr);
484}
485
486/// A function type attribute was written on the declarator. Try to
487/// apply it somewhere.
488static void
489distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
490 AttributeList &attr,
491 QualType &declSpecType) {
492 Declarator &declarator = state.getDeclarator();
493
494 // Try to distribute to the innermost.
495 if (distributeFunctionTypeAttrToInnermost(state, attr,
496 declarator.getAttrListRef(),
497 declSpecType))
498 return;
499
500 // If that failed, diagnose the bad attribute when the declarator is
501 // fully built.
502 spliceAttrOutOfList(attr, declarator.getAttrListRef());
503 state.addIgnoredTypeAttr(attr);
504}
505
506/// \brief Given that there are attributes written on the declarator
507/// itself, try to distribute any type attributes to the appropriate
508/// declarator chunk.
509///
510/// These are attributes like the following:
511/// int f ATTR;
512/// int (f ATTR)();
513/// but not necessarily this:
514/// int f() ATTR;
515static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
516 QualType &declSpecType) {
517 // Collect all the type attributes from the declarator itself.
518 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
519 AttributeList *attr = state.getDeclarator().getAttributes();
520 AttributeList *next;
521 do {
522 next = attr->getNext();
523
Richard Smith5c521662013-01-15 02:48:13 +0000524 // Do not distribute C++11 attributes. They have strict rules for what
525 // they appertain to.
526 if (attr->isCXX11Attribute())
527 continue;
528
John McCall711c52b2011-01-05 12:14:39 +0000529 switch (attr->getKind()) {
530 OBJC_POINTER_TYPE_ATTRS_CASELIST:
531 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
532 break;
533
Sean Hunt8e083e72012-06-19 23:57:03 +0000534 case AttributeList::AT_NSReturnsRetained:
David Blaikie4e4d0842012-03-11 07:00:24 +0000535 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000536 break;
537 // fallthrough
538
John McCall711c52b2011-01-05 12:14:39 +0000539 FUNCTION_TYPE_ATTRS_CASELIST:
540 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
541 break;
542
543 default:
544 break;
545 }
546 } while ((attr = next));
547}
548
549/// Add a synthetic '()' to a block-literal declarator if it is
550/// required, given the return type.
551static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
552 QualType declSpecType) {
553 Declarator &declarator = state.getDeclarator();
554
555 // First, check whether the declarator would produce a function,
556 // i.e. whether the innermost semantic chunk is a function.
557 if (declarator.isFunctionDeclarator()) {
558 // If so, make that declarator a prototyped declarator.
559 declarator.getFunctionTypeInfo().hasPrototype = true;
560 return;
561 }
562
John McCallda263792011-02-08 01:59:10 +0000563 // If there are any type objects, the type as written won't name a
564 // function, regardless of the decl spec type. This is because a
565 // block signature declarator is always an abstract-declarator, and
566 // abstract-declarators can't just be parentheses chunks. Therefore
567 // we need to build a function chunk unless there are no type
568 // objects and the decl spec type is a function.
John McCall711c52b2011-01-05 12:14:39 +0000569 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
570 return;
571
John McCallda263792011-02-08 01:59:10 +0000572 // Note that there *are* cases with invalid declarators where
573 // declarators consist solely of parentheses. In general, these
574 // occur only in failed efforts to make function declarators, so
575 // faking up the function chunk is still the right thing to do.
John McCall711c52b2011-01-05 12:14:39 +0000576
577 // Otherwise, we need to fake up a function declarator.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000578 SourceLocation loc = declarator.getLocStart();
John McCall711c52b2011-01-05 12:14:39 +0000579
580 // ...and *prepend* it to the declarator.
Abramo Bagnara59c0a812012-10-04 21:42:10 +0000581 SourceLocation NoLoc;
John McCall711c52b2011-01-05 12:14:39 +0000582 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
Abramo Bagnara59c0a812012-10-04 21:42:10 +0000583 /*HasProto=*/true,
584 /*IsAmbiguous=*/false,
585 /*LParenLoc=*/NoLoc,
586 /*ArgInfo=*/0,
587 /*NumArgs=*/0,
588 /*EllipsisLoc=*/NoLoc,
589 /*RParenLoc=*/NoLoc,
590 /*TypeQuals=*/0,
591 /*RefQualifierIsLvalueRef=*/true,
592 /*RefQualifierLoc=*/NoLoc,
593 /*ConstQualifierLoc=*/NoLoc,
594 /*VolatileQualifierLoc=*/NoLoc,
595 /*MutableLoc=*/NoLoc,
596 EST_None,
597 /*ESpecLoc=*/NoLoc,
598 /*Exceptions=*/0,
599 /*ExceptionRanges=*/0,
600 /*NumExceptions=*/0,
601 /*NoexceptExpr=*/0,
602 loc, loc, declarator));
John McCall711c52b2011-01-05 12:14:39 +0000603
604 // For consistency, make sure the state still has us as processing
605 // the decl spec.
606 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
607 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
John McCall04a67a62010-02-05 21:31:56 +0000608}
609
Douglas Gregor930d8b52009-01-30 22:09:00 +0000610/// \brief Convert the specified declspec to the appropriate type
611/// object.
James Dennett1dfbd922012-06-14 21:40:34 +0000612/// \param state Specifies the declarator containing the declaration specifier
613/// to be converted, along with other associated processing state.
Chris Lattner5153ee62009-04-25 08:47:54 +0000614/// \returns The type described by the declaration specifiers. This function
615/// never returns null.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000616static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
618 // checking.
John McCall711c52b2011-01-05 12:14:39 +0000619
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +0000620 Sema &S = state.getSema();
John McCall711c52b2011-01-05 12:14:39 +0000621 Declarator &declarator = state.getDeclarator();
622 const DeclSpec &DS = declarator.getDeclSpec();
623 SourceLocation DeclLoc = declarator.getIdentifierLoc();
Chris Lattner5db2bb12009-10-25 18:21:37 +0000624 if (DeclLoc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000625 DeclLoc = DS.getLocStart();
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000626
John McCall711c52b2011-01-05 12:14:39 +0000627 ASTContext &Context = S.Context;
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattner5db2bb12009-10-25 18:21:37 +0000629 QualType Result;
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 switch (DS.getTypeSpecType()) {
Chris Lattner96b77fc2008-04-02 06:50:17 +0000631 case DeclSpec::TST_void:
632 Result = Context.VoidTy;
633 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 case DeclSpec::TST_char:
635 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000636 Result = Context.CharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000638 Result = Context.SignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000639 else {
640 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
641 "Unknown TSS value");
Chris Lattnerfab5b452008-02-20 23:53:49 +0000642 Result = Context.UnsignedCharTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 }
Chris Lattner958858e2008-02-20 21:40:32 +0000644 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000645 case DeclSpec::TST_wchar:
646 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
647 Result = Context.WCharTy;
648 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
John McCall711c52b2011-01-05 12:14:39 +0000649 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000650 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000651 Result = Context.getSignedWCharType();
652 } else {
653 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
654 "Unknown TSS value");
John McCall711c52b2011-01-05 12:14:39 +0000655 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000656 << DS.getSpecifierName(DS.getTypeSpecType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000657 Result = Context.getUnsignedWCharType();
658 }
659 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000660 case DeclSpec::TST_char16:
661 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
662 "Unknown TSS value");
663 Result = Context.Char16Ty;
664 break;
665 case DeclSpec::TST_char32:
666 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
667 "Unknown TSS value");
668 Result = Context.Char32Ty;
669 break;
Chris Lattnerd658b562008-04-05 06:32:51 +0000670 case DeclSpec::TST_unspecified:
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000671 // "<proto1,proto2>" is an objc qualified ID with a missing id.
Chris Lattner097e9162008-10-20 02:01:50 +0000672 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000673 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
Roman Divacky31ba6132012-09-06 15:59:27 +0000674 (ObjCProtocolDecl*const*)PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000675 DS.getNumProtocolQualifiers());
676 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner62f5f7f2008-07-26 00:46:50 +0000677 break;
678 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000679
Chris Lattner5db2bb12009-10-25 18:21:37 +0000680 // If this is a missing declspec in a block literal return context, then it
681 // is inferred from the return statements inside the block.
Eli Friedmanf88c4002012-01-04 04:41:38 +0000682 // The declspec is always missing in a lambda expr context; it is either
683 // specified with a trailing return type or inferred.
684 if (declarator.getContext() == Declarator::LambdaExprContext ||
685 isOmittedBlockReturnType(declarator)) {
Chris Lattner5db2bb12009-10-25 18:21:37 +0000686 Result = Context.DependentTy;
687 break;
688 }
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Chris Lattnerd658b562008-04-05 06:32:51 +0000690 // Unspecified typespec defaults to int in C90. However, the C90 grammar
691 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
692 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
693 // Note that the one exception to this is function definitions, which are
694 // allowed to be completely missing a declspec. This is handled in the
695 // parser already though by it pretending to have seen an 'int' in this
696 // case.
David Blaikie4e4d0842012-03-11 07:00:24 +0000697 if (S.getLangOpts().ImplicitInt) {
Chris Lattner35d276f2009-02-27 18:53:28 +0000698 // In C89 mode, we only warn if there is a completely missing declspec
699 // when one is not allowed.
Chris Lattner3f84ad22009-04-22 05:27:59 +0000700 if (DS.isEmpty()) {
John McCall711c52b2011-01-05 12:14:39 +0000701 S.Diag(DeclLoc, diag::ext_missing_declspec)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000702 << DS.getSourceRange()
Daniel Dunbar96a00142012-03-09 18:35:03 +0000703 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
Chris Lattner3f84ad22009-04-22 05:27:59 +0000704 }
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000705 } else if (!DS.hasTypeSpecifier()) {
Chris Lattnerd658b562008-04-05 06:32:51 +0000706 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
707 // "At least one type specifier shall be given in the declaration
708 // specifiers in each declaration, and in the specifier-qualifier list in
709 // each struct declaration and type name."
Douglas Gregor4310f4e2009-02-16 22:38:20 +0000710 // FIXME: Does Microsoft really have the implicit int extension in C++?
David Blaikie4e4d0842012-03-11 07:00:24 +0000711 if (S.getLangOpts().CPlusPlus &&
712 !S.getLangOpts().MicrosoftExt) {
John McCall711c52b2011-01-05 12:14:39 +0000713 S.Diag(DeclLoc, diag::err_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000714 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattnerb78d8332009-06-26 04:45:06 +0000716 // When this occurs in C++ code, often something is very broken with the
717 // value being declared, poison it as invalid so we don't get chains of
718 // errors.
John McCall711c52b2011-01-05 12:14:39 +0000719 declarator.setInvalidType(true);
Chris Lattnerb78d8332009-06-26 04:45:06 +0000720 } else {
John McCall711c52b2011-01-05 12:14:39 +0000721 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000722 << DS.getSourceRange();
Chris Lattnerb78d8332009-06-26 04:45:06 +0000723 }
Chris Lattnerd658b562008-04-05 06:32:51 +0000724 }
Mike Stump1eb44332009-09-09 15:08:12 +0000725
726 // FALL THROUGH.
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000727 case DeclSpec::TST_int: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
729 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000730 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
731 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
732 case DeclSpec::TSW_long: Result = Context.LongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000733 case DeclSpec::TSW_longlong:
734 Result = Context.LongLongTy;
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000735
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000736 // 'long long' is a C99 or C++11 feature.
737 if (!S.getLangOpts().C99) {
738 if (S.getLangOpts().CPlusPlus)
739 S.Diag(DS.getTypeSpecWidthLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000740 S.getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000741 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
742 else
743 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
744 }
Chris Lattner311157f2009-10-25 18:25:04 +0000745 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 }
747 } else {
748 switch (DS.getTypeSpecWidth()) {
Chris Lattnerfab5b452008-02-20 23:53:49 +0000749 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
750 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
751 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
Chris Lattner311157f2009-10-25 18:25:04 +0000752 case DeclSpec::TSW_longlong:
753 Result = Context.UnsignedLongLongTy;
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000754
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000755 // 'long long' is a C99 or C++11 feature.
756 if (!S.getLangOpts().C99) {
757 if (S.getLangOpts().CPlusPlus)
758 S.Diag(DS.getTypeSpecWidthLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +0000759 S.getLangOpts().CPlusPlus11 ?
Dmitri Gribenkoe3b136b2012-09-24 18:19:21 +0000760 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
761 else
762 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
763 }
Chris Lattner311157f2009-10-25 18:25:04 +0000764 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 }
766 }
Chris Lattner958858e2008-02-20 21:40:32 +0000767 break;
Chris Lattner3cbc38b2007-08-21 17:02:28 +0000768 }
Richard Smith5a5a9712012-04-04 06:24:32 +0000769 case DeclSpec::TST_int128:
Richard Smith84268902012-11-29 05:41:51 +0000770 if (!S.PP.getTargetInfo().hasInt128Type())
771 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
Richard Smith5a5a9712012-04-04 06:24:32 +0000772 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
773 Result = Context.UnsignedInt128Ty;
774 else
775 Result = Context.Int128Ty;
776 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000777 case DeclSpec::TST_half: Result = Context.HalfTy; break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000778 case DeclSpec::TST_float: Result = Context.FloatTy; break;
Chris Lattner958858e2008-02-20 21:40:32 +0000779 case DeclSpec::TST_double:
780 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
Chris Lattnerfab5b452008-02-20 23:53:49 +0000781 Result = Context.LongDoubleTy;
Chris Lattner958858e2008-02-20 21:40:32 +0000782 else
Chris Lattnerfab5b452008-02-20 23:53:49 +0000783 Result = Context.DoubleTy;
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000784
David Blaikie4e4d0842012-03-11 07:00:24 +0000785 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
Peter Collingbourne39d3e7a2011-02-15 19:46:23 +0000786 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
787 declarator.setInvalidType(true);
788 }
Chris Lattner958858e2008-02-20 21:40:32 +0000789 break;
Chris Lattnerfab5b452008-02-20 23:53:49 +0000790 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
Reid Spencer5f016e22007-07-11 17:01:13 +0000791 case DeclSpec::TST_decimal32: // _Decimal32
792 case DeclSpec::TST_decimal64: // _Decimal64
793 case DeclSpec::TST_decimal128: // _Decimal128
John McCall711c52b2011-01-05 12:14:39 +0000794 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
Chris Lattner8f12f652009-05-13 05:02:08 +0000795 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000796 declarator.setInvalidType(true);
Chris Lattner8f12f652009-05-13 05:02:08 +0000797 break;
Chris Lattner99dc9142008-04-13 18:59:07 +0000798 case DeclSpec::TST_class:
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 case DeclSpec::TST_enum:
800 case DeclSpec::TST_union:
Joao Matos6666ed42012-08-31 18:45:21 +0000801 case DeclSpec::TST_struct:
802 case DeclSpec::TST_interface: {
John McCallb3d87482010-08-24 05:47:05 +0000803 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
John McCall6e247262009-10-10 05:48:19 +0000804 if (!D) {
805 // This can happen in C++ with ambiguous lookups.
806 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000807 declarator.setInvalidType(true);
John McCall6e247262009-10-10 05:48:19 +0000808 break;
809 }
810
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000811 // If the type is deprecated or unavailable, diagnose it.
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000812 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000813
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000815 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000816
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 // TypeQuals handled by caller.
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000818 Result = Context.getTypeDeclType(D);
John McCall2191b202009-09-05 06:31:47 +0000819
Abramo Bagnara0daaf322011-03-16 20:16:18 +0000820 // In both C and C++, make an ElaboratedType.
821 ElaboratedTypeKeyword Keyword
822 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
823 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000824 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000825 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000826 case DeclSpec::TST_typename: {
Reid Spencer5f016e22007-07-11 17:01:13 +0000827 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
828 DS.getTypeSpecSign() == 0 &&
829 "Can't handle qualifiers on typedef names yet!");
John McCall711c52b2011-01-05 12:14:39 +0000830 Result = S.GetTypeFromParser(DS.getRepAsType());
John McCall27940d22010-07-30 05:17:22 +0000831 if (Result.isNull())
John McCall711c52b2011-01-05 12:14:39 +0000832 declarator.setInvalidType(true);
John McCall27940d22010-07-30 05:17:22 +0000833 else if (DeclSpec::ProtocolQualifierListTy PQ
834 = DS.getProtocolQualifiers()) {
John McCallc12c5bb2010-05-15 11:32:37 +0000835 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
836 // Silently drop any existing protocol qualifiers.
837 // TODO: determine whether that's the right thing to do.
838 if (ObjT->getNumProtocols())
839 Result = ObjT->getBaseType();
840
841 if (DS.getNumProtocolQualifiers())
842 Result = Context.getObjCObjectType(Result,
Roman Divacky31ba6132012-09-06 15:59:27 +0000843 (ObjCProtocolDecl*const*) PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000844 DS.getNumProtocolQualifiers());
845 } else if (Result->isObjCIdType()) {
Chris Lattnerae4da612008-07-26 01:53:50 +0000846 // id<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000847 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
Roman Divacky31ba6132012-09-06 15:59:27 +0000848 (ObjCProtocolDecl*const*) PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000849 DS.getNumProtocolQualifiers());
850 Result = Context.getObjCObjectPointerType(Result);
851 } else if (Result->isObjCClassType()) {
Steve Naroff4262a072009-02-23 18:53:24 +0000852 // Class<protocol-list>
John McCallc12c5bb2010-05-15 11:32:37 +0000853 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
Roman Divacky31ba6132012-09-06 15:59:27 +0000854 (ObjCProtocolDecl*const*) PQ,
John McCallc12c5bb2010-05-15 11:32:37 +0000855 DS.getNumProtocolQualifiers());
856 Result = Context.getObjCObjectPointerType(Result);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000857 } else {
John McCall711c52b2011-01-05 12:14:39 +0000858 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
Chris Lattner3f84ad22009-04-22 05:27:59 +0000859 << DS.getSourceRange();
John McCall711c52b2011-01-05 12:14:39 +0000860 declarator.setInvalidType(true);
Chris Lattner3f84ad22009-04-22 05:27:59 +0000861 }
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 // TypeQuals handled by caller.
Chris Lattner958858e2008-02-20 21:40:32 +0000865 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 }
Chris Lattner958858e2008-02-20 21:40:32 +0000867 case DeclSpec::TST_typeofType:
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000868 // FIXME: Preserve type source info.
John McCall711c52b2011-01-05 12:14:39 +0000869 Result = S.GetTypeFromParser(DS.getRepAsType());
Chris Lattner958858e2008-02-20 21:40:32 +0000870 assert(!Result.isNull() && "Didn't get a type for typeof?");
Fariborz Jahanian730e1752010-10-06 17:00:02 +0000871 if (!Result->isDependentType())
872 if (const TagType *TT = Result->getAs<TagType>())
John McCall711c52b2011-01-05 12:14:39 +0000873 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
Steve Naroffd1861fd2007-07-31 12:34:36 +0000874 // TypeQuals handled by caller.
Chris Lattnerfab5b452008-02-20 23:53:49 +0000875 Result = Context.getTypeOfType(Result);
Chris Lattner958858e2008-02-20 21:40:32 +0000876 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000877 case DeclSpec::TST_typeofExpr: {
John McCallb3d87482010-08-24 05:47:05 +0000878 Expr *E = DS.getRepAsExpr();
Steve Naroffd1861fd2007-07-31 12:34:36 +0000879 assert(E && "Didn't get an expression for typeof?");
880 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000881 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +0000882 if (Result.isNull()) {
883 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000884 declarator.setInvalidType(true);
Douglas Gregor4b52e252009-12-21 23:17:24 +0000885 }
Chris Lattner958858e2008-02-20 21:40:32 +0000886 break;
Steve Naroffd1861fd2007-07-31 12:34:36 +0000887 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000888 case DeclSpec::TST_decltype: {
John McCallb3d87482010-08-24 05:47:05 +0000889 Expr *E = DS.getRepAsExpr();
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000890 assert(E && "Didn't get an expression for decltype?");
891 // TypeQuals handled by caller.
John McCall711c52b2011-01-05 12:14:39 +0000892 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
Anders Carlssonaf017e62009-06-29 22:58:55 +0000893 if (Result.isNull()) {
894 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000895 declarator.setInvalidType(true);
Anders Carlssonaf017e62009-06-29 22:58:55 +0000896 }
Anders Carlsson6fd634f2009-06-24 17:47:40 +0000897 break;
898 }
Sean Huntca63c202011-05-24 22:41:36 +0000899 case DeclSpec::TST_underlyingType:
Sean Huntdb5d44b2011-05-19 05:37:45 +0000900 Result = S.GetTypeFromParser(DS.getRepAsType());
901 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
Sean Huntca63c202011-05-24 22:41:36 +0000902 Result = S.BuildUnaryTransformType(Result,
903 UnaryTransformType::EnumUnderlyingType,
904 DS.getTypeSpecTypeLoc());
905 if (Result.isNull()) {
906 Result = Context.IntTy;
907 declarator.setInvalidType(true);
Sean Huntdb5d44b2011-05-19 05:37:45 +0000908 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000909 break;
Sean Huntdb5d44b2011-05-19 05:37:45 +0000910
Anders Carlssone89d1592009-06-26 18:41:36 +0000911 case DeclSpec::TST_auto: {
912 // TypeQuals handled by caller.
Richard Smith34b41d92011-02-20 03:19:35 +0000913 Result = Context.getAutoType(QualType());
Anders Carlssone89d1592009-06-26 18:41:36 +0000914 break;
915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
John McCalla5fc4722011-04-09 22:50:59 +0000917 case DeclSpec::TST_unknown_anytype:
918 Result = Context.UnknownAnyTy;
919 break;
920
Eli Friedmanb001de72011-10-06 23:00:33 +0000921 case DeclSpec::TST_atomic:
922 Result = S.GetTypeFromParser(DS.getRepAsType());
923 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
924 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
925 if (Result.isNull()) {
926 Result = Context.IntTy;
927 declarator.setInvalidType(true);
928 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +0000929 break;
Eli Friedmanb001de72011-10-06 23:00:33 +0000930
Guy Benyeib13621d2012-12-18 14:38:23 +0000931 case DeclSpec::TST_image1d_t:
932 Result = Context.OCLImage1dTy;
933 break;
934
935 case DeclSpec::TST_image1d_array_t:
936 Result = Context.OCLImage1dArrayTy;
937 break;
938
939 case DeclSpec::TST_image1d_buffer_t:
940 Result = Context.OCLImage1dBufferTy;
941 break;
942
943 case DeclSpec::TST_image2d_t:
944 Result = Context.OCLImage2dTy;
945 break;
946
947 case DeclSpec::TST_image2d_array_t:
948 Result = Context.OCLImage2dArrayTy;
949 break;
950
951 case DeclSpec::TST_image3d_t:
952 Result = Context.OCLImage3dTy;
953 break;
954
Douglas Gregor809070a2009-02-18 17:45:20 +0000955 case DeclSpec::TST_error:
Chris Lattner5153ee62009-04-25 08:47:54 +0000956 Result = Context.IntTy;
John McCall711c52b2011-01-05 12:14:39 +0000957 declarator.setInvalidType(true);
Chris Lattner5153ee62009-04-25 08:47:54 +0000958 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner958858e2008-02-20 21:40:32 +0000961 // Handle complex types.
Douglas Gregorf244cd72009-02-14 21:06:05 +0000962 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000963 if (S.getLangOpts().Freestanding)
John McCall711c52b2011-01-05 12:14:39 +0000964 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
Chris Lattnerfab5b452008-02-20 23:53:49 +0000965 Result = Context.getComplexType(Result);
John Thompson82287d12010-02-05 00:12:22 +0000966 } else if (DS.isTypeAltiVecVector()) {
967 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
968 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
Bob Wilsone86d78c2010-11-10 21:56:12 +0000969 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000970 if (DS.isTypeAltiVecPixel())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000971 VecKind = VectorType::AltiVecPixel;
Chris Lattner788b0fd2010-06-23 06:00:24 +0000972 else if (DS.isTypeAltiVecBool())
Bob Wilsone86d78c2010-11-10 21:56:12 +0000973 VecKind = VectorType::AltiVecBool;
974 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
Douglas Gregorf244cd72009-02-14 21:06:05 +0000975 }
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Argyrios Kyrtzidis47423bd2010-09-23 09:40:31 +0000977 // FIXME: Imaginary.
978 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
John McCall711c52b2011-01-05 12:14:39 +0000979 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
John McCall711c52b2011-01-05 12:14:39 +0000981 // Before we process any type attributes, synthesize a block literal
982 // function declarator if necessary.
983 if (declarator.getContext() == Declarator::BlockLiteralContext)
984 maybeSynthesizeBlockSignature(state, Result);
985
986 // Apply any type attributes from the decl spec. This may cause the
987 // list of type attributes to be temporarily saved while the type
988 // attributes are pushed around.
989 if (AttributeList *attrs = DS.getAttributes().getList())
Richard Smithf7a05272013-01-14 07:53:01 +0000990 processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner96b77fc2008-04-02 06:50:17 +0000992 // Apply const/volatile/restrict qualifiers to T.
993 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
994
995 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
996 // or incomplete types shall not be restrict-qualified." C++ also allows
997 // restrict-qualified references.
John McCall0953e762009-09-24 19:53:00 +0000998 if (TypeQuals & DeclSpec::TQ_restrict) {
Fariborz Jahanian2b5ff1a2009-12-07 18:08:58 +0000999 if (Result->isAnyPointerType() || Result->isReferenceType()) {
1000 QualType EltTy;
1001 if (Result->isObjCObjectPointerType())
1002 EltTy = Result;
1003 else
1004 EltTy = Result->isPointerType() ?
1005 Result->getAs<PointerType>()->getPointeeType() :
1006 Result->getAs<ReferenceType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Douglas Gregorbad0e652009-03-24 20:32:41 +00001008 // If we have a pointer or reference, the pointee must have an object
Chris Lattnerbdcd6372008-04-02 17:35:06 +00001009 // incomplete type.
1010 if (!EltTy->isIncompleteOrObjectType()) {
John McCall711c52b2011-01-05 12:14:39 +00001011 S.Diag(DS.getRestrictSpecLoc(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001012 diag::err_typecheck_invalid_restrict_invalid_pointee)
Chris Lattnerd1625842008-11-24 06:25:27 +00001013 << EltTy << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +00001014 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattnerbdcd6372008-04-02 17:35:06 +00001015 }
1016 } else {
John McCall711c52b2011-01-05 12:14:39 +00001017 S.Diag(DS.getRestrictSpecLoc(),
1018 diag::err_typecheck_invalid_restrict_not_pointer)
Chris Lattnerd1625842008-11-24 06:25:27 +00001019 << Result << DS.getSourceRange();
John McCall0953e762009-09-24 19:53:00 +00001020 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
Chris Lattner96b77fc2008-04-02 06:50:17 +00001021 }
Chris Lattner96b77fc2008-04-02 06:50:17 +00001022 }
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Chris Lattner96b77fc2008-04-02 06:50:17 +00001024 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
1025 // of a function type includes any type qualifiers, the behavior is
1026 // undefined."
1027 if (Result->isFunctionType() && TypeQuals) {
1028 // Get some location to point at, either the C or V location.
1029 SourceLocation Loc;
John McCall0953e762009-09-24 19:53:00 +00001030 if (TypeQuals & DeclSpec::TQ_const)
Chris Lattner96b77fc2008-04-02 06:50:17 +00001031 Loc = DS.getConstSpecLoc();
John McCall0953e762009-09-24 19:53:00 +00001032 else if (TypeQuals & DeclSpec::TQ_volatile)
Chris Lattner96b77fc2008-04-02 06:50:17 +00001033 Loc = DS.getVolatileSpecLoc();
John McCall0953e762009-09-24 19:53:00 +00001034 else {
1035 assert((TypeQuals & DeclSpec::TQ_restrict) &&
1036 "Has CVR quals but not C, V, or R?");
1037 Loc = DS.getRestrictSpecLoc();
Chris Lattner96b77fc2008-04-02 06:50:17 +00001038 }
John McCall711c52b2011-01-05 12:14:39 +00001039 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
Chris Lattnerd1625842008-11-24 06:25:27 +00001040 << Result << DS.getSourceRange();
Chris Lattner96b77fc2008-04-02 06:50:17 +00001041 }
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +00001043 // C++ [dcl.ref]p1:
1044 // Cv-qualified references are ill-formed except when the
1045 // cv-qualifiers are introduced through the use of a typedef
1046 // (7.1.3) or of a template type argument (14.3), in which
1047 // case the cv-qualifiers are ignored.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001048 // FIXME: Shouldn't we be checking SCS_typedef here?
1049 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
Douglas Gregorf1f9b4e2008-11-03 15:51:28 +00001050 TypeQuals && Result->isReferenceType()) {
John McCall0953e762009-09-24 19:53:00 +00001051 TypeQuals &= ~DeclSpec::TQ_const;
1052 TypeQuals &= ~DeclSpec::TQ_volatile;
Mike Stump1eb44332009-09-09 15:08:12 +00001053 }
1054
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001055 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1056 // than once in the same specifier-list or qualifier-list, either directly
1057 // or via one or more typedefs."
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001058 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001059 && TypeQuals & Result.getCVRQualifiers()) {
1060 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001061 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001062 << "const";
1063 }
1064
1065 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001066 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
Eli Friedmanbc1029b2012-04-05 22:47:34 +00001067 << "volatile";
1068 }
1069
1070 // C90 doesn't have restrict, so it doesn't force us to produce a warning
1071 // in this case.
1072 }
1073
John McCall0953e762009-09-24 19:53:00 +00001074 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
1075 Result = Context.getQualifiedType(Result, Quals);
Chris Lattner96b77fc2008-04-02 06:50:17 +00001076 }
John McCall0953e762009-09-24 19:53:00 +00001077
Chris Lattnerf1d705c2008-02-21 01:07:18 +00001078 return Result;
1079}
1080
Douglas Gregorcd281c32009-02-28 00:25:32 +00001081static std::string getPrintableNameForEntity(DeclarationName Entity) {
1082 if (Entity)
1083 return Entity.getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Douglas Gregorcd281c32009-02-28 00:25:32 +00001085 return "type name";
1086}
1087
John McCall28654742010-06-05 06:41:15 +00001088QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1089 Qualifiers Qs) {
1090 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1091 // object or incomplete types shall not be restrict-qualified."
1092 if (Qs.hasRestrict()) {
1093 unsigned DiagID = 0;
1094 QualType ProblemTy;
1095
1096 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
1097 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
1098 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
1099 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1100 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
1101 }
1102 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1103 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1104 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1105 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1106 }
1107 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1108 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1109 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1110 ProblemTy = T->getAs<PointerType>()->getPointeeType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001111 }
John McCall28654742010-06-05 06:41:15 +00001112 } else if (!Ty->isDependentType()) {
1113 // FIXME: this deserves a proper diagnostic
1114 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1115 ProblemTy = T;
1116 }
1117
1118 if (DiagID) {
1119 Diag(Loc, DiagID) << ProblemTy;
1120 Qs.removeRestrict();
1121 }
1122 }
1123
1124 return Context.getQualifiedType(T, Qs);
1125}
1126
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001127/// \brief Build a paren type including \p T.
1128QualType Sema::BuildParenType(QualType T) {
1129 return Context.getParenType(T);
1130}
1131
John McCallf85e1932011-06-15 23:02:42 +00001132/// Given that we're building a pointer or reference to the given
1133static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1134 SourceLocation loc,
1135 bool isReference) {
1136 // Bail out if retention is unrequired or already specified.
1137 if (!type->isObjCLifetimeType() ||
1138 type.getObjCLifetime() != Qualifiers::OCL_None)
1139 return type;
1140
1141 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1142
1143 // If the object type is const-qualified, we can safely use
1144 // __unsafe_unretained. This is safe (because there are no read
1145 // barriers), and it'll be safe to coerce anything but __weak* to
1146 // the resulting type.
1147 if (type.isConstQualified()) {
1148 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1149
1150 // Otherwise, check whether the static type does not require
1151 // retaining. This currently only triggers for Class (possibly
1152 // protocol-qualifed, and arrays thereof).
1153 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1154 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1155
Eli Friedmanef331b72012-01-20 01:26:23 +00001156 // If we are in an unevaluated context, like sizeof, skip adding a
1157 // qualification.
David Blaikie71f55f72012-08-06 22:47:24 +00001158 } else if (S.isUnevaluatedContext()) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001159 return type;
Argyrios Kyrtzidis5b76f372011-09-20 23:49:22 +00001160
John McCalle8c904f2012-01-26 20:04:03 +00001161 // If that failed, give an error and recover using __strong. __strong
1162 // is the option most likely to prevent spurious second-order diagnostics,
1163 // like when binding a reference to a field.
John McCallf85e1932011-06-15 23:02:42 +00001164 } else {
1165 // These types can show up in private ivars in system headers, so
1166 // we need this to not be an error in those cases. Instead we
1167 // want to delay.
1168 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
Eli Friedmanef331b72012-01-20 01:26:23 +00001169 S.DelayedDiagnostics.add(
1170 sema::DelayedDiagnostic::makeForbiddenType(loc,
1171 diag::err_arc_indirect_no_ownership, type, isReference));
John McCallf85e1932011-06-15 23:02:42 +00001172 } else {
Eli Friedmanef331b72012-01-20 01:26:23 +00001173 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
John McCallf85e1932011-06-15 23:02:42 +00001174 }
John McCalle8c904f2012-01-26 20:04:03 +00001175 implicitLifetime = Qualifiers::OCL_Strong;
John McCallf85e1932011-06-15 23:02:42 +00001176 }
1177 assert(implicitLifetime && "didn't infer any lifetime!");
1178
1179 Qualifiers qs;
1180 qs.addObjCLifetime(implicitLifetime);
1181 return S.Context.getQualifiedType(type, qs);
1182}
1183
Douglas Gregorcd281c32009-02-28 00:25:32 +00001184/// \brief Build a pointer type.
1185///
1186/// \param T The type to which we'll be building a pointer.
1187///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001188/// \param Loc The location of the entity whose type involves this
1189/// pointer type or, if there is no such entity, the location of the
1190/// type that will have pointer type.
1191///
1192/// \param Entity The name of the entity that involves the pointer
1193/// type, if known.
1194///
1195/// \returns A suitable pointer type, if there are no
1196/// errors. Otherwise, returns a NULL type.
John McCall28654742010-06-05 06:41:15 +00001197QualType Sema::BuildPointerType(QualType T,
Douglas Gregorcd281c32009-02-28 00:25:32 +00001198 SourceLocation Loc, DeclarationName Entity) {
1199 if (T->isReferenceType()) {
1200 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1201 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001202 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001203 return QualType();
1204 }
1205
John McCallc12c5bb2010-05-15 11:32:37 +00001206 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
Douglas Gregor92e986e2010-04-22 16:44:27 +00001207
John McCallf85e1932011-06-15 23:02:42 +00001208 // In ARC, it is forbidden to build pointers to unqualified pointers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001209 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001210 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1211
Douglas Gregorcd281c32009-02-28 00:25:32 +00001212 // Build the pointer type.
John McCall28654742010-06-05 06:41:15 +00001213 return Context.getPointerType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001214}
1215
1216/// \brief Build a reference type.
1217///
1218/// \param T The type to which we'll be building a reference.
1219///
Douglas Gregorcd281c32009-02-28 00:25:32 +00001220/// \param Loc The location of the entity whose type involves this
1221/// reference type or, if there is no such entity, the location of the
1222/// type that will have reference type.
1223///
1224/// \param Entity The name of the entity that involves the reference
1225/// type, if known.
1226///
1227/// \returns A suitable reference type, if there are no
1228/// errors. Otherwise, returns a NULL type.
John McCall54e14c42009-10-22 22:37:11 +00001229QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
John McCall28654742010-06-05 06:41:15 +00001230 SourceLocation Loc,
John McCall54e14c42009-10-22 22:37:11 +00001231 DeclarationName Entity) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001232 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
Douglas Gregor9625e442011-05-21 22:16:50 +00001233 "Unresolved overloaded function type");
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001234
Douglas Gregor69d83162011-01-20 16:08:06 +00001235 // C++0x [dcl.ref]p6:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001236 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1237 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1238 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1239 // the type "lvalue reference to T", while an attempt to create the type
Douglas Gregor69d83162011-01-20 16:08:06 +00001240 // "rvalue reference to cv TR" creates the type TR.
John McCall54e14c42009-10-22 22:37:11 +00001241 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1242
John McCall54e14c42009-10-22 22:37:11 +00001243 // C++ [dcl.ref]p4: There shall be no references to references.
1244 //
1245 // According to C++ DR 106, references to references are only
1246 // diagnosed when they are written directly (e.g., "int & &"),
1247 // but not when they happen via a typedef:
1248 //
1249 // typedef int& intref;
1250 // typedef intref& intref2;
1251 //
1252 // Parser::ParseDeclaratorInternal diagnoses the case where
1253 // references are written directly; here, we handle the
Douglas Gregor69d83162011-01-20 16:08:06 +00001254 // collapsing of references-to-references as described in C++0x.
1255 // DR 106 and 540 introduce reference-collapsing into C++98/03.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001256
1257 // C++ [dcl.ref]p1:
Eli Friedman33a31382009-08-05 19:21:58 +00001258 // A declarator that specifies the type "reference to cv void"
Douglas Gregorcd281c32009-02-28 00:25:32 +00001259 // is ill-formed.
1260 if (T->isVoidType()) {
1261 Diag(Loc, diag::err_reference_to_void);
1262 return QualType();
1263 }
1264
John McCallf85e1932011-06-15 23:02:42 +00001265 // In ARC, it is forbidden to build references to unqualified pointers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001266 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001267 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1268
Douglas Gregorcd281c32009-02-28 00:25:32 +00001269 // Handle restrict on references.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001270 if (LValueRef)
John McCall28654742010-06-05 06:41:15 +00001271 return Context.getLValueReferenceType(T, SpelledAsLValue);
1272 return Context.getRValueReferenceType(T);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001273}
1274
Chris Lattnere1eed382011-06-14 06:38:10 +00001275/// Check whether the specified array size makes the array type a VLA. If so,
1276/// return true, if not, return the size of the array in SizeVal.
Richard Smith282e7e62012-02-04 09:53:13 +00001277static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1278 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1279 // (like gnu99, but not c99) accept any evaluatable value as an extension.
Douglas Gregorab41fe92012-05-04 22:38:52 +00001280 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1281 public:
1282 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001283
Douglas Gregorab41fe92012-05-04 22:38:52 +00001284 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1285 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001286
Douglas Gregorab41fe92012-05-04 22:38:52 +00001287 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) {
1288 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1289 }
1290 } Diagnoser;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001291
Douglas Gregorab41fe92012-05-04 22:38:52 +00001292 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1293 S.LangOpts.GNUMode).isInvalid();
Chris Lattnere1eed382011-06-14 06:38:10 +00001294}
1295
1296
Douglas Gregorcd281c32009-02-28 00:25:32 +00001297/// \brief Build an array type.
1298///
1299/// \param T The type of each element in the array.
1300///
1301/// \param ASM C99 array size modifier (e.g., '*', 'static').
Mike Stump1eb44332009-09-09 15:08:12 +00001302///
1303/// \param ArraySize Expression describing the size of the array.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001304///
James Dennettefce31f2012-06-22 08:10:18 +00001305/// \param Brackets The range from the opening '[' to the closing ']'.
Douglas Gregorcd281c32009-02-28 00:25:32 +00001306///
1307/// \param Entity The name of the entity that involves the array
1308/// type, if known.
1309///
1310/// \returns A suitable array type, if there are no errors. Otherwise,
1311/// returns a NULL type.
1312QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1313 Expr *ArraySize, unsigned Quals,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001314 SourceRange Brackets, DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001315
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001316 SourceLocation Loc = Brackets.getBegin();
David Blaikie4e4d0842012-03-11 07:00:24 +00001317 if (getLangOpts().CPlusPlus) {
Douglas Gregor138bb232010-04-27 19:38:14 +00001318 // C++ [dcl.array]p1:
1319 // T is called the array element type; this type shall not be a reference
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001320 // type, the (possibly cv-qualified) type void, a function type or an
Douglas Gregor138bb232010-04-27 19:38:14 +00001321 // abstract class type.
1322 //
Richard Smithbb351512012-07-07 23:00:31 +00001323 // C++ [dcl.array]p3:
1324 // When several "array of" specifications are adjacent, [...] only the
1325 // first of the constant expressions that specify the bounds of the arrays
1326 // may be omitted.
1327 //
Douglas Gregor138bb232010-04-27 19:38:14 +00001328 // Note: function types are handled in the common path with C.
1329 if (T->isReferenceType()) {
1330 Diag(Loc, diag::err_illegal_decl_array_of_references)
1331 << getPrintableNameForEntity(Entity) << T;
1332 return QualType();
1333 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001334
Richard Smithbb351512012-07-07 23:00:31 +00001335 if (T->isVoidType() || T->isIncompleteArrayType()) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001336 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1337 return QualType();
1338 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001339
1340 if (RequireNonAbstractType(Brackets.getBegin(), T,
Douglas Gregor138bb232010-04-27 19:38:14 +00001341 diag::err_array_of_abstract_type))
1342 return QualType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001343
Sebastian Redl923d56d2009-11-05 15:52:31 +00001344 } else {
Douglas Gregor138bb232010-04-27 19:38:14 +00001345 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1346 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
Sebastian Redl923d56d2009-11-05 15:52:31 +00001347 if (RequireCompleteType(Loc, T,
1348 diag::err_illegal_decl_array_incomplete_type))
1349 return QualType();
1350 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001351
1352 if (T->isFunctionType()) {
1353 Diag(Loc, diag::err_illegal_decl_array_of_functions)
John McCallac406052009-10-30 00:37:20 +00001354 << getPrintableNameForEntity(Entity) << T;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001355 return QualType();
1356 }
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Richard Smith34b41d92011-02-20 03:19:35 +00001358 if (T->getContainedAutoType()) {
1359 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1360 << getPrintableNameForEntity(Entity) << T;
Anders Carlssone7cf07d2009-06-26 19:33:28 +00001361 return QualType();
1362 }
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Ted Kremenek6217b802009-07-29 21:53:49 +00001364 if (const RecordType *EltTy = T->getAs<RecordType>()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001365 // If the element type is a struct or union that contains a variadic
1366 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1367 if (EltTy->getDecl()->hasFlexibleArrayMember())
1368 Diag(Loc, diag::ext_flexible_array_in_array) << T;
John McCallc12c5bb2010-05-15 11:32:37 +00001369 } else if (T->isObjCObjectType()) {
Chris Lattnerc7c11b12009-04-27 01:55:56 +00001370 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1371 return QualType();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001372 }
Mike Stump1eb44332009-09-09 15:08:12 +00001373
John McCall806054d2012-01-11 00:14:46 +00001374 // Do placeholder conversions on the array size expression.
1375 if (ArraySize && ArraySize->hasPlaceholderType()) {
1376 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1377 if (Result.isInvalid()) return QualType();
1378 ArraySize = Result.take();
1379 }
1380
John McCall5e3c67b2010-12-15 04:42:30 +00001381 // Do lvalue-to-rvalue conversions on the array size expression.
John Wiegley429bb272011-04-08 18:41:53 +00001382 if (ArraySize && !ArraySize->isRValue()) {
1383 ExprResult Result = DefaultLvalueConversion(ArraySize);
1384 if (Result.isInvalid())
1385 return QualType();
1386
1387 ArraySize = Result.take();
1388 }
John McCall5e3c67b2010-12-15 04:42:30 +00001389
Douglas Gregorcd281c32009-02-28 00:25:32 +00001390 // C99 6.7.5.2p1: The size expression shall have integer type.
Richard Smith282e7e62012-02-04 09:53:13 +00001391 // C++11 allows contextual conversions to such types.
Richard Smith80ad52f2013-01-02 11:42:31 +00001392 if (!getLangOpts().CPlusPlus11 &&
Richard Smith282e7e62012-02-04 09:53:13 +00001393 ArraySize && !ArraySize->isTypeDependent() &&
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001394 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
Douglas Gregorcd281c32009-02-28 00:25:32 +00001395 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1396 << ArraySize->getType() << ArraySize->getSourceRange();
Douglas Gregorcd281c32009-02-28 00:25:32 +00001397 return QualType();
1398 }
Richard Smith282e7e62012-02-04 09:53:13 +00001399
Douglas Gregor2767ce22010-08-18 00:39:00 +00001400 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
Douglas Gregorcd281c32009-02-28 00:25:32 +00001401 if (!ArraySize) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001402 if (ASM == ArrayType::Star)
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001403 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00001404 else
1405 T = Context.getIncompleteArrayType(T, ASM, Quals);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00001406 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001407 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
Richard Smith282e7e62012-02-04 09:53:13 +00001408 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1409 !T->isConstantSizeType()) ||
1410 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1411 // Even in C++11, don't allow contextual conversions in the array bound
1412 // of a VLA.
Richard Smith80ad52f2013-01-02 11:42:31 +00001413 if (getLangOpts().CPlusPlus11 &&
Richard Smith282e7e62012-02-04 09:53:13 +00001414 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1415 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1416 << ArraySize->getType() << ArraySize->getSourceRange();
1417 return QualType();
1418 }
1419
Chris Lattnere1eed382011-06-14 06:38:10 +00001420 // C99: an array with an element type that has a non-constant-size is a VLA.
Chris Lattnere1eed382011-06-14 06:38:10 +00001421 // C99: an array with a non-ICE size is a VLA. We accept any expression
1422 // that we can fold to a non-zero positive value as an extension.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001423 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001424 } else {
1425 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1426 // have a value greater than zero.
Sebastian Redl923d56d2009-11-05 15:52:31 +00001427 if (ConstVal.isSigned() && ConstVal.isNegative()) {
Chandler Carruthb2b5cc02011-01-04 04:44:35 +00001428 if (Entity)
1429 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1430 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1431 else
1432 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1433 << ArraySize->getSourceRange();
Sebastian Redl923d56d2009-11-05 15:52:31 +00001434 return QualType();
1435 }
1436 if (ConstVal == 0) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001437 // GCC accepts zero sized static arrays. We allow them when
1438 // we're not in a SFINAE context.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001439 Diag(ArraySize->getLocStart(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001440 isSFINAEContext()? diag::err_typecheck_zero_array_size
1441 : diag::ext_typecheck_zero_array_size)
Sebastian Redl923d56d2009-11-05 15:52:31 +00001442 << ArraySize->getSourceRange();
Peter Collingbourne20cdbeb2011-10-16 21:17:32 +00001443
1444 if (ASM == ArrayType::Static) {
1445 Diag(ArraySize->getLocStart(),
1446 diag::warn_typecheck_zero_static_array_size)
1447 << ArraySize->getSourceRange();
1448 ASM = ArrayType::Normal;
1449 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001450 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
Douglas Gregor2767ce22010-08-18 00:39:00 +00001451 !T->isIncompleteType()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001452 // Is the array too large?
Douglas Gregor2767ce22010-08-18 00:39:00 +00001453 unsigned ActiveSizeBits
1454 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1455 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1456 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1457 << ConstVal.toString(10)
1458 << ArraySize->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001459 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001460
John McCall46a617a2009-10-16 00:14:28 +00001461 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
Douglas Gregorcd281c32009-02-28 00:25:32 +00001462 }
Joey Gouly617bb312013-01-17 17:35:00 +00001463
1464 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1465 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1466 Diag(Loc, diag::err_opencl_vla);
1467 return QualType();
1468 }
David Chisnallaf407762010-01-11 23:08:08 +00001469 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
David Blaikie4e4d0842012-03-11 07:00:24 +00001470 if (!getLangOpts().C99) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001471 if (T->isVariableArrayType()) {
1472 // Prohibit the use of non-POD types in VLAs.
John McCallf85e1932011-06-15 23:02:42 +00001473 QualType BaseT = Context.getBaseElementType(T);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001474 if (!T->isDependentType() &&
Douglas Gregor3c7236e2013-01-08 00:01:45 +00001475 !BaseT.isPODType(Context) &&
1476 !BaseT->isObjCLifetimeType()) {
Douglas Gregor0fddb972010-05-22 16:17:30 +00001477 Diag(Loc, diag::err_vla_non_pod)
John McCallf85e1932011-06-15 23:02:42 +00001478 << BaseT;
Douglas Gregor0fddb972010-05-22 16:17:30 +00001479 return QualType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001480 }
Douglas Gregora481ec42010-05-23 19:57:01 +00001481 // Prohibit the use of VLAs during template argument deduction.
1482 else if (isSFINAEContext()) {
1483 Diag(Loc, diag::err_vla_in_sfinae);
1484 return QualType();
1485 }
Douglas Gregor0fddb972010-05-22 16:17:30 +00001486 // Just extwarn about VLAs.
1487 else
1488 Diag(Loc, diag::ext_vla);
1489 } else if (ASM != ArrayType::Normal || Quals != 0)
Richard Smithd7c56e12011-12-29 21:57:33 +00001490 Diag(Loc,
David Blaikie4e4d0842012-03-11 07:00:24 +00001491 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
Richard Smithd7c56e12011-12-29 21:57:33 +00001492 : diag::ext_c99_array_usage) << ASM;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001493 }
1494
1495 return T;
1496}
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001497
1498/// \brief Build an ext-vector type.
1499///
1500/// Run the required checks for the extended vector type.
John McCall9ae2f072010-08-23 23:25:46 +00001501QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001502 SourceLocation AttrLoc) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001503 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1504 // in conjunction with complex types (pointers, arrays, functions, etc.).
Mike Stump1eb44332009-09-09 15:08:12 +00001505 if (!T->isDependentType() &&
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001506 !T->isIntegerType() && !T->isRealFloatingType()) {
1507 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1508 return QualType();
1509 }
1510
John McCall9ae2f072010-08-23 23:25:46 +00001511 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001512 llvm::APSInt vecSize(32);
John McCall9ae2f072010-08-23 23:25:46 +00001513 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001514 Diag(AttrLoc, diag::err_attribute_argument_not_int)
John McCall9ae2f072010-08-23 23:25:46 +00001515 << "ext_vector_type" << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001516 return QualType();
1517 }
Mike Stump1eb44332009-09-09 15:08:12 +00001518
1519 // unlike gcc's vector_size attribute, the size is specified as the
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001520 // number of elements, not the number of bytes.
Mike Stump1eb44332009-09-09 15:08:12 +00001521 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1522
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001523 if (vectorSize == 0) {
1524 Diag(AttrLoc, diag::err_attribute_zero_size)
John McCall9ae2f072010-08-23 23:25:46 +00001525 << ArraySize->getSourceRange();
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001526 return QualType();
1527 }
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Douglas Gregor4ac01402011-06-15 16:02:29 +00001529 return Context.getExtVectorType(T, vectorSize);
Mike Stump1eb44332009-09-09 15:08:12 +00001530 }
1531
John McCall9ae2f072010-08-23 23:25:46 +00001532 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001533}
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Douglas Gregor724651c2009-02-28 01:04:19 +00001535/// \brief Build a function type.
1536///
1537/// This routine checks the function type according to C++ rules and
1538/// under the assumption that the result type and parameter types have
1539/// just been instantiated from a template. It therefore duplicates
Douglas Gregor2943aed2009-03-03 04:44:36 +00001540/// some of the behavior of GetTypeForDeclarator, but in a much
Douglas Gregor724651c2009-02-28 01:04:19 +00001541/// simpler form that is only suitable for this narrow use case.
1542///
1543/// \param T The return type of the function.
1544///
1545/// \param ParamTypes The parameter types of the function. This array
1546/// will be modified to account for adjustments to the types of the
1547/// function parameters.
1548///
1549/// \param NumParamTypes The number of parameter types in ParamTypes.
1550///
1551/// \param Variadic Whether this is a variadic function type.
1552///
Richard Smitheefb3d52012-02-10 09:58:53 +00001553/// \param HasTrailingReturn Whether this function has a trailing return type.
1554///
Douglas Gregor724651c2009-02-28 01:04:19 +00001555/// \param Quals The cvr-qualifiers to be applied to the function type.
1556///
1557/// \param Loc The location of the entity whose type involves this
1558/// function type or, if there is no such entity, the location of the
1559/// type that will have function type.
1560///
1561/// \param Entity The name of the entity that involves the function
1562/// type, if known.
1563///
1564/// \returns A suitable function type, if there are no
1565/// errors. Otherwise, returns a NULL type.
1566QualType Sema::BuildFunctionType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001567 QualType *ParamTypes,
Douglas Gregor724651c2009-02-28 01:04:19 +00001568 unsigned NumParamTypes,
Richard Smitheefb3d52012-02-10 09:58:53 +00001569 bool Variadic, bool HasTrailingReturn,
1570 unsigned Quals,
Douglas Gregorc938c162011-01-26 05:01:58 +00001571 RefQualifierKind RefQualifier,
Eli Friedmanfa869542010-08-05 02:54:05 +00001572 SourceLocation Loc, DeclarationName Entity,
John McCalle23cf432010-12-14 08:05:40 +00001573 FunctionType::ExtInfo Info) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001574 if (T->isArrayType() || T->isFunctionType()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001575 Diag(Loc, diag::err_func_returning_array_function)
Douglas Gregor58408bc2010-01-11 18:46:21 +00001576 << T->isFunctionType() << T;
Douglas Gregor724651c2009-02-28 01:04:19 +00001577 return QualType();
1578 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001579
1580 // Functions cannot return half FP.
1581 if (T->isHalfType()) {
1582 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1583 FixItHint::CreateInsertion(Loc, "*");
1584 return QualType();
1585 }
1586
Douglas Gregor724651c2009-02-28 01:04:19 +00001587 bool Invalid = false;
1588 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001589 // FIXME: Loc is too inprecise here, should use proper locations for args.
Douglas Gregor79e6bd32011-07-12 04:42:08 +00001590 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001591 if (ParamType->isVoidType()) {
Douglas Gregor724651c2009-02-28 01:04:19 +00001592 Diag(Loc, diag::err_param_with_void_type);
1593 Invalid = true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001594 } else if (ParamType->isHalfType()) {
1595 // Disallow half FP arguments.
1596 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1597 FixItHint::CreateInsertion(Loc, "*");
1598 Invalid = true;
Douglas Gregor724651c2009-02-28 01:04:19 +00001599 }
Douglas Gregorcd281c32009-02-28 00:25:32 +00001600
John McCall54e14c42009-10-22 22:37:11 +00001601 ParamTypes[Idx] = ParamType;
Douglas Gregor724651c2009-02-28 01:04:19 +00001602 }
1603
1604 if (Invalid)
1605 return QualType();
1606
John McCalle23cf432010-12-14 08:05:40 +00001607 FunctionProtoType::ExtProtoInfo EPI;
1608 EPI.Variadic = Variadic;
Richard Smitheefb3d52012-02-10 09:58:53 +00001609 EPI.HasTrailingReturn = HasTrailingReturn;
John McCalle23cf432010-12-14 08:05:40 +00001610 EPI.TypeQuals = Quals;
Douglas Gregorc938c162011-01-26 05:01:58 +00001611 EPI.RefQualifier = RefQualifier;
John McCalle23cf432010-12-14 08:05:40 +00001612 EPI.ExtInfo = Info;
1613
1614 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
Douglas Gregor724651c2009-02-28 01:04:19 +00001615}
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Douglas Gregor949bf692009-06-09 22:17:39 +00001617/// \brief Build a member pointer type \c T Class::*.
1618///
1619/// \param T the type to which the member pointer refers.
1620/// \param Class the class type into which the member pointer points.
Douglas Gregor949bf692009-06-09 22:17:39 +00001621/// \param Loc the location where this type begins
1622/// \param Entity the name of the entity that will have this member pointer type
1623///
1624/// \returns a member pointer type, if successful, or a NULL type if there was
1625/// an error.
Mike Stump1eb44332009-09-09 15:08:12 +00001626QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
John McCall28654742010-06-05 06:41:15 +00001627 SourceLocation Loc,
Douglas Gregor949bf692009-06-09 22:17:39 +00001628 DeclarationName Entity) {
1629 // Verify that we're not building a pointer to pointer to function with
1630 // exception specification.
1631 if (CheckDistantExceptionSpec(T)) {
1632 Diag(Loc, diag::err_distant_exception_spec);
1633
1634 // FIXME: If we're doing this as part of template instantiation,
1635 // we should return immediately.
1636
1637 // Build the type anyway, but use the canonical type so that the
1638 // exception specifiers are stripped off.
1639 T = Context.getCanonicalType(T);
1640 }
1641
Sebastian Redl73780122010-06-09 21:19:43 +00001642 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
Douglas Gregor949bf692009-06-09 22:17:39 +00001643 // with reference type, or "cv void."
1644 if (T->isReferenceType()) {
Anders Carlsson8d4655d2009-06-30 00:06:57 +00001645 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
John McCallac406052009-10-30 00:37:20 +00001646 << (Entity? Entity.getAsString() : "type name") << T;
Douglas Gregor949bf692009-06-09 22:17:39 +00001647 return QualType();
1648 }
1649
1650 if (T->isVoidType()) {
1651 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1652 << (Entity? Entity.getAsString() : "type name");
1653 return QualType();
1654 }
1655
Douglas Gregor949bf692009-06-09 22:17:39 +00001656 if (!Class->isDependentType() && !Class->isRecordType()) {
1657 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1658 return QualType();
1659 }
1660
Joao Matos679fc932012-09-04 17:18:12 +00001661 // In the Microsoft ABI, the class is allowed to be an incomplete
1662 // type. In such cases, the compiler makes a worst-case assumption.
1663 // We make no such assumption right now, so emit an error if the
1664 // class isn't a complete type.
1665 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
1666 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1667 return QualType();
1668
John McCall28654742010-06-05 06:41:15 +00001669 return Context.getMemberPointerType(T, Class.getTypePtr());
Douglas Gregor949bf692009-06-09 22:17:39 +00001670}
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Anders Carlsson9a917e42009-06-12 22:56:54 +00001672/// \brief Build a block pointer type.
1673///
1674/// \param T The type to which we'll be building a block pointer.
1675///
James Dennettefce31f2012-06-22 08:10:18 +00001676/// \param Loc The source location, used for diagnostics.
Anders Carlsson9a917e42009-06-12 22:56:54 +00001677///
Anders Carlsson9a917e42009-06-12 22:56:54 +00001678/// \param Entity The name of the entity that involves the block pointer
1679/// type, if known.
1680///
1681/// \returns A suitable block pointer type, if there are no
1682/// errors. Otherwise, returns a NULL type.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001683QualType Sema::BuildBlockPointerType(QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00001684 SourceLocation Loc,
Anders Carlsson9a917e42009-06-12 22:56:54 +00001685 DeclarationName Entity) {
John McCall0953e762009-09-24 19:53:00 +00001686 if (!T->isFunctionType()) {
Anders Carlsson9a917e42009-06-12 22:56:54 +00001687 Diag(Loc, diag::err_nonfunction_block_type);
1688 return QualType();
1689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690
John McCall28654742010-06-05 06:41:15 +00001691 return Context.getBlockPointerType(T);
Anders Carlsson9a917e42009-06-12 22:56:54 +00001692}
1693
John McCallb3d87482010-08-24 05:47:05 +00001694QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1695 QualType QT = Ty.get();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001696 if (QT.isNull()) {
John McCalla93c9342009-12-07 02:54:59 +00001697 if (TInfo) *TInfo = 0;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001698 return QualType();
1699 }
1700
John McCalla93c9342009-12-07 02:54:59 +00001701 TypeSourceInfo *DI = 0;
John McCallf4c73712011-01-19 06:33:43 +00001702 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001703 QT = LIT->getType();
John McCalla93c9342009-12-07 02:54:59 +00001704 DI = LIT->getTypeSourceInfo();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001705 }
Mike Stump1eb44332009-09-09 15:08:12 +00001706
John McCalla93c9342009-12-07 02:54:59 +00001707 if (TInfo) *TInfo = DI;
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001708 return QT;
1709}
1710
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001711static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1712 Qualifiers::ObjCLifetime ownership,
1713 unsigned chunkIndex);
1714
John McCallf85e1932011-06-15 23:02:42 +00001715/// Given that this is the declaration of a parameter under ARC,
1716/// attempt to infer attributes and such for pointer-to-whatever
1717/// types.
1718static void inferARCWriteback(TypeProcessingState &state,
1719 QualType &declSpecType) {
1720 Sema &S = state.getSema();
1721 Declarator &declarator = state.getDeclarator();
1722
1723 // TODO: should we care about decl qualifiers?
1724
1725 // Check whether the declarator has the expected form. We walk
1726 // from the inside out in order to make the block logic work.
1727 unsigned outermostPointerIndex = 0;
1728 bool isBlockPointer = false;
1729 unsigned numPointers = 0;
1730 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1731 unsigned chunkIndex = i;
1732 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1733 switch (chunk.Kind) {
1734 case DeclaratorChunk::Paren:
1735 // Ignore parens.
1736 break;
1737
1738 case DeclaratorChunk::Reference:
1739 case DeclaratorChunk::Pointer:
1740 // Count the number of pointers. Treat references
1741 // interchangeably as pointers; if they're mis-ordered, normal
1742 // type building will discover that.
1743 outermostPointerIndex = chunkIndex;
1744 numPointers++;
1745 break;
1746
1747 case DeclaratorChunk::BlockPointer:
1748 // If we have a pointer to block pointer, that's an acceptable
1749 // indirect reference; anything else is not an application of
1750 // the rules.
1751 if (numPointers != 1) return;
1752 numPointers++;
1753 outermostPointerIndex = chunkIndex;
1754 isBlockPointer = true;
1755
1756 // We don't care about pointer structure in return values here.
1757 goto done;
1758
1759 case DeclaratorChunk::Array: // suppress if written (id[])?
1760 case DeclaratorChunk::Function:
1761 case DeclaratorChunk::MemberPointer:
1762 return;
1763 }
1764 }
1765 done:
1766
1767 // If we have *one* pointer, then we want to throw the qualifier on
1768 // the declaration-specifiers, which means that it needs to be a
1769 // retainable object type.
1770 if (numPointers == 1) {
1771 // If it's not a retainable object type, the rule doesn't apply.
1772 if (!declSpecType->isObjCRetainableType()) return;
1773
1774 // If it already has lifetime, don't do anything.
1775 if (declSpecType.getObjCLifetime()) return;
1776
1777 // Otherwise, modify the type in-place.
1778 Qualifiers qs;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001779
John McCallf85e1932011-06-15 23:02:42 +00001780 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1781 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1782 else
1783 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1784 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1785
1786 // If we have *two* pointers, then we want to throw the qualifier on
1787 // the outermost pointer.
1788 } else if (numPointers == 2) {
1789 // If we don't have a block pointer, we need to check whether the
1790 // declaration-specifiers gave us something that will turn into a
1791 // retainable object pointer after we slap the first pointer on it.
1792 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1793 return;
1794
1795 // Look for an explicit lifetime attribute there.
1796 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
Argyrios Kyrtzidis1c73dcb2011-07-01 22:23:03 +00001797 if (chunk.Kind != DeclaratorChunk::Pointer &&
1798 chunk.Kind != DeclaratorChunk::BlockPointer)
1799 return;
John McCallf85e1932011-06-15 23:02:42 +00001800 for (const AttributeList *attr = chunk.getAttrs(); attr;
1801 attr = attr->getNext())
Sean Hunt8e083e72012-06-19 23:57:03 +00001802 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
John McCallf85e1932011-06-15 23:02:42 +00001803 return;
1804
Argyrios Kyrtzidisa8349f52011-07-01 22:23:05 +00001805 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1806 outermostPointerIndex);
John McCallf85e1932011-06-15 23:02:42 +00001807
1808 // Any other number of pointers/references does not trigger the rule.
1809 } else return;
1810
1811 // TODO: mark whether we did this inference?
1812}
1813
Chandler Carruthd067c072011-02-23 18:51:59 +00001814static void DiagnoseIgnoredQualifiers(unsigned Quals,
1815 SourceLocation ConstQualLoc,
1816 SourceLocation VolatileQualLoc,
1817 SourceLocation RestrictQualLoc,
1818 Sema& S) {
1819 std::string QualStr;
1820 unsigned NumQuals = 0;
1821 SourceLocation Loc;
1822
1823 FixItHint ConstFixIt;
1824 FixItHint VolatileFixIt;
1825 FixItHint RestrictFixIt;
1826
Hans Wennborga08fcb82011-06-03 17:37:26 +00001827 const SourceManager &SM = S.getSourceManager();
1828
Chandler Carruthd067c072011-02-23 18:51:59 +00001829 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1830 // find a range and grow it to encompass all the qualifiers, regardless of
1831 // the order in which they textually appear.
1832 if (Quals & Qualifiers::Const) {
1833 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
Chandler Carruthd067c072011-02-23 18:51:59 +00001834 QualStr = "const";
Hans Wennborga08fcb82011-06-03 17:37:26 +00001835 ++NumQuals;
1836 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1837 Loc = ConstQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001838 }
1839 if (Quals & Qualifiers::Volatile) {
1840 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001841 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
Chandler Carruthd067c072011-02-23 18:51:59 +00001842 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001843 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1844 Loc = VolatileQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001845 }
1846 if (Quals & Qualifiers::Restrict) {
1847 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
Hans Wennborga08fcb82011-06-03 17:37:26 +00001848 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
Chandler Carruthd067c072011-02-23 18:51:59 +00001849 ++NumQuals;
Hans Wennborga08fcb82011-06-03 17:37:26 +00001850 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1851 Loc = RestrictQualLoc;
Chandler Carruthd067c072011-02-23 18:51:59 +00001852 }
1853
1854 assert(NumQuals > 0 && "No known qualifiers?");
1855
1856 S.Diag(Loc, diag::warn_qual_return_type)
Hans Wennborga08fcb82011-06-03 17:37:26 +00001857 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
Chandler Carruthd067c072011-02-23 18:51:59 +00001858}
1859
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001860static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1861 TypeSourceInfo *&ReturnTypeInfo) {
1862 Sema &SemaRef = state.getSema();
1863 Declarator &D = state.getDeclarator();
Douglas Gregor930d8b52009-01-30 22:09:00 +00001864 QualType T;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001865 ReturnTypeInfo = 0;
1866
1867 // The TagDecl owned by the DeclSpec.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001868 TagDecl *OwnedTagDecl = 0;
John McCall711c52b2011-01-05 12:14:39 +00001869
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001870 switch (D.getName().getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00001871 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001872 case UnqualifiedId::IK_OperatorFunctionId:
Sebastian Redl8999fe12011-03-14 18:08:30 +00001873 case UnqualifiedId::IK_Identifier:
Sean Hunt0486d742009-11-28 04:44:28 +00001874 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001875 case UnqualifiedId::IK_TemplateId:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001876 T = ConvertDeclSpecToType(state);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001877
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001878 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001879 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
Abramo Bagnara15987972011-03-08 22:33:38 +00001880 // Owned declaration is embedded in declarator.
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00001881 OwnedTagDecl->setEmbeddedInDeclarator(true);
Douglas Gregor591bd3c2010-02-08 22:07:33 +00001882 }
Douglas Gregor930d8b52009-01-30 22:09:00 +00001883 break;
1884
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001885 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00001886 case UnqualifiedId::IK_ConstructorTemplateId:
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001887 case UnqualifiedId::IK_DestructorName:
Douglas Gregor930d8b52009-01-30 22:09:00 +00001888 // Constructors and destructors don't have return types. Use
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001889 // "void" instead.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001890 T = SemaRef.Context.VoidTy;
Rafael Espindolaa78a6402012-07-31 01:54:04 +00001891 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
Richard Smithf7a05272013-01-14 07:53:01 +00001892 processTypeAttrs(state, T, TAL_DeclSpec, attrs);
Douglas Gregor930d8b52009-01-30 22:09:00 +00001893 break;
Douglas Gregor48026d22010-01-11 18:40:55 +00001894
1895 case UnqualifiedId::IK_ConversionFunctionId:
1896 // The result type of a conversion function is the type that it
1897 // converts to.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00001898 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001899 &ReturnTypeInfo);
Douglas Gregor48026d22010-01-11 18:40:55 +00001900 break;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001901 }
Douglas Gregordab60ad2010-10-01 18:44:50 +00001902
John McCall711c52b2011-01-05 12:14:39 +00001903 if (D.getAttributes())
1904 distributeTypeAttrsFromDeclarator(state, T);
1905
Richard Smithd37b3602012-02-10 11:05:11 +00001906 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1907 // In C++11, a function declarator using 'auto' must have a trailing return
Richard Smith8110f042011-02-22 01:22:29 +00001908 // type (this is checked later) and we can skip this. In other languages
1909 // using auto, we need to check regardless.
Richard Smith34b41d92011-02-20 03:19:35 +00001910 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Richard Smith80ad52f2013-01-02 11:42:31 +00001911 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001912 int Error = -1;
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001914 switch (D.getContext()) {
1915 case Declarator::KNRTypeListContext:
David Blaikieb219cfc2011-09-23 05:06:16 +00001916 llvm_unreachable("K&R type lists aren't allowed in C++");
Eli Friedmanf88c4002012-01-04 04:41:38 +00001917 case Declarator::LambdaExprContext:
1918 llvm_unreachable("Can't specify a type specifier in lambda grammar");
John McCallcdda47f2011-10-01 09:56:14 +00001919 case Declarator::ObjCParameterContext:
1920 case Declarator::ObjCResultContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001921 case Declarator::PrototypeContext:
1922 Error = 0; // Function prototype
1923 break;
1924 case Declarator::MemberContext:
Richard Smith7a614d82011-06-11 17:19:42 +00001925 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1926 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001927 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
David Blaikieeb2d1f12011-09-23 20:26:49 +00001928 case TTK_Enum: llvm_unreachable("unhandled tag kind");
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001929 case TTK_Struct: Error = 1; /* Struct member */ break;
1930 case TTK_Union: Error = 2; /* Union member */ break;
1931 case TTK_Class: Error = 3; /* Class member */ break;
Joao Matos6666ed42012-08-31 18:45:21 +00001932 case TTK_Interface: Error = 4; /* Interface member */ break;
Mike Stump1eb44332009-09-09 15:08:12 +00001933 }
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001934 break;
1935 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00001936 case Declarator::ObjCCatchContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001937 Error = 5; // Exception declaration
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001938 break;
1939 case Declarator::TemplateParamContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001940 Error = 6; // Template parameter
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001941 break;
1942 case Declarator::BlockLiteralContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001943 Error = 7; // Block literal
Richard Smith34b41d92011-02-20 03:19:35 +00001944 break;
1945 case Declarator::TemplateTypeArgContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001946 Error = 8; // Template type argument
Richard Smith34b41d92011-02-20 03:19:35 +00001947 break;
Richard Smith162e1c12011-04-15 14:24:37 +00001948 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00001949 case Declarator::AliasTemplateContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001950 Error = 10; // Type alias
Richard Smith162e1c12011-04-15 14:24:37 +00001951 break;
Richard Smith7796eb52012-03-12 08:56:40 +00001952 case Declarator::TrailingReturnContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001953 Error = 11; // Function return type
Richard Smith7796eb52012-03-12 08:56:40 +00001954 break;
Richard Smith34b41d92011-02-20 03:19:35 +00001955 case Declarator::TypeNameContext:
Joao Matos6666ed42012-08-31 18:45:21 +00001956 Error = 12; // Generic
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001957 break;
1958 case Declarator::FileContext:
1959 case Declarator::BlockContext:
1960 case Declarator::ForContext:
1961 case Declarator::ConditionContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001962 case Declarator::CXXNewContext:
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001963 break;
1964 }
1965
Richard Smithddc83f92011-02-21 23:18:00 +00001966 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
Joao Matos6666ed42012-08-31 18:45:21 +00001967 Error = 9;
Richard Smithddc83f92011-02-21 23:18:00 +00001968
Richard Smith8110f042011-02-22 01:22:29 +00001969 // In Objective-C it is an error to use 'auto' on a function declarator.
1970 if (D.isFunctionDeclarator())
Joao Matos6666ed42012-08-31 18:45:21 +00001971 Error = 11;
Richard Smith8110f042011-02-22 01:22:29 +00001972
Richard Smithd37b3602012-02-10 11:05:11 +00001973 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
Richard Smithe7397c62011-02-22 00:36:53 +00001974 // contains a trailing return type. That is only legal at the outermost
1975 // level. Check all declarator chunks (outermost first) anyway, to give
1976 // better diagnostics.
Richard Smith80ad52f2013-01-02 11:42:31 +00001977 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
Richard Smithe7397c62011-02-22 00:36:53 +00001978 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1979 unsigned chunkIndex = e - i - 1;
1980 state.setCurrentChunkIndex(chunkIndex);
1981 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1982 if (DeclType.Kind == DeclaratorChunk::Function) {
1983 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Richard Smith54655be2012-06-12 01:51:59 +00001984 if (FTI.hasTrailingReturnType()) {
Richard Smithe7397c62011-02-22 00:36:53 +00001985 Error = -1;
1986 break;
1987 }
1988 }
1989 }
1990 }
1991
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001992 if (Error != -1) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001993 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1994 diag::err_auto_not_allowed)
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001995 << Error;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00001996 T = SemaRef.Context.IntTy;
Anders Carlssonbaf45d32009-06-26 22:18:59 +00001997 D.setInvalidType(true);
Richard Smith0aa86c02011-10-15 05:42:01 +00001998 } else
1999 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2000 diag::warn_cxx98_compat_auto_type_specifier);
Anders Carlssonbaf45d32009-06-26 22:18:59 +00002001 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002002
David Blaikie4e4d0842012-03-11 07:00:24 +00002003 if (SemaRef.getLangOpts().CPlusPlus &&
John McCall5e1cdac2011-10-07 06:10:15 +00002004 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002005 // Check the contexts where C++ forbids the declaration of a new class
2006 // or enumeration in a type-specifier-seq.
2007 switch (D.getContext()) {
Richard Smith7796eb52012-03-12 08:56:40 +00002008 case Declarator::TrailingReturnContext:
2009 // Class and enumeration definitions are syntactically not allowed in
2010 // trailing return types.
2011 llvm_unreachable("parser should not have allowed this");
2012 break;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002013 case Declarator::FileContext:
2014 case Declarator::MemberContext:
2015 case Declarator::BlockContext:
2016 case Declarator::ForContext:
2017 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00002018 case Declarator::LambdaExprContext:
Richard Smithd37b3602012-02-10 11:05:11 +00002019 // C++11 [dcl.type]p3:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002020 // A type-specifier-seq shall not define a class or enumeration unless
2021 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2022 // the declaration of a template-declaration.
2023 case Declarator::AliasDeclContext:
2024 break;
2025 case Declarator::AliasTemplateContext:
2026 SemaRef.Diag(OwnedTagDecl->getLocation(),
2027 diag::err_type_defined_in_alias_template)
2028 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002029 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002030 break;
2031 case Declarator::TypeNameContext:
2032 case Declarator::TemplateParamContext:
2033 case Declarator::CXXNewContext:
2034 case Declarator::CXXCatchContext:
2035 case Declarator::ObjCCatchContext:
2036 case Declarator::TemplateTypeArgContext:
2037 SemaRef.Diag(OwnedTagDecl->getLocation(),
2038 diag::err_type_defined_in_type_specifier)
2039 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002040 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002041 break;
2042 case Declarator::PrototypeContext:
John McCallcdda47f2011-10-01 09:56:14 +00002043 case Declarator::ObjCParameterContext:
2044 case Declarator::ObjCResultContext:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002045 case Declarator::KNRTypeListContext:
2046 // C++ [dcl.fct]p6:
2047 // Types shall not be defined in return or parameter types.
2048 SemaRef.Diag(OwnedTagDecl->getLocation(),
2049 diag::err_type_defined_in_param_type)
2050 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002051 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002052 break;
2053 case Declarator::ConditionContext:
2054 // C++ 6.4p2:
2055 // The type-specifier-seq shall not contain typedef and shall not declare
2056 // a new class or enumeration.
2057 SemaRef.Diag(OwnedTagDecl->getLocation(),
2058 diag::err_type_defined_in_condition);
Enea Zaffanella601e6e82013-01-11 14:34:39 +00002059 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002060 break;
2061 }
2062 }
2063
2064 return T;
2065}
2066
Benjamin Kramera08c2fb2012-02-24 22:19:42 +00002067static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
Richard Smithd37b3602012-02-10 11:05:11 +00002068 std::string Quals =
2069 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2070
2071 switch (FnTy->getRefQualifier()) {
2072 case RQ_None:
2073 break;
2074
2075 case RQ_LValue:
2076 if (!Quals.empty())
2077 Quals += ' ';
2078 Quals += '&';
2079 break;
2080
2081 case RQ_RValue:
2082 if (!Quals.empty())
2083 Quals += ' ';
2084 Quals += "&&";
2085 break;
2086 }
2087
2088 return Quals;
2089}
2090
2091/// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
2092/// can be contained within the declarator chunk DeclType, and produce an
2093/// appropriate diagnostic if not.
2094static void checkQualifiedFunction(Sema &S, QualType T,
2095 DeclaratorChunk &DeclType) {
2096 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
2097 // cv-qualifier or a ref-qualifier can only appear at the topmost level
2098 // of a type.
2099 int DiagKind = -1;
2100 switch (DeclType.Kind) {
2101 case DeclaratorChunk::Paren:
2102 case DeclaratorChunk::MemberPointer:
2103 // These cases are permitted.
2104 return;
2105 case DeclaratorChunk::Array:
2106 case DeclaratorChunk::Function:
2107 // These cases don't allow function types at all; no need to diagnose the
2108 // qualifiers separately.
2109 return;
2110 case DeclaratorChunk::BlockPointer:
2111 DiagKind = 0;
2112 break;
2113 case DeclaratorChunk::Pointer:
2114 DiagKind = 1;
2115 break;
2116 case DeclaratorChunk::Reference:
2117 DiagKind = 2;
2118 break;
2119 }
2120
2121 assert(DiagKind != -1);
2122 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
2123 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
2124 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
2125}
2126
Richard Smithb9c62612012-07-30 21:30:52 +00002127/// Produce an approprioate diagnostic for an ambiguity between a function
2128/// declarator and a C++ direct-initializer.
2129static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2130 DeclaratorChunk &DeclType, QualType RT) {
2131 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2132 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2133
2134 // If the return type is void there is no ambiguity.
2135 if (RT->isVoidType())
2136 return;
2137
2138 // An initializer for a non-class type can have at most one argument.
2139 if (!RT->isRecordType() && FTI.NumArgs > 1)
2140 return;
2141
2142 // An initializer for a reference must have exactly one argument.
2143 if (RT->isReferenceType() && FTI.NumArgs != 1)
2144 return;
2145
2146 // Only warn if this declarator is declaring a function at block scope, and
2147 // doesn't have a storage class (such as 'extern') specified.
2148 if (!D.isFunctionDeclarator() ||
2149 D.getFunctionDefinitionKind() != FDK_Declaration ||
2150 !S.CurContext->isFunctionOrMethod() ||
2151 D.getDeclSpec().getStorageClassSpecAsWritten()
2152 != DeclSpec::SCS_unspecified)
2153 return;
2154
2155 // Inside a condition, a direct initializer is not permitted. We allow one to
2156 // be parsed in order to give better diagnostics in condition parsing.
2157 if (D.getContext() == Declarator::ConditionContext)
2158 return;
2159
2160 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2161
Richard Smithd64effc2012-07-30 21:42:05 +00002162 S.Diag(DeclType.Loc,
2163 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration
2164 : diag::warn_empty_parens_are_function_decl)
2165 << ParenRange;
Richard Smithb9c62612012-07-30 21:30:52 +00002166
Richard Smithd64effc2012-07-30 21:42:05 +00002167 // If the declaration looks like:
2168 // T var1,
2169 // f();
2170 // and name lookup finds a function named 'f', then the ',' was
2171 // probably intended to be a ';'.
2172 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2173 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2174 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2175 if (Comma.getFileID() != Name.getFileID() ||
2176 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2177 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2178 Sema::LookupOrdinaryName);
2179 if (S.LookupName(Result, S.getCurScope()))
2180 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2181 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2182 << D.getIdentifier();
2183 }
2184 }
2185
2186 if (FTI.NumArgs > 0) {
2187 // For a declaration with parameters, eg. "T var(T());", suggest adding parens
2188 // around the first parameter to turn the declaration into a variable
2189 // declaration.
Richard Smithb9c62612012-07-30 21:30:52 +00002190 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange();
2191 SourceLocation B = Range.getBegin();
2192 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd());
2193 // FIXME: Maybe we should suggest adding braces instead of parens
2194 // in C++11 for classes that don't have an initializer_list constructor.
2195 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2196 << FixItHint::CreateInsertion(B, "(")
2197 << FixItHint::CreateInsertion(E, ")");
Richard Smithd64effc2012-07-30 21:42:05 +00002198 } else {
2199 // For a declaration without parameters, eg. "T var();", suggest replacing the
2200 // parens with an initializer to turn the declaration into a variable
2201 // declaration.
Richard Smithb9c62612012-07-30 21:30:52 +00002202 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Richard Smithd64effc2012-07-30 21:42:05 +00002203
Richard Smithb9c62612012-07-30 21:30:52 +00002204 // Empty parens mean value-initialization, and no parens mean
2205 // default initialization. These are equivalent if the default
2206 // constructor is user-provided or if zero-initialization is a
2207 // no-op.
2208 if (RD && RD->hasDefinition() &&
2209 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2210 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2211 << FixItHint::CreateRemoval(ParenRange);
2212 else {
2213 std::string Init = S.getFixItZeroInitializerForType(RT);
Richard Smith80ad52f2013-01-02 11:42:31 +00002214 if (Init.empty() && S.LangOpts.CPlusPlus11)
Richard Smithb9c62612012-07-30 21:30:52 +00002215 Init = "{}";
2216 if (!Init.empty())
2217 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2218 << FixItHint::CreateReplacement(ParenRange, Init);
2219 }
2220 }
2221}
2222
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002223static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2224 QualType declSpecType,
2225 TypeSourceInfo *TInfo) {
2226
2227 QualType T = declSpecType;
2228 Declarator &D = state.getDeclarator();
2229 Sema &S = state.getSema();
2230 ASTContext &Context = S.Context;
David Blaikie4e4d0842012-03-11 07:00:24 +00002231 const LangOptions &LangOpts = S.getLangOpts();
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002232
Douglas Gregorcd281c32009-02-28 00:25:32 +00002233 // The name we're declaring, if any.
2234 DeclarationName Name;
2235 if (D.getIdentifier())
2236 Name = D.getIdentifier();
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Richard Smith162e1c12011-04-15 14:24:37 +00002238 // Does this declaration declare a typedef-name?
2239 bool IsTypedefName =
2240 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
Richard Smith3e4c6c42011-05-05 21:57:07 +00002241 D.getContext() == Declarator::AliasDeclContext ||
2242 D.getContext() == Declarator::AliasTemplateContext;
Richard Smith162e1c12011-04-15 14:24:37 +00002243
Richard Smithd37b3602012-02-10 11:05:11 +00002244 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2245 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2246 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2247 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2248
Mike Stump98eb8a72009-02-04 22:31:32 +00002249 // Walk the DeclTypeInfo, building the recursive type as we go.
2250 // DeclTypeInfos are ordered from the identifier out, which is
2251 // opposite of what we want :).
Sebastian Redl8ce35b02009-10-25 21:45:37 +00002252 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall711c52b2011-01-05 12:14:39 +00002253 unsigned chunkIndex = e - i - 1;
2254 state.setCurrentChunkIndex(chunkIndex);
2255 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
Richard Smithd37b3602012-02-10 11:05:11 +00002256 if (IsQualifiedFunction) {
2257 checkQualifiedFunction(S, T, DeclType);
2258 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
2259 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002260 switch (DeclType.Kind) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002261 case DeclaratorChunk::Paren:
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002262 T = S.BuildParenType(T);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002263 break;
Steve Naroff5618bd42008-08-27 16:04:49 +00002264 case DeclaratorChunk::BlockPointer:
Chris Lattner9af55002009-03-27 04:18:06 +00002265 // If blocks are disabled, emit an error.
2266 if (!LangOpts.Blocks)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002267 S.Diag(DeclType.Loc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002269 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
John McCall28654742010-06-05 06:41:15 +00002270 if (DeclType.Cls.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002271 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
Steve Naroff5618bd42008-08-27 16:04:49 +00002272 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002273 case DeclaratorChunk::Pointer:
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002274 // Verify that we're not building a pointer to pointer to function with
2275 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002276 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2277 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002278 D.setInvalidType(true);
2279 // Build the type anyway.
2280 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002281 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
John McCallc12c5bb2010-05-15 11:32:37 +00002282 T = Context.getObjCObjectPointerType(T);
John McCall28654742010-06-05 06:41:15 +00002283 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002284 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
Steve Naroff14108da2009-07-10 23:34:53 +00002285 break;
2286 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002287 T = S.BuildPointerType(T, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002288 if (DeclType.Ptr.TypeQuals)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002289 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
John McCall711c52b2011-01-05 12:14:39 +00002290
Reid Spencer5f016e22007-07-11 17:01:13 +00002291 break;
John McCall0953e762009-09-24 19:53:00 +00002292 case DeclaratorChunk::Reference: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002293 // Verify that we're not building a reference to pointer to function with
2294 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002295 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2296 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002297 D.setInvalidType(true);
2298 // Build the type anyway.
2299 }
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002300 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
John McCall28654742010-06-05 06:41:15 +00002301
2302 Qualifiers Quals;
2303 if (DeclType.Ref.HasRestrict)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002304 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
Reid Spencer5f016e22007-07-11 17:01:13 +00002305 break;
John McCall0953e762009-09-24 19:53:00 +00002306 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 case DeclaratorChunk::Array: {
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002308 // Verify that we're not building an array of pointers to function with
2309 // exception specification.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002310 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2311 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
Sebastian Redl6a7330c2009-05-29 15:01:05 +00002312 D.setInvalidType(true);
2313 // Build the type anyway.
2314 }
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002315 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
Chris Lattner94f81fd2007-08-28 16:54:00 +00002316 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
Reid Spencer5f016e22007-07-11 17:01:13 +00002317 ArrayType::ArraySizeModifier ASM;
2318 if (ATI.isStar)
2319 ASM = ArrayType::Star;
2320 else if (ATI.hasStatic)
2321 ASM = ArrayType::Static;
2322 else
2323 ASM = ArrayType::Normal;
John McCallc05a94b2011-03-23 23:43:04 +00002324 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002325 // FIXME: This check isn't quite right: it allows star in prototypes
2326 // for function definitions, and disallows some edge cases detailed
2327 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002328 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
Eli Friedmanf91f5c82009-04-26 21:57:51 +00002329 ASM = ArrayType::Normal;
2330 D.setInvalidType(true);
2331 }
Hans Wennborg7f397c52012-08-15 07:42:30 +00002332
2333 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2334 // shall appear only in a declaration of a function parameter with an
2335 // array type, ...
2336 if (ASM == ArrayType::Static || ATI.TypeQuals) {
Matt Beaumont-Gay99570a52012-08-15 19:53:19 +00002337 if (!(D.isPrototypeContext() ||
2338 D.getContext() == Declarator::KNRTypeListContext)) {
Hans Wennborg7f397c52012-08-15 07:42:30 +00002339 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2340 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2341 // Remove the 'static' and the type qualifiers.
2342 if (ASM == ArrayType::Static)
2343 ASM = ArrayType::Normal;
2344 ATI.TypeQuals = 0;
2345 D.setInvalidType(true);
2346 }
2347
2348 // C99 6.7.5.2p1: ... and then only in the outermost array type
2349 // derivation.
2350 unsigned x = chunkIndex;
2351 while (x != 0) {
2352 // Walk outwards along the declarator chunks.
2353 x--;
2354 const DeclaratorChunk &DC = D.getTypeObject(x);
2355 switch (DC.Kind) {
2356 case DeclaratorChunk::Paren:
2357 continue;
2358 case DeclaratorChunk::Array:
2359 case DeclaratorChunk::Pointer:
2360 case DeclaratorChunk::Reference:
2361 case DeclaratorChunk::MemberPointer:
2362 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2363 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2364 if (ASM == ArrayType::Static)
2365 ASM = ArrayType::Normal;
2366 ATI.TypeQuals = 0;
2367 D.setInvalidType(true);
2368 break;
2369 case DeclaratorChunk::Function:
2370 case DeclaratorChunk::BlockPointer:
2371 // These are invalid anyway, so just ignore.
2372 break;
2373 }
2374 }
2375 }
2376
Eli Friedman8ac2c662011-11-11 02:00:42 +00002377 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002378 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 break;
2380 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002381 case DeclaratorChunk::Function: {
Reid Spencer5f016e22007-07-11 17:01:13 +00002382 // If the function declarator has a prototype (i.e. it is not () and
2383 // does not have a K&R-style identifier list), then the arguments are part
2384 // of the type, otherwise the argument list is ().
2385 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
Richard Smithd37b3602012-02-10 11:05:11 +00002386 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
Sebastian Redl3cc97262009-05-31 11:47:27 +00002387
Richard Smithe7397c62011-02-22 00:36:53 +00002388 // Check for auto functions and trailing return type and adjust the
2389 // return type accordingly.
2390 if (!D.isInvalidType()) {
2391 // trailing-return-type is only required if we're declaring a function,
2392 // and not, for instance, a pointer to a function.
2393 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
Richard Smith54655be2012-06-12 01:51:59 +00002394 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002395 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002396 diag::err_auto_missing_trailing_return);
2397 T = Context.IntTy;
2398 D.setInvalidType(true);
Richard Smith54655be2012-06-12 01:51:59 +00002399 } else if (FTI.hasTrailingReturnType()) {
Richard Smithe7397c62011-02-22 00:36:53 +00002400 // T must be exactly 'auto' at this point. See CWG issue 681.
2401 if (isa<ParenType>(T)) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002402 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002403 diag::err_trailing_return_in_parens)
2404 << T << D.getDeclSpec().getSourceRange();
2405 D.setInvalidType(true);
Eli Friedmanf88c4002012-01-04 04:41:38 +00002406 } else if (D.getContext() != Declarator::LambdaExprContext &&
2407 (T.hasQualifiers() || !isa<AutoType>(T))) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002408 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
Richard Smithe7397c62011-02-22 00:36:53 +00002409 diag::err_trailing_return_without_auto)
2410 << T << D.getDeclSpec().getSourceRange();
2411 D.setInvalidType(true);
2412 }
Richard Smith54655be2012-06-12 01:51:59 +00002413 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2414 if (T.isNull()) {
2415 // An error occurred parsing the trailing return type.
2416 T = Context.IntTy;
2417 D.setInvalidType(true);
2418 }
Richard Smithe7397c62011-02-22 00:36:53 +00002419 }
2420 }
2421
Chris Lattnercd881292007-12-19 05:31:29 +00002422 // C99 6.7.5.3p1: The return type may not be a function or array type.
Douglas Gregor58408bc2010-01-11 18:46:21 +00002423 // For conversion functions, we'll diagnose this particular error later.
Douglas Gregor48026d22010-01-11 18:40:55 +00002424 if ((T->isArrayType() || T->isFunctionType()) &&
2425 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002426 unsigned diagID = diag::err_func_returning_array_function;
Argyrios Kyrtzidisa4356ad2011-01-26 01:26:44 +00002427 // Last processing chunk in block context means this function chunk
2428 // represents the block.
2429 if (chunkIndex == 0 &&
2430 D.getContext() == Declarator::BlockLiteralContext)
Argyrios Kyrtzidis98650442011-01-25 23:16:33 +00002431 diagID = diag::err_block_returning_array_function;
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002432 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
Chris Lattnercd881292007-12-19 05:31:29 +00002433 T = Context.IntTy;
2434 D.setInvalidType(true);
2435 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002436
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002437 // Do not allow returning half FP value.
2438 // FIXME: This really should be in BuildFunctionType.
2439 if (T->isHalfType()) {
2440 S.Diag(D.getIdentifierLoc(),
2441 diag::err_parameters_retval_cannot_have_fp16_type) << 1
2442 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
2443 D.setInvalidType(true);
2444 }
2445
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002446 // cv-qualifiers on return types are pointless except when the type is a
2447 // class type in C++.
Douglas Gregorfff95132011-03-01 17:04:42 +00002448 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
Rafael Espindola1e153942011-03-11 04:56:58 +00002449 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002450 (!LangOpts.CPlusPlus || !T->isDependentType())) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002451 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2452 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2453 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2454
2455 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2456
2457 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2458 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2459 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2460 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002461 S);
Chandler Carruthd067c072011-02-23 18:51:59 +00002462
2463 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002464 (!LangOpts.CPlusPlus ||
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002465 (!T->isDependentType() && !T->isRecordType()))) {
Chandler Carruthd067c072011-02-23 18:51:59 +00002466
2467 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2468 D.getDeclSpec().getConstSpecLoc(),
2469 D.getDeclSpec().getVolatileSpecLoc(),
2470 D.getDeclSpec().getRestrictSpecLoc(),
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002471 S);
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002472 }
Chandler Carruthd067c072011-02-23 18:51:59 +00002473
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002474 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
Douglas Gregor402abb52009-05-28 23:31:59 +00002475 // C++ [dcl.fct]p6:
2476 // Types shall not be defined in return or parameter types.
John McCallb3d87482010-08-24 05:47:05 +00002477 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
John McCall5e1cdac2011-10-07 06:10:15 +00002478 if (Tag->isCompleteDefinition())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002479 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
Douglas Gregor402abb52009-05-28 23:31:59 +00002480 << Context.getTypeDeclType(Tag);
2481 }
2482
Sebastian Redl3cc97262009-05-31 11:47:27 +00002483 // Exception specs are not allowed in typedefs. Complain, but add it
2484 // anyway.
Richard Smith162e1c12011-04-15 14:24:37 +00002485 if (IsTypedefName && FTI.getExceptionSpecType())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002486 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
Richard Smith3e4c6c42011-05-05 21:57:07 +00002487 << (D.getContext() == Declarator::AliasDeclContext ||
2488 D.getContext() == Declarator::AliasTemplateContext);
Sebastian Redl3cc97262009-05-31 11:47:27 +00002489
Richard Smithb9c62612012-07-30 21:30:52 +00002490 // If we see "T var();" or "T var(T());" at block scope, it is probably
2491 // an attempt to initialize a variable, not a function declaration.
2492 if (FTI.isAmbiguous)
2493 warnAboutAmbiguousFunction(S, D, DeclType, T);
2494
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002495 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
John McCall28654742010-06-05 06:41:15 +00002496 // Simple void foo(), where the incoming T is the result type.
2497 T = Context.getFunctionNoProtoType(T);
2498 } else {
2499 // We allow a zero-parameter variadic function in C if the
2500 // function is marked with the "overloadable" attribute. Scan
2501 // for this attribute now.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002502 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002503 bool Overloadable = false;
2504 for (const AttributeList *Attrs = D.getAttributes();
2505 Attrs; Attrs = Attrs->getNext()) {
Sean Hunt8e083e72012-06-19 23:57:03 +00002506 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
Douglas Gregor965acbb2009-02-18 07:07:28 +00002507 Overloadable = true;
2508 break;
2509 }
2510 }
2511
2512 if (!Overloadable)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002513 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
Argyrios Kyrtzidisc6f73452008-10-16 17:31:08 +00002514 }
John McCall28654742010-06-05 06:41:15 +00002515
2516 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002517 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2518 // definition.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002519 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
John McCall28654742010-06-05 06:41:15 +00002520 D.setInvalidType(true);
2521 break;
2522 }
2523
John McCalle23cf432010-12-14 08:05:40 +00002524 FunctionProtoType::ExtProtoInfo EPI;
2525 EPI.Variadic = FTI.isVariadic;
Richard Smith54655be2012-06-12 01:51:59 +00002526 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
John McCalle23cf432010-12-14 08:05:40 +00002527 EPI.TypeQuals = FTI.TypeQuals;
Douglas Gregorc938c162011-01-26 05:01:58 +00002528 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2529 : FTI.RefQualifierIsLValueRef? RQ_LValue
2530 : RQ_RValue;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002531
Reid Spencer5f016e22007-07-11 17:01:13 +00002532 // Otherwise, we have a function with an argument list that is
2533 // potentially variadic.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002534 SmallVector<QualType, 16> ArgTys;
John McCall28654742010-06-05 06:41:15 +00002535 ArgTys.reserve(FTI.NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Chris Lattner5f9e2722011-07-23 10:55:15 +00002537 SmallVector<bool, 16> ConsumedArguments;
John McCallf85e1932011-06-15 23:02:42 +00002538 ConsumedArguments.reserve(FTI.NumArgs);
2539 bool HasAnyConsumedArguments = false;
2540
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00002542 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Chris Lattner8123a952008-04-10 02:22:51 +00002543 QualType ArgTy = Param->getType();
Chris Lattner78c75fb2007-07-21 05:30:18 +00002544 assert(!ArgTy.isNull() && "Couldn't parse type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002545
2546 // Adjust the parameter type.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002547 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
Douglas Gregor79e6bd32011-07-12 04:42:08 +00002548 "Unadjusted type?");
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002549
Reid Spencer5f016e22007-07-11 17:01:13 +00002550 // Look for 'void'. void is allowed only as a single argument to a
2551 // function with no other parameters (C99 6.7.5.3p10). We record
Douglas Gregor72564e72009-02-26 23:50:07 +00002552 // int(void) as a FunctionProtoType with an empty argument list.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002553 if (ArgTy->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002554 // If this is something like 'float(int, void)', reject it. 'void'
2555 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2556 // have arguments of incomplete type.
2557 if (FTI.NumArgs != 1 || FTI.isVariadic) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002558 S.Diag(DeclType.Loc, diag::err_void_only_param);
Chris Lattner2ff54262007-07-21 05:18:12 +00002559 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002560 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002561 } else if (FTI.ArgInfo[i].Ident) {
2562 // Reject, but continue to parse 'int(void abc)'.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002563 S.Diag(FTI.ArgInfo[i].IdentLoc,
Chris Lattner4565d4e2007-07-21 05:26:43 +00002564 diag::err_param_with_void_type);
Chris Lattner2ff54262007-07-21 05:18:12 +00002565 ArgTy = Context.IntTy;
Chris Lattner8123a952008-04-10 02:22:51 +00002566 Param->setType(ArgTy);
Chris Lattner2ff54262007-07-21 05:18:12 +00002567 } else {
2568 // Reject, but continue to parse 'float(const void)'.
John McCall0953e762009-09-24 19:53:00 +00002569 if (ArgTy.hasQualifiers())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002570 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
Mike Stump1eb44332009-09-09 15:08:12 +00002571
Chris Lattner2ff54262007-07-21 05:18:12 +00002572 // Do not add 'void' to the ArgTys list.
2573 break;
2574 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002575 } else if (ArgTy->isHalfType()) {
2576 // Disallow half FP arguments.
2577 // FIXME: This really should be in BuildFunctionType.
2578 S.Diag(Param->getLocation(),
2579 diag::err_parameters_retval_cannot_have_fp16_type) << 0
2580 << FixItHint::CreateInsertion(Param->getLocation(), "*");
2581 D.setInvalidType();
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002582 } else if (!FTI.hasPrototype) {
2583 if (ArgTy->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00002584 ArgTy = Context.getPromotedIntegerType(ArgTy);
John McCalleecf5fa2011-03-09 04:22:44 +00002585 Param->setKNRPromoted(true);
John McCall183700f2009-09-21 23:43:11 +00002586 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
John McCalleecf5fa2011-03-09 04:22:44 +00002587 if (BTy->getKind() == BuiltinType::Float) {
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002588 ArgTy = Context.DoubleTy;
John McCalleecf5fa2011-03-09 04:22:44 +00002589 Param->setKNRPromoted(true);
2590 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00002591 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002592 }
Fariborz Jahanian56a965c2010-09-08 21:36:35 +00002593
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002594 if (LangOpts.ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002595 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2596 ConsumedArguments.push_back(Consumed);
2597 HasAnyConsumedArguments |= Consumed;
2598 }
2599
John McCall54e14c42009-10-22 22:37:11 +00002600 ArgTys.push_back(ArgTy);
Reid Spencer5f016e22007-07-11 17:01:13 +00002601 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002602
John McCallf85e1932011-06-15 23:02:42 +00002603 if (HasAnyConsumedArguments)
2604 EPI.ConsumedArguments = ConsumedArguments.data();
2605
Chris Lattner5f9e2722011-07-23 10:55:15 +00002606 SmallVector<QualType, 4> Exceptions;
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002607 SmallVector<ParsedType, 2> DynamicExceptions;
2608 SmallVector<SourceRange, 2> DynamicExceptionRanges;
2609 Expr *NoexceptExpr = 0;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002610
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002611 if (FTI.getExceptionSpecType() == EST_Dynamic) {
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002612 // FIXME: It's rather inefficient to have to split into two vectors
2613 // here.
2614 unsigned N = FTI.NumExceptions;
2615 DynamicExceptions.reserve(N);
2616 DynamicExceptionRanges.reserve(N);
2617 for (unsigned I = 0; I != N; ++I) {
2618 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
2619 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
John McCalle23cf432010-12-14 08:05:40 +00002620 }
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002621 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002622 NoexceptExpr = FTI.NoexceptExpr;
2623 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002624
Douglas Gregor74e2fc32012-04-16 18:27:27 +00002625 S.checkExceptionSpecification(FTI.getExceptionSpecType(),
2626 DynamicExceptions,
2627 DynamicExceptionRanges,
2628 NoexceptExpr,
2629 Exceptions,
2630 EPI);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002631
John McCalle23cf432010-12-14 08:05:40 +00002632 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 }
John McCall04a67a62010-02-05 21:31:56 +00002634
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 break;
2636 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002637 case DeclaratorChunk::MemberPointer:
2638 // The scope spec must refer to a class, or be dependent.
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002639 CXXScopeSpec &SS = DeclType.Mem.Scope();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002640 QualType ClsType;
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002641 if (SS.isInvalid()) {
Jeffrey Yasskinedc28772010-04-07 23:29:58 +00002642 // Avoid emitting extra errors if we already errored on the scope.
2643 D.setInvalidType(true);
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002644 } else if (S.isDependentScopeSpecifier(SS) ||
2645 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002646 NestedNameSpecifier *NNS
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002647 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002648 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2649 switch (NNS->getKind()) {
2650 case NestedNameSpecifier::Identifier:
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002651 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002652 NNS->getAsIdentifier());
Douglas Gregor87c12c42009-11-04 16:49:01 +00002653 break;
2654
2655 case NestedNameSpecifier::Namespace:
Douglas Gregor14aba762011-02-24 02:36:08 +00002656 case NestedNameSpecifier::NamespaceAlias:
Douglas Gregor87c12c42009-11-04 16:49:01 +00002657 case NestedNameSpecifier::Global:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002658 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002659
Douglas Gregor87c12c42009-11-04 16:49:01 +00002660 case NestedNameSpecifier::TypeSpec:
2661 case NestedNameSpecifier::TypeSpecWithTemplate:
2662 ClsType = QualType(NNS->getAsType(), 0);
Abramo Bagnara91ce2c42011-03-10 10:18:27 +00002663 // Note: if the NNS has a prefix and ClsType is a nondependent
2664 // TemplateSpecializationType, then the NNS prefix is NOT included
2665 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2666 // NOTE: in particular, no wrap occurs if ClsType already is an
2667 // Elaborated, DependentName, or DependentTemplateSpecialization.
2668 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
Abramo Bagnara7bd06762010-08-13 12:56:25 +00002669 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
Douglas Gregor87c12c42009-11-04 16:49:01 +00002670 break;
2671 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002672 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002673 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
Douglas Gregor949bf692009-06-09 22:17:39 +00002674 diag::err_illegal_decl_mempointer_in_nonclass)
2675 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2676 << DeclType.Mem.Scope().getRange();
Sebastian Redlf30208a2009-01-24 21:16:55 +00002677 D.setInvalidType(true);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002678 }
2679
Douglas Gregor949bf692009-06-09 22:17:39 +00002680 if (!ClsType.isNull())
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002681 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
Douglas Gregor949bf692009-06-09 22:17:39 +00002682 if (T.isNull()) {
2683 T = Context.IntTy;
Sebastian Redlf30208a2009-01-24 21:16:55 +00002684 D.setInvalidType(true);
John McCall28654742010-06-05 06:41:15 +00002685 } else if (DeclType.Mem.TypeQuals) {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002686 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
Sebastian Redlf30208a2009-01-24 21:16:55 +00002687 }
Sebastian Redlf30208a2009-01-24 21:16:55 +00002688 break;
2689 }
2690
Douglas Gregorcd281c32009-02-28 00:25:32 +00002691 if (T.isNull()) {
2692 D.setInvalidType(true);
2693 T = Context.IntTy;
2694 }
2695
Chris Lattnerc9b346d2008-06-29 00:50:08 +00002696 // See if there are any attributes on this declarator chunk.
John McCall711c52b2011-01-05 12:14:39 +00002697 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
Richard Smithf7a05272013-01-14 07:53:01 +00002698 processTypeAttrs(state, T, TAL_DeclChunk, attrs);
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002700
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002701 if (LangOpts.CPlusPlus && T->isFunctionType()) {
John McCall183700f2009-09-21 23:43:11 +00002702 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
Chris Lattner778ed742009-10-25 17:36:50 +00002703 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002704
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002705 // C++ 8.3.5p4:
Douglas Gregor708f3b82010-10-14 22:03:51 +00002706 // A cv-qualifier-seq shall only be part of the function type
2707 // for a nonstatic member function, the function type to which a pointer
2708 // to member refers, or the top-level function type of a function typedef
2709 // declaration.
Douglas Gregor683a81f2011-01-31 16:09:46 +00002710 //
2711 // Core issue 547 also allows cv-qualifiers on function types that are
2712 // top-level template type arguments.
John McCall613ef3d2010-10-19 01:54:45 +00002713 bool FreeFunction;
2714 if (!D.getCXXScopeSpec().isSet()) {
Eli Friedman906a7e12012-01-06 03:05:34 +00002715 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
2716 D.getContext() != Declarator::LambdaExprContext) ||
John McCall613ef3d2010-10-19 01:54:45 +00002717 D.getDeclSpec().isFriendSpecified());
2718 } else {
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002719 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
John McCall613ef3d2010-10-19 01:54:45 +00002720 FreeFunction = (DC && !DC->isRecord());
2721 }
2722
Richard Smithd37b3602012-02-10 11:05:11 +00002723 // C++11 [dcl.fct]p6 (w/DR1417):
2724 // An attempt to specify a function type with a cv-qualifier-seq or a
2725 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
2726 // - the function type for a non-static member function,
2727 // - the function type to which a pointer to member refers,
2728 // - the top-level function type of a function typedef declaration or
2729 // alias-declaration,
2730 // - the type-id in the default argument of a type-parameter, or
2731 // - the type-id of a template-argument for a type-parameter
2732 if (IsQualifiedFunction &&
2733 !(!FreeFunction &&
2734 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
2735 !IsTypedefName &&
2736 D.getContext() != Declarator::TemplateTypeArgContext) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00002737 SourceLocation Loc = D.getLocStart();
Richard Smithd37b3602012-02-10 11:05:11 +00002738 SourceRange RemovalRange;
2739 unsigned I;
2740 if (D.isFunctionDeclarator(I)) {
2741 SmallVector<SourceLocation, 4> RemovalLocs;
2742 const DeclaratorChunk &Chunk = D.getTypeObject(I);
2743 assert(Chunk.Kind == DeclaratorChunk::Function);
2744 if (Chunk.Fun.hasRefQualifier())
2745 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
2746 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
2747 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
2748 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
2749 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
2750 // FIXME: We do not track the location of the __restrict qualifier.
2751 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
2752 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
2753 if (!RemovalLocs.empty()) {
2754 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002755 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
Richard Smithd37b3602012-02-10 11:05:11 +00002756 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
2757 Loc = RemovalLocs.front();
Douglas Gregorc938c162011-01-26 05:01:58 +00002758 }
2759 }
Richard Smithd37b3602012-02-10 11:05:11 +00002760
2761 S.Diag(Loc, diag::err_invalid_qualified_function_type)
2762 << FreeFunction << D.isFunctionDeclarator() << T
2763 << getFunctionQualifiersAsString(FnTy)
2764 << FixItHint::CreateRemoval(RemovalRange);
2765
2766 // Strip the cv-qualifiers and ref-qualifiers from the type.
2767 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2768 EPI.TypeQuals = 0;
2769 EPI.RefQualifier = RQ_None;
2770
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002771 T = Context.getFunctionType(FnTy->getResultType(),
Richard Smithd37b3602012-02-10 11:05:11 +00002772 FnTy->arg_type_begin(),
2773 FnTy->getNumArgs(), EPI);
Richard Smithe9253222012-10-24 23:51:56 +00002774 // Rebuild any parens around the identifier in the function type.
2775 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2776 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
2777 break;
2778 T = S.BuildParenType(T);
2779 }
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002780 }
2781 }
Mike Stump1eb44332009-09-09 15:08:12 +00002782
John McCall711c52b2011-01-05 12:14:39 +00002783 // Apply any undistributed attributes from the declarator.
2784 if (!T.isNull())
2785 if (AttributeList *attrs = D.getAttributes())
Richard Smithf7a05272013-01-14 07:53:01 +00002786 processTypeAttrs(state, T, TAL_DeclName, attrs);
John McCall711c52b2011-01-05 12:14:39 +00002787
2788 // Diagnose any ignored type attributes.
2789 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2790
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002791 // C++0x [dcl.constexpr]p9:
2792 // A constexpr specifier used in an object declaration declares the object
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002793 // as const.
Peter Collingbourne148f1f72011-03-20 08:06:45 +00002794 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
Sebastian Redl73780122010-06-09 21:19:43 +00002795 T.addConst();
2796 }
2797
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002798 // If there was an ellipsis in the declarator, the declaration declares a
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002799 // parameter pack whose type may be a pack expansion type.
2800 if (D.hasEllipsis() && !T.isNull()) {
2801 // C++0x [dcl.fct]p13:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002802 // A declarator-id or abstract-declarator containing an ellipsis shall
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002803 // only be used in a parameter-declaration. Such a parameter-declaration
2804 // is a parameter pack (14.5.3). [...]
2805 switch (D.getContext()) {
2806 case Declarator::PrototypeContext:
2807 // C++0x [dcl.fct]p13:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002808 // [...] When it is part of a parameter-declaration-clause, the
2809 // parameter pack is a function parameter pack (14.5.3). The type T
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002810 // of the declarator-id of the function parameter pack shall contain
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002811 // a template parameter pack; each template parameter pack in T is
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002812 // expanded by the function parameter pack.
2813 //
2814 // We represent function parameter packs as function parameters whose
2815 // type is a pack expansion.
2816 if (!T->containsUnexpandedParameterPack()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002817 S.Diag(D.getEllipsisLoc(),
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002818 diag::err_function_parameter_pack_without_parameter_packs)
2819 << T << D.getSourceRange();
2820 D.setEllipsisLoc(SourceLocation());
2821 } else {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002822 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002823 }
2824 break;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002825
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002826 case Declarator::TemplateParamContext:
2827 // C++0x [temp.param]p15:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002828 // If a template-parameter is a [...] is a parameter-declaration that
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002829 // declares a parameter pack (8.3.5), then the template-parameter is a
2830 // template parameter pack (14.5.3).
2831 //
2832 // Note: core issue 778 clarifies that, if there are any unexpanded
2833 // parameter packs in the type of the non-type template parameter, then
2834 // it expands those parameter packs.
2835 if (T->containsUnexpandedParameterPack())
Douglas Gregorcded4f62011-01-14 17:04:44 +00002836 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
Richard Smithe5acd132011-10-14 20:31:37 +00002837 else
2838 S.Diag(D.getEllipsisLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00002839 LangOpts.CPlusPlus11
Richard Smithe5acd132011-10-14 20:31:37 +00002840 ? diag::warn_cxx98_compat_variadic_templates
2841 : diag::ext_variadic_templates);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002842 break;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002843
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002844 case Declarator::FileContext:
2845 case Declarator::KNRTypeListContext:
John McCallcdda47f2011-10-01 09:56:14 +00002846 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
2847 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002848 case Declarator::TypeNameContext:
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002849 case Declarator::CXXNewContext:
Richard Smith162e1c12011-04-15 14:24:37 +00002850 case Declarator::AliasDeclContext:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002851 case Declarator::AliasTemplateContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002852 case Declarator::MemberContext:
2853 case Declarator::BlockContext:
2854 case Declarator::ForContext:
2855 case Declarator::ConditionContext:
2856 case Declarator::CXXCatchContext:
Argyrios Kyrtzidis17b63992011-07-01 22:22:40 +00002857 case Declarator::ObjCCatchContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002858 case Declarator::BlockLiteralContext:
Eli Friedmanf88c4002012-01-04 04:41:38 +00002859 case Declarator::LambdaExprContext:
Richard Smith7796eb52012-03-12 08:56:40 +00002860 case Declarator::TrailingReturnContext:
Douglas Gregor683a81f2011-01-31 16:09:46 +00002861 case Declarator::TemplateTypeArgContext:
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002862 // FIXME: We may want to allow parameter packs in block-literal contexts
2863 // in the future.
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002864 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
Douglas Gregora8bc8c92010-12-23 22:44:42 +00002865 D.setEllipsisLoc(SourceLocation());
2866 break;
2867 }
2868 }
Richard Smithe7397c62011-02-22 00:36:53 +00002869
John McCallbf1a0282010-06-04 23:28:52 +00002870 if (T.isNull())
2871 return Context.getNullTypeSourceInfo();
2872 else if (D.isInvalidType())
2873 return Context.getTrivialTypeSourceInfo(T);
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +00002874
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002875 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2876}
2877
2878/// GetTypeForDeclarator - Convert the type for the specified
2879/// declarator to Type instances.
2880///
2881/// The result of this call will never be null, but the associated
2882/// type may be a null type if there's an unrecoverable error.
2883TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2884 // Determine the type of the declarator. Not all forms of declarator
2885 // have a type.
2886
2887 TypeProcessingState state(*this, D);
2888
2889 TypeSourceInfo *ReturnTypeInfo = 0;
2890 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2891 if (T.isNull())
2892 return Context.getNullTypeSourceInfo();
2893
David Blaikie4e4d0842012-03-11 07:00:24 +00002894 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002895 inferARCWriteback(state, T);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002896
Argyrios Kyrtzidis8cfa57b2011-07-01 22:22:42 +00002897 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002898}
2899
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002900static void transferARCOwnershipToDeclSpec(Sema &S,
2901 QualType &declSpecTy,
2902 Qualifiers::ObjCLifetime ownership) {
2903 if (declSpecTy->isObjCRetainableType() &&
2904 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2905 Qualifiers qs;
2906 qs.addObjCLifetime(ownership);
2907 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2908 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002909}
2910
2911static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2912 Qualifiers::ObjCLifetime ownership,
2913 unsigned chunkIndex) {
2914 Sema &S = state.getSema();
2915 Declarator &D = state.getDeclarator();
2916
2917 // Look for an explicit lifetime attribute.
2918 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2919 for (const AttributeList *attr = chunk.getAttrs(); attr;
2920 attr = attr->getNext())
Sean Hunt8e083e72012-06-19 23:57:03 +00002921 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002922 return;
2923
2924 const char *attrStr = 0;
2925 switch (ownership) {
David Blaikie30263482012-01-20 21:50:17 +00002926 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002927 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2928 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2929 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2930 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2931 }
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002932
2933 // If there wasn't one, add one (with an invalid source location
2934 // so that we don't make an AttributedType for it).
2935 AttributeList *attr = D.getAttributePool()
2936 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2937 /*scope*/ 0, SourceLocation(),
2938 &S.Context.Idents.get(attrStr), SourceLocation(),
Sean Hunt93f95f22012-06-18 16:13:52 +00002939 /*args*/ 0, 0, AttributeList::AS_GNU);
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002940 spliceAttrIntoList(*attr, chunk.getAttrListRef());
2941
2942 // TODO: mark whether we did this inference?
2943}
2944
Benjamin Kramer48d798c2012-06-02 10:20:41 +00002945/// \brief Used for transferring ownership in casts resulting in l-values.
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002946static void transferARCOwnership(TypeProcessingState &state,
2947 QualType &declSpecTy,
2948 Qualifiers::ObjCLifetime ownership) {
2949 Sema &S = state.getSema();
2950 Declarator &D = state.getDeclarator();
2951
2952 int inner = -1;
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002953 bool hasIndirection = false;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002954 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2955 DeclaratorChunk &chunk = D.getTypeObject(i);
2956 switch (chunk.Kind) {
2957 case DeclaratorChunk::Paren:
2958 // Ignore parens.
2959 break;
2960
2961 case DeclaratorChunk::Array:
2962 case DeclaratorChunk::Reference:
2963 case DeclaratorChunk::Pointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002964 if (inner != -1)
2965 hasIndirection = true;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002966 inner = i;
2967 break;
2968
2969 case DeclaratorChunk::BlockPointer:
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002970 if (inner != -1)
2971 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2972 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002973
2974 case DeclaratorChunk::Function:
2975 case DeclaratorChunk::MemberPointer:
2976 return;
2977 }
2978 }
2979
2980 if (inner == -1)
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002981 return;
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002982
Chad Rosier91cbbbf2012-06-26 21:41:40 +00002983 DeclaratorChunk &chunk = D.getTypeObject(inner);
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002984 if (chunk.Kind == DeclaratorChunk::Pointer) {
2985 if (declSpecTy->isObjCRetainableType())
2986 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
Argyrios Kyrtzidis6ee54922011-10-28 22:54:28 +00002987 if (declSpecTy->isObjCObjectType() && hasIndirection)
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00002988 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2989 } else {
2990 assert(chunk.Kind == DeclaratorChunk::Array ||
2991 chunk.Kind == DeclaratorChunk::Reference);
2992 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2993 }
2994}
2995
2996TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2997 TypeProcessingState state(*this, D);
2998
2999 TypeSourceInfo *ReturnTypeInfo = 0;
3000 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3001 if (declSpecTy.isNull())
3002 return Context.getNullTypeSourceInfo();
3003
David Blaikie4e4d0842012-03-11 07:00:24 +00003004 if (getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003005 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3006 if (ownership != Qualifiers::OCL_None)
3007 transferARCOwnership(state, declSpecTy, ownership);
3008 }
3009
3010 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3011}
3012
John McCall14aa2172011-03-04 04:00:19 +00003013/// Map an AttributedType::Kind to an AttributeList::Kind.
3014static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3015 switch (kind) {
3016 case AttributedType::attr_address_space:
Sean Hunt8e083e72012-06-19 23:57:03 +00003017 return AttributeList::AT_AddressSpace;
John McCall14aa2172011-03-04 04:00:19 +00003018 case AttributedType::attr_regparm:
Sean Hunt8e083e72012-06-19 23:57:03 +00003019 return AttributeList::AT_Regparm;
John McCall14aa2172011-03-04 04:00:19 +00003020 case AttributedType::attr_vector_size:
Sean Hunt8e083e72012-06-19 23:57:03 +00003021 return AttributeList::AT_VectorSize;
John McCall14aa2172011-03-04 04:00:19 +00003022 case AttributedType::attr_neon_vector_type:
Sean Hunt8e083e72012-06-19 23:57:03 +00003023 return AttributeList::AT_NeonVectorType;
John McCall14aa2172011-03-04 04:00:19 +00003024 case AttributedType::attr_neon_polyvector_type:
Sean Hunt8e083e72012-06-19 23:57:03 +00003025 return AttributeList::AT_NeonPolyVectorType;
John McCall14aa2172011-03-04 04:00:19 +00003026 case AttributedType::attr_objc_gc:
Sean Hunt8e083e72012-06-19 23:57:03 +00003027 return AttributeList::AT_ObjCGC;
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003028 case AttributedType::attr_objc_ownership:
Sean Hunt8e083e72012-06-19 23:57:03 +00003029 return AttributeList::AT_ObjCOwnership;
John McCall14aa2172011-03-04 04:00:19 +00003030 case AttributedType::attr_noreturn:
Sean Hunt8e083e72012-06-19 23:57:03 +00003031 return AttributeList::AT_NoReturn;
John McCall14aa2172011-03-04 04:00:19 +00003032 case AttributedType::attr_cdecl:
Sean Hunt8e083e72012-06-19 23:57:03 +00003033 return AttributeList::AT_CDecl;
John McCall14aa2172011-03-04 04:00:19 +00003034 case AttributedType::attr_fastcall:
Sean Hunt8e083e72012-06-19 23:57:03 +00003035 return AttributeList::AT_FastCall;
John McCall14aa2172011-03-04 04:00:19 +00003036 case AttributedType::attr_stdcall:
Sean Hunt8e083e72012-06-19 23:57:03 +00003037 return AttributeList::AT_StdCall;
John McCall14aa2172011-03-04 04:00:19 +00003038 case AttributedType::attr_thiscall:
Sean Hunt8e083e72012-06-19 23:57:03 +00003039 return AttributeList::AT_ThisCall;
John McCall14aa2172011-03-04 04:00:19 +00003040 case AttributedType::attr_pascal:
Sean Hunt8e083e72012-06-19 23:57:03 +00003041 return AttributeList::AT_Pascal;
Anton Korobeynikov414d8962011-04-14 20:06:49 +00003042 case AttributedType::attr_pcs:
Sean Hunt8e083e72012-06-19 23:57:03 +00003043 return AttributeList::AT_Pcs;
Derek Schuff263366f2012-10-16 22:30:41 +00003044 case AttributedType::attr_pnaclcall:
3045 return AttributeList::AT_PnaclCall;
Guy Benyei38980082012-12-25 08:53:55 +00003046 case AttributedType::attr_inteloclbicc:
3047 return AttributeList::AT_IntelOclBicc;
John McCall14aa2172011-03-04 04:00:19 +00003048 }
3049 llvm_unreachable("unexpected attribute kind!");
John McCall14aa2172011-03-04 04:00:19 +00003050}
3051
3052static void fillAttributedTypeLoc(AttributedTypeLoc TL,
3053 const AttributeList *attrs) {
3054 AttributedType::Kind kind = TL.getAttrKind();
3055
3056 assert(attrs && "no type attributes in the expected location!");
3057 AttributeList::Kind parsedKind = getAttrListKind(kind);
3058 while (attrs->getKind() != parsedKind) {
3059 attrs = attrs->getNext();
3060 assert(attrs && "no matching attribute in expected location!");
3061 }
3062
3063 TL.setAttrNameLoc(attrs->getLoc());
3064 if (TL.hasAttrExprOperand())
3065 TL.setAttrExprOperand(attrs->getArg(0));
3066 else if (TL.hasAttrEnumOperand())
3067 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
3068
3069 // FIXME: preserve this information to here.
3070 if (TL.hasAttrOperand())
3071 TL.setAttrOperandParensRange(SourceRange());
3072}
3073
John McCall51bd8032009-10-18 01:05:36 +00003074namespace {
3075 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003076 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00003077 const DeclSpec &DS;
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003078
John McCall51bd8032009-10-18 01:05:36 +00003079 public:
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003080 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003081 : Context(Context), DS(DS) {}
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003082
John McCall14aa2172011-03-04 04:00:19 +00003083 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3084 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3085 Visit(TL.getModifiedLoc());
3086 }
John McCall51bd8032009-10-18 01:05:36 +00003087 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3088 Visit(TL.getUnqualifiedLoc());
3089 }
3090 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3091 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3092 }
3093 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3094 TL.setNameLoc(DS.getTypeSpecTypeLoc());
Fariborz Jahanian1de6a6c2012-05-09 21:49:29 +00003095 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3096 // addition field. What we have is good enough for dispay of location
3097 // of 'fixit' on interface name.
3098 TL.setNameEndLoc(DS.getLocEnd());
John McCallc12c5bb2010-05-15 11:32:37 +00003099 }
3100 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3101 // Handle the base type, which might not have been written explicitly.
3102 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3103 TL.setHasBaseTypeAsWritten(false);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003104 TL.getBaseLoc().initialize(Context, SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00003105 } else {
3106 TL.setHasBaseTypeAsWritten(true);
3107 Visit(TL.getBaseLoc());
3108 }
Argyrios Kyrtzidiseb667592009-09-29 19:45:22 +00003109
John McCallc12c5bb2010-05-15 11:32:37 +00003110 // Protocol qualifiers.
John McCall54e14c42009-10-22 22:37:11 +00003111 if (DS.getProtocolQualifiers()) {
3112 assert(TL.getNumProtocols() > 0);
3113 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3114 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3115 TL.setRAngleLoc(DS.getSourceRange().getEnd());
3116 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3117 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3118 } else {
3119 assert(TL.getNumProtocols() == 0);
3120 TL.setLAngleLoc(SourceLocation());
3121 TL.setRAngleLoc(SourceLocation());
3122 }
3123 }
3124 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall54e14c42009-10-22 22:37:11 +00003125 TL.setStarLoc(SourceLocation());
John McCallc12c5bb2010-05-15 11:32:37 +00003126 Visit(TL.getPointeeLoc());
John McCall51bd8032009-10-18 01:05:36 +00003127 }
John McCall833ca992009-10-29 08:12:44 +00003128 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
John McCalla93c9342009-12-07 02:54:59 +00003129 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00003130 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCall833ca992009-10-29 08:12:44 +00003131
3132 // If we got no declarator info from previous Sema routines,
3133 // just fill with the typespec loc.
John McCalla93c9342009-12-07 02:54:59 +00003134 if (!TInfo) {
Abramo Bagnara0daaf322011-03-16 20:16:18 +00003135 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
John McCall833ca992009-10-29 08:12:44 +00003136 return;
3137 }
3138
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003139 TypeLoc OldTL = TInfo->getTypeLoc();
3140 if (TInfo->getType()->getAs<ElaboratedType>()) {
3141 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
3142 TemplateSpecializationTypeLoc NamedTL =
3143 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
3144 TL.copy(NamedTL);
3145 }
3146 else
3147 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
John McCall833ca992009-10-29 08:12:44 +00003148 }
John McCallcfb708c2010-01-13 20:03:27 +00003149 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3150 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3151 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3152 TL.setParensRange(DS.getTypeofParensRange());
3153 }
3154 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3155 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3156 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3157 TL.setParensRange(DS.getTypeofParensRange());
John McCallb3d87482010-08-24 05:47:05 +00003158 assert(DS.getRepAsType());
John McCallcfb708c2010-01-13 20:03:27 +00003159 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00003160 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
John McCallcfb708c2010-01-13 20:03:27 +00003161 TL.setUnderlyingTInfo(TInfo);
3162 }
Sean Huntca63c202011-05-24 22:41:36 +00003163 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3164 // FIXME: This holds only because we only have one unary transform.
3165 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3166 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3167 TL.setParensRange(DS.getTypeofParensRange());
3168 assert(DS.getRepAsType());
3169 TypeSourceInfo *TInfo = 0;
3170 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3171 TL.setUnderlyingTInfo(TInfo);
3172 }
Douglas Gregorddf889a2010-01-18 18:04:31 +00003173 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3174 // By default, use the source location of the type specifier.
3175 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3176 if (TL.needsExtraLocalData()) {
3177 // Set info for the written builtin specifiers.
3178 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3179 // Try to have a meaningful source location.
3180 if (TL.getWrittenSignSpec() != TSS_unspecified)
3181 // Sign spec loc overrides the others (e.g., 'unsigned long').
3182 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3183 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3184 // Width spec loc overrides type spec loc (e.g., 'short int').
3185 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3186 }
3187 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003188 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3189 ElaboratedTypeKeyword Keyword
3190 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
Nico Weber253e80b2010-11-22 10:30:56 +00003191 if (DS.getTypeSpecType() == TST_typename) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003192 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +00003193 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003194 if (TInfo) {
3195 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
3196 return;
3197 }
3198 }
Abramo Bagnara38a42912012-02-06 19:09:27 +00003199 TL.setElaboratedKeywordLoc(Keyword != ETK_None
3200 ? DS.getTypeSpecTypeLoc()
3201 : SourceLocation());
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003202 const CXXScopeSpec& SS = DS.getTypeSpecScope();
Douglas Gregor9e876872011-03-01 18:12:44 +00003203 TL.setQualifierLoc(SS.getWithLocInContext(Context));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003204 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3205 }
3206 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00003207 assert(DS.getTypeSpecType() == TST_typename);
3208 TypeSourceInfo *TInfo = 0;
3209 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3210 assert(TInfo);
3211 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003212 }
John McCall33500952010-06-11 00:33:02 +00003213 void VisitDependentTemplateSpecializationTypeLoc(
3214 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara66581d42012-02-06 22:45:07 +00003215 assert(DS.getTypeSpecType() == TST_typename);
3216 TypeSourceInfo *TInfo = 0;
3217 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3218 assert(TInfo);
3219 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
3220 TInfo->getTypeLoc()));
Abramo Bagnara0daaf322011-03-16 20:16:18 +00003221 }
3222 void VisitTagTypeLoc(TagTypeLoc TL) {
3223 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
John McCall33500952010-06-11 00:33:02 +00003224 }
Eli Friedmanb001de72011-10-06 23:00:33 +00003225 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3226 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3227 TL.setParensRange(DS.getTypeofParensRange());
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003228
Douglas Gregor43fe2452011-10-09 18:45:17 +00003229 TypeSourceInfo *TInfo = 0;
3230 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3231 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
Eli Friedmanb001de72011-10-06 23:00:33 +00003232 }
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00003233
John McCall51bd8032009-10-18 01:05:36 +00003234 void VisitTypeLoc(TypeLoc TL) {
3235 // FIXME: add other typespec types and change this to an assert.
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003236 TL.initialize(Context, DS.getTypeSpecTypeLoc());
John McCall51bd8032009-10-18 01:05:36 +00003237 }
3238 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003239
John McCall51bd8032009-10-18 01:05:36 +00003240 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003241 ASTContext &Context;
John McCall51bd8032009-10-18 01:05:36 +00003242 const DeclaratorChunk &Chunk;
3243
3244 public:
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003245 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3246 : Context(Context), Chunk(Chunk) {}
John McCall51bd8032009-10-18 01:05:36 +00003247
3248 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003249 llvm_unreachable("qualified type locs not expected here!");
John McCall51bd8032009-10-18 01:05:36 +00003250 }
3251
John McCallf85e1932011-06-15 23:02:42 +00003252 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3253 fillAttributedTypeLoc(TL, Chunk.getAttrs());
3254 }
John McCall51bd8032009-10-18 01:05:36 +00003255 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3256 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3257 TL.setCaretLoc(Chunk.Loc);
3258 }
3259 void VisitPointerTypeLoc(PointerTypeLoc TL) {
3260 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3261 TL.setStarLoc(Chunk.Loc);
3262 }
3263 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3264 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3265 TL.setStarLoc(Chunk.Loc);
3266 }
3267 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3268 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003269 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3270 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3271
3272 const Type* ClsTy = TL.getClass();
3273 QualType ClsQT = QualType(ClsTy, 0);
3274 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3275 // Now copy source location info into the type loc component.
3276 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3277 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3278 case NestedNameSpecifier::Identifier:
3279 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3280 {
Abramo Bagnarafd9c42e2011-03-06 22:48:24 +00003281 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
Abramo Bagnara38a42912012-02-06 19:09:27 +00003282 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003283 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3284 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3285 }
3286 break;
3287
3288 case NestedNameSpecifier::TypeSpec:
3289 case NestedNameSpecifier::TypeSpecWithTemplate:
3290 if (isa<ElaboratedType>(ClsTy)) {
3291 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
Abramo Bagnara38a42912012-02-06 19:09:27 +00003292 ETLoc.setElaboratedKeywordLoc(SourceLocation());
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003293 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3294 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3295 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3296 } else {
3297 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3298 }
3299 break;
3300
3301 case NestedNameSpecifier::Namespace:
3302 case NestedNameSpecifier::NamespaceAlias:
3303 case NestedNameSpecifier::Global:
3304 llvm_unreachable("Nested-name-specifier must name a type");
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003305 }
3306
3307 // Finally fill in MemberPointerLocInfo fields.
John McCall51bd8032009-10-18 01:05:36 +00003308 TL.setStarLoc(Chunk.Loc);
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003309 TL.setClassTInfo(ClsTInfo);
John McCall51bd8032009-10-18 01:05:36 +00003310 }
3311 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3312 assert(Chunk.Kind == DeclaratorChunk::Reference);
John McCall54e14c42009-10-22 22:37:11 +00003313 // 'Amp' is misleading: this might have been originally
3314 /// spelled with AmpAmp.
John McCall51bd8032009-10-18 01:05:36 +00003315 TL.setAmpLoc(Chunk.Loc);
3316 }
3317 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3318 assert(Chunk.Kind == DeclaratorChunk::Reference);
3319 assert(!Chunk.Ref.LValueRef);
3320 TL.setAmpAmpLoc(Chunk.Loc);
3321 }
3322 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3323 assert(Chunk.Kind == DeclaratorChunk::Array);
3324 TL.setLBracketLoc(Chunk.Loc);
3325 TL.setRBracketLoc(Chunk.EndLoc);
3326 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3327 }
3328 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3329 assert(Chunk.Kind == DeclaratorChunk::Function);
Abramo Bagnara796aa442011-03-12 11:17:06 +00003330 TL.setLocalRangeBegin(Chunk.Loc);
3331 TL.setLocalRangeEnd(Chunk.EndLoc);
John McCall51bd8032009-10-18 01:05:36 +00003332
3333 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
Abramo Bagnara59c0a812012-10-04 21:42:10 +00003334 TL.setLParenLoc(FTI.getLParenLoc());
3335 TL.setRParenLoc(FTI.getRParenLoc());
John McCall54e14c42009-10-22 22:37:11 +00003336 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00003337 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
John McCall54e14c42009-10-22 22:37:11 +00003338 TL.setArg(tpi++, Param);
John McCall51bd8032009-10-18 01:05:36 +00003339 }
3340 // FIXME: exception specs
3341 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003342 void VisitParenTypeLoc(ParenTypeLoc TL) {
3343 assert(Chunk.Kind == DeclaratorChunk::Paren);
3344 TL.setLParenLoc(Chunk.Loc);
3345 TL.setRParenLoc(Chunk.EndLoc);
3346 }
John McCall51bd8032009-10-18 01:05:36 +00003347
3348 void VisitTypeLoc(TypeLoc TL) {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003349 llvm_unreachable("unsupported TypeLoc kind in declarator!");
John McCall51bd8032009-10-18 01:05:36 +00003350 }
3351 };
Argyrios Kyrtzidisf352bdd2009-09-29 19:43:35 +00003352}
3353
John McCalla93c9342009-12-07 02:54:59 +00003354/// \brief Create and instantiate a TypeSourceInfo with type source information.
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003355///
3356/// \param T QualType referring to the type as written in source code.
Douglas Gregor05baacb2010-04-12 23:19:01 +00003357///
3358/// \param ReturnTypeInfo For declarators whose return type does not show
3359/// up in the normal place in the declaration specifiers (such as a C++
3360/// conversion function), this pointer will refer to a type source information
3361/// for that return type.
John McCalla93c9342009-12-07 02:54:59 +00003362TypeSourceInfo *
Douglas Gregor05baacb2010-04-12 23:19:01 +00003363Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3364 TypeSourceInfo *ReturnTypeInfo) {
John McCalla93c9342009-12-07 02:54:59 +00003365 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3366 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003367
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003368 // Handle parameter packs whose type is a pack expansion.
3369 if (isa<PackExpansionType>(T)) {
3370 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003371 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Douglas Gregora8bc8c92010-12-23 22:44:42 +00003372 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003373
Sebastian Redl8ce35b02009-10-25 21:45:37 +00003374 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
John McCall14aa2172011-03-04 04:00:19 +00003375 while (isa<AttributedTypeLoc>(CurrTL)) {
3376 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3377 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3378 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3379 }
3380
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00003381 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
John McCall51bd8032009-10-18 01:05:36 +00003382 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003383 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003384
John McCallb3d87482010-08-24 05:47:05 +00003385 // If we have different source information for the return type, use
3386 // that. This really only applies to C++ conversion functions.
3387 if (ReturnTypeInfo) {
Douglas Gregor05baacb2010-04-12 23:19:01 +00003388 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3389 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3390 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
John McCallb3d87482010-08-24 05:47:05 +00003391 } else {
Douglas Gregorc21c7e92011-01-25 19:13:18 +00003392 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
Douglas Gregor05baacb2010-04-12 23:19:01 +00003393 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003394
John McCalla93c9342009-12-07 02:54:59 +00003395 return TInfo;
Argyrios Kyrtzidis4adab7f2009-08-19 01:28:06 +00003396}
3397
John McCalla93c9342009-12-07 02:54:59 +00003398/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
John McCallb3d87482010-08-24 05:47:05 +00003399ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003400 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3401 // and Sema during declaration parsing. Try deallocating/caching them when
3402 // it's appropriate, instead of allocating them and keeping them around.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003403 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
Douglas Gregoreb0eb492010-12-10 08:12:03 +00003404 TypeAlignment);
John McCalla93c9342009-12-07 02:54:59 +00003405 new (LocT) LocInfoType(T, TInfo);
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003406 assert(LocT->getTypeClass() != T->getTypeClass() &&
3407 "LocInfoType's TypeClass conflicts with an existing Type class");
John McCallb3d87482010-08-24 05:47:05 +00003408 return ParsedType::make(QualType(LocT, 0));
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003409}
3410
3411void LocInfoType::getAsStringInternal(std::string &Str,
3412 const PrintingPolicy &Policy) const {
David Blaikieb219cfc2011-09-23 05:06:16 +00003413 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
Argyrios Kyrtzidis35d44e52009-08-19 01:46:06 +00003414 " was used directly instead of getting the QualType through"
3415 " GetTypeFromParser");
Argyrios Kyrtzidis1bb8a452009-08-19 01:28:17 +00003416}
3417
John McCallf312b1e2010-08-26 23:41:50 +00003418TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003419 // C99 6.7.6: Type names have no identifier. This is already validated by
3420 // the parser.
3421 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
Mike Stump1eb44332009-09-09 15:08:12 +00003422
Argyrios Kyrtzidisd3880f82011-06-28 03:01:18 +00003423 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00003424 QualType T = TInfo->getType();
Chris Lattner5153ee62009-04-25 08:47:54 +00003425 if (D.isInvalidType())
Douglas Gregor809070a2009-02-18 17:45:20 +00003426 return true;
Steve Naroff5912a352007-08-28 20:14:24 +00003427
John McCalle82247a2011-10-01 05:17:03 +00003428 // Make sure there are no unused decl attributes on the declarator.
John McCallcdda47f2011-10-01 09:56:14 +00003429 // We don't want to do this for ObjC parameters because we're going
3430 // to apply them to the actual parameter declaration.
3431 if (D.getContext() != Declarator::ObjCParameterContext)
3432 checkUnusedDeclAttributes(D);
John McCalle82247a2011-10-01 05:17:03 +00003433
David Blaikie4e4d0842012-03-11 07:00:24 +00003434 if (getLangOpts().CPlusPlus) {
Douglas Gregor402abb52009-05-28 23:31:59 +00003435 // Check that there are no default arguments (C++ only).
Douglas Gregor6d6eb572008-05-07 04:49:29 +00003436 CheckExtraCXXDefaultArguments(D);
Douglas Gregor402abb52009-05-28 23:31:59 +00003437 }
3438
John McCallb3d87482010-08-24 05:47:05 +00003439 return CreateParsedType(T, TInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00003440}
3441
Douglas Gregore97179c2011-09-08 01:46:34 +00003442ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3443 QualType T = Context.getObjCInstanceType();
3444 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3445 return CreateParsedType(T, TInfo);
3446}
3447
3448
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003449//===----------------------------------------------------------------------===//
3450// Type Attribute Processing
3451//===----------------------------------------------------------------------===//
3452
3453/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3454/// specified type. The attribute contains 1 argument, the id of the address
3455/// space for the type.
Mike Stump1eb44332009-09-09 15:08:12 +00003456static void HandleAddressSpaceTypeAttribute(QualType &Type,
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003457 const AttributeList &Attr, Sema &S){
John McCall0953e762009-09-24 19:53:00 +00003458
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003459 // If this type is already address space qualified, reject it.
Peter Collingbourne29e3ef82011-07-27 20:29:53 +00003460 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3461 // qualifiers for two or more different address spaces."
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003462 if (Type.getAddressSpace()) {
3463 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
Abramo Bagnarae215f722010-04-30 13:10:51 +00003464 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003465 return;
3466 }
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Peter Collingbourne020972d2011-07-27 20:30:05 +00003468 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3469 // qualified by an address-space qualifier."
3470 if (Type->isFunctionType()) {
3471 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3472 Attr.setInvalid();
3473 return;
3474 }
3475
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003476 // Check the attribute arguments.
3477 if (Attr.getNumArgs() != 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003478 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003479 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003480 return;
3481 }
3482 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3483 llvm::APSInt addrSpace(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00003484 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3485 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003486 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3487 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003488 Attr.setInvalid();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003489 return;
3490 }
3491
John McCallefadb772009-07-28 06:52:18 +00003492 // Bounds checking.
3493 if (addrSpace.isSigned()) {
3494 if (addrSpace.isNegative()) {
3495 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3496 << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003497 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003498 return;
3499 }
3500 addrSpace.setIsSigned(false);
3501 }
3502 llvm::APSInt max(addrSpace.getBitWidth());
John McCall0953e762009-09-24 19:53:00 +00003503 max = Qualifiers::MaxAddressSpace;
John McCallefadb772009-07-28 06:52:18 +00003504 if (addrSpace > max) {
3505 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
John McCall0953e762009-09-24 19:53:00 +00003506 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00003507 Attr.setInvalid();
John McCallefadb772009-07-28 06:52:18 +00003508 return;
3509 }
3510
Mike Stump1eb44332009-09-09 15:08:12 +00003511 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003512 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
Chris Lattnerc9b346d2008-06-29 00:50:08 +00003513}
3514
John McCalld85bf9d2012-02-08 00:46:41 +00003515/// Does this type have a "direct" ownership qualifier? That is,
3516/// is it written like "__strong id", as opposed to something like
3517/// "typeof(foo)", where that happens to be strong?
3518static bool hasDirectOwnershipQualifier(QualType type) {
3519 // Fast path: no qualifier at all.
3520 assert(type.getQualifiers().hasObjCLifetime());
3521
3522 while (true) {
3523 // __strong id
3524 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3525 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3526 return true;
3527
3528 type = attr->getModifiedType();
3529
3530 // X *__strong (...)
3531 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3532 type = paren->getInnerType();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003533
John McCalld85bf9d2012-02-08 00:46:41 +00003534 // That's it for things we want to complain about. In particular,
3535 // we do not want to look through typedefs, typeof(expr),
3536 // typeof(type), or any other way that the type is somehow
3537 // abstracted.
3538 } else {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003539
John McCalld85bf9d2012-02-08 00:46:41 +00003540 return false;
3541 }
3542 }
3543}
3544
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003545/// handleObjCOwnershipTypeAttr - Process an objc_ownership
John McCallf85e1932011-06-15 23:02:42 +00003546/// attribute on the specified type.
3547///
3548/// Returns 'true' if the attribute was handled.
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003549static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
John McCallf85e1932011-06-15 23:02:42 +00003550 AttributeList &attr,
3551 QualType &type) {
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003552 bool NonObjCPointer = false;
3553
3554 if (!type->isDependentType()) {
3555 if (const PointerType *ptr = type->getAs<PointerType>()) {
3556 QualType pointee = ptr->getPointeeType();
3557 if (pointee->isObjCRetainableType() || pointee->isPointerType())
3558 return false;
3559 // It is important not to lose the source info that there was an attribute
3560 // applied to non-objc pointer. We will create an attributed type but
3561 // its type will be the same as the original type.
3562 NonObjCPointer = true;
3563 } else if (!type->isObjCRetainableType()) {
3564 return false;
3565 }
3566 }
John McCallf85e1932011-06-15 23:02:42 +00003567
3568 Sema &S = state.getSema();
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003569 SourceLocation AttrLoc = attr.getLoc();
3570 if (AttrLoc.isMacroID())
3571 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
John McCallf85e1932011-06-15 23:02:42 +00003572
John McCallf85e1932011-06-15 23:02:42 +00003573 if (!attr.getParameterName()) {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003574 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003575 << "objc_ownership" << 1;
John McCallf85e1932011-06-15 23:02:42 +00003576 attr.setInvalid();
3577 return true;
3578 }
3579
John McCalld85bf9d2012-02-08 00:46:41 +00003580 // Consume lifetime attributes without further comment outside of
3581 // ARC mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003582 if (!S.getLangOpts().ObjCAutoRefCount)
John McCalld85bf9d2012-02-08 00:46:41 +00003583 return true;
3584
John McCallf85e1932011-06-15 23:02:42 +00003585 Qualifiers::ObjCLifetime lifetime;
3586 if (attr.getParameterName()->isStr("none"))
3587 lifetime = Qualifiers::OCL_ExplicitNone;
3588 else if (attr.getParameterName()->isStr("strong"))
3589 lifetime = Qualifiers::OCL_Strong;
3590 else if (attr.getParameterName()->isStr("weak"))
3591 lifetime = Qualifiers::OCL_Weak;
3592 else if (attr.getParameterName()->isStr("autoreleasing"))
3593 lifetime = Qualifiers::OCL_Autoreleasing;
3594 else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003595 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003596 << "objc_ownership" << attr.getParameterName();
John McCallf85e1932011-06-15 23:02:42 +00003597 attr.setInvalid();
3598 return true;
3599 }
3600
John McCalld85bf9d2012-02-08 00:46:41 +00003601 SplitQualType underlyingType = type.split();
3602
3603 // Check for redundant/conflicting ownership qualifiers.
3604 if (Qualifiers::ObjCLifetime previousLifetime
3605 = type.getQualifiers().getObjCLifetime()) {
3606 // If it's written directly, that's an error.
3607 if (hasDirectOwnershipQualifier(type)) {
3608 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3609 << type;
3610 return true;
3611 }
3612
3613 // Otherwise, if the qualifiers actually conflict, pull sugar off
3614 // until we reach a type that is directly qualified.
3615 if (previousLifetime != lifetime) {
3616 // This should always terminate: the canonical type is
3617 // qualified, so some bit of sugar must be hiding it.
3618 while (!underlyingType.Quals.hasObjCLifetime()) {
3619 underlyingType = underlyingType.getSingleStepDesugaredType();
3620 }
3621 underlyingType.Quals.removeObjCLifetime();
3622 }
3623 }
3624
3625 underlyingType.Quals.addObjCLifetime(lifetime);
John McCallf85e1932011-06-15 23:02:42 +00003626
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003627 if (NonObjCPointer) {
3628 StringRef name = attr.getName()->getName();
3629 switch (lifetime) {
3630 case Qualifiers::OCL_None:
3631 case Qualifiers::OCL_ExplicitNone:
3632 break;
3633 case Qualifiers::OCL_Strong: name = "__strong"; break;
3634 case Qualifiers::OCL_Weak: name = "__weak"; break;
3635 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3636 }
3637 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3638 << name << type;
3639 }
3640
John McCallf85e1932011-06-15 23:02:42 +00003641 QualType origType = type;
Argyrios Kyrtzidise71202e2011-11-04 20:37:24 +00003642 if (!NonObjCPointer)
John McCalld85bf9d2012-02-08 00:46:41 +00003643 type = S.Context.getQualifiedType(underlyingType);
John McCallf85e1932011-06-15 23:02:42 +00003644
3645 // If we have a valid source location for the attribute, use an
3646 // AttributedType instead.
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003647 if (AttrLoc.isValid())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00003648 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
John McCallf85e1932011-06-15 23:02:42 +00003649 origType, type);
3650
John McCall9f084a32011-07-06 00:26:06 +00003651 // Forbid __weak if the runtime doesn't support it.
John McCallf85e1932011-06-15 23:02:42 +00003652 if (lifetime == Qualifiers::OCL_Weak &&
John McCall0a7dd782012-08-21 02:47:43 +00003653 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
John McCallf85e1932011-06-15 23:02:42 +00003654
3655 // Actually, delay this until we know what we're parsing.
3656 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3657 S.DelayedDiagnostics.add(
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003658 sema::DelayedDiagnostic::makeForbiddenType(
3659 S.getSourceManager().getExpansionLoc(AttrLoc),
John McCallf85e1932011-06-15 23:02:42 +00003660 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3661 } else {
Argyrios Kyrtzidis440ec2e2011-09-28 18:35:06 +00003662 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
John McCallf85e1932011-06-15 23:02:42 +00003663 }
3664
3665 attr.setInvalid();
3666 return true;
3667 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003668
3669 // Forbid __weak for class objects marked as
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003670 // objc_arc_weak_reference_unavailable
3671 if (lifetime == Qualifiers::OCL_Weak) {
3672 QualType T = type;
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003673 while (const PointerType *ptr = T->getAs<PointerType>())
3674 T = ptr->getPointeeType();
3675 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
Richard Smith4e90bc32012-08-23 04:53:18 +00003676 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
3677 if (Class->isArcWeakrefUnavailable()) {
3678 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
3679 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3680 diag::note_class_declared);
3681 }
Fariborz Jahanian742352a2011-07-06 19:24:05 +00003682 }
3683 }
3684 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003685
John McCallf85e1932011-06-15 23:02:42 +00003686 return true;
3687}
3688
John McCall711c52b2011-01-05 12:14:39 +00003689/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3690/// attribute on the specified type. Returns true to indicate that
3691/// the attribute was handled, false to indicate that the type does
3692/// not permit the attribute.
3693static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3694 AttributeList &attr,
3695 QualType &type) {
3696 Sema &S = state.getSema();
3697
3698 // Delay if this isn't some kind of pointer.
3699 if (!type->isPointerType() &&
3700 !type->isObjCObjectPointerType() &&
3701 !type->isBlockPointerType())
3702 return false;
3703
3704 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3705 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3706 attr.setInvalid();
3707 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003708 }
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003710 // Check the attribute arguments.
John McCall711c52b2011-01-05 12:14:39 +00003711 if (!attr.getParameterName()) {
3712 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003713 << "objc_gc" << 1;
John McCall711c52b2011-01-05 12:14:39 +00003714 attr.setInvalid();
3715 return true;
Fariborz Jahanianba372b82009-02-18 17:52:36 +00003716 }
John McCall0953e762009-09-24 19:53:00 +00003717 Qualifiers::GC GCAttr;
John McCall711c52b2011-01-05 12:14:39 +00003718 if (attr.getNumArgs() != 0) {
3719 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3720 attr.setInvalid();
3721 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003722 }
John McCall711c52b2011-01-05 12:14:39 +00003723 if (attr.getParameterName()->isStr("weak"))
John McCall0953e762009-09-24 19:53:00 +00003724 GCAttr = Qualifiers::Weak;
John McCall711c52b2011-01-05 12:14:39 +00003725 else if (attr.getParameterName()->isStr("strong"))
John McCall0953e762009-09-24 19:53:00 +00003726 GCAttr = Qualifiers::Strong;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003727 else {
John McCall711c52b2011-01-05 12:14:39 +00003728 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3729 << "objc_gc" << attr.getParameterName();
3730 attr.setInvalid();
3731 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003732 }
Mike Stump1eb44332009-09-09 15:08:12 +00003733
John McCall14aa2172011-03-04 04:00:19 +00003734 QualType origType = type;
3735 type = S.Context.getObjCGCQualType(origType, GCAttr);
3736
3737 // Make an attributed type to preserve the source information.
3738 if (attr.getLoc().isValid())
3739 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3740 origType, type);
3741
John McCall711c52b2011-01-05 12:14:39 +00003742 return true;
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00003743}
3744
John McCalle6a365d2010-12-19 02:44:49 +00003745namespace {
3746 /// A helper class to unwrap a type down to a function for the
3747 /// purposes of applying attributes there.
3748 ///
3749 /// Use:
3750 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3751 /// if (unwrapped.isFunctionType()) {
3752 /// const FunctionType *fn = unwrapped.get();
3753 /// // change fn somehow
3754 /// T = unwrapped.wrap(fn);
3755 /// }
3756 struct FunctionTypeUnwrapper {
3757 enum WrapKind {
3758 Desugar,
3759 Parens,
3760 Pointer,
3761 BlockPointer,
3762 Reference,
3763 MemberPointer
3764 };
3765
3766 QualType Original;
3767 const FunctionType *Fn;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003768 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
John McCalle6a365d2010-12-19 02:44:49 +00003769
3770 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3771 while (true) {
3772 const Type *Ty = T.getTypePtr();
3773 if (isa<FunctionType>(Ty)) {
3774 Fn = cast<FunctionType>(Ty);
3775 return;
3776 } else if (isa<ParenType>(Ty)) {
3777 T = cast<ParenType>(Ty)->getInnerType();
3778 Stack.push_back(Parens);
3779 } else if (isa<PointerType>(Ty)) {
3780 T = cast<PointerType>(Ty)->getPointeeType();
3781 Stack.push_back(Pointer);
3782 } else if (isa<BlockPointerType>(Ty)) {
3783 T = cast<BlockPointerType>(Ty)->getPointeeType();
3784 Stack.push_back(BlockPointer);
3785 } else if (isa<MemberPointerType>(Ty)) {
3786 T = cast<MemberPointerType>(Ty)->getPointeeType();
3787 Stack.push_back(MemberPointer);
3788 } else if (isa<ReferenceType>(Ty)) {
3789 T = cast<ReferenceType>(Ty)->getPointeeType();
3790 Stack.push_back(Reference);
3791 } else {
3792 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3793 if (Ty == DTy) {
3794 Fn = 0;
3795 return;
3796 }
3797
3798 T = QualType(DTy, 0);
3799 Stack.push_back(Desugar);
3800 }
3801 }
3802 }
3803
3804 bool isFunctionType() const { return (Fn != 0); }
3805 const FunctionType *get() const { return Fn; }
3806
3807 QualType wrap(Sema &S, const FunctionType *New) {
3808 // If T wasn't modified from the unwrapped type, do nothing.
3809 if (New == get()) return Original;
3810
3811 Fn = New;
3812 return wrap(S.Context, Original, 0);
3813 }
3814
3815 private:
3816 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3817 if (I == Stack.size())
3818 return C.getQualifiedType(Fn, Old.getQualifiers());
3819
3820 // Build up the inner type, applying the qualifiers from the old
3821 // type to the new type.
3822 SplitQualType SplitOld = Old.split();
3823
3824 // As a special case, tail-recurse if there are no qualifiers.
John McCall200fa532012-02-08 00:46:36 +00003825 if (SplitOld.Quals.empty())
3826 return wrap(C, SplitOld.Ty, I);
3827 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
John McCalle6a365d2010-12-19 02:44:49 +00003828 }
3829
3830 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3831 if (I == Stack.size()) return QualType(Fn, 0);
3832
3833 switch (static_cast<WrapKind>(Stack[I++])) {
3834 case Desugar:
3835 // This is the point at which we potentially lose source
3836 // information.
3837 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3838
3839 case Parens: {
3840 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3841 return C.getParenType(New);
3842 }
3843
3844 case Pointer: {
3845 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3846 return C.getPointerType(New);
3847 }
3848
3849 case BlockPointer: {
3850 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3851 return C.getBlockPointerType(New);
3852 }
3853
3854 case MemberPointer: {
3855 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3856 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3857 return C.getMemberPointerType(New, OldMPT->getClass());
3858 }
3859
3860 case Reference: {
3861 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3862 QualType New = wrap(C, OldRef->getPointeeType(), I);
3863 if (isa<LValueReferenceType>(OldRef))
3864 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3865 else
3866 return C.getRValueReferenceType(New);
3867 }
3868 }
3869
3870 llvm_unreachable("unknown wrapping kind");
John McCalle6a365d2010-12-19 02:44:49 +00003871 }
3872 };
3873}
3874
John McCall711c52b2011-01-05 12:14:39 +00003875/// Process an individual function attribute. Returns true to
3876/// indicate that the attribute was handled, false if it wasn't.
3877static bool handleFunctionTypeAttr(TypeProcessingState &state,
3878 AttributeList &attr,
3879 QualType &type) {
3880 Sema &S = state.getSema();
John McCalle6a365d2010-12-19 02:44:49 +00003881
John McCall711c52b2011-01-05 12:14:39 +00003882 FunctionTypeUnwrapper unwrapped(S, type);
Mike Stump24556362009-07-25 21:26:53 +00003883
Sean Hunt8e083e72012-06-19 23:57:03 +00003884 if (attr.getKind() == AttributeList::AT_NoReturn) {
John McCall711c52b2011-01-05 12:14:39 +00003885 if (S.CheckNoReturnAttr(attr))
John McCall04a67a62010-02-05 21:31:56 +00003886 return true;
John McCalle6a365d2010-12-19 02:44:49 +00003887
John McCall711c52b2011-01-05 12:14:39 +00003888 // Delay if this is not a function type.
3889 if (!unwrapped.isFunctionType())
3890 return false;
3891
John McCall04a67a62010-02-05 21:31:56 +00003892 // Otherwise we can process right away.
John McCall711c52b2011-01-05 12:14:39 +00003893 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3894 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3895 return true;
John McCall04a67a62010-02-05 21:31:56 +00003896 }
Mike Stump24556362009-07-25 21:26:53 +00003897
John McCallf85e1932011-06-15 23:02:42 +00003898 // ns_returns_retained is not always a type attribute, but if we got
3899 // here, we're treating it as one right now.
Sean Hunt8e083e72012-06-19 23:57:03 +00003900 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003901 assert(S.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003902 "ns_returns_retained treated as type attribute in non-ARC");
3903 if (attr.getNumArgs()) return true;
3904
3905 // Delay if this is not a function type.
3906 if (!unwrapped.isFunctionType())
3907 return false;
3908
3909 FunctionType::ExtInfo EI
3910 = unwrapped.get()->getExtInfo().withProducesResult(true);
3911 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3912 return true;
3913 }
3914
Sean Hunt8e083e72012-06-19 23:57:03 +00003915 if (attr.getKind() == AttributeList::AT_Regparm) {
John McCall711c52b2011-01-05 12:14:39 +00003916 unsigned value;
3917 if (S.CheckRegparmAttr(attr, value))
Rafael Espindola425ef722010-03-30 22:15:11 +00003918 return true;
3919
John McCall711c52b2011-01-05 12:14:39 +00003920 // Delay if this is not a function type.
3921 if (!unwrapped.isFunctionType())
Rafael Espindola425ef722010-03-30 22:15:11 +00003922 return false;
3923
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003924 // Diagnose regparm with fastcall.
3925 const FunctionType *fn = unwrapped.get();
3926 CallingConv CC = fn->getCallConv();
3927 if (CC == CC_X86FastCall) {
3928 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3929 << FunctionType::getNameForCallConv(CC)
3930 << "regparm";
3931 attr.setInvalid();
3932 return true;
3933 }
3934
Chad Rosier91cbbbf2012-06-26 21:41:40 +00003935 FunctionType::ExtInfo EI =
John McCall711c52b2011-01-05 12:14:39 +00003936 unwrapped.get()->getExtInfo().withRegParm(value);
3937 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3938 return true;
Rafael Espindola425ef722010-03-30 22:15:11 +00003939 }
3940
Aaron Ballman82bfa192012-10-02 14:26:08 +00003941 // Delay if the type didn't work out to a function.
3942 if (!unwrapped.isFunctionType()) return false;
3943
John McCall04a67a62010-02-05 21:31:56 +00003944 // Otherwise, a calling convention.
John McCall711c52b2011-01-05 12:14:39 +00003945 CallingConv CC;
3946 if (S.CheckCallingConvAttr(attr, CC))
3947 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003948
John McCall711c52b2011-01-05 12:14:39 +00003949 const FunctionType *fn = unwrapped.get();
3950 CallingConv CCOld = fn->getCallConv();
Charles Davis064f7db2010-02-23 06:13:55 +00003951 if (S.Context.getCanonicalCallConv(CC) ==
Abramo Bagnarae215f722010-04-30 13:10:51 +00003952 S.Context.getCanonicalCallConv(CCOld)) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003953 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3954 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
John McCall711c52b2011-01-05 12:14:39 +00003955 return true;
Abramo Bagnarae215f722010-04-30 13:10:51 +00003956 }
John McCall04a67a62010-02-05 21:31:56 +00003957
Roman Divacky8e68f1c2011-08-05 16:37:22 +00003958 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
John McCall04a67a62010-02-05 21:31:56 +00003959 // Should we diagnose reapplications of the same convention?
John McCall711c52b2011-01-05 12:14:39 +00003960 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
John McCall04a67a62010-02-05 21:31:56 +00003961 << FunctionType::getNameForCallConv(CC)
3962 << FunctionType::getNameForCallConv(CCOld);
John McCall711c52b2011-01-05 12:14:39 +00003963 attr.setInvalid();
3964 return true;
John McCall04a67a62010-02-05 21:31:56 +00003965 }
3966
3967 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3968 if (CC == CC_X86FastCall) {
John McCall711c52b2011-01-05 12:14:39 +00003969 if (isa<FunctionNoProtoType>(fn)) {
3970 S.Diag(attr.getLoc(), diag::err_cconv_knr)
John McCall04a67a62010-02-05 21:31:56 +00003971 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003972 attr.setInvalid();
3973 return true;
John McCall04a67a62010-02-05 21:31:56 +00003974 }
3975
John McCall711c52b2011-01-05 12:14:39 +00003976 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
John McCall04a67a62010-02-05 21:31:56 +00003977 if (FnP->isVariadic()) {
John McCall711c52b2011-01-05 12:14:39 +00003978 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
John McCall04a67a62010-02-05 21:31:56 +00003979 << FunctionType::getNameForCallConv(CC);
John McCall711c52b2011-01-05 12:14:39 +00003980 attr.setInvalid();
3981 return true;
John McCall04a67a62010-02-05 21:31:56 +00003982 }
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003983
3984 // Also diagnose fastcall with regparm.
Eli Friedmana49218e2011-04-09 08:18:08 +00003985 if (fn->getHasRegParm()) {
Argyrios Kyrtzidisce955662011-01-25 23:16:40 +00003986 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3987 << "regparm"
3988 << FunctionType::getNameForCallConv(CC);
3989 attr.setInvalid();
3990 return true;
3991 }
John McCall04a67a62010-02-05 21:31:56 +00003992 }
3993
John McCall711c52b2011-01-05 12:14:39 +00003994 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3995 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3996 return true;
John McCallf82b4e82010-02-04 05:44:44 +00003997}
3998
Peter Collingbourne207f4d82011-03-18 22:38:29 +00003999/// Handle OpenCL image access qualifiers: read_only, write_only, read_write
4000static void HandleOpenCLImageAccessAttribute(QualType& CurType,
4001 const AttributeList &Attr,
4002 Sema &S) {
4003 // Check the attribute arguments.
4004 if (Attr.getNumArgs() != 1) {
4005 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4006 Attr.setInvalid();
4007 return;
4008 }
4009 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4010 llvm::APSInt arg(32);
4011 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4012 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
4013 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4014 << "opencl_image_access" << sizeExpr->getSourceRange();
4015 Attr.setInvalid();
4016 return;
4017 }
4018 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
4019 switch (iarg) {
4020 case CLIA_read_only:
4021 case CLIA_write_only:
4022 case CLIA_read_write:
4023 // Implemented in a separate patch
4024 break;
4025 default:
4026 // Implemented in a separate patch
4027 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4028 << sizeExpr->getSourceRange();
4029 Attr.setInvalid();
4030 break;
4031 }
4032}
4033
John Thompson6e132aa2009-12-04 21:51:28 +00004034/// HandleVectorSizeAttribute - this attribute is only applicable to integral
4035/// and float scalars, although arrays, pointers, and function return values are
4036/// allowed in conjunction with this construct. Aggregates with this attribute
4037/// are invalid, even if they are of the same size as a corresponding scalar.
4038/// The raw attribute should contain precisely 1 argument, the vector size for
4039/// the variable, measured in bytes. If curType and rawAttr are well formed,
4040/// this routine will return a new vector type.
Chris Lattner788b0fd2010-06-23 06:00:24 +00004041static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4042 Sema &S) {
Bob Wilson56affbc2010-11-16 00:32:16 +00004043 // Check the attribute arguments.
John Thompson6e132aa2009-12-04 21:51:28 +00004044 if (Attr.getNumArgs() != 1) {
4045 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
Abramo Bagnarae215f722010-04-30 13:10:51 +00004046 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004047 return;
4048 }
4049 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4050 llvm::APSInt vecSize(32);
Douglas Gregorac06a0e2010-05-18 23:01:22 +00004051 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4052 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
John Thompson6e132aa2009-12-04 21:51:28 +00004053 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4054 << "vector_size" << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00004055 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004056 return;
4057 }
4058 // the base type must be integer or float, and can't already be a vector.
Douglas Gregorf6094622010-07-23 15:58:24 +00004059 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
John Thompson6e132aa2009-12-04 21:51:28 +00004060 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
Abramo Bagnarae215f722010-04-30 13:10:51 +00004061 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004062 return;
4063 }
4064 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4065 // vecSize is specified in bytes - convert to bits.
4066 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4067
4068 // the vector size needs to be an integral multiple of the type size.
4069 if (vectorSize % typeSize) {
4070 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4071 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00004072 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004073 return;
4074 }
4075 if (vectorSize == 0) {
4076 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4077 << sizeExpr->getSourceRange();
Abramo Bagnarae215f722010-04-30 13:10:51 +00004078 Attr.setInvalid();
John Thompson6e132aa2009-12-04 21:51:28 +00004079 return;
4080 }
4081
4082 // Success! Instantiate the vector type, the number of elements is > 0, and
4083 // not required to be a power of 2, unlike GCC.
Chris Lattner788b0fd2010-06-23 06:00:24 +00004084 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
Bob Wilsone86d78c2010-11-10 21:56:12 +00004085 VectorType::GenericVector);
John Thompson6e132aa2009-12-04 21:51:28 +00004086}
4087
Douglas Gregor4ac01402011-06-15 16:02:29 +00004088/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4089/// a type.
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004090static void HandleExtVectorTypeAttr(QualType &CurType,
4091 const AttributeList &Attr,
Douglas Gregor4ac01402011-06-15 16:02:29 +00004092 Sema &S) {
4093 Expr *sizeExpr;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004094
Douglas Gregor4ac01402011-06-15 16:02:29 +00004095 // Special case where the argument is a template id.
4096 if (Attr.getParameterName()) {
4097 CXXScopeSpec SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004098 SourceLocation TemplateKWLoc;
Douglas Gregor4ac01402011-06-15 16:02:29 +00004099 UnqualifiedId id;
4100 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00004101
4102 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4103 id, false, false);
Douglas Gregor4ac01402011-06-15 16:02:29 +00004104 if (Size.isInvalid())
4105 return;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004106
Douglas Gregor4ac01402011-06-15 16:02:29 +00004107 sizeExpr = Size.get();
4108 } else {
4109 // check the attribute arguments.
4110 if (Attr.getNumArgs() != 1) {
4111 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4112 return;
4113 }
4114 sizeExpr = Attr.getArg(0);
4115 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004116
Douglas Gregor4ac01402011-06-15 16:02:29 +00004117 // Create the vector type.
4118 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4119 if (!T.isNull())
4120 CurType = T;
4121}
4122
Bob Wilson4211bb62010-11-16 00:32:24 +00004123/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4124/// "neon_polyvector_type" attributes are used to create vector types that
4125/// are mangled according to ARM's ABI. Otherwise, these types are identical
4126/// to those created with the "vector_size" attribute. Unlike "vector_size"
4127/// the argument to these Neon attributes is the number of vector elements,
4128/// not the vector size in bytes. The vector width and element type must
4129/// match one of the standard Neon vector types.
4130static void HandleNeonVectorTypeAttr(QualType& CurType,
4131 const AttributeList &Attr, Sema &S,
4132 VectorType::VectorKind VecKind,
4133 const char *AttrName) {
4134 // Check the attribute arguments.
4135 if (Attr.getNumArgs() != 1) {
4136 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4137 Attr.setInvalid();
4138 return;
4139 }
4140 // The number of elements must be an ICE.
4141 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
4142 llvm::APSInt numEltsInt(32);
4143 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4144 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4145 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4146 << AttrName << numEltsExpr->getSourceRange();
4147 Attr.setInvalid();
4148 return;
4149 }
4150 // Only certain element types are supported for Neon vectors.
4151 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
4152 if (!BTy ||
4153 (VecKind == VectorType::NeonPolyVector &&
4154 BTy->getKind() != BuiltinType::SChar &&
4155 BTy->getKind() != BuiltinType::Short) ||
4156 (BTy->getKind() != BuiltinType::SChar &&
4157 BTy->getKind() != BuiltinType::UChar &&
4158 BTy->getKind() != BuiltinType::Short &&
4159 BTy->getKind() != BuiltinType::UShort &&
4160 BTy->getKind() != BuiltinType::Int &&
4161 BTy->getKind() != BuiltinType::UInt &&
4162 BTy->getKind() != BuiltinType::LongLong &&
4163 BTy->getKind() != BuiltinType::ULongLong &&
4164 BTy->getKind() != BuiltinType::Float)) {
4165 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
4166 Attr.setInvalid();
4167 return;
4168 }
4169 // The total size of the vector must be 64 or 128 bits.
4170 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4171 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4172 unsigned vecSize = typeSize * numElts;
4173 if (vecSize != 64 && vecSize != 128) {
4174 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4175 Attr.setInvalid();
4176 return;
4177 }
4178
4179 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4180}
4181
John McCall711c52b2011-01-05 12:14:39 +00004182static void processTypeAttrs(TypeProcessingState &state, QualType &type,
Richard Smithf7a05272013-01-14 07:53:01 +00004183 TypeAttrLocation TAL, AttributeList *attrs) {
Chris Lattner232e8822008-02-21 01:08:11 +00004184 // Scan through and apply attributes to this type where it makes sense. Some
4185 // attributes (such as __address_space__, __vector_size__, etc) apply to the
4186 // type, but others can be present in the type specifiers even though they
Chris Lattnerfca0ddd2008-06-26 06:27:57 +00004187 // apply to the decl. Here we apply type attributes and ignore the rest.
John McCall711c52b2011-01-05 12:14:39 +00004188
4189 AttributeList *next;
4190 do {
4191 AttributeList &attr = *attrs;
4192 next = attr.getNext();
4193
Abramo Bagnarae215f722010-04-30 13:10:51 +00004194 // Skip attributes that were marked to be invalid.
John McCall711c52b2011-01-05 12:14:39 +00004195 if (attr.isInvalid())
Abramo Bagnarae215f722010-04-30 13:10:51 +00004196 continue;
4197
Richard Smithcd8ab512013-01-17 01:30:42 +00004198 if (attr.isCXX11Attribute()) {
4199 // [[gnu::...]] attributes are treated as declaration attributes, so may
4200 // not appertain to a DeclaratorChunk, even if we handle them as type
4201 // attributes.
4202 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4203 if (TAL == TAL_DeclChunk) {
4204 state.getSema().Diag(attr.getLoc(),
4205 diag::warn_cxx11_gnu_attribute_on_type)
4206 << attr.getName();
4207 continue;
4208 }
4209 } else if (TAL != TAL_DeclChunk) {
4210 // Otherwise, only consider type processing for a C++11 attribute if
4211 // it's actually been applied to a type.
4212 continue;
4213 }
Richard Smithf7a05272013-01-14 07:53:01 +00004214 }
4215
Abramo Bagnarab1f1b262010-04-30 09:13:03 +00004216 // If this is an attribute we can handle, do so now,
4217 // otherwise, add it to the FnAttrs list for rechaining.
John McCall711c52b2011-01-05 12:14:39 +00004218 switch (attr.getKind()) {
Richard Smithcd8ab512013-01-17 01:30:42 +00004219 default:
4220 // A C++11 attribute on a declarator chunk must appertain to a type.
4221 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4222 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
4223 << attr.getName()->getName();
4224 break;
4225
4226 case AttributeList::UnknownAttribute:
4227 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4228 state.getSema().Diag(attr.getLoc(),
4229 diag::warn_unknown_attribute_ignored)
4230 << attr.getName();
4231 break;
4232
4233 case AttributeList::IgnoredAttribute:
4234 break;
John McCall04a67a62010-02-05 21:31:56 +00004235
Sean Hunt8e083e72012-06-19 23:57:03 +00004236 case AttributeList::AT_MayAlias:
Chandler Carruth682eae22011-10-07 18:40:27 +00004237 // FIXME: This attribute needs to actually be handled, but if we ignore
4238 // it it breaks large amounts of Linux software.
4239 attr.setUsedAsTypeAttr();
4240 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004241 case AttributeList::AT_AddressSpace:
John McCall711c52b2011-01-05 12:14:39 +00004242 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004243 attr.setUsedAsTypeAttr();
Chris Lattnerc9b346d2008-06-29 00:50:08 +00004244 break;
John McCall711c52b2011-01-05 12:14:39 +00004245 OBJC_POINTER_TYPE_ATTRS_CASELIST:
4246 if (!handleObjCPointerTypeAttr(state, attr, type))
4247 distributeObjCPointerTypeAttr(state, attr, type);
John McCalle82247a2011-10-01 05:17:03 +00004248 attr.setUsedAsTypeAttr();
Mike Stump24556362009-07-25 21:26:53 +00004249 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004250 case AttributeList::AT_VectorSize:
John McCall711c52b2011-01-05 12:14:39 +00004251 HandleVectorSizeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004252 attr.setUsedAsTypeAttr();
John McCall04a67a62010-02-05 21:31:56 +00004253 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004254 case AttributeList::AT_ExtVectorType:
Richard Smitha4fa9002013-01-13 02:11:23 +00004255 HandleExtVectorTypeAttr(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004256 attr.setUsedAsTypeAttr();
Douglas Gregor4ac01402011-06-15 16:02:29 +00004257 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004258 case AttributeList::AT_NeonVectorType:
John McCall711c52b2011-01-05 12:14:39 +00004259 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4260 VectorType::NeonVector, "neon_vector_type");
John McCalle82247a2011-10-01 05:17:03 +00004261 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00004262 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004263 case AttributeList::AT_NeonPolyVectorType:
John McCall711c52b2011-01-05 12:14:39 +00004264 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4265 VectorType::NeonPolyVector,
Bob Wilson4211bb62010-11-16 00:32:24 +00004266 "neon_polyvector_type");
John McCalle82247a2011-10-01 05:17:03 +00004267 attr.setUsedAsTypeAttr();
Bob Wilson4211bb62010-11-16 00:32:24 +00004268 break;
Sean Hunt8e083e72012-06-19 23:57:03 +00004269 case AttributeList::AT_OpenCLImageAccess:
Peter Collingbourne207f4d82011-03-18 22:38:29 +00004270 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
John McCalle82247a2011-10-01 05:17:03 +00004271 attr.setUsedAsTypeAttr();
Peter Collingbourne207f4d82011-03-18 22:38:29 +00004272 break;
4273
Sean Hunt8e083e72012-06-19 23:57:03 +00004274 case AttributeList::AT_Win64:
4275 case AttributeList::AT_Ptr32:
4276 case AttributeList::AT_Ptr64:
John McCallc052dbb2012-05-22 21:28:12 +00004277 // FIXME: don't ignore these
4278 attr.setUsedAsTypeAttr();
4279 break;
4280
Sean Hunt8e083e72012-06-19 23:57:03 +00004281 case AttributeList::AT_NSReturnsRetained:
David Blaikie4e4d0842012-03-11 07:00:24 +00004282 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
Richard Smithcd8ab512013-01-17 01:30:42 +00004283 break;
John McCallf85e1932011-06-15 23:02:42 +00004284 // fallthrough into the function attrs
4285
John McCall711c52b2011-01-05 12:14:39 +00004286 FUNCTION_TYPE_ATTRS_CASELIST:
John McCalle82247a2011-10-01 05:17:03 +00004287 attr.setUsedAsTypeAttr();
4288
John McCall711c52b2011-01-05 12:14:39 +00004289 // Never process function type attributes as part of the
4290 // declaration-specifiers.
Richard Smithf7a05272013-01-14 07:53:01 +00004291 if (TAL == TAL_DeclSpec)
John McCall711c52b2011-01-05 12:14:39 +00004292 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4293
4294 // Otherwise, handle the possible delays.
4295 else if (!handleFunctionTypeAttr(state, attr, type))
4296 distributeFunctionTypeAttr(state, attr, type);
John Thompson6e132aa2009-12-04 21:51:28 +00004297 break;
Chris Lattner232e8822008-02-21 01:08:11 +00004298 }
John McCall711c52b2011-01-05 12:14:39 +00004299 } while ((attrs = next));
Chris Lattner232e8822008-02-21 01:08:11 +00004300}
4301
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004302/// \brief Ensure that the type of the given expression is complete.
4303///
4304/// This routine checks whether the expression \p E has a complete type. If the
4305/// expression refers to an instantiable construct, that instantiation is
4306/// performed as needed to complete its type. Furthermore
4307/// Sema::RequireCompleteType is called for the expression's type (or in the
4308/// case of a reference type, the referred-to type).
4309///
4310/// \param E The expression whose type is required to be complete.
Douglas Gregord10099e2012-05-04 16:32:21 +00004311/// \param Diagnoser The object that will emit a diagnostic if the type is
4312/// incomplete.
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004313///
4314/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4315/// otherwise.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004316bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004317 QualType T = E->getType();
4318
4319 // Fast path the case where the type is already complete.
4320 if (!T->isIncompleteType())
4321 return false;
4322
4323 // Incomplete array types may be completed by the initializer attached to
4324 // their definitions. For static data members of class templates we need to
4325 // instantiate the definition to get this initializer and complete the type.
4326 if (T->isIncompleteArrayType()) {
4327 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4328 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4329 if (Var->isStaticDataMember() &&
4330 Var->getInstantiatedFromStaticDataMember()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004331
Douglas Gregor36f255c2011-06-03 14:28:43 +00004332 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4333 assert(MSInfo && "Missing member specialization information?");
4334 if (MSInfo->getTemplateSpecializationKind()
4335 != TSK_ExplicitSpecialization) {
4336 // If we don't already have a point of instantiation, this is it.
4337 if (MSInfo->getPointOfInstantiation().isInvalid()) {
4338 MSInfo->setPointOfInstantiation(E->getLocStart());
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004339
4340 // This is a modification of an existing AST node. Notify
Douglas Gregor36f255c2011-06-03 14:28:43 +00004341 // listeners.
4342 if (ASTMutationListener *L = getASTMutationListener())
4343 L->StaticDataMemberInstantiated(Var);
4344 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004345
Douglas Gregor36f255c2011-06-03 14:28:43 +00004346 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004347
Douglas Gregor36f255c2011-06-03 14:28:43 +00004348 // Update the type to the newly instantiated definition's type both
4349 // here and within the expression.
4350 if (VarDecl *Def = Var->getDefinition()) {
4351 DRE->setDecl(Def);
4352 T = Def->getType();
4353 DRE->setType(T);
4354 E->setType(T);
4355 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00004356 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004357
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004358 // We still go on to try to complete the type independently, as it
4359 // may also require instantiations or diagnostics if it remains
4360 // incomplete.
4361 }
4362 }
4363 }
4364 }
4365
4366 // FIXME: Are there other cases which require instantiating something other
4367 // than the type to complete the type of an expression?
4368
4369 // Look through reference types and complete the referred type.
4370 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4371 T = Ref->getPointeeType();
4372
Douglas Gregord10099e2012-05-04 16:32:21 +00004373 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
4374}
4375
4376namespace {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004377 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
Douglas Gregord10099e2012-05-04 16:32:21 +00004378 unsigned DiagID;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004379
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004380 TypeDiagnoserDiag(unsigned DiagID)
4381 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004382
Douglas Gregord10099e2012-05-04 16:32:21 +00004383 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
4384 if (Suppressed) return;
4385 S.Diag(Loc, DiagID) << T;
4386 }
4387 };
4388}
4389
4390bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004391 TypeDiagnoserDiag Diagnoser(DiagID);
Douglas Gregord10099e2012-05-04 16:32:21 +00004392 return RequireCompleteExprType(E, Diagnoser);
Chandler Carruthe4d645c2011-05-27 01:33:31 +00004393}
4394
Mike Stump1eb44332009-09-09 15:08:12 +00004395/// @brief Ensure that the type T is a complete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004396///
4397/// This routine checks whether the type @p T is complete in any
4398/// context where a complete type is required. If @p T is a complete
Douglas Gregor86447ec2009-03-09 16:13:40 +00004399/// type, returns false. If @p T is a class template specialization,
4400/// this routine then attempts to perform class template
4401/// instantiation. If instantiation fails, or if @p T is incomplete
4402/// and cannot be completed, issues the diagnostic @p diag (giving it
4403/// the type @p T) and returns true.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004404///
4405/// @param Loc The location in the source that the incomplete type
4406/// diagnostic should refer to.
4407///
4408/// @param T The type that this routine is examining for completeness.
4409///
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004410/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4411/// @c false otherwise.
Anders Carlsson91a0cc92009-08-26 22:33:56 +00004412bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004413 TypeDiagnoser &Diagnoser) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004414 // FIXME: Add this assertion to make sure we always get instantiation points.
4415 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004416 // FIXME: Add this assertion to help us flush out problems with
4417 // checking for dependent types and type-dependent expressions.
4418 //
Mike Stump1eb44332009-09-09 15:08:12 +00004419 // assert(!T->isDependentType() &&
Douglas Gregor690dc7f2009-05-21 23:48:18 +00004420 // "Can't ask whether a dependent type is complete");
4421
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004422 // If we have a complete type, we're done.
Douglas Gregord07cc362012-01-02 17:18:37 +00004423 NamedDecl *Def = 0;
4424 if (!T->isIncompleteType(&Def)) {
4425 // If we know about the definition but it is not visible, complain.
Douglas Gregord10099e2012-05-04 16:32:21 +00004426 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) {
Douglas Gregord07cc362012-01-02 17:18:37 +00004427 // Suppress this error outside of a SFINAE context if we've already
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004428 // emitted the error once for this type. There's no usefulness in
Douglas Gregord07cc362012-01-02 17:18:37 +00004429 // repeating the diagnostic.
4430 // FIXME: Add a Fix-It that imports the corresponding module or includes
4431 // the header.
Douglas Gregorca2ab452013-01-12 01:29:50 +00004432 Module *Owner = Def->getOwningModule();
4433 Diag(Loc, diag::err_module_private_definition)
4434 << T << Owner->getFullModuleName();
4435 Diag(Def->getLocation(), diag::note_previous_definition);
4436
4437 if (!isSFINAEContext()) {
4438 // Recover by implicitly importing this module.
4439 createImplicitModuleImport(Loc, Owner);
Douglas Gregord07cc362012-01-02 17:18:37 +00004440 }
4441 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004442
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004443 return false;
Douglas Gregord07cc362012-01-02 17:18:37 +00004444 }
Eli Friedman3c0eb162008-05-27 03:33:27 +00004445
Sean Callananbd791192011-12-16 00:20:31 +00004446 const TagType *Tag = T->getAs<TagType>();
4447 const ObjCInterfaceType *IFace = 0;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004448
Sean Callananbd791192011-12-16 00:20:31 +00004449 if (Tag) {
4450 // Avoid diagnosing invalid decls as incomplete.
4451 if (Tag->getDecl()->isInvalidDecl())
4452 return true;
4453
4454 // Give the external AST source a chance to complete the type.
4455 if (Tag->getDecl()->hasExternalLexicalStorage()) {
4456 Context.getExternalSource()->CompleteType(Tag->getDecl());
4457 if (!Tag->isIncompleteType())
4458 return false;
4459 }
4460 }
4461 else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4462 // Avoid diagnosing invalid decls as incomplete.
4463 if (IFace->getDecl()->isInvalidDecl())
4464 return true;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004465
Sean Callananbd791192011-12-16 00:20:31 +00004466 // Give the external AST source a chance to complete the type.
4467 if (IFace->getDecl()->hasExternalLexicalStorage()) {
4468 Context.getExternalSource()->CompleteType(IFace->getDecl());
4469 if (!IFace->isIncompleteType())
4470 return false;
4471 }
4472 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004473
Douglas Gregord475b8d2009-03-25 21:17:03 +00004474 // If we have a class template specialization or a class member of a
Sebastian Redl923d56d2009-11-05 15:52:31 +00004475 // class template specialization, or an array with known size of such,
4476 // try to instantiate it.
4477 QualType MaybeTemplate = T;
Douglas Gregore656b832012-04-23 16:42:52 +00004478 while (const ConstantArrayType *Array
4479 = Context.getAsConstantArrayType(MaybeTemplate))
Sebastian Redl923d56d2009-11-05 15:52:31 +00004480 MaybeTemplate = Array->getElementType();
4481 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00004482 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004483 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004484 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4485 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00004486 TSK_ImplicitInstantiation,
Douglas Gregord10099e2012-05-04 16:32:21 +00004487 /*Complain=*/!Diagnoser.Suppressed);
Mike Stump1eb44332009-09-09 15:08:12 +00004488 } else if (CXXRecordDecl *Rec
Douglas Gregord475b8d2009-03-25 21:17:03 +00004489 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
Richard Smith564f4c52012-03-22 03:35:28 +00004490 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
4491 if (!Rec->isBeingDefined() && Pattern) {
4492 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
4493 assert(MSI && "Missing member specialization information?");
Douglas Gregor357bbd02009-08-28 20:50:45 +00004494 // This record was instantiated from a class within a template.
Richard Smith564f4c52012-03-22 03:35:28 +00004495 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregorf6b11852009-10-08 15:14:33 +00004496 return InstantiateClass(Loc, Rec, Pattern,
4497 getTemplateInstantiationArgs(Rec),
4498 TSK_ImplicitInstantiation,
Douglas Gregord10099e2012-05-04 16:32:21 +00004499 /*Complain=*/!Diagnoser.Suppressed);
Douglas Gregord475b8d2009-03-25 21:17:03 +00004500 }
4501 }
4502 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00004503
Douglas Gregord10099e2012-05-04 16:32:21 +00004504 if (Diagnoser.Suppressed)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004505 return true;
Douglas Gregord10099e2012-05-04 16:32:21 +00004506
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004507 // We have an incomplete type. Produce a diagnostic.
Douglas Gregord10099e2012-05-04 16:32:21 +00004508 Diagnoser.diagnose(*this, Loc, T);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004509
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004510 // If the type was a forward declaration of a class/struct/union
Rafael Espindola01620702010-03-21 22:56:43 +00004511 // type, produce a note.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004512 if (Tag && !Tag->getDecl()->isInvalidDecl())
Mike Stump1eb44332009-09-09 15:08:12 +00004513 Diag(Tag->getDecl()->getLocation(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004514 Tag->isBeingDefined() ? diag::note_type_being_defined
4515 : diag::note_forward_declaration)
Douglas Gregorb3029962011-11-14 22:10:01 +00004516 << QualType(Tag, 0);
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004517
Douglas Gregorb3029962011-11-14 22:10:01 +00004518 // If the Objective-C class was a forward declaration, produce a note.
4519 if (IFace && !IFace->getDecl()->isInvalidDecl())
4520 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004521
4522 return true;
4523}
Douglas Gregore6258932009-03-19 00:39:20 +00004524
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004525bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004526 unsigned DiagID) {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004527 TypeDiagnoserDiag Diagnoser(DiagID);
Douglas Gregord10099e2012-05-04 16:32:21 +00004528 return RequireCompleteType(Loc, T, Diagnoser);
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004529}
4530
Joao Matos6666ed42012-08-31 18:45:21 +00004531/// \brief Get diagnostic %select index for tag kind for
4532/// literal type diagnostic message.
4533/// WARNING: Indexes apply to particular diagnostics only!
4534///
4535/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +00004536static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
Joao Matos6666ed42012-08-31 18:45:21 +00004537 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +00004538 case TTK_Struct: return 0;
4539 case TTK_Interface: return 1;
4540 case TTK_Class: return 2;
4541 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
Joao Matos6666ed42012-08-31 18:45:21 +00004542 }
Joao Matos6666ed42012-08-31 18:45:21 +00004543}
4544
Richard Smith9f569cc2011-10-01 02:31:28 +00004545/// @brief Ensure that the type T is a literal type.
4546///
4547/// This routine checks whether the type @p T is a literal type. If @p T is an
4548/// incomplete type, an attempt is made to complete it. If @p T is a literal
4549/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4550/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4551/// it the type @p T), along with notes explaining why the type is not a
4552/// literal type, and returns true.
4553///
4554/// @param Loc The location in the source that the non-literal type
4555/// diagnostic should refer to.
4556///
4557/// @param T The type that this routine is examining for literalness.
4558///
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004559/// @param Diagnoser Emits a diagnostic if T is not a literal type.
Richard Smith9f569cc2011-10-01 02:31:28 +00004560///
Richard Smith9f569cc2011-10-01 02:31:28 +00004561/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4562/// @c false otherwise.
4563bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004564 TypeDiagnoser &Diagnoser) {
Richard Smith9f569cc2011-10-01 02:31:28 +00004565 assert(!T->isDependentType() && "type should not be dependent");
4566
Eli Friedmanee065392012-02-20 23:58:14 +00004567 QualType ElemType = Context.getBaseElementType(T);
4568 RequireCompleteType(Loc, ElemType, 0);
4569
Richard Smith86c3ae42012-02-13 03:54:03 +00004570 if (T->isLiteralType())
Richard Smith9f569cc2011-10-01 02:31:28 +00004571 return false;
4572
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004573 if (Diagnoser.Suppressed)
Richard Smith9f569cc2011-10-01 02:31:28 +00004574 return true;
4575
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004576 Diagnoser.diagnose(*this, Loc, T);
Richard Smith9f569cc2011-10-01 02:31:28 +00004577
4578 if (T->isVariableArrayType())
4579 return true;
4580
Eli Friedmanee065392012-02-20 23:58:14 +00004581 const RecordType *RT = ElemType->getAs<RecordType>();
Richard Smith9f569cc2011-10-01 02:31:28 +00004582 if (!RT)
4583 return true;
4584
4585 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4586
Richard Smithc799a6a2012-04-25 23:23:48 +00004587 // A partially-defined class type can't be a literal type, because a literal
4588 // class type must have a trivial destructor (which can't be checked until
4589 // the class definition is complete).
4590 if (!RD->isCompleteDefinition()) {
Douglas Gregord10099e2012-05-04 16:32:21 +00004591 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
Eli Friedmanee065392012-02-20 23:58:14 +00004592 return true;
Richard Smithc799a6a2012-04-25 23:23:48 +00004593 }
Eli Friedmanee065392012-02-20 23:58:14 +00004594
Richard Smith9f569cc2011-10-01 02:31:28 +00004595 // If the class has virtual base classes, then it's not an aggregate, and
Richard Smith86c3ae42012-02-13 03:54:03 +00004596 // cannot have any constexpr constructors or a trivial default constructor,
4597 // so is non-literal. This is better to diagnose than the resulting absence
4598 // of constexpr constructors.
Richard Smith9f569cc2011-10-01 02:31:28 +00004599 if (RD->getNumVBases()) {
4600 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
Joao Matos6666ed42012-08-31 18:45:21 +00004601 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Richard Smith9f569cc2011-10-01 02:31:28 +00004602 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4603 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +00004604 Diag(I->getLocStart(),
Richard Smith9f569cc2011-10-01 02:31:28 +00004605 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith86c3ae42012-02-13 03:54:03 +00004606 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
4607 !RD->hasTrivialDefaultConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00004608 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
Richard Smith9f569cc2011-10-01 02:31:28 +00004609 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4610 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4611 E = RD->bases_end(); I != E; ++I) {
4612 if (!I->getType()->isLiteralType()) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004613 Diag(I->getLocStart(),
Richard Smith9f569cc2011-10-01 02:31:28 +00004614 diag::note_non_literal_base_class)
4615 << RD << I->getType() << I->getSourceRange();
4616 return true;
4617 }
4618 }
4619 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4620 E = RD->field_end(); I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00004621 if (!I->getType()->isLiteralType() ||
4622 I->getType().isVolatileQualified()) {
4623 Diag(I->getLocation(), diag::note_non_literal_field)
David Blaikie581deb32012-06-06 20:45:41 +00004624 << RD << *I << I->getType()
David Blaikie262bc182012-04-30 02:36:29 +00004625 << I->getType().isVolatileQualified();
Richard Smith9f569cc2011-10-01 02:31:28 +00004626 return true;
4627 }
4628 }
4629 } else if (!RD->hasTrivialDestructor()) {
4630 // All fields and bases are of literal types, so have trivial destructors.
4631 // If this class's destructor is non-trivial it must be user-declared.
4632 CXXDestructorDecl *Dtor = RD->getDestructor();
4633 assert(Dtor && "class has literal fields and bases but no dtor?");
4634 if (!Dtor)
4635 return true;
4636
4637 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4638 diag::note_non_literal_user_provided_dtor :
4639 diag::note_non_literal_nontrivial_dtor) << RD;
Richard Smithac713512012-12-08 02:53:02 +00004640 if (!Dtor->isUserProvided())
4641 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
Richard Smith9f569cc2011-10-01 02:31:28 +00004642 }
4643
4644 return true;
4645}
4646
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004647bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
Douglas Gregorf502d8e2012-05-04 16:48:41 +00004648 TypeDiagnoserDiag Diagnoser(DiagID);
4649 return RequireLiteralType(Loc, T, Diagnoser);
4650}
4651
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004652/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4653/// and qualified by the nested-name-specifier contained in SS.
4654QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4655 const CXXScopeSpec &SS, QualType T) {
4656 if (T.isNull())
Douglas Gregore6258932009-03-19 00:39:20 +00004657 return T;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004658 NestedNameSpecifier *NNS;
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00004659 if (SS.isValid())
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004660 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4661 else {
4662 if (Keyword == ETK_None)
4663 return T;
4664 NNS = 0;
4665 }
4666 return Context.getElaboratedType(Keyword, NNS, T);
Douglas Gregore6258932009-03-19 00:39:20 +00004667}
Anders Carlssonaf017e62009-06-29 22:58:55 +00004668
John McCall2a984ca2010-10-12 00:20:44 +00004669QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004670 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004671 if (ER.isInvalid()) return QualType();
4672 E = ER.take();
4673
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004674 if (!E->isTypeDependent()) {
4675 QualType T = E->getType();
Fariborz Jahanianaca7f7b2010-10-06 00:23:25 +00004676 if (const TagType *TT = T->getAs<TagType>())
4677 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
Fariborz Jahanian2b1d51b2010-10-05 23:24:00 +00004678 }
Anders Carlssonaf017e62009-06-29 22:58:55 +00004679 return Context.getTypeOfExprType(E);
4680}
4681
Douglas Gregorf8af9822012-02-12 18:42:33 +00004682/// getDecltypeForExpr - Given an expr, will return the decltype for
4683/// that expression, according to the rules in C++11
4684/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
4685static QualType getDecltypeForExpr(Sema &S, Expr *E) {
4686 if (E->isTypeDependent())
4687 return S.Context.DependentTy;
4688
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004689 // C++11 [dcl.type.simple]p4:
4690 // The type denoted by decltype(e) is defined as follows:
4691 //
4692 // - if e is an unparenthesized id-expression or an unparenthesized class
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004693 // member access (5.2.5), decltype(e) is the type of the entity named
4694 // by e. If there is no such entity, or if e names a set of overloaded
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004695 // functions, the program is ill-formed;
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004696 //
4697 // We apply the same rules for Objective-C ivar and property references.
Douglas Gregorf8af9822012-02-12 18:42:33 +00004698 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4699 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
4700 return VD->getType();
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004701 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Douglas Gregorf8af9822012-02-12 18:42:33 +00004702 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4703 return FD->getType();
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004704 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
4705 return IR->getDecl()->getType();
4706 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
4707 if (PR->isExplicitProperty())
4708 return PR->getExplicitProperty()->getType();
Douglas Gregorf8af9822012-02-12 18:42:33 +00004709 }
Douglas Gregor84dd82e2012-09-13 23:40:46 +00004710
Douglas Gregorf8af9822012-02-12 18:42:33 +00004711 // C++11 [expr.lambda.prim]p18:
4712 // Every occurrence of decltype((x)) where x is a possibly
4713 // parenthesized id-expression that names an entity of automatic
4714 // storage duration is treated as if x were transformed into an
4715 // access to a corresponding data member of the closure type that
4716 // would have been declared if x were an odr-use of the denoted
4717 // entity.
4718 using namespace sema;
4719 if (S.getCurLambda()) {
4720 if (isa<ParenExpr>(E)) {
4721 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4722 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor68932842012-02-18 05:51:20 +00004723 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
4724 if (!T.isNull())
4725 return S.Context.getLValueReferenceType(T);
Douglas Gregorf8af9822012-02-12 18:42:33 +00004726 }
4727 }
4728 }
4729 }
4730
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004731
4732 // C++11 [dcl.type.simple]p4:
4733 // [...]
Douglas Gregorf8af9822012-02-12 18:42:33 +00004734 QualType T = E->getType();
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004735 switch (E->getValueKind()) {
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004736 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004737 // type of e;
4738 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004739 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
Douglas Gregor6d9ef302012-02-12 18:57:57 +00004740 // type of e;
4741 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
4742 // - otherwise, decltype(e) is the type of e.
4743 case VK_RValue: break;
4744 }
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004745
Douglas Gregorf8af9822012-02-12 18:42:33 +00004746 return T;
4747}
4748
John McCall2a984ca2010-10-12 00:20:44 +00004749QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
John McCallfb8721c2011-04-10 19:13:55 +00004750 ExprResult ER = CheckPlaceholderExpr(E);
John McCall2a984ca2010-10-12 00:20:44 +00004751 if (ER.isInvalid()) return QualType();
4752 E = ER.take();
Chad Rosier91cbbbf2012-06-26 21:41:40 +00004753
Douglas Gregorf8af9822012-02-12 18:42:33 +00004754 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
Anders Carlssonaf017e62009-06-29 22:58:55 +00004755}
Sean Huntca63c202011-05-24 22:41:36 +00004756
4757QualType Sema::BuildUnaryTransformType(QualType BaseType,
4758 UnaryTransformType::UTTKind UKind,
4759 SourceLocation Loc) {
4760 switch (UKind) {
4761 case UnaryTransformType::EnumUnderlyingType:
4762 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4763 Diag(Loc, diag::err_only_enums_have_underlying_types);
4764 return QualType();
4765 } else {
4766 QualType Underlying = BaseType;
4767 if (!BaseType->isDependentType()) {
4768 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4769 assert(ED && "EnumType has no EnumDecl");
4770 DiagnoseUseOfDecl(ED, Loc);
4771 Underlying = ED->getIntegerType();
4772 }
4773 assert(!Underlying.isNull());
4774 return Context.getUnaryTransformType(BaseType, Underlying,
4775 UnaryTransformType::EnumUnderlyingType);
4776 }
4777 }
4778 llvm_unreachable("unknown unary transform type");
4779}
Eli Friedmanb001de72011-10-06 23:00:33 +00004780
4781QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4782 if (!T->isDependentType()) {
Richard Smith83271182012-02-11 18:03:45 +00004783 // FIXME: It isn't entirely clear whether incomplete atomic types
4784 // are allowed or not; for simplicity, ban them for the moment.
Douglas Gregord10099e2012-05-04 16:32:21 +00004785 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
Richard Smith83271182012-02-11 18:03:45 +00004786 return QualType();
4787
Eli Friedmanb001de72011-10-06 23:00:33 +00004788 int DisallowedKind = -1;
Richard Smith83271182012-02-11 18:03:45 +00004789 if (T->isArrayType())
Eli Friedmanb001de72011-10-06 23:00:33 +00004790 DisallowedKind = 1;
4791 else if (T->isFunctionType())
4792 DisallowedKind = 2;
4793 else if (T->isReferenceType())
4794 DisallowedKind = 3;
4795 else if (T->isAtomicType())
4796 DisallowedKind = 4;
4797 else if (T.hasQualifiers())
4798 DisallowedKind = 5;
4799 else if (!T.isTriviallyCopyableType(Context))
4800 // Some other non-trivially-copyable type (probably a C++ class)
4801 DisallowedKind = 6;
4802
4803 if (DisallowedKind != -1) {
4804 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4805 return QualType();
4806 }
4807
4808 // FIXME: Do we need any handling for ARC here?
4809 }
4810
4811 // Build the pointer type.
4812 return Context.getAtomicType(T);
4813}