Bug Summary

File:tools/clang/lib/Sema/SemaType.cpp
Warning:line 5217, column 15
Called C++ object pointer is null

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp

1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements type-related semantic analysis.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TypeLocBuilder.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/ASTStructuralEquivalence.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/TypeLoc.h"
24#include "clang/AST/TypeLocVisitor.h"
25#include "clang/Basic/PartialDiagnostic.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Lex/Preprocessor.h"
28#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/DelayedDiagnostic.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/ScopeInfo.h"
32#include "clang/Sema/SemaInternal.h"
33#include "clang/Sema/Template.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include "llvm/ADT/SmallString.h"
36#include "llvm/ADT/StringSwitch.h"
37#include "llvm/Support/ErrorHandling.h"
38
39using namespace clang;
40
41enum TypeDiagSelector {
42 TDS_Function,
43 TDS_Pointer,
44 TDS_ObjCObjOrBlock
45};
46
47/// isOmittedBlockReturnType - Return true if this declarator is missing a
48/// return type because this is a omitted return type on a block literal.
49static bool isOmittedBlockReturnType(const Declarator &D) {
50 if (D.getContext() != Declarator::BlockLiteralContext ||
51 D.getDeclSpec().hasTypeSpecifier())
52 return false;
53
54 if (D.getNumTypeObjects() == 0)
55 return true; // ^{ ... }
56
57 if (D.getNumTypeObjects() == 1 &&
58 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
59 return true; // ^(int X, float Y) { ... }
60
61 return false;
62}
63
64/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
65/// doesn't apply to the given type.
66static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
67 QualType type) {
68 TypeDiagSelector WhichType;
69 bool useExpansionLoc = true;
70 switch (attr.getKind()) {
71 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
72 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
73 default:
74 // Assume everything else was a function attribute.
75 WhichType = TDS_Function;
76 useExpansionLoc = false;
77 break;
78 }
79
80 SourceLocation loc = attr.getLoc();
81 StringRef name = attr.getName()->getName();
82
83 // The GC attributes are usually written with macros; special-case them.
84 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
85 : nullptr;
86 if (useExpansionLoc && loc.isMacroID() && II) {
87 if (II->isStr("strong")) {
88 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
89 } else if (II->isStr("weak")) {
90 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
91 }
92 }
93
94 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
95 << type;
96}
97
98// objc_gc applies to Objective-C pointers or, otherwise, to the
99// smallest available pointer type (i.e. 'void*' in 'void**').
100#define OBJC_POINTER_TYPE_ATTRS_CASELISTcase AttributeList::AT_ObjCGC: case AttributeList::AT_ObjCOwnership \
101 case AttributeList::AT_ObjCGC: \
102 case AttributeList::AT_ObjCOwnership
103
104// Calling convention attributes.
105#define CALLING_CONV_ATTRS_CASELISTcase AttributeList::AT_CDecl: case AttributeList::AT_FastCall
: case AttributeList::AT_StdCall: case AttributeList::AT_ThisCall
: case AttributeList::AT_RegCall: case AttributeList::AT_Pascal
: case AttributeList::AT_SwiftCall: case AttributeList::AT_VectorCall
: case AttributeList::AT_MSABI: case AttributeList::AT_SysVABI
: case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc
: case AttributeList::AT_PreserveMost: case AttributeList::AT_PreserveAll
\
106 case AttributeList::AT_CDecl: \
107 case AttributeList::AT_FastCall: \
108 case AttributeList::AT_StdCall: \
109 case AttributeList::AT_ThisCall: \
110 case AttributeList::AT_RegCall: \
111 case AttributeList::AT_Pascal: \
112 case AttributeList::AT_SwiftCall: \
113 case AttributeList::AT_VectorCall: \
114 case AttributeList::AT_MSABI: \
115 case AttributeList::AT_SysVABI: \
116 case AttributeList::AT_Pcs: \
117 case AttributeList::AT_IntelOclBicc: \
118 case AttributeList::AT_PreserveMost: \
119 case AttributeList::AT_PreserveAll
120
121// Function type attributes.
122#define FUNCTION_TYPE_ATTRS_CASELISTcase AttributeList::AT_NSReturnsRetained: case AttributeList::
AT_NoReturn: case AttributeList::AT_Regparm: case AttributeList
::AT_AnyX86NoCallerSavedRegisters: case AttributeList::AT_CDecl
: case AttributeList::AT_FastCall: case AttributeList::AT_StdCall
: case AttributeList::AT_ThisCall: case AttributeList::AT_RegCall
: case AttributeList::AT_Pascal: case AttributeList::AT_SwiftCall
: case AttributeList::AT_VectorCall: case AttributeList::AT_MSABI
: case AttributeList::AT_SysVABI: case AttributeList::AT_Pcs:
case AttributeList::AT_IntelOclBicc: case AttributeList::AT_PreserveMost
: case AttributeList::AT_PreserveAll
\
123 case AttributeList::AT_NSReturnsRetained: \
124 case AttributeList::AT_NoReturn: \
125 case AttributeList::AT_Regparm: \
126 case AttributeList::AT_AnyX86NoCallerSavedRegisters: \
127 CALLING_CONV_ATTRS_CASELISTcase AttributeList::AT_CDecl: case AttributeList::AT_FastCall
: case AttributeList::AT_StdCall: case AttributeList::AT_ThisCall
: case AttributeList::AT_RegCall: case AttributeList::AT_Pascal
: case AttributeList::AT_SwiftCall: case AttributeList::AT_VectorCall
: case AttributeList::AT_MSABI: case AttributeList::AT_SysVABI
: case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc
: case AttributeList::AT_PreserveMost: case AttributeList::AT_PreserveAll
128
129// Microsoft-specific type qualifiers.
130#define MS_TYPE_ATTRS_CASELISTcase AttributeList::AT_Ptr32: case AttributeList::AT_Ptr64: case
AttributeList::AT_SPtr: case AttributeList::AT_UPtr
\
131 case AttributeList::AT_Ptr32: \
132 case AttributeList::AT_Ptr64: \
133 case AttributeList::AT_SPtr: \
134 case AttributeList::AT_UPtr
135
136// Nullability qualifiers.
137#define NULLABILITY_TYPE_ATTRS_CASELISTcase AttributeList::AT_TypeNonNull: case AttributeList::AT_TypeNullable
: case AttributeList::AT_TypeNullUnspecified
\
138 case AttributeList::AT_TypeNonNull: \
139 case AttributeList::AT_TypeNullable: \
140 case AttributeList::AT_TypeNullUnspecified
141
142namespace {
143 /// An object which stores processing state for the entire
144 /// GetTypeForDeclarator process.
145 class TypeProcessingState {
146 Sema &sema;
147
148 /// The declarator being processed.
149 Declarator &declarator;
150
151 /// The index of the declarator chunk we're currently processing.
152 /// May be the total number of valid chunks, indicating the
153 /// DeclSpec.
154 unsigned chunkIndex;
155
156 /// Whether there are non-trivial modifications to the decl spec.
157 bool trivial;
158
159 /// Whether we saved the attributes in the decl spec.
160 bool hasSavedAttrs;
161
162 /// The original set of attributes on the DeclSpec.
163 SmallVector<AttributeList*, 2> savedAttrs;
164
165 /// A list of attributes to diagnose the uselessness of when the
166 /// processing is complete.
167 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
168
169 public:
170 TypeProcessingState(Sema &sema, Declarator &declarator)
171 : sema(sema), declarator(declarator),
172 chunkIndex(declarator.getNumTypeObjects()),
173 trivial(true), hasSavedAttrs(false) {}
174
175 Sema &getSema() const {
176 return sema;
177 }
178
179 Declarator &getDeclarator() const {
180 return declarator;
181 }
182
183 bool isProcessingDeclSpec() const {
184 return chunkIndex == declarator.getNumTypeObjects();
185 }
186
187 unsigned getCurrentChunkIndex() const {
188 return chunkIndex;
189 }
190
191 void setCurrentChunkIndex(unsigned idx) {
192 assert(idx <= declarator.getNumTypeObjects())(static_cast <bool> (idx <= declarator.getNumTypeObjects
()) ? void (0) : __assert_fail ("idx <= declarator.getNumTypeObjects()"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 192, __extension__ __PRETTY_FUNCTION__))
;
193 chunkIndex = idx;
194 }
195
196 AttributeList *&getCurrentAttrListRef() const {
197 if (isProcessingDeclSpec())
198 return getMutableDeclSpec().getAttributes().getListRef();
199 return declarator.getTypeObject(chunkIndex).getAttrListRef();
200 }
201
202 /// Save the current set of attributes on the DeclSpec.
203 void saveDeclSpecAttrs() {
204 // Don't try to save them multiple times.
205 if (hasSavedAttrs) return;
206
207 DeclSpec &spec = getMutableDeclSpec();
208 for (AttributeList *attr = spec.getAttributes().getList(); attr;
209 attr = attr->getNext())
210 savedAttrs.push_back(attr);
211 trivial &= savedAttrs.empty();
212 hasSavedAttrs = true;
213 }
214
215 /// Record that we had nowhere to put the given type attribute.
216 /// We will diagnose such attributes later.
217 void addIgnoredTypeAttr(AttributeList &attr) {
218 ignoredTypeAttrs.push_back(&attr);
219 }
220
221 /// Diagnose all the ignored type attributes, given that the
222 /// declarator worked out to the given type.
223 void diagnoseIgnoredTypeAttrs(QualType type) const {
224 for (auto *Attr : ignoredTypeAttrs)
225 diagnoseBadTypeAttribute(getSema(), *Attr, type);
226 }
227
228 ~TypeProcessingState() {
229 if (trivial) return;
230
231 restoreDeclSpecAttrs();
232 }
233
234 private:
235 DeclSpec &getMutableDeclSpec() const {
236 return const_cast<DeclSpec&>(declarator.getDeclSpec());
237 }
238
239 void restoreDeclSpecAttrs() {
240 assert(hasSavedAttrs)(static_cast <bool> (hasSavedAttrs) ? void (0) : __assert_fail
("hasSavedAttrs", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 240, __extension__ __PRETTY_FUNCTION__))
;
241
242 if (savedAttrs.empty()) {
243 getMutableDeclSpec().getAttributes().set(nullptr);
244 return;
245 }
246
247 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
248 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
249 savedAttrs[i]->setNext(savedAttrs[i+1]);
250 savedAttrs.back()->setNext(nullptr);
251 }
252 };
253} // end anonymous namespace
254
255static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
256 attr.setNext(head);
257 head = &attr;
258}
259
260static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
261 if (head == &attr) {
262 head = attr.getNext();
263 return;
264 }
265
266 AttributeList *cur = head;
267 while (true) {
268 assert(cur && cur->getNext() && "ran out of attrs?")(static_cast <bool> (cur && cur->getNext() &&
"ran out of attrs?") ? void (0) : __assert_fail ("cur && cur->getNext() && \"ran out of attrs?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 268, __extension__ __PRETTY_FUNCTION__))
;
269 if (cur->getNext() == &attr) {
270 cur->setNext(attr.getNext());
271 return;
272 }
273 cur = cur->getNext();
274 }
275}
276
277static void moveAttrFromListToList(AttributeList &attr,
278 AttributeList *&fromList,
279 AttributeList *&toList) {
280 spliceAttrOutOfList(attr, fromList);
281 spliceAttrIntoList(attr, toList);
282}
283
284/// The location of a type attribute.
285enum TypeAttrLocation {
286 /// The attribute is in the decl-specifier-seq.
287 TAL_DeclSpec,
288 /// The attribute is part of a DeclaratorChunk.
289 TAL_DeclChunk,
290 /// The attribute is immediately after the declaration's name.
291 TAL_DeclName
292};
293
294static void processTypeAttrs(TypeProcessingState &state,
295 QualType &type, TypeAttrLocation TAL,
296 AttributeList *attrs);
297
298static bool handleFunctionTypeAttr(TypeProcessingState &state,
299 AttributeList &attr,
300 QualType &type);
301
302static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
303 AttributeList &attr,
304 QualType &type);
305
306static bool handleObjCGCTypeAttr(TypeProcessingState &state,
307 AttributeList &attr, QualType &type);
308
309static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
310 AttributeList &attr, QualType &type);
311
312static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
313 AttributeList &attr, QualType &type) {
314 if (attr.getKind() == AttributeList::AT_ObjCGC)
315 return handleObjCGCTypeAttr(state, attr, type);
316 assert(attr.getKind() == AttributeList::AT_ObjCOwnership)(static_cast <bool> (attr.getKind() == AttributeList::AT_ObjCOwnership
) ? void (0) : __assert_fail ("attr.getKind() == AttributeList::AT_ObjCOwnership"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 316, __extension__ __PRETTY_FUNCTION__))
;
317 return handleObjCOwnershipTypeAttr(state, attr, type);
318}
319
320/// Given the index of a declarator chunk, check whether that chunk
321/// directly specifies the return type of a function and, if so, find
322/// an appropriate place for it.
323///
324/// \param i - a notional index which the search will start
325/// immediately inside
326///
327/// \param onlyBlockPointers Whether we should only look into block
328/// pointer types (vs. all pointer types).
329static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
330 unsigned i,
331 bool onlyBlockPointers) {
332 assert(i <= declarator.getNumTypeObjects())(static_cast <bool> (i <= declarator.getNumTypeObjects
()) ? void (0) : __assert_fail ("i <= declarator.getNumTypeObjects()"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 332, __extension__ __PRETTY_FUNCTION__))
;
333
334 DeclaratorChunk *result = nullptr;
335
336 // First, look inwards past parens for a function declarator.
337 for (; i != 0; --i) {
338 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
339 switch (fnChunk.Kind) {
340 case DeclaratorChunk::Paren:
341 continue;
342
343 // If we find anything except a function, bail out.
344 case DeclaratorChunk::Pointer:
345 case DeclaratorChunk::BlockPointer:
346 case DeclaratorChunk::Array:
347 case DeclaratorChunk::Reference:
348 case DeclaratorChunk::MemberPointer:
349 case DeclaratorChunk::Pipe:
350 return result;
351
352 // If we do find a function declarator, scan inwards from that,
353 // looking for a (block-)pointer declarator.
354 case DeclaratorChunk::Function:
355 for (--i; i != 0; --i) {
356 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
357 switch (ptrChunk.Kind) {
358 case DeclaratorChunk::Paren:
359 case DeclaratorChunk::Array:
360 case DeclaratorChunk::Function:
361 case DeclaratorChunk::Reference:
362 case DeclaratorChunk::Pipe:
363 continue;
364
365 case DeclaratorChunk::MemberPointer:
366 case DeclaratorChunk::Pointer:
367 if (onlyBlockPointers)
368 continue;
369
370 // fallthrough
371
372 case DeclaratorChunk::BlockPointer:
373 result = &ptrChunk;
374 goto continue_outer;
375 }
376 llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 376)
;
377 }
378
379 // If we run out of declarators doing that, we're done.
380 return result;
381 }
382 llvm_unreachable("bad declarator chunk kind")::llvm::llvm_unreachable_internal("bad declarator chunk kind"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 382)
;
383
384 // Okay, reconsider from our new point.
385 continue_outer: ;
386 }
387
388 // Ran out of chunks, bail out.
389 return result;
390}
391
392/// Given that an objc_gc attribute was written somewhere on a
393/// declaration *other* than on the declarator itself (for which, use
394/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
395/// didn't apply in whatever position it was written in, try to move
396/// it to a more appropriate position.
397static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
398 AttributeList &attr,
399 QualType type) {
400 Declarator &declarator = state.getDeclarator();
401
402 // Move it to the outermost normal or block pointer declarator.
403 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
404 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
405 switch (chunk.Kind) {
406 case DeclaratorChunk::Pointer:
407 case DeclaratorChunk::BlockPointer: {
408 // But don't move an ARC ownership attribute to the return type
409 // of a block.
410 DeclaratorChunk *destChunk = nullptr;
411 if (state.isProcessingDeclSpec() &&
412 attr.getKind() == AttributeList::AT_ObjCOwnership)
413 destChunk = maybeMovePastReturnType(declarator, i - 1,
414 /*onlyBlockPointers=*/true);
415 if (!destChunk) destChunk = &chunk;
416
417 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
418 destChunk->getAttrListRef());
419 return;
420 }
421
422 case DeclaratorChunk::Paren:
423 case DeclaratorChunk::Array:
424 continue;
425
426 // We may be starting at the return type of a block.
427 case DeclaratorChunk::Function:
428 if (state.isProcessingDeclSpec() &&
429 attr.getKind() == AttributeList::AT_ObjCOwnership) {
430 if (DeclaratorChunk *dest = maybeMovePastReturnType(
431 declarator, i,
432 /*onlyBlockPointers=*/true)) {
433 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
434 dest->getAttrListRef());
435 return;
436 }
437 }
438 goto error;
439
440 // Don't walk through these.
441 case DeclaratorChunk::Reference:
442 case DeclaratorChunk::MemberPointer:
443 case DeclaratorChunk::Pipe:
444 goto error;
445 }
446 }
447 error:
448
449 diagnoseBadTypeAttribute(state.getSema(), attr, type);
450}
451
452/// Distribute an objc_gc type attribute that was written on the
453/// declarator.
454static void
455distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
456 AttributeList &attr,
457 QualType &declSpecType) {
458 Declarator &declarator = state.getDeclarator();
459
460 // objc_gc goes on the innermost pointer to something that's not a
461 // pointer.
462 unsigned innermost = -1U;
463 bool considerDeclSpec = true;
464 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
465 DeclaratorChunk &chunk = declarator.getTypeObject(i);
466 switch (chunk.Kind) {
467 case DeclaratorChunk::Pointer:
468 case DeclaratorChunk::BlockPointer:
469 innermost = i;
470 continue;
471
472 case DeclaratorChunk::Reference:
473 case DeclaratorChunk::MemberPointer:
474 case DeclaratorChunk::Paren:
475 case DeclaratorChunk::Array:
476 case DeclaratorChunk::Pipe:
477 continue;
478
479 case DeclaratorChunk::Function:
480 considerDeclSpec = false;
481 goto done;
482 }
483 }
484 done:
485
486 // That might actually be the decl spec if we weren't blocked by
487 // anything in the declarator.
488 if (considerDeclSpec) {
489 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
490 // Splice the attribute into the decl spec. Prevents the
491 // attribute from being applied multiple times and gives
492 // the source-location-filler something to work with.
493 state.saveDeclSpecAttrs();
494 moveAttrFromListToList(attr, declarator.getAttrListRef(),
495 declarator.getMutableDeclSpec().getAttributes().getListRef());
496 return;
497 }
498 }
499
500 // Otherwise, if we found an appropriate chunk, splice the attribute
501 // into it.
502 if (innermost != -1U) {
503 moveAttrFromListToList(attr, declarator.getAttrListRef(),
504 declarator.getTypeObject(innermost).getAttrListRef());
505 return;
506 }
507
508 // Otherwise, diagnose when we're done building the type.
509 spliceAttrOutOfList(attr, declarator.getAttrListRef());
510 state.addIgnoredTypeAttr(attr);
511}
512
513/// A function type attribute was written somewhere in a declaration
514/// *other* than on the declarator itself or in the decl spec. Given
515/// that it didn't apply in whatever position it was written in, try
516/// to move it to a more appropriate position.
517static void distributeFunctionTypeAttr(TypeProcessingState &state,
518 AttributeList &attr,
519 QualType type) {
520 Declarator &declarator = state.getDeclarator();
521
522 // Try to push the attribute from the return type of a function to
523 // the function itself.
524 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
525 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
526 switch (chunk.Kind) {
527 case DeclaratorChunk::Function:
528 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
529 chunk.getAttrListRef());
530 return;
531
532 case DeclaratorChunk::Paren:
533 case DeclaratorChunk::Pointer:
534 case DeclaratorChunk::BlockPointer:
535 case DeclaratorChunk::Array:
536 case DeclaratorChunk::Reference:
537 case DeclaratorChunk::MemberPointer:
538 case DeclaratorChunk::Pipe:
539 continue;
540 }
541 }
542
543 diagnoseBadTypeAttribute(state.getSema(), attr, type);
544}
545
546/// Try to distribute a function type attribute to the innermost
547/// function chunk or type. Returns true if the attribute was
548/// distributed, false if no location was found.
549static bool
550distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
551 AttributeList &attr,
552 AttributeList *&attrList,
553 QualType &declSpecType) {
554 Declarator &declarator = state.getDeclarator();
555
556 // Put it on the innermost function chunk, if there is one.
557 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
558 DeclaratorChunk &chunk = declarator.getTypeObject(i);
559 if (chunk.Kind != DeclaratorChunk::Function) continue;
560
561 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
562 return true;
563 }
564
565 return handleFunctionTypeAttr(state, attr, declSpecType);
566}
567
568/// A function type attribute was written in the decl spec. Try to
569/// apply it somewhere.
570static void
571distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
572 AttributeList &attr,
573 QualType &declSpecType) {
574 state.saveDeclSpecAttrs();
575
576 // C++11 attributes before the decl specifiers actually appertain to
577 // the declarators. Move them straight there. We don't support the
578 // 'put them wherever you like' semantics we allow for GNU attributes.
579 if (attr.isCXX11Attribute()) {
580 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
581 state.getDeclarator().getAttrListRef());
582 return;
583 }
584
585 // Try to distribute to the innermost.
586 if (distributeFunctionTypeAttrToInnermost(state, attr,
587 state.getCurrentAttrListRef(),
588 declSpecType))
589 return;
590
591 // If that failed, diagnose the bad attribute when the declarator is
592 // fully built.
593 state.addIgnoredTypeAttr(attr);
594}
595
596/// A function type attribute was written on the declarator. Try to
597/// apply it somewhere.
598static void
599distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
600 AttributeList &attr,
601 QualType &declSpecType) {
602 Declarator &declarator = state.getDeclarator();
603
604 // Try to distribute to the innermost.
605 if (distributeFunctionTypeAttrToInnermost(state, attr,
606 declarator.getAttrListRef(),
607 declSpecType))
608 return;
609
610 // If that failed, diagnose the bad attribute when the declarator is
611 // fully built.
612 spliceAttrOutOfList(attr, declarator.getAttrListRef());
613 state.addIgnoredTypeAttr(attr);
614}
615
616/// \brief Given that there are attributes written on the declarator
617/// itself, try to distribute any type attributes to the appropriate
618/// declarator chunk.
619///
620/// These are attributes like the following:
621/// int f ATTR;
622/// int (f ATTR)();
623/// but not necessarily this:
624/// int f() ATTR;
625static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
626 QualType &declSpecType) {
627 // Collect all the type attributes from the declarator itself.
628 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!")(static_cast <bool> (state.getDeclarator().getAttributes
() && "declarator has no attrs!") ? void (0) : __assert_fail
("state.getDeclarator().getAttributes() && \"declarator has no attrs!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 628, __extension__ __PRETTY_FUNCTION__))
;
629 AttributeList *attr = state.getDeclarator().getAttributes();
630 AttributeList *next;
631 do {
632 next = attr->getNext();
633
634 // Do not distribute C++11 attributes. They have strict rules for what
635 // they appertain to.
636 if (attr->isCXX11Attribute())
637 continue;
638
639 switch (attr->getKind()) {
640 OBJC_POINTER_TYPE_ATTRS_CASELISTcase AttributeList::AT_ObjCGC: case AttributeList::AT_ObjCOwnership:
641 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
642 break;
643
644 FUNCTION_TYPE_ATTRS_CASELISTcase AttributeList::AT_NSReturnsRetained: case AttributeList::
AT_NoReturn: case AttributeList::AT_Regparm: case AttributeList
::AT_AnyX86NoCallerSavedRegisters: case AttributeList::AT_CDecl
: case AttributeList::AT_FastCall: case AttributeList::AT_StdCall
: case AttributeList::AT_ThisCall: case AttributeList::AT_RegCall
: case AttributeList::AT_Pascal: case AttributeList::AT_SwiftCall
: case AttributeList::AT_VectorCall: case AttributeList::AT_MSABI
: case AttributeList::AT_SysVABI: case AttributeList::AT_Pcs:
case AttributeList::AT_IntelOclBicc: case AttributeList::AT_PreserveMost
: case AttributeList::AT_PreserveAll
:
645 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
646 break;
647
648 MS_TYPE_ATTRS_CASELISTcase AttributeList::AT_Ptr32: case AttributeList::AT_Ptr64: case
AttributeList::AT_SPtr: case AttributeList::AT_UPtr
:
649 // Microsoft type attributes cannot go after the declarator-id.
650 continue;
651
652 NULLABILITY_TYPE_ATTRS_CASELISTcase AttributeList::AT_TypeNonNull: case AttributeList::AT_TypeNullable
: case AttributeList::AT_TypeNullUnspecified
:
653 // Nullability specifiers cannot go after the declarator-id.
654
655 // Objective-C __kindof does not get distributed.
656 case AttributeList::AT_ObjCKindOf:
657 continue;
658
659 default:
660 break;
661 }
662 } while ((attr = next));
663}
664
665/// Add a synthetic '()' to a block-literal declarator if it is
666/// required, given the return type.
667static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
668 QualType declSpecType) {
669 Declarator &declarator = state.getDeclarator();
670
671 // First, check whether the declarator would produce a function,
672 // i.e. whether the innermost semantic chunk is a function.
673 if (declarator.isFunctionDeclarator()) {
674 // If so, make that declarator a prototyped declarator.
675 declarator.getFunctionTypeInfo().hasPrototype = true;
676 return;
677 }
678
679 // If there are any type objects, the type as written won't name a
680 // function, regardless of the decl spec type. This is because a
681 // block signature declarator is always an abstract-declarator, and
682 // abstract-declarators can't just be parentheses chunks. Therefore
683 // we need to build a function chunk unless there are no type
684 // objects and the decl spec type is a function.
685 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
686 return;
687
688 // Note that there *are* cases with invalid declarators where
689 // declarators consist solely of parentheses. In general, these
690 // occur only in failed efforts to make function declarators, so
691 // faking up the function chunk is still the right thing to do.
692
693 // Otherwise, we need to fake up a function declarator.
694 SourceLocation loc = declarator.getLocStart();
695
696 // ...and *prepend* it to the declarator.
697 SourceLocation NoLoc;
698 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
699 /*HasProto=*/true,
700 /*IsAmbiguous=*/false,
701 /*LParenLoc=*/NoLoc,
702 /*ArgInfo=*/nullptr,
703 /*NumArgs=*/0,
704 /*EllipsisLoc=*/NoLoc,
705 /*RParenLoc=*/NoLoc,
706 /*TypeQuals=*/0,
707 /*RefQualifierIsLvalueRef=*/true,
708 /*RefQualifierLoc=*/NoLoc,
709 /*ConstQualifierLoc=*/NoLoc,
710 /*VolatileQualifierLoc=*/NoLoc,
711 /*RestrictQualifierLoc=*/NoLoc,
712 /*MutableLoc=*/NoLoc, EST_None,
713 /*ESpecRange=*/SourceRange(),
714 /*Exceptions=*/nullptr,
715 /*ExceptionRanges=*/nullptr,
716 /*NumExceptions=*/0,
717 /*NoexceptExpr=*/nullptr,
718 /*ExceptionSpecTokens=*/nullptr,
719 /*DeclsInPrototype=*/None,
720 loc, loc, declarator));
721
722 // For consistency, make sure the state still has us as processing
723 // the decl spec.
724 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1)(static_cast <bool> (state.getCurrentChunkIndex() == declarator
.getNumTypeObjects() - 1) ? void (0) : __assert_fail ("state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 724, __extension__ __PRETTY_FUNCTION__))
;
725 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
726}
727
728static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
729 unsigned &TypeQuals,
730 QualType TypeSoFar,
731 unsigned RemoveTQs,
732 unsigned DiagID) {
733 // If this occurs outside a template instantiation, warn the user about
734 // it; they probably didn't mean to specify a redundant qualifier.
735 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
736 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
737 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
738 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
739 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
740 if (!(RemoveTQs & Qual.first))
741 continue;
742
743 if (!S.inTemplateInstantiation()) {
744 if (TypeQuals & Qual.first)
745 S.Diag(Qual.second, DiagID)
746 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
747 << FixItHint::CreateRemoval(Qual.second);
748 }
749
750 TypeQuals &= ~Qual.first;
751 }
752}
753
754/// Return true if this is omitted block return type. Also check type
755/// attributes and type qualifiers when returning true.
756static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
757 QualType Result) {
758 if (!isOmittedBlockReturnType(declarator))
759 return false;
760
761 // Warn if we see type attributes for omitted return type on a block literal.
762 AttributeList *&attrs =
763 declarator.getMutableDeclSpec().getAttributes().getListRef();
764 AttributeList *prev = nullptr;
765 for (AttributeList *cur = attrs; cur; cur = cur->getNext()) {
766 AttributeList &attr = *cur;
767 // Skip attributes that were marked to be invalid or non-type
768 // attributes.
769 if (attr.isInvalid() || !attr.isTypeAttr()) {
770 prev = cur;
771 continue;
772 }
773 S.Diag(attr.getLoc(),
774 diag::warn_block_literal_attributes_on_omitted_return_type)
775 << attr.getName();
776 // Remove cur from the list.
777 if (prev) {
778 prev->setNext(cur->getNext());
779 prev = cur;
780 } else {
781 attrs = cur->getNext();
782 }
783 }
784
785 // Warn if we see type qualifiers for omitted return type on a block literal.
786 const DeclSpec &DS = declarator.getDeclSpec();
787 unsigned TypeQuals = DS.getTypeQualifiers();
788 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
789 diag::warn_block_literal_qualifiers_on_omitted_return_type);
790 declarator.getMutableDeclSpec().ClearTypeQualifiers();
791
792 return true;
793}
794
795/// Apply Objective-C type arguments to the given type.
796static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
797 ArrayRef<TypeSourceInfo *> typeArgs,
798 SourceRange typeArgsRange,
799 bool failOnError = false) {
800 // We can only apply type arguments to an Objective-C class type.
801 const auto *objcObjectType = type->getAs<ObjCObjectType>();
802 if (!objcObjectType || !objcObjectType->getInterface()) {
803 S.Diag(loc, diag::err_objc_type_args_non_class)
804 << type
805 << typeArgsRange;
806
807 if (failOnError)
808 return QualType();
809 return type;
810 }
811
812 // The class type must be parameterized.
813 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
814 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
815 if (!typeParams) {
816 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
817 << objcClass->getDeclName()
818 << FixItHint::CreateRemoval(typeArgsRange);
819
820 if (failOnError)
821 return QualType();
822
823 return type;
824 }
825
826 // The type must not already be specialized.
827 if (objcObjectType->isSpecialized()) {
828 S.Diag(loc, diag::err_objc_type_args_specialized_class)
829 << type
830 << FixItHint::CreateRemoval(typeArgsRange);
831
832 if (failOnError)
833 return QualType();
834
835 return type;
836 }
837
838 // Check the type arguments.
839 SmallVector<QualType, 4> finalTypeArgs;
840 unsigned numTypeParams = typeParams->size();
841 bool anyPackExpansions = false;
842 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
843 TypeSourceInfo *typeArgInfo = typeArgs[i];
844 QualType typeArg = typeArgInfo->getType();
845
846 // Type arguments cannot have explicit qualifiers or nullability.
847 // We ignore indirect sources of these, e.g. behind typedefs or
848 // template arguments.
849 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
850 bool diagnosed = false;
851 SourceRange rangeToRemove;
852 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
853 rangeToRemove = attr.getLocalSourceRange();
854 if (attr.getTypePtr()->getImmediateNullability()) {
855 typeArg = attr.getTypePtr()->getModifiedType();
856 S.Diag(attr.getLocStart(),
857 diag::err_objc_type_arg_explicit_nullability)
858 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
859 diagnosed = true;
860 }
861 }
862
863 if (!diagnosed) {
864 S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
865 << typeArg << typeArg.getQualifiers().getAsString()
866 << FixItHint::CreateRemoval(rangeToRemove);
867 }
868 }
869
870 // Remove qualifiers even if they're non-local.
871 typeArg = typeArg.getUnqualifiedType();
872
873 finalTypeArgs.push_back(typeArg);
874
875 if (typeArg->getAs<PackExpansionType>())
876 anyPackExpansions = true;
877
878 // Find the corresponding type parameter, if there is one.
879 ObjCTypeParamDecl *typeParam = nullptr;
880 if (!anyPackExpansions) {
881 if (i < numTypeParams) {
882 typeParam = typeParams->begin()[i];
883 } else {
884 // Too many arguments.
885 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
886 << false
887 << objcClass->getDeclName()
888 << (unsigned)typeArgs.size()
889 << numTypeParams;
890 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
891 << objcClass;
892
893 if (failOnError)
894 return QualType();
895
896 return type;
897 }
898 }
899
900 // Objective-C object pointer types must be substitutable for the bounds.
901 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
902 // If we don't have a type parameter to match against, assume
903 // everything is fine. There was a prior pack expansion that
904 // means we won't be able to match anything.
905 if (!typeParam) {
906 assert(anyPackExpansions && "Too many arguments?")(static_cast <bool> (anyPackExpansions && "Too many arguments?"
) ? void (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 906, __extension__ __PRETTY_FUNCTION__))
;
907 continue;
908 }
909
910 // Retrieve the bound.
911 QualType bound = typeParam->getUnderlyingType();
912 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
913
914 // Determine whether the type argument is substitutable for the bound.
915 if (typeArgObjC->isObjCIdType()) {
916 // When the type argument is 'id', the only acceptable type
917 // parameter bound is 'id'.
918 if (boundObjC->isObjCIdType())
919 continue;
920 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
921 // Otherwise, we follow the assignability rules.
922 continue;
923 }
924
925 // Diagnose the mismatch.
926 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
927 diag::err_objc_type_arg_does_not_match_bound)
928 << typeArg << bound << typeParam->getDeclName();
929 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
930 << typeParam->getDeclName();
931
932 if (failOnError)
933 return QualType();
934
935 return type;
936 }
937
938 // Block pointer types are permitted for unqualified 'id' bounds.
939 if (typeArg->isBlockPointerType()) {
940 // If we don't have a type parameter to match against, assume
941 // everything is fine. There was a prior pack expansion that
942 // means we won't be able to match anything.
943 if (!typeParam) {
944 assert(anyPackExpansions && "Too many arguments?")(static_cast <bool> (anyPackExpansions && "Too many arguments?"
) ? void (0) : __assert_fail ("anyPackExpansions && \"Too many arguments?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 944, __extension__ __PRETTY_FUNCTION__))
;
945 continue;
946 }
947
948 // Retrieve the bound.
949 QualType bound = typeParam->getUnderlyingType();
950 if (bound->isBlockCompatibleObjCPointerType(S.Context))
951 continue;
952
953 // Diagnose the mismatch.
954 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
955 diag::err_objc_type_arg_does_not_match_bound)
956 << typeArg << bound << typeParam->getDeclName();
957 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
958 << typeParam->getDeclName();
959
960 if (failOnError)
961 return QualType();
962
963 return type;
964 }
965
966 // Dependent types will be checked at instantiation time.
967 if (typeArg->isDependentType()) {
968 continue;
969 }
970
971 // Diagnose non-id-compatible type arguments.
972 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
973 diag::err_objc_type_arg_not_id_compatible)
974 << typeArg
975 << typeArgInfo->getTypeLoc().getSourceRange();
976
977 if (failOnError)
978 return QualType();
979
980 return type;
981 }
982
983 // Make sure we didn't have the wrong number of arguments.
984 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
985 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
986 << (typeArgs.size() < typeParams->size())
987 << objcClass->getDeclName()
988 << (unsigned)finalTypeArgs.size()
989 << (unsigned)numTypeParams;
990 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
991 << objcClass;
992
993 if (failOnError)
994 return QualType();
995
996 return type;
997 }
998
999 // Success. Form the specialized type.
1000 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1001}
1002
1003QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1004 SourceLocation ProtocolLAngleLoc,
1005 ArrayRef<ObjCProtocolDecl *> Protocols,
1006 ArrayRef<SourceLocation> ProtocolLocs,
1007 SourceLocation ProtocolRAngleLoc,
1008 bool FailOnError) {
1009 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1010 if (!Protocols.empty()) {
1011 bool HasError;
1012 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1013 HasError);
1014 if (HasError) {
1015 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1016 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1017 if (FailOnError) Result = QualType();
1018 }
1019 if (FailOnError && Result.isNull())
1020 return QualType();
1021 }
1022
1023 return Result;
1024}
1025
1026QualType Sema::BuildObjCObjectType(QualType BaseType,
1027 SourceLocation Loc,
1028 SourceLocation TypeArgsLAngleLoc,
1029 ArrayRef<TypeSourceInfo *> TypeArgs,
1030 SourceLocation TypeArgsRAngleLoc,
1031 SourceLocation ProtocolLAngleLoc,
1032 ArrayRef<ObjCProtocolDecl *> Protocols,
1033 ArrayRef<SourceLocation> ProtocolLocs,
1034 SourceLocation ProtocolRAngleLoc,
1035 bool FailOnError) {
1036 QualType Result = BaseType;
1037 if (!TypeArgs.empty()) {
1038 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1039 SourceRange(TypeArgsLAngleLoc,
1040 TypeArgsRAngleLoc),
1041 FailOnError);
1042 if (FailOnError && Result.isNull())
1043 return QualType();
1044 }
1045
1046 if (!Protocols.empty()) {
1047 bool HasError;
1048 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1049 HasError);
1050 if (HasError) {
1051 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1052 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1053 if (FailOnError) Result = QualType();
1054 }
1055 if (FailOnError && Result.isNull())
1056 return QualType();
1057 }
1058
1059 return Result;
1060}
1061
1062TypeResult Sema::actOnObjCProtocolQualifierType(
1063 SourceLocation lAngleLoc,
1064 ArrayRef<Decl *> protocols,
1065 ArrayRef<SourceLocation> protocolLocs,
1066 SourceLocation rAngleLoc) {
1067 // Form id<protocol-list>.
1068 QualType Result = Context.getObjCObjectType(
1069 Context.ObjCBuiltinIdTy, { },
1070 llvm::makeArrayRef(
1071 (ObjCProtocolDecl * const *)protocols.data(),
1072 protocols.size()),
1073 false);
1074 Result = Context.getObjCObjectPointerType(Result);
1075
1076 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1077 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1078
1079 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1080 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1081
1082 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1083 .castAs<ObjCObjectTypeLoc>();
1084 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1085 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1086
1087 // No type arguments.
1088 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1089 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1090
1091 // Fill in protocol qualifiers.
1092 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1093 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1094 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1095 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1096
1097 // We're done. Return the completed type to the parser.
1098 return CreateParsedType(Result, ResultTInfo);
1099}
1100
1101TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1102 Scope *S,
1103 SourceLocation Loc,
1104 ParsedType BaseType,
1105 SourceLocation TypeArgsLAngleLoc,
1106 ArrayRef<ParsedType> TypeArgs,
1107 SourceLocation TypeArgsRAngleLoc,
1108 SourceLocation ProtocolLAngleLoc,
1109 ArrayRef<Decl *> Protocols,
1110 ArrayRef<SourceLocation> ProtocolLocs,
1111 SourceLocation ProtocolRAngleLoc) {
1112 TypeSourceInfo *BaseTypeInfo = nullptr;
1113 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1114 if (T.isNull())
1115 return true;
1116
1117 // Handle missing type-source info.
1118 if (!BaseTypeInfo)
1119 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1120
1121 // Extract type arguments.
1122 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1123 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1124 TypeSourceInfo *TypeArgInfo = nullptr;
1125 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1126 if (TypeArg.isNull()) {
1127 ActualTypeArgInfos.clear();
1128 break;
1129 }
1130
1131 assert(TypeArgInfo && "No type source info?")(static_cast <bool> (TypeArgInfo && "No type source info?"
) ? void (0) : __assert_fail ("TypeArgInfo && \"No type source info?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1131, __extension__ __PRETTY_FUNCTION__))
;
1132 ActualTypeArgInfos.push_back(TypeArgInfo);
1133 }
1134
1135 // Build the object type.
1136 QualType Result = BuildObjCObjectType(
1137 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1138 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1139 ProtocolLAngleLoc,
1140 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1141 Protocols.size()),
1142 ProtocolLocs, ProtocolRAngleLoc,
1143 /*FailOnError=*/false);
1144
1145 if (Result == T)
1146 return BaseType;
1147
1148 // Create source information for this type.
1149 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1150 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1151
1152 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1153 // object pointer type. Fill in source information for it.
1154 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1155 // The '*' is implicit.
1156 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1157 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1158 }
1159
1160 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1161 // Protocol qualifier information.
1162 if (OTPTL.getNumProtocols() > 0) {
1163 assert(OTPTL.getNumProtocols() == Protocols.size())(static_cast <bool> (OTPTL.getNumProtocols() == Protocols
.size()) ? void (0) : __assert_fail ("OTPTL.getNumProtocols() == Protocols.size()"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1163, __extension__ __PRETTY_FUNCTION__))
;
1164 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1165 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1166 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1167 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1168 }
1169
1170 // We're done. Return the completed type to the parser.
1171 return CreateParsedType(Result, ResultTInfo);
1172 }
1173
1174 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1175
1176 // Type argument information.
1177 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1178 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size())(static_cast <bool> (ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos
.size()) ? void (0) : __assert_fail ("ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1178, __extension__ __PRETTY_FUNCTION__))
;
1179 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1180 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1181 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1182 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1183 } else {
1184 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1185 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1186 }
1187
1188 // Protocol qualifier information.
1189 if (ObjCObjectTL.getNumProtocols() > 0) {
1190 assert(ObjCObjectTL.getNumProtocols() == Protocols.size())(static_cast <bool> (ObjCObjectTL.getNumProtocols() == Protocols
.size()) ? void (0) : __assert_fail ("ObjCObjectTL.getNumProtocols() == Protocols.size()"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1190, __extension__ __PRETTY_FUNCTION__))
;
1191 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1192 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1193 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1194 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1195 } else {
1196 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1197 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1198 }
1199
1200 // Base type.
1201 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1202 if (ObjCObjectTL.getType() == T)
1203 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1204 else
1205 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1206
1207 // We're done. Return the completed type to the parser.
1208 return CreateParsedType(Result, ResultTInfo);
1209}
1210
1211static OpenCLAccessAttr::Spelling getImageAccess(const AttributeList *Attrs) {
1212 if (Attrs) {
1213 const AttributeList *Next = Attrs;
1214 do {
1215 const AttributeList &Attr = *Next;
1216 Next = Attr.getNext();
1217 if (Attr.getKind() == AttributeList::AT_OpenCLAccess) {
1218 return static_cast<OpenCLAccessAttr::Spelling>(
1219 Attr.getSemanticSpelling());
1220 }
1221 } while (Next);
1222 }
1223 return OpenCLAccessAttr::Keyword_read_only;
1224}
1225
1226/// \brief Convert the specified declspec to the appropriate type
1227/// object.
1228/// \param state Specifies the declarator containing the declaration specifier
1229/// to be converted, along with other associated processing state.
1230/// \returns The type described by the declaration specifiers. This function
1231/// never returns null.
1232static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1233 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1234 // checking.
1235
1236 Sema &S = state.getSema();
1237 Declarator &declarator = state.getDeclarator();
1238 const DeclSpec &DS = declarator.getDeclSpec();
1239 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1240 if (DeclLoc.isInvalid())
1241 DeclLoc = DS.getLocStart();
1242
1243 ASTContext &Context = S.Context;
1244
1245 QualType Result;
1246 switch (DS.getTypeSpecType()) {
1247 case DeclSpec::TST_void:
1248 Result = Context.VoidTy;
1249 break;
1250 case DeclSpec::TST_char:
1251 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1252 Result = Context.CharTy;
1253 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1254 Result = Context.SignedCharTy;
1255 else {
1256 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec::
TSS_unsigned && "Unknown TSS value") ? void (0) : __assert_fail
("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1257, __extension__ __PRETTY_FUNCTION__))
1257 "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec::
TSS_unsigned && "Unknown TSS value") ? void (0) : __assert_fail
("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1257, __extension__ __PRETTY_FUNCTION__))
;
1258 Result = Context.UnsignedCharTy;
1259 }
1260 break;
1261 case DeclSpec::TST_wchar:
1262 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1263 Result = Context.WCharTy;
1264 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1265 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1266 << DS.getSpecifierName(DS.getTypeSpecType(),
1267 Context.getPrintingPolicy());
1268 Result = Context.getSignedWCharType();
1269 } else {
1270 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec::
TSS_unsigned && "Unknown TSS value") ? void (0) : __assert_fail
("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1271, __extension__ __PRETTY_FUNCTION__))
1271 "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec::
TSS_unsigned && "Unknown TSS value") ? void (0) : __assert_fail
("DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && \"Unknown TSS value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1271, __extension__ __PRETTY_FUNCTION__))
;
1272 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1273 << DS.getSpecifierName(DS.getTypeSpecType(),
1274 Context.getPrintingPolicy());
1275 Result = Context.getUnsignedWCharType();
1276 }
1277 break;
1278 case DeclSpec::TST_char16:
1279 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec::
TSS_unspecified && "Unknown TSS value") ? void (0) : __assert_fail
("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1280, __extension__ __PRETTY_FUNCTION__))
1280 "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec::
TSS_unspecified && "Unknown TSS value") ? void (0) : __assert_fail
("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1280, __extension__ __PRETTY_FUNCTION__))
;
1281 Result = Context.Char16Ty;
1282 break;
1283 case DeclSpec::TST_char32:
1284 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec::
TSS_unspecified && "Unknown TSS value") ? void (0) : __assert_fail
("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1285, __extension__ __PRETTY_FUNCTION__))
1285 "Unknown TSS value")(static_cast <bool> (DS.getTypeSpecSign() == DeclSpec::
TSS_unspecified && "Unknown TSS value") ? void (0) : __assert_fail
("DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && \"Unknown TSS value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1285, __extension__ __PRETTY_FUNCTION__))
;
1286 Result = Context.Char32Ty;
1287 break;
1288 case DeclSpec::TST_unspecified:
1289 // If this is a missing declspec in a block literal return context, then it
1290 // is inferred from the return statements inside the block.
1291 // The declspec is always missing in a lambda expr context; it is either
1292 // specified with a trailing return type or inferred.
1293 if (S.getLangOpts().CPlusPlus14 &&
1294 declarator.getContext() == Declarator::LambdaExprContext) {
1295 // In C++1y, a lambda's implicit return type is 'auto'.
1296 Result = Context.getAutoDeductType();
1297 break;
1298 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1299 checkOmittedBlockReturnType(S, declarator,
1300 Context.DependentTy)) {
1301 Result = Context.DependentTy;
1302 break;
1303 }
1304
1305 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1306 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1307 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1308 // Note that the one exception to this is function definitions, which are
1309 // allowed to be completely missing a declspec. This is handled in the
1310 // parser already though by it pretending to have seen an 'int' in this
1311 // case.
1312 if (S.getLangOpts().ImplicitInt) {
1313 // In C89 mode, we only warn if there is a completely missing declspec
1314 // when one is not allowed.
1315 if (DS.isEmpty()) {
1316 S.Diag(DeclLoc, diag::ext_missing_declspec)
1317 << DS.getSourceRange()
1318 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1319 }
1320 } else if (!DS.hasTypeSpecifier()) {
1321 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1322 // "At least one type specifier shall be given in the declaration
1323 // specifiers in each declaration, and in the specifier-qualifier list in
1324 // each struct declaration and type name."
1325 if (S.getLangOpts().CPlusPlus) {
1326 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1327 << DS.getSourceRange();
1328
1329 // When this occurs in C++ code, often something is very broken with the
1330 // value being declared, poison it as invalid so we don't get chains of
1331 // errors.
1332 declarator.setInvalidType(true);
1333 } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1334 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1335 << DS.getSourceRange();
1336 declarator.setInvalidType(true);
1337 } else {
1338 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1339 << DS.getSourceRange();
1340 }
1341 }
1342
1343 // FALL THROUGH.
1344 case DeclSpec::TST_int: {
1345 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1346 switch (DS.getTypeSpecWidth()) {
1347 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1348 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1349 case DeclSpec::TSW_long: Result = Context.LongTy; break;
1350 case DeclSpec::TSW_longlong:
1351 Result = Context.LongLongTy;
1352
1353 // 'long long' is a C99 or C++11 feature.
1354 if (!S.getLangOpts().C99) {
1355 if (S.getLangOpts().CPlusPlus)
1356 S.Diag(DS.getTypeSpecWidthLoc(),
1357 S.getLangOpts().CPlusPlus11 ?
1358 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1359 else
1360 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1361 }
1362 break;
1363 }
1364 } else {
1365 switch (DS.getTypeSpecWidth()) {
1366 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1367 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1368 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1369 case DeclSpec::TSW_longlong:
1370 Result = Context.UnsignedLongLongTy;
1371
1372 // 'long long' is a C99 or C++11 feature.
1373 if (!S.getLangOpts().C99) {
1374 if (S.getLangOpts().CPlusPlus)
1375 S.Diag(DS.getTypeSpecWidthLoc(),
1376 S.getLangOpts().CPlusPlus11 ?
1377 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1378 else
1379 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1380 }
1381 break;
1382 }
1383 }
1384 break;
1385 }
1386 case DeclSpec::TST_int128:
1387 if (!S.Context.getTargetInfo().hasInt128Type())
1388 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1389 << "__int128";
1390 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1391 Result = Context.UnsignedInt128Ty;
1392 else
1393 Result = Context.Int128Ty;
1394 break;
1395 case DeclSpec::TST_float16: Result = Context.Float16Ty; break;
1396 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1397 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1398 case DeclSpec::TST_double:
1399 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1400 Result = Context.LongDoubleTy;
1401 else
1402 Result = Context.DoubleTy;
1403 break;
1404 case DeclSpec::TST_float128:
1405 if (!S.Context.getTargetInfo().hasFloat128Type())
1406 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1407 << "__float128";
1408 Result = Context.Float128Ty;
1409 break;
1410 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1411 break;
1412 case DeclSpec::TST_decimal32: // _Decimal32
1413 case DeclSpec::TST_decimal64: // _Decimal64
1414 case DeclSpec::TST_decimal128: // _Decimal128
1415 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1416 Result = Context.IntTy;
1417 declarator.setInvalidType(true);
1418 break;
1419 case DeclSpec::TST_class:
1420 case DeclSpec::TST_enum:
1421 case DeclSpec::TST_union:
1422 case DeclSpec::TST_struct:
1423 case DeclSpec::TST_interface: {
1424 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1425 if (!D) {
1426 // This can happen in C++ with ambiguous lookups.
1427 Result = Context.IntTy;
1428 declarator.setInvalidType(true);
1429 break;
1430 }
1431
1432 // If the type is deprecated or unavailable, diagnose it.
1433 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1434
1435 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == 0 &&
DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign()
== 0 && "No qualifiers on tag names!") ? void (0) : __assert_fail
("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"No qualifiers on tag names!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1436, __extension__ __PRETTY_FUNCTION__))
1436 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!")(static_cast <bool> (DS.getTypeSpecWidth() == 0 &&
DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign()
== 0 && "No qualifiers on tag names!") ? void (0) : __assert_fail
("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"No qualifiers on tag names!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1436, __extension__ __PRETTY_FUNCTION__))
;
1437
1438 // TypeQuals handled by caller.
1439 Result = Context.getTypeDeclType(D);
1440
1441 // In both C and C++, make an ElaboratedType.
1442 ElaboratedTypeKeyword Keyword
1443 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1444 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1445 break;
1446 }
1447 case DeclSpec::TST_typename: {
1448 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == 0 &&
DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign()
== 0 && "Can't handle qualifiers on typedef names yet!"
) ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"Can't handle qualifiers on typedef names yet!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1450, __extension__ __PRETTY_FUNCTION__))
1449 DS.getTypeSpecSign() == 0 &&(static_cast <bool> (DS.getTypeSpecWidth() == 0 &&
DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign()
== 0 && "Can't handle qualifiers on typedef names yet!"
) ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"Can't handle qualifiers on typedef names yet!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1450, __extension__ __PRETTY_FUNCTION__))
1450 "Can't handle qualifiers on typedef names yet!")(static_cast <bool> (DS.getTypeSpecWidth() == 0 &&
DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign()
== 0 && "Can't handle qualifiers on typedef names yet!"
) ? void (0) : __assert_fail ("DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && DS.getTypeSpecSign() == 0 && \"Can't handle qualifiers on typedef names yet!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1450, __extension__ __PRETTY_FUNCTION__))
;
1451 Result = S.GetTypeFromParser(DS.getRepAsType());
1452 if (Result.isNull()) {
1453 declarator.setInvalidType(true);
1454 }
1455
1456 // TypeQuals handled by caller.
1457 break;
1458 }
1459 case DeclSpec::TST_typeofType:
1460 // FIXME: Preserve type source info.
1461 Result = S.GetTypeFromParser(DS.getRepAsType());
1462 assert(!Result.isNull() && "Didn't get a type for typeof?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for typeof?"
) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for typeof?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1462, __extension__ __PRETTY_FUNCTION__))
;
1463 if (!Result->isDependentType())
1464 if (const TagType *TT = Result->getAs<TagType>())
1465 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1466 // TypeQuals handled by caller.
1467 Result = Context.getTypeOfType(Result);
1468 break;
1469 case DeclSpec::TST_typeofExpr: {
1470 Expr *E = DS.getRepAsExpr();
1471 assert(E && "Didn't get an expression for typeof?")(static_cast <bool> (E && "Didn't get an expression for typeof?"
) ? void (0) : __assert_fail ("E && \"Didn't get an expression for typeof?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1471, __extension__ __PRETTY_FUNCTION__))
;
1472 // TypeQuals handled by caller.
1473 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1474 if (Result.isNull()) {
1475 Result = Context.IntTy;
1476 declarator.setInvalidType(true);
1477 }
1478 break;
1479 }
1480 case DeclSpec::TST_decltype: {
1481 Expr *E = DS.getRepAsExpr();
1482 assert(E && "Didn't get an expression for decltype?")(static_cast <bool> (E && "Didn't get an expression for decltype?"
) ? void (0) : __assert_fail ("E && \"Didn't get an expression for decltype?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1482, __extension__ __PRETTY_FUNCTION__))
;
1483 // TypeQuals handled by caller.
1484 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1485 if (Result.isNull()) {
1486 Result = Context.IntTy;
1487 declarator.setInvalidType(true);
1488 }
1489 break;
1490 }
1491 case DeclSpec::TST_underlyingType:
1492 Result = S.GetTypeFromParser(DS.getRepAsType());
1493 assert(!Result.isNull() && "Didn't get a type for __underlying_type?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for __underlying_type?"
) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for __underlying_type?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1493, __extension__ __PRETTY_FUNCTION__))
;
1494 Result = S.BuildUnaryTransformType(Result,
1495 UnaryTransformType::EnumUnderlyingType,
1496 DS.getTypeSpecTypeLoc());
1497 if (Result.isNull()) {
1498 Result = Context.IntTy;
1499 declarator.setInvalidType(true);
1500 }
1501 break;
1502
1503 case DeclSpec::TST_auto:
1504 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1505 break;
1506
1507 case DeclSpec::TST_auto_type:
1508 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1509 break;
1510
1511 case DeclSpec::TST_decltype_auto:
1512 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1513 /*IsDependent*/ false);
1514 break;
1515
1516 case DeclSpec::TST_unknown_anytype:
1517 Result = Context.UnknownAnyTy;
1518 break;
1519
1520 case DeclSpec::TST_atomic:
1521 Result = S.GetTypeFromParser(DS.getRepAsType());
1522 assert(!Result.isNull() && "Didn't get a type for _Atomic?")(static_cast <bool> (!Result.isNull() && "Didn't get a type for _Atomic?"
) ? void (0) : __assert_fail ("!Result.isNull() && \"Didn't get a type for _Atomic?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1522, __extension__ __PRETTY_FUNCTION__))
;
1523 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1524 if (Result.isNull()) {
1525 Result = Context.IntTy;
1526 declarator.setInvalidType(true);
1527 }
1528 break;
1529
1530#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1531 case DeclSpec::TST_##ImgType##_t: \
1532 switch (getImageAccess(DS.getAttributes().getList())) { \
1533 case OpenCLAccessAttr::Keyword_write_only: \
1534 Result = Context.Id##WOTy; break; \
1535 case OpenCLAccessAttr::Keyword_read_write: \
1536 Result = Context.Id##RWTy; break; \
1537 case OpenCLAccessAttr::Keyword_read_only: \
1538 Result = Context.Id##ROTy; break; \
1539 } \
1540 break;
1541#include "clang/Basic/OpenCLImageTypes.def"
1542
1543 case DeclSpec::TST_error:
1544 Result = Context.IntTy;
1545 declarator.setInvalidType(true);
1546 break;
1547 }
1548
1549 if (S.getLangOpts().OpenCL &&
1550 S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1551 declarator.setInvalidType(true);
1552
1553 // Handle complex types.
1554 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1555 if (S.getLangOpts().Freestanding)
1556 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1557 Result = Context.getComplexType(Result);
1558 } else if (DS.isTypeAltiVecVector()) {
1559 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1560 assert(typeSize > 0 && "type size for vector must be greater than 0 bits")(static_cast <bool> (typeSize > 0 && "type size for vector must be greater than 0 bits"
) ? void (0) : __assert_fail ("typeSize > 0 && \"type size for vector must be greater than 0 bits\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1560, __extension__ __PRETTY_FUNCTION__))
;
1561 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1562 if (DS.isTypeAltiVecPixel())
1563 VecKind = VectorType::AltiVecPixel;
1564 else if (DS.isTypeAltiVecBool())
1565 VecKind = VectorType::AltiVecBool;
1566 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1567 }
1568
1569 // FIXME: Imaginary.
1570 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1571 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1572
1573 // Before we process any type attributes, synthesize a block literal
1574 // function declarator if necessary.
1575 if (declarator.getContext() == Declarator::BlockLiteralContext)
1576 maybeSynthesizeBlockSignature(state, Result);
1577
1578 // Apply any type attributes from the decl spec. This may cause the
1579 // list of type attributes to be temporarily saved while the type
1580 // attributes are pushed around.
1581 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1582 if (!DS.isTypeSpecPipe())
1583 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1584
1585 // Apply const/volatile/restrict qualifiers to T.
1586 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1587 // Warn about CV qualifiers on function types.
1588 // C99 6.7.3p8:
1589 // If the specification of a function type includes any type qualifiers,
1590 // the behavior is undefined.
1591 // C++11 [dcl.fct]p7:
1592 // The effect of a cv-qualifier-seq in a function declarator is not the
1593 // same as adding cv-qualification on top of the function type. In the
1594 // latter case, the cv-qualifiers are ignored.
1595 if (TypeQuals && Result->isFunctionType()) {
1596 diagnoseAndRemoveTypeQualifiers(
1597 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1598 S.getLangOpts().CPlusPlus
1599 ? diag::warn_typecheck_function_qualifiers_ignored
1600 : diag::warn_typecheck_function_qualifiers_unspecified);
1601 // No diagnostic for 'restrict' or '_Atomic' applied to a
1602 // function type; we'll diagnose those later, in BuildQualifiedType.
1603 }
1604
1605 // C++11 [dcl.ref]p1:
1606 // Cv-qualified references are ill-formed except when the
1607 // cv-qualifiers are introduced through the use of a typedef-name
1608 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1609 //
1610 // There don't appear to be any other contexts in which a cv-qualified
1611 // reference type could be formed, so the 'ill-formed' clause here appears
1612 // to never happen.
1613 if (TypeQuals && Result->isReferenceType()) {
1614 diagnoseAndRemoveTypeQualifiers(
1615 S, DS, TypeQuals, Result,
1616 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1617 diag::warn_typecheck_reference_qualifiers);
1618 }
1619
1620 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1621 // than once in the same specifier-list or qualifier-list, either directly
1622 // or via one or more typedefs."
1623 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1624 && TypeQuals & Result.getCVRQualifiers()) {
1625 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1626 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1627 << "const";
1628 }
1629
1630 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1631 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1632 << "volatile";
1633 }
1634
1635 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1636 // produce a warning in this case.
1637 }
1638
1639 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1640
1641 // If adding qualifiers fails, just use the unqualified type.
1642 if (Qualified.isNull())
1643 declarator.setInvalidType(true);
1644 else
1645 Result = Qualified;
1646 }
1647
1648 assert(!Result.isNull() && "This function should not return a null type")(static_cast <bool> (!Result.isNull() && "This function should not return a null type"
) ? void (0) : __assert_fail ("!Result.isNull() && \"This function should not return a null type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1648, __extension__ __PRETTY_FUNCTION__))
;
1649 return Result;
1650}
1651
1652static std::string getPrintableNameForEntity(DeclarationName Entity) {
1653 if (Entity)
1654 return Entity.getAsString();
1655
1656 return "type name";
1657}
1658
1659QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1660 Qualifiers Qs, const DeclSpec *DS) {
1661 if (T.isNull())
1662 return QualType();
1663
1664 // Ignore any attempt to form a cv-qualified reference.
1665 if (T->isReferenceType()) {
1666 Qs.removeConst();
1667 Qs.removeVolatile();
1668 }
1669
1670 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1671 // object or incomplete types shall not be restrict-qualified."
1672 if (Qs.hasRestrict()) {
1673 unsigned DiagID = 0;
1674 QualType ProblemTy;
1675
1676 if (T->isAnyPointerType() || T->isReferenceType() ||
1677 T->isMemberPointerType()) {
1678 QualType EltTy;
1679 if (T->isObjCObjectPointerType())
1680 EltTy = T;
1681 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1682 EltTy = PTy->getPointeeType();
1683 else
1684 EltTy = T->getPointeeType();
1685
1686 // If we have a pointer or reference, the pointee must have an object
1687 // incomplete type.
1688 if (!EltTy->isIncompleteOrObjectType()) {
1689 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1690 ProblemTy = EltTy;
1691 }
1692 } else if (!T->isDependentType()) {
1693 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1694 ProblemTy = T;
1695 }
1696
1697 if (DiagID) {
1698 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1699 Qs.removeRestrict();
1700 }
1701 }
1702
1703 return Context.getQualifiedType(T, Qs);
1704}
1705
1706QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1707 unsigned CVRAU, const DeclSpec *DS) {
1708 if (T.isNull())
1709 return QualType();
1710
1711 // Ignore any attempt to form a cv-qualified reference.
1712 if (T->isReferenceType())
1713 CVRAU &=
1714 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1715
1716 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1717 // TQ_unaligned;
1718 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1719
1720 // C11 6.7.3/5:
1721 // If the same qualifier appears more than once in the same
1722 // specifier-qualifier-list, either directly or via one or more typedefs,
1723 // the behavior is the same as if it appeared only once.
1724 //
1725 // It's not specified what happens when the _Atomic qualifier is applied to
1726 // a type specified with the _Atomic specifier, but we assume that this
1727 // should be treated as if the _Atomic qualifier appeared multiple times.
1728 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1729 // C11 6.7.3/5:
1730 // If other qualifiers appear along with the _Atomic qualifier in a
1731 // specifier-qualifier-list, the resulting type is the so-qualified
1732 // atomic type.
1733 //
1734 // Don't need to worry about array types here, since _Atomic can't be
1735 // applied to such types.
1736 SplitQualType Split = T.getSplitUnqualifiedType();
1737 T = BuildAtomicType(QualType(Split.Ty, 0),
1738 DS ? DS->getAtomicSpecLoc() : Loc);
1739 if (T.isNull())
1740 return T;
1741 Split.Quals.addCVRQualifiers(CVR);
1742 return BuildQualifiedType(T, Loc, Split.Quals);
1743 }
1744
1745 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1746 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1747 return BuildQualifiedType(T, Loc, Q, DS);
1748}
1749
1750/// \brief Build a paren type including \p T.
1751QualType Sema::BuildParenType(QualType T) {
1752 return Context.getParenType(T);
1753}
1754
1755/// Given that we're building a pointer or reference to the given
1756static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1757 SourceLocation loc,
1758 bool isReference) {
1759 // Bail out if retention is unrequired or already specified.
1760 if (!type->isObjCLifetimeType() ||
1761 type.getObjCLifetime() != Qualifiers::OCL_None)
1762 return type;
1763
1764 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1765
1766 // If the object type is const-qualified, we can safely use
1767 // __unsafe_unretained. This is safe (because there are no read
1768 // barriers), and it'll be safe to coerce anything but __weak* to
1769 // the resulting type.
1770 if (type.isConstQualified()) {
1771 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1772
1773 // Otherwise, check whether the static type does not require
1774 // retaining. This currently only triggers for Class (possibly
1775 // protocol-qualifed, and arrays thereof).
1776 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1777 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1778
1779 // If we are in an unevaluated context, like sizeof, skip adding a
1780 // qualification.
1781 } else if (S.isUnevaluatedContext()) {
1782 return type;
1783
1784 // If that failed, give an error and recover using __strong. __strong
1785 // is the option most likely to prevent spurious second-order diagnostics,
1786 // like when binding a reference to a field.
1787 } else {
1788 // These types can show up in private ivars in system headers, so
1789 // we need this to not be an error in those cases. Instead we
1790 // want to delay.
1791 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1792 S.DelayedDiagnostics.add(
1793 sema::DelayedDiagnostic::makeForbiddenType(loc,
1794 diag::err_arc_indirect_no_ownership, type, isReference));
1795 } else {
1796 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1797 }
1798 implicitLifetime = Qualifiers::OCL_Strong;
1799 }
1800 assert(implicitLifetime && "didn't infer any lifetime!")(static_cast <bool> (implicitLifetime && "didn't infer any lifetime!"
) ? void (0) : __assert_fail ("implicitLifetime && \"didn't infer any lifetime!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1800, __extension__ __PRETTY_FUNCTION__))
;
1801
1802 Qualifiers qs;
1803 qs.addObjCLifetime(implicitLifetime);
1804 return S.Context.getQualifiedType(type, qs);
1805}
1806
1807static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1808 std::string Quals =
1809 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1810
1811 switch (FnTy->getRefQualifier()) {
1812 case RQ_None:
1813 break;
1814
1815 case RQ_LValue:
1816 if (!Quals.empty())
1817 Quals += ' ';
1818 Quals += '&';
1819 break;
1820
1821 case RQ_RValue:
1822 if (!Quals.empty())
1823 Quals += ' ';
1824 Quals += "&&";
1825 break;
1826 }
1827
1828 return Quals;
1829}
1830
1831namespace {
1832/// Kinds of declarator that cannot contain a qualified function type.
1833///
1834/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1835/// a function type with a cv-qualifier or a ref-qualifier can only appear
1836/// at the topmost level of a type.
1837///
1838/// Parens and member pointers are permitted. We don't diagnose array and
1839/// function declarators, because they don't allow function types at all.
1840///
1841/// The values of this enum are used in diagnostics.
1842enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1843} // end anonymous namespace
1844
1845/// Check whether the type T is a qualified function type, and if it is,
1846/// diagnose that it cannot be contained within the given kind of declarator.
1847static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1848 QualifiedFunctionKind QFK) {
1849 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1850 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1851 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1852 return false;
1853
1854 S.Diag(Loc, diag::err_compound_qualified_function_type)
1855 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1856 << getFunctionQualifiersAsString(FPT);
1857 return true;
1858}
1859
1860/// \brief Build a pointer type.
1861///
1862/// \param T The type to which we'll be building a pointer.
1863///
1864/// \param Loc The location of the entity whose type involves this
1865/// pointer type or, if there is no such entity, the location of the
1866/// type that will have pointer type.
1867///
1868/// \param Entity The name of the entity that involves the pointer
1869/// type, if known.
1870///
1871/// \returns A suitable pointer type, if there are no
1872/// errors. Otherwise, returns a NULL type.
1873QualType Sema::BuildPointerType(QualType T,
1874 SourceLocation Loc, DeclarationName Entity) {
1875 if (T->isReferenceType()) {
1876 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1877 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1878 << getPrintableNameForEntity(Entity) << T;
1879 return QualType();
1880 }
1881
1882 if (T->isFunctionType() && getLangOpts().OpenCL) {
1883 Diag(Loc, diag::err_opencl_function_pointer);
1884 return QualType();
1885 }
1886
1887 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1888 return QualType();
1889
1890 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType")(static_cast <bool> (!T->isObjCObjectType() &&
"Should build ObjCObjectPointerType") ? void (0) : __assert_fail
("!T->isObjCObjectType() && \"Should build ObjCObjectPointerType\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1890, __extension__ __PRETTY_FUNCTION__))
;
1891
1892 // In ARC, it is forbidden to build pointers to unqualified pointers.
1893 if (getLangOpts().ObjCAutoRefCount)
1894 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1895
1896 // Build the pointer type.
1897 return Context.getPointerType(T);
1898}
1899
1900/// \brief Build a reference type.
1901///
1902/// \param T The type to which we'll be building a reference.
1903///
1904/// \param Loc The location of the entity whose type involves this
1905/// reference type or, if there is no such entity, the location of the
1906/// type that will have reference type.
1907///
1908/// \param Entity The name of the entity that involves the reference
1909/// type, if known.
1910///
1911/// \returns A suitable reference type, if there are no
1912/// errors. Otherwise, returns a NULL type.
1913QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1914 SourceLocation Loc,
1915 DeclarationName Entity) {
1916 assert(Context.getCanonicalType(T) != Context.OverloadTy &&(static_cast <bool> (Context.getCanonicalType(T) != Context
.OverloadTy && "Unresolved overloaded function type")
? void (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1917, __extension__ __PRETTY_FUNCTION__))
1917 "Unresolved overloaded function type")(static_cast <bool> (Context.getCanonicalType(T) != Context
.OverloadTy && "Unresolved overloaded function type")
? void (0) : __assert_fail ("Context.getCanonicalType(T) != Context.OverloadTy && \"Unresolved overloaded function type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 1917, __extension__ __PRETTY_FUNCTION__))
;
1918
1919 // C++0x [dcl.ref]p6:
1920 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1921 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1922 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1923 // the type "lvalue reference to T", while an attempt to create the type
1924 // "rvalue reference to cv TR" creates the type TR.
1925 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1926
1927 // C++ [dcl.ref]p4: There shall be no references to references.
1928 //
1929 // According to C++ DR 106, references to references are only
1930 // diagnosed when they are written directly (e.g., "int & &"),
1931 // but not when they happen via a typedef:
1932 //
1933 // typedef int& intref;
1934 // typedef intref& intref2;
1935 //
1936 // Parser::ParseDeclaratorInternal diagnoses the case where
1937 // references are written directly; here, we handle the
1938 // collapsing of references-to-references as described in C++0x.
1939 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1940
1941 // C++ [dcl.ref]p1:
1942 // A declarator that specifies the type "reference to cv void"
1943 // is ill-formed.
1944 if (T->isVoidType()) {
1945 Diag(Loc, diag::err_reference_to_void);
1946 return QualType();
1947 }
1948
1949 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1950 return QualType();
1951
1952 // In ARC, it is forbidden to build references to unqualified pointers.
1953 if (getLangOpts().ObjCAutoRefCount)
1954 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1955
1956 // Handle restrict on references.
1957 if (LValueRef)
1958 return Context.getLValueReferenceType(T, SpelledAsLValue);
1959 return Context.getRValueReferenceType(T);
1960}
1961
1962/// \brief Build a Read-only Pipe type.
1963///
1964/// \param T The type to which we'll be building a Pipe.
1965///
1966/// \param Loc We do not use it for now.
1967///
1968/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1969/// NULL type.
1970QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
1971 return Context.getReadPipeType(T);
1972}
1973
1974/// \brief Build a Write-only Pipe type.
1975///
1976/// \param T The type to which we'll be building a Pipe.
1977///
1978/// \param Loc We do not use it for now.
1979///
1980/// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1981/// NULL type.
1982QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
1983 return Context.getWritePipeType(T);
1984}
1985
1986/// Check whether the specified array size makes the array type a VLA. If so,
1987/// return true, if not, return the size of the array in SizeVal.
1988static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1989 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1990 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1991 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1992 public:
1993 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1994
1995 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1996 }
1997
1998 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1999 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2000 }
2001 } Diagnoser;
2002
2003 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2004 S.LangOpts.GNUMode ||
2005 S.LangOpts.OpenCL).isInvalid();
2006}
2007
2008/// \brief Build an array type.
2009///
2010/// \param T The type of each element in the array.
2011///
2012/// \param ASM C99 array size modifier (e.g., '*', 'static').
2013///
2014/// \param ArraySize Expression describing the size of the array.
2015///
2016/// \param Brackets The range from the opening '[' to the closing ']'.
2017///
2018/// \param Entity The name of the entity that involves the array
2019/// type, if known.
2020///
2021/// \returns A suitable array type, if there are no errors. Otherwise,
2022/// returns a NULL type.
2023QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2024 Expr *ArraySize, unsigned Quals,
2025 SourceRange Brackets, DeclarationName Entity) {
2026
2027 SourceLocation Loc = Brackets.getBegin();
2028 if (getLangOpts().CPlusPlus) {
2029 // C++ [dcl.array]p1:
2030 // T is called the array element type; this type shall not be a reference
2031 // type, the (possibly cv-qualified) type void, a function type or an
2032 // abstract class type.
2033 //
2034 // C++ [dcl.array]p3:
2035 // When several "array of" specifications are adjacent, [...] only the
2036 // first of the constant expressions that specify the bounds of the arrays
2037 // may be omitted.
2038 //
2039 // Note: function types are handled in the common path with C.
2040 if (T->isReferenceType()) {
2041 Diag(Loc, diag::err_illegal_decl_array_of_references)
2042 << getPrintableNameForEntity(Entity) << T;
2043 return QualType();
2044 }
2045
2046 if (T->isVoidType() || T->isIncompleteArrayType()) {
2047 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2048 return QualType();
2049 }
2050
2051 if (RequireNonAbstractType(Brackets.getBegin(), T,
2052 diag::err_array_of_abstract_type))
2053 return QualType();
2054
2055 // Mentioning a member pointer type for an array type causes us to lock in
2056 // an inheritance model, even if it's inside an unused typedef.
2057 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2058 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2059 if (!MPTy->getClass()->isDependentType())
2060 (void)isCompleteType(Loc, T);
2061
2062 } else {
2063 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2064 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2065 if (RequireCompleteType(Loc, T,
2066 diag::err_illegal_decl_array_incomplete_type))
2067 return QualType();
2068 }
2069
2070 if (T->isFunctionType()) {
2071 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2072 << getPrintableNameForEntity(Entity) << T;
2073 return QualType();
2074 }
2075
2076 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2077 // If the element type is a struct or union that contains a variadic
2078 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2079 if (EltTy->getDecl()->hasFlexibleArrayMember())
2080 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2081 } else if (T->isObjCObjectType()) {
2082 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2083 return QualType();
2084 }
2085
2086 // Do placeholder conversions on the array size expression.
2087 if (ArraySize && ArraySize->hasPlaceholderType()) {
2088 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2089 if (Result.isInvalid()) return QualType();
2090 ArraySize = Result.get();
2091 }
2092
2093 // Do lvalue-to-rvalue conversions on the array size expression.
2094 if (ArraySize && !ArraySize->isRValue()) {
2095 ExprResult Result = DefaultLvalueConversion(ArraySize);
2096 if (Result.isInvalid())
2097 return QualType();
2098
2099 ArraySize = Result.get();
2100 }
2101
2102 // C99 6.7.5.2p1: The size expression shall have integer type.
2103 // C++11 allows contextual conversions to such types.
2104 if (!getLangOpts().CPlusPlus11 &&
2105 ArraySize && !ArraySize->isTypeDependent() &&
2106 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2107 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2108 << ArraySize->getType() << ArraySize->getSourceRange();
2109 return QualType();
2110 }
2111
2112 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2113 if (!ArraySize) {
2114 if (ASM == ArrayType::Star)
2115 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2116 else
2117 T = Context.getIncompleteArrayType(T, ASM, Quals);
2118 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2119 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2120 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2121 !T->isConstantSizeType()) ||
2122 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2123 // Even in C++11, don't allow contextual conversions in the array bound
2124 // of a VLA.
2125 if (getLangOpts().CPlusPlus11 &&
2126 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2127 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2128 << ArraySize->getType() << ArraySize->getSourceRange();
2129 return QualType();
2130 }
2131
2132 // C99: an array with an element type that has a non-constant-size is a VLA.
2133 // C99: an array with a non-ICE size is a VLA. We accept any expression
2134 // that we can fold to a non-zero positive value as an extension.
2135 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2136 } else {
2137 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2138 // have a value greater than zero.
2139 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2140 if (Entity)
2141 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2142 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2143 else
2144 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2145 << ArraySize->getSourceRange();
2146 return QualType();
2147 }
2148 if (ConstVal == 0) {
2149 // GCC accepts zero sized static arrays. We allow them when
2150 // we're not in a SFINAE context.
2151 Diag(ArraySize->getLocStart(),
2152 isSFINAEContext()? diag::err_typecheck_zero_array_size
2153 : diag::ext_typecheck_zero_array_size)
2154 << ArraySize->getSourceRange();
2155
2156 if (ASM == ArrayType::Static) {
2157 Diag(ArraySize->getLocStart(),
2158 diag::warn_typecheck_zero_static_array_size)
2159 << ArraySize->getSourceRange();
2160 ASM = ArrayType::Normal;
2161 }
2162 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2163 !T->isIncompleteType() && !T->isUndeducedType()) {
2164 // Is the array too large?
2165 unsigned ActiveSizeBits
2166 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2167 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2168 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2169 << ConstVal.toString(10)
2170 << ArraySize->getSourceRange();
2171 return QualType();
2172 }
2173 }
2174
2175 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2176 }
2177
2178 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2179 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2180 Diag(Loc, diag::err_opencl_vla);
2181 return QualType();
2182 }
2183 // CUDA device code doesn't support VLAs.
2184 if (getLangOpts().CUDA && T->isVariableArrayType())
2185 CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2186 // Some targets don't support VLAs.
2187 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported() &&
2188 shouldDiagnoseTargetSupportFromOpenMP()) {
2189 Diag(Loc, diag::err_vla_unsupported);
2190 return QualType();
2191 }
2192
2193 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2194 if (!getLangOpts().C99) {
2195 if (T->isVariableArrayType()) {
2196 // Prohibit the use of VLAs during template argument deduction.
2197 if (isSFINAEContext()) {
2198 Diag(Loc, diag::err_vla_in_sfinae);
2199 return QualType();
2200 }
2201 // Just extwarn about VLAs.
2202 else
2203 Diag(Loc, diag::ext_vla);
2204 } else if (ASM != ArrayType::Normal || Quals != 0)
2205 Diag(Loc,
2206 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2207 : diag::ext_c99_array_usage) << ASM;
2208 }
2209
2210 if (T->isVariableArrayType()) {
2211 // Warn about VLAs for -Wvla.
2212 Diag(Loc, diag::warn_vla_used);
2213 }
2214
2215 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2216 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2217 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2218 if (getLangOpts().OpenCL) {
2219 const QualType ArrType = Context.getBaseElementType(T);
2220 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2221 ArrType->isSamplerT() || ArrType->isImageType()) {
2222 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2223 return QualType();
2224 }
2225 }
2226
2227 return T;
2228}
2229
2230/// \brief Build an ext-vector type.
2231///
2232/// Run the required checks for the extended vector type.
2233QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2234 SourceLocation AttrLoc) {
2235 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2236 // in conjunction with complex types (pointers, arrays, functions, etc.).
2237 //
2238 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2239 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2240 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2241 // of bool aren't allowed.
2242 if ((!T->isDependentType() && !T->isIntegerType() &&
2243 !T->isRealFloatingType()) ||
2244 T->isBooleanType()) {
2245 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2246 return QualType();
2247 }
2248
2249 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2250 llvm::APSInt vecSize(32);
2251 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2252 Diag(AttrLoc, diag::err_attribute_argument_type)
2253 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2254 << ArraySize->getSourceRange();
2255 return QualType();
2256 }
2257
2258 // Unlike gcc's vector_size attribute, the size is specified as the
2259 // number of elements, not the number of bytes.
2260 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2261
2262 if (vectorSize == 0) {
2263 Diag(AttrLoc, diag::err_attribute_zero_size)
2264 << ArraySize->getSourceRange();
2265 return QualType();
2266 }
2267
2268 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2269 Diag(AttrLoc, diag::err_attribute_size_too_large)
2270 << ArraySize->getSourceRange();
2271 return QualType();
2272 }
2273
2274 return Context.getExtVectorType(T, vectorSize);
2275 }
2276
2277 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2278}
2279
2280bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2281 if (T->isArrayType() || T->isFunctionType()) {
2282 Diag(Loc, diag::err_func_returning_array_function)
2283 << T->isFunctionType() << T;
2284 return true;
2285 }
2286
2287 // Functions cannot return half FP.
2288 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2289 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2290 FixItHint::CreateInsertion(Loc, "*");
2291 return true;
2292 }
2293
2294 // Methods cannot return interface types. All ObjC objects are
2295 // passed by reference.
2296 if (T->isObjCObjectType()) {
2297 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2298 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2299 return true;
2300 }
2301
2302 return false;
2303}
2304
2305/// Check the extended parameter information. Most of the necessary
2306/// checking should occur when applying the parameter attribute; the
2307/// only other checks required are positional restrictions.
2308static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2309 const FunctionProtoType::ExtProtoInfo &EPI,
2310 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2311 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos")(static_cast <bool> (EPI.ExtParameterInfos && "shouldn't get here without param infos"
) ? void (0) : __assert_fail ("EPI.ExtParameterInfos && \"shouldn't get here without param infos\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 2311, __extension__ __PRETTY_FUNCTION__))
;
2312
2313 bool hasCheckedSwiftCall = false;
2314 auto checkForSwiftCC = [&](unsigned paramIndex) {
2315 // Only do this once.
2316 if (hasCheckedSwiftCall) return;
2317 hasCheckedSwiftCall = true;
2318 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2319 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2320 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2321 };
2322
2323 for (size_t paramIndex = 0, numParams = paramTypes.size();
2324 paramIndex != numParams; ++paramIndex) {
2325 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2326 // Nothing interesting to check for orindary-ABI parameters.
2327 case ParameterABI::Ordinary:
2328 continue;
2329
2330 // swift_indirect_result parameters must be a prefix of the function
2331 // arguments.
2332 case ParameterABI::SwiftIndirectResult:
2333 checkForSwiftCC(paramIndex);
2334 if (paramIndex != 0 &&
2335 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2336 != ParameterABI::SwiftIndirectResult) {
2337 S.Diag(getParamLoc(paramIndex),
2338 diag::err_swift_indirect_result_not_first);
2339 }
2340 continue;
2341
2342 case ParameterABI::SwiftContext:
2343 checkForSwiftCC(paramIndex);
2344 continue;
2345
2346 // swift_error parameters must be preceded by a swift_context parameter.
2347 case ParameterABI::SwiftErrorResult:
2348 checkForSwiftCC(paramIndex);
2349 if (paramIndex == 0 ||
2350 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2351 ParameterABI::SwiftContext) {
2352 S.Diag(getParamLoc(paramIndex),
2353 diag::err_swift_error_result_not_after_swift_context);
2354 }
2355 continue;
2356 }
2357 llvm_unreachable("bad ABI kind")::llvm::llvm_unreachable_internal("bad ABI kind", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 2357)
;
2358 }
2359}
2360
2361QualType Sema::BuildFunctionType(QualType T,
2362 MutableArrayRef<QualType> ParamTypes,
2363 SourceLocation Loc, DeclarationName Entity,
2364 const FunctionProtoType::ExtProtoInfo &EPI) {
2365 bool Invalid = false;
2366
2367 Invalid |= CheckFunctionReturnType(T, Loc);
2368
2369 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2370 // FIXME: Loc is too inprecise here, should use proper locations for args.
2371 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2372 if (ParamType->isVoidType()) {
2373 Diag(Loc, diag::err_param_with_void_type);
2374 Invalid = true;
2375 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2376 // Disallow half FP arguments.
2377 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2378 FixItHint::CreateInsertion(Loc, "*");
2379 Invalid = true;
2380 }
2381
2382 ParamTypes[Idx] = ParamType;
2383 }
2384
2385 if (EPI.ExtParameterInfos) {
2386 checkExtParameterInfos(*this, ParamTypes, EPI,
2387 [=](unsigned i) { return Loc; });
2388 }
2389
2390 if (EPI.ExtInfo.getProducesResult()) {
2391 // This is just a warning, so we can't fail to build if we see it.
2392 checkNSReturnsRetainedReturnType(Loc, T);
2393 }
2394
2395 if (Invalid)
2396 return QualType();
2397
2398 return Context.getFunctionType(T, ParamTypes, EPI);
2399}
2400
2401/// \brief Build a member pointer type \c T Class::*.
2402///
2403/// \param T the type to which the member pointer refers.
2404/// \param Class the class type into which the member pointer points.
2405/// \param Loc the location where this type begins
2406/// \param Entity the name of the entity that will have this member pointer type
2407///
2408/// \returns a member pointer type, if successful, or a NULL type if there was
2409/// an error.
2410QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2411 SourceLocation Loc,
2412 DeclarationName Entity) {
2413 // Verify that we're not building a pointer to pointer to function with
2414 // exception specification.
2415 if (CheckDistantExceptionSpec(T)) {
2416 Diag(Loc, diag::err_distant_exception_spec);
2417 return QualType();
2418 }
2419
2420 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2421 // with reference type, or "cv void."
2422 if (T->isReferenceType()) {
2423 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2424 << getPrintableNameForEntity(Entity) << T;
2425 return QualType();
2426 }
2427
2428 if (T->isVoidType()) {
2429 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2430 << getPrintableNameForEntity(Entity);
2431 return QualType();
2432 }
2433
2434 if (!Class->isDependentType() && !Class->isRecordType()) {
2435 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2436 return QualType();
2437 }
2438
2439 // Adjust the default free function calling convention to the default method
2440 // calling convention.
2441 bool IsCtorOrDtor =
2442 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2443 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2444 if (T->isFunctionType())
2445 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2446
2447 return Context.getMemberPointerType(T, Class.getTypePtr());
2448}
2449
2450/// \brief Build a block pointer type.
2451///
2452/// \param T The type to which we'll be building a block pointer.
2453///
2454/// \param Loc The source location, used for diagnostics.
2455///
2456/// \param Entity The name of the entity that involves the block pointer
2457/// type, if known.
2458///
2459/// \returns A suitable block pointer type, if there are no
2460/// errors. Otherwise, returns a NULL type.
2461QualType Sema::BuildBlockPointerType(QualType T,
2462 SourceLocation Loc,
2463 DeclarationName Entity) {
2464 if (!T->isFunctionType()) {
2465 Diag(Loc, diag::err_nonfunction_block_type);
2466 return QualType();
2467 }
2468
2469 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2470 return QualType();
2471
2472 return Context.getBlockPointerType(T);
2473}
2474
2475QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2476 QualType QT = Ty.get();
30
Calling 'OpaquePtr::get'
41
Returning from 'OpaquePtr::get'
2477 if (QT.isNull()) {
42
Calling 'QualType::isNull'
74
Returning from 'QualType::isNull'
75
Taking true branch
2478 if (TInfo) *TInfo = nullptr;
76
Taking true branch
77
Null pointer value stored to 'RepTInfo'
2479 return QualType();
78
Calling defaulted default constructor for 'QualType'
81
Returning from default constructor for 'QualType'
2480 }
2481
2482 TypeSourceInfo *DI = nullptr;
2483 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2484 QT = LIT->getType();
2485 DI = LIT->getTypeSourceInfo();
2486 }
2487
2488 if (TInfo) *TInfo = DI;
2489 return QT;
2490}
2491
2492static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2493 Qualifiers::ObjCLifetime ownership,
2494 unsigned chunkIndex);
2495
2496/// Given that this is the declaration of a parameter under ARC,
2497/// attempt to infer attributes and such for pointer-to-whatever
2498/// types.
2499static void inferARCWriteback(TypeProcessingState &state,
2500 QualType &declSpecType) {
2501 Sema &S = state.getSema();
2502 Declarator &declarator = state.getDeclarator();
2503
2504 // TODO: should we care about decl qualifiers?
2505
2506 // Check whether the declarator has the expected form. We walk
2507 // from the inside out in order to make the block logic work.
2508 unsigned outermostPointerIndex = 0;
2509 bool isBlockPointer = false;
2510 unsigned numPointers = 0;
2511 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2512 unsigned chunkIndex = i;
2513 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2514 switch (chunk.Kind) {
2515 case DeclaratorChunk::Paren:
2516 // Ignore parens.
2517 break;
2518
2519 case DeclaratorChunk::Reference:
2520 case DeclaratorChunk::Pointer:
2521 // Count the number of pointers. Treat references
2522 // interchangeably as pointers; if they're mis-ordered, normal
2523 // type building will discover that.
2524 outermostPointerIndex = chunkIndex;
2525 numPointers++;
2526 break;
2527
2528 case DeclaratorChunk::BlockPointer:
2529 // If we have a pointer to block pointer, that's an acceptable
2530 // indirect reference; anything else is not an application of
2531 // the rules.
2532 if (numPointers != 1) return;
2533 numPointers++;
2534 outermostPointerIndex = chunkIndex;
2535 isBlockPointer = true;
2536
2537 // We don't care about pointer structure in return values here.
2538 goto done;
2539
2540 case DeclaratorChunk::Array: // suppress if written (id[])?
2541 case DeclaratorChunk::Function:
2542 case DeclaratorChunk::MemberPointer:
2543 case DeclaratorChunk::Pipe:
2544 return;
2545 }
2546 }
2547 done:
2548
2549 // If we have *one* pointer, then we want to throw the qualifier on
2550 // the declaration-specifiers, which means that it needs to be a
2551 // retainable object type.
2552 if (numPointers == 1) {
2553 // If it's not a retainable object type, the rule doesn't apply.
2554 if (!declSpecType->isObjCRetainableType()) return;
2555
2556 // If it already has lifetime, don't do anything.
2557 if (declSpecType.getObjCLifetime()) return;
2558
2559 // Otherwise, modify the type in-place.
2560 Qualifiers qs;
2561
2562 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2563 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2564 else
2565 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2566 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2567
2568 // If we have *two* pointers, then we want to throw the qualifier on
2569 // the outermost pointer.
2570 } else if (numPointers == 2) {
2571 // If we don't have a block pointer, we need to check whether the
2572 // declaration-specifiers gave us something that will turn into a
2573 // retainable object pointer after we slap the first pointer on it.
2574 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2575 return;
2576
2577 // Look for an explicit lifetime attribute there.
2578 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2579 if (chunk.Kind != DeclaratorChunk::Pointer &&
2580 chunk.Kind != DeclaratorChunk::BlockPointer)
2581 return;
2582 for (const AttributeList *attr = chunk.getAttrs(); attr;
2583 attr = attr->getNext())
2584 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2585 return;
2586
2587 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2588 outermostPointerIndex);
2589
2590 // Any other number of pointers/references does not trigger the rule.
2591 } else return;
2592
2593 // TODO: mark whether we did this inference?
2594}
2595
2596void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2597 SourceLocation FallbackLoc,
2598 SourceLocation ConstQualLoc,
2599 SourceLocation VolatileQualLoc,
2600 SourceLocation RestrictQualLoc,
2601 SourceLocation AtomicQualLoc,
2602 SourceLocation UnalignedQualLoc) {
2603 if (!Quals)
2604 return;
2605
2606 struct Qual {
2607 const char *Name;
2608 unsigned Mask;
2609 SourceLocation Loc;
2610 } const QualKinds[5] = {
2611 { "const", DeclSpec::TQ_const, ConstQualLoc },
2612 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2613 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2614 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2615 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2616 };
2617
2618 SmallString<32> QualStr;
2619 unsigned NumQuals = 0;
2620 SourceLocation Loc;
2621 FixItHint FixIts[5];
2622
2623 // Build a string naming the redundant qualifiers.
2624 for (auto &E : QualKinds) {
2625 if (Quals & E.Mask) {
2626 if (!QualStr.empty()) QualStr += ' ';
2627 QualStr += E.Name;
2628
2629 // If we have a location for the qualifier, offer a fixit.
2630 SourceLocation QualLoc = E.Loc;
2631 if (QualLoc.isValid()) {
2632 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2633 if (Loc.isInvalid() ||
2634 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2635 Loc = QualLoc;
2636 }
2637
2638 ++NumQuals;
2639 }
2640 }
2641
2642 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2643 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2644}
2645
2646// Diagnose pointless type qualifiers on the return type of a function.
2647static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2648 Declarator &D,
2649 unsigned FunctionChunkIndex) {
2650 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2651 // FIXME: TypeSourceInfo doesn't preserve location information for
2652 // qualifiers.
2653 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2654 RetTy.getLocalCVRQualifiers(),
2655 D.getIdentifierLoc());
2656 return;
2657 }
2658
2659 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2660 End = D.getNumTypeObjects();
2661 OuterChunkIndex != End; ++OuterChunkIndex) {
2662 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2663 switch (OuterChunk.Kind) {
2664 case DeclaratorChunk::Paren:
2665 continue;
2666
2667 case DeclaratorChunk::Pointer: {
2668 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2669 S.diagnoseIgnoredQualifiers(
2670 diag::warn_qual_return_type,
2671 PTI.TypeQuals,
2672 SourceLocation(),
2673 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2674 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2675 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2676 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2677 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2678 return;
2679 }
2680
2681 case DeclaratorChunk::Function:
2682 case DeclaratorChunk::BlockPointer:
2683 case DeclaratorChunk::Reference:
2684 case DeclaratorChunk::Array:
2685 case DeclaratorChunk::MemberPointer:
2686 case DeclaratorChunk::Pipe:
2687 // FIXME: We can't currently provide an accurate source location and a
2688 // fix-it hint for these.
2689 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2690 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2691 RetTy.getCVRQualifiers() | AtomicQual,
2692 D.getIdentifierLoc());
2693 return;
2694 }
2695
2696 llvm_unreachable("unknown declarator chunk kind")::llvm::llvm_unreachable_internal("unknown declarator chunk kind"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 2696)
;
2697 }
2698
2699 // If the qualifiers come from a conversion function type, don't diagnose
2700 // them -- they're not necessarily redundant, since such a conversion
2701 // operator can be explicitly called as "x.operator const int()".
2702 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2703 return;
2704
2705 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2706 // which are present there.
2707 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2708 D.getDeclSpec().getTypeQualifiers(),
2709 D.getIdentifierLoc(),
2710 D.getDeclSpec().getConstSpecLoc(),
2711 D.getDeclSpec().getVolatileSpecLoc(),
2712 D.getDeclSpec().getRestrictSpecLoc(),
2713 D.getDeclSpec().getAtomicSpecLoc(),
2714 D.getDeclSpec().getUnalignedSpecLoc());
2715}
2716
2717static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2718 TypeSourceInfo *&ReturnTypeInfo) {
2719 Sema &SemaRef = state.getSema();
2720 Declarator &D = state.getDeclarator();
2721 QualType T;
2722 ReturnTypeInfo = nullptr;
2723
2724 // The TagDecl owned by the DeclSpec.
2725 TagDecl *OwnedTagDecl = nullptr;
2726
2727 switch (D.getName().getKind()) {
2728 case UnqualifiedId::IK_ImplicitSelfParam:
2729 case UnqualifiedId::IK_OperatorFunctionId:
2730 case UnqualifiedId::IK_Identifier:
2731 case UnqualifiedId::IK_LiteralOperatorId:
2732 case UnqualifiedId::IK_TemplateId:
2733 T = ConvertDeclSpecToType(state);
2734
2735 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2736 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2737 // Owned declaration is embedded in declarator.
2738 OwnedTagDecl->setEmbeddedInDeclarator(true);
2739 }
2740 break;
2741
2742 case UnqualifiedId::IK_ConstructorName:
2743 case UnqualifiedId::IK_ConstructorTemplateId:
2744 case UnqualifiedId::IK_DestructorName:
2745 // Constructors and destructors don't have return types. Use
2746 // "void" instead.
2747 T = SemaRef.Context.VoidTy;
2748 processTypeAttrs(state, T, TAL_DeclSpec,
2749 D.getDeclSpec().getAttributes().getList());
2750 break;
2751
2752 case UnqualifiedId::IK_DeductionGuideName:
2753 // Deduction guides have a trailing return type and no type in their
2754 // decl-specifier sequence. Use a placeholder return type for now.
2755 T = SemaRef.Context.DependentTy;
2756 break;
2757
2758 case UnqualifiedId::IK_ConversionFunctionId:
2759 // The result type of a conversion function is the type that it
2760 // converts to.
2761 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2762 &ReturnTypeInfo);
2763 break;
2764 }
2765
2766 if (D.getAttributes())
2767 distributeTypeAttrsFromDeclarator(state, T);
2768
2769 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2770 if (DeducedType *Deduced = T->getContainedDeducedType()) {
2771 AutoType *Auto = dyn_cast<AutoType>(Deduced);
2772 int Error = -1;
2773
2774 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2775 // class template argument deduction)?
2776 bool IsCXXAutoType =
2777 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2778
2779 switch (D.getContext()) {
2780 case Declarator::LambdaExprContext:
2781 // Declared return type of a lambda-declarator is implicit and is always
2782 // 'auto'.
2783 break;
2784 case Declarator::ObjCParameterContext:
2785 case Declarator::ObjCResultContext:
2786 case Declarator::PrototypeContext:
2787 Error = 0;
2788 break;
2789 case Declarator::LambdaExprParameterContext:
2790 // In C++14, generic lambdas allow 'auto' in their parameters.
2791 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2792 !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2793 Error = 16;
2794 else {
2795 // If auto is mentioned in a lambda parameter context, convert it to a
2796 // template parameter type.
2797 sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2798 assert(LSI && "No LambdaScopeInfo on the stack!")(static_cast <bool> (LSI && "No LambdaScopeInfo on the stack!"
) ? void (0) : __assert_fail ("LSI && \"No LambdaScopeInfo on the stack!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 2798, __extension__ __PRETTY_FUNCTION__))
;
2799 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2800 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2801 const bool IsParameterPack = D.hasEllipsis();
2802
2803 // Create the TemplateTypeParmDecl here to retrieve the corresponding
2804 // template parameter type. Template parameters are temporarily added
2805 // to the TU until the associated TemplateDecl is created.
2806 TemplateTypeParmDecl *CorrespondingTemplateParam =
2807 TemplateTypeParmDecl::Create(
2808 SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2809 /*KeyLoc*/SourceLocation(), /*NameLoc*/D.getLocStart(),
2810 TemplateParameterDepth, AutoParameterPosition,
2811 /*Identifier*/nullptr, false, IsParameterPack);
2812 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2813 // Replace the 'auto' in the function parameter with this invented
2814 // template type parameter.
2815 // FIXME: Retain some type sugar to indicate that this was written
2816 // as 'auto'.
2817 T = SemaRef.ReplaceAutoType(
2818 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2819 }
2820 break;
2821 case Declarator::MemberContext: {
2822 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2823 D.isFunctionDeclarator())
2824 break;
2825 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2826 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2827 case TTK_Enum: llvm_unreachable("unhandled tag kind")::llvm::llvm_unreachable_internal("unhandled tag kind", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 2827)
;
2828 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2829 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2830 case TTK_Class: Error = 5; /* Class member */ break;
2831 case TTK_Interface: Error = 6; /* Interface member */ break;
2832 }
2833 if (D.getDeclSpec().isFriendSpecified())
2834 Error = 20; // Friend type
2835 break;
2836 }
2837 case Declarator::CXXCatchContext:
2838 case Declarator::ObjCCatchContext:
2839 Error = 7; // Exception declaration
2840 break;
2841 case Declarator::TemplateParamContext:
2842 if (isa<DeducedTemplateSpecializationType>(Deduced))
2843 Error = 19; // Template parameter
2844 else if (!SemaRef.getLangOpts().CPlusPlus1z)
2845 Error = 8; // Template parameter (until C++1z)
2846 break;
2847 case Declarator::BlockLiteralContext:
2848 Error = 9; // Block literal
2849 break;
2850 case Declarator::TemplateTypeArgContext:
2851 Error = 10; // Template type argument
2852 break;
2853 case Declarator::AliasDeclContext:
2854 case Declarator::AliasTemplateContext:
2855 Error = 12; // Type alias
2856 break;
2857 case Declarator::TrailingReturnContext:
2858 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2859 Error = 13; // Function return type
2860 break;
2861 case Declarator::ConversionIdContext:
2862 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2863 Error = 14; // conversion-type-id
2864 break;
2865 case Declarator::FunctionalCastContext:
2866 if (isa<DeducedTemplateSpecializationType>(Deduced))
2867 break;
2868 LLVM_FALLTHROUGH[[clang::fallthrough]];
2869 case Declarator::TypeNameContext:
2870 Error = 15; // Generic
2871 break;
2872 case Declarator::FileContext:
2873 case Declarator::BlockContext:
2874 case Declarator::ForContext:
2875 case Declarator::InitStmtContext:
2876 case Declarator::ConditionContext:
2877 // FIXME: P0091R3 (erroneously) does not permit class template argument
2878 // deduction in conditions, for-init-statements, and other declarations
2879 // that are not simple-declarations.
2880 break;
2881 case Declarator::CXXNewContext:
2882 // FIXME: P0091R3 does not permit class template argument deduction here,
2883 // but we follow GCC and allow it anyway.
2884 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
2885 Error = 17; // 'new' type
2886 break;
2887 case Declarator::KNRTypeListContext:
2888 Error = 18; // K&R function parameter
2889 break;
2890 }
2891
2892 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2893 Error = 11;
2894
2895 // In Objective-C it is an error to use 'auto' on a function declarator
2896 // (and everywhere for '__auto_type').
2897 if (D.isFunctionDeclarator() &&
2898 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
2899 Error = 13;
2900
2901 bool HaveTrailing = false;
2902
2903 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2904 // contains a trailing return type. That is only legal at the outermost
2905 // level. Check all declarator chunks (outermost first) anyway, to give
2906 // better diagnostics.
2907 // We don't support '__auto_type' with trailing return types.
2908 // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
2909 if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
2910 D.hasTrailingReturnType()) {
2911 HaveTrailing = true;
2912 Error = -1;
2913 }
2914
2915 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2916 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2917 AutoRange = D.getName().getSourceRange();
2918
2919 if (Error != -1) {
2920 unsigned Kind;
2921 if (Auto) {
2922 switch (Auto->getKeyword()) {
2923 case AutoTypeKeyword::Auto: Kind = 0; break;
2924 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
2925 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
2926 }
2927 } else {
2928 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&(static_cast <bool> (isa<DeducedTemplateSpecializationType
>(Deduced) && "unknown auto type") ? void (0) : __assert_fail
("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 2929, __extension__ __PRETTY_FUNCTION__))
2929 "unknown auto type")(static_cast <bool> (isa<DeducedTemplateSpecializationType
>(Deduced) && "unknown auto type") ? void (0) : __assert_fail
("isa<DeducedTemplateSpecializationType>(Deduced) && \"unknown auto type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 2929, __extension__ __PRETTY_FUNCTION__))
;
2930 Kind = 3;
2931 }
2932
2933 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
2934 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
2935
2936 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2937 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
2938 << QualType(Deduced, 0) << AutoRange;
2939 if (auto *TD = TN.getAsTemplateDecl())
2940 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
2941
2942 T = SemaRef.Context.IntTy;
2943 D.setInvalidType(true);
2944 } else if (!HaveTrailing) {
2945 // If there was a trailing return type, we already got
2946 // warn_cxx98_compat_trailing_return_type in the parser.
2947 SemaRef.Diag(AutoRange.getBegin(),
2948 diag::warn_cxx98_compat_auto_type_specifier)
2949 << AutoRange;
2950 }
2951 }
2952
2953 if (SemaRef.getLangOpts().CPlusPlus &&
2954 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2955 // Check the contexts where C++ forbids the declaration of a new class
2956 // or enumeration in a type-specifier-seq.
2957 unsigned DiagID = 0;
2958 switch (D.getContext()) {
2959 case Declarator::TrailingReturnContext:
2960 // Class and enumeration definitions are syntactically not allowed in
2961 // trailing return types.
2962 llvm_unreachable("parser should not have allowed this")::llvm::llvm_unreachable_internal("parser should not have allowed this"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 2962)
;
2963 break;
2964 case Declarator::FileContext:
2965 case Declarator::MemberContext:
2966 case Declarator::BlockContext:
2967 case Declarator::ForContext:
2968 case Declarator::InitStmtContext:
2969 case Declarator::BlockLiteralContext:
2970 case Declarator::LambdaExprContext:
2971 // C++11 [dcl.type]p3:
2972 // A type-specifier-seq shall not define a class or enumeration unless
2973 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2974 // the declaration of a template-declaration.
2975 case Declarator::AliasDeclContext:
2976 break;
2977 case Declarator::AliasTemplateContext:
2978 DiagID = diag::err_type_defined_in_alias_template;
2979 break;
2980 case Declarator::TypeNameContext:
2981 case Declarator::FunctionalCastContext:
2982 case Declarator::ConversionIdContext:
2983 case Declarator::TemplateParamContext:
2984 case Declarator::CXXNewContext:
2985 case Declarator::CXXCatchContext:
2986 case Declarator::ObjCCatchContext:
2987 case Declarator::TemplateTypeArgContext:
2988 DiagID = diag::err_type_defined_in_type_specifier;
2989 break;
2990 case Declarator::PrototypeContext:
2991 case Declarator::LambdaExprParameterContext:
2992 case Declarator::ObjCParameterContext:
2993 case Declarator::ObjCResultContext:
2994 case Declarator::KNRTypeListContext:
2995 // C++ [dcl.fct]p6:
2996 // Types shall not be defined in return or parameter types.
2997 DiagID = diag::err_type_defined_in_param_type;
2998 break;
2999 case Declarator::ConditionContext:
3000 // C++ 6.4p2:
3001 // The type-specifier-seq shall not contain typedef and shall not declare
3002 // a new class or enumeration.
3003 DiagID = diag::err_type_defined_in_condition;
3004 break;
3005 }
3006
3007 if (DiagID != 0) {
3008 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3009 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3010 D.setInvalidType(true);
3011 }
3012 }
3013
3014 assert(!T.isNull() && "This function should not return a null type")(static_cast <bool> (!T.isNull() && "This function should not return a null type"
) ? void (0) : __assert_fail ("!T.isNull() && \"This function should not return a null type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 3014, __extension__ __PRETTY_FUNCTION__))
;
3015 return T;
3016}
3017
3018/// Produce an appropriate diagnostic for an ambiguity between a function
3019/// declarator and a C++ direct-initializer.
3020static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3021 DeclaratorChunk &DeclType, QualType RT) {
3022 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3023 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity")(static_cast <bool> (FTI.isAmbiguous && "no direct-initializer / function ambiguity"
) ? void (0) : __assert_fail ("FTI.isAmbiguous && \"no direct-initializer / function ambiguity\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 3023, __extension__ __PRETTY_FUNCTION__))
;
3024
3025 // If the return type is void there is no ambiguity.
3026 if (RT->isVoidType())
3027 return;
3028
3029 // An initializer for a non-class type can have at most one argument.
3030 if (!RT->isRecordType() && FTI.NumParams > 1)
3031 return;
3032
3033 // An initializer for a reference must have exactly one argument.
3034 if (RT->isReferenceType() && FTI.NumParams != 1)
3035 return;
3036
3037 // Only warn if this declarator is declaring a function at block scope, and
3038 // doesn't have a storage class (such as 'extern') specified.
3039 if (!D.isFunctionDeclarator() ||
3040 D.getFunctionDefinitionKind() != FDK_Declaration ||
3041 !S.CurContext->isFunctionOrMethod() ||
3042 D.getDeclSpec().getStorageClassSpec()
3043 != DeclSpec::SCS_unspecified)
3044 return;
3045
3046 // Inside a condition, a direct initializer is not permitted. We allow one to
3047 // be parsed in order to give better diagnostics in condition parsing.
3048 if (D.getContext() == Declarator::ConditionContext)
3049 return;
3050
3051 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3052
3053 S.Diag(DeclType.Loc,
3054 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3055 : diag::warn_empty_parens_are_function_decl)
3056 << ParenRange;
3057
3058 // If the declaration looks like:
3059 // T var1,
3060 // f();
3061 // and name lookup finds a function named 'f', then the ',' was
3062 // probably intended to be a ';'.
3063 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3064 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3065 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3066 if (Comma.getFileID() != Name.getFileID() ||
3067 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3068 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3069 Sema::LookupOrdinaryName);
3070 if (S.LookupName(Result, S.getCurScope()))
3071 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3072 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3073 << D.getIdentifier();
3074 Result.suppressDiagnostics();
3075 }
3076 }
3077
3078 if (FTI.NumParams > 0) {
3079 // For a declaration with parameters, eg. "T var(T());", suggest adding
3080 // parens around the first parameter to turn the declaration into a
3081 // variable declaration.
3082 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3083 SourceLocation B = Range.getBegin();
3084 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3085 // FIXME: Maybe we should suggest adding braces instead of parens
3086 // in C++11 for classes that don't have an initializer_list constructor.
3087 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3088 << FixItHint::CreateInsertion(B, "(")
3089 << FixItHint::CreateInsertion(E, ")");
3090 } else {
3091 // For a declaration without parameters, eg. "T var();", suggest replacing
3092 // the parens with an initializer to turn the declaration into a variable
3093 // declaration.
3094 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3095
3096 // Empty parens mean value-initialization, and no parens mean
3097 // default initialization. These are equivalent if the default
3098 // constructor is user-provided or if zero-initialization is a
3099 // no-op.
3100 if (RD && RD->hasDefinition() &&
3101 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3102 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3103 << FixItHint::CreateRemoval(ParenRange);
3104 else {
3105 std::string Init =
3106 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3107 if (Init.empty() && S.LangOpts.CPlusPlus11)
3108 Init = "{}";
3109 if (!Init.empty())
3110 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3111 << FixItHint::CreateReplacement(ParenRange, Init);
3112 }
3113 }
3114}
3115
3116/// Produce an appropriate diagnostic for a declarator with top-level
3117/// parentheses.
3118static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3119 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3120 assert(Paren.Kind == DeclaratorChunk::Paren &&(static_cast <bool> (Paren.Kind == DeclaratorChunk::Paren
&& "do not have redundant top-level parentheses") ? void
(0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 3121, __extension__ __PRETTY_FUNCTION__))
3121 "do not have redundant top-level parentheses")(static_cast <bool> (Paren.Kind == DeclaratorChunk::Paren
&& "do not have redundant top-level parentheses") ? void
(0) : __assert_fail ("Paren.Kind == DeclaratorChunk::Paren && \"do not have redundant top-level parentheses\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 3121, __extension__ __PRETTY_FUNCTION__))
;
3122
3123 // This is a syntactic check; we're not interested in cases that arise
3124 // during template instantiation.
3125 if (S.inTemplateInstantiation())
3126 return;
3127
3128 // Check whether this could be intended to be a construction of a temporary
3129 // object in C++ via a function-style cast.
3130 bool CouldBeTemporaryObject =
3131 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3132 !D.isInvalidType() && D.getIdentifier() &&
3133 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3134 (T->isRecordType() || T->isDependentType()) &&
3135 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3136
3137 for (auto &C : D.type_objects()) {
3138 switch (C.Kind) {
3139 case DeclaratorChunk::Pointer:
3140 case DeclaratorChunk::Paren:
3141 continue;
3142
3143 case DeclaratorChunk::Array:
3144 if (!C.Arr.NumElts)
3145 CouldBeTemporaryObject = false;
3146 continue;
3147
3148 case DeclaratorChunk::Reference:
3149 // FIXME: Suppress the warning here if there is no initializer; we're
3150 // going to give an error anyway.
3151 // We assume that something like 'T (&x) = y;' is highly likely to not
3152 // be intended to be a temporary object.
3153 CouldBeTemporaryObject = false;
3154 continue;
3155
3156 case DeclaratorChunk::Function:
3157 // In a new-type-id, function chunks require parentheses.
3158 if (D.getContext() == Declarator::CXXNewContext)
3159 return;
3160 LLVM_FALLTHROUGH[[clang::fallthrough]];
3161 case DeclaratorChunk::BlockPointer:
3162 case DeclaratorChunk::MemberPointer:
3163 case DeclaratorChunk::Pipe:
3164 // These cannot appear in expressions.
3165 CouldBeTemporaryObject = false;
3166 continue;
3167 }
3168 }
3169
3170 // FIXME: If there is an initializer, assume that this is not intended to be
3171 // a construction of a temporary object.
3172
3173 // Check whether the name has already been declared; if not, this is not a
3174 // function-style cast.
3175 if (CouldBeTemporaryObject) {
3176 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3177 Sema::LookupOrdinaryName);
3178 if (!S.LookupName(Result, S.getCurScope()))
3179 CouldBeTemporaryObject = false;
3180 Result.suppressDiagnostics();
3181 }
3182
3183 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3184
3185 if (!CouldBeTemporaryObject) {
3186 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3187 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3188 << FixItHint::CreateRemoval(Paren.EndLoc);
3189 return;
3190 }
3191
3192 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3193 << ParenRange << D.getIdentifier();
3194 auto *RD = T->getAsCXXRecordDecl();
3195 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3196 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3197 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3198 << D.getIdentifier();
3199 // FIXME: A cast to void is probably a better suggestion in cases where it's
3200 // valid (when there is no initializer and we're not in a condition).
3201 S.Diag(D.getLocStart(), diag::note_function_style_cast_add_parentheses)
3202 << FixItHint::CreateInsertion(D.getLocStart(), "(")
3203 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getLocEnd()), ")");
3204 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3205 << FixItHint::CreateRemoval(Paren.Loc)
3206 << FixItHint::CreateRemoval(Paren.EndLoc);
3207}
3208
3209/// Helper for figuring out the default CC for a function declarator type. If
3210/// this is the outermost chunk, then we can determine the CC from the
3211/// declarator context. If not, then this could be either a member function
3212/// type or normal function type.
3213static CallingConv
3214getCCForDeclaratorChunk(Sema &S, Declarator &D,
3215 const DeclaratorChunk::FunctionTypeInfo &FTI,
3216 unsigned ChunkIndex) {
3217 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function)(static_cast <bool> (D.getTypeObject(ChunkIndex).Kind ==
DeclaratorChunk::Function) ? void (0) : __assert_fail ("D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 3217, __extension__ __PRETTY_FUNCTION__))
;
3218
3219 // Check for an explicit CC attribute.
3220 for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3221 switch (Attr->getKind()) {
3222 CALLING_CONV_ATTRS_CASELISTcase AttributeList::AT_CDecl: case AttributeList::AT_FastCall
: case AttributeList::AT_StdCall: case AttributeList::AT_ThisCall
: case AttributeList::AT_RegCall: case AttributeList::AT_Pascal
: case AttributeList::AT_SwiftCall: case AttributeList::AT_VectorCall
: case AttributeList::AT_MSABI: case AttributeList::AT_SysVABI
: case AttributeList::AT_Pcs: case AttributeList::AT_IntelOclBicc
: case AttributeList::AT_PreserveMost: case AttributeList::AT_PreserveAll
: {
3223 // Ignore attributes that don't validate or can't apply to the
3224 // function type. We'll diagnose the failure to apply them in
3225 // handleFunctionTypeAttr.
3226 CallingConv CC;
3227 if (!S.CheckCallingConvAttr(*Attr, CC) &&
3228 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3229 return CC;
3230 }
3231 break;
3232 }
3233
3234 default:
3235 break;
3236 }
3237 }
3238
3239 bool IsCXXInstanceMethod = false;
3240
3241 if (S.getLangOpts().CPlusPlus) {
3242 // Look inwards through parentheses to see if this chunk will form a
3243 // member pointer type or if we're the declarator. Any type attributes
3244 // between here and there will override the CC we choose here.
3245 unsigned I = ChunkIndex;
3246 bool FoundNonParen = false;
3247 while (I && !FoundNonParen) {
3248 --I;
3249 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3250 FoundNonParen = true;
3251 }
3252
3253 if (FoundNonParen) {
3254 // If we're not the declarator, we're a regular function type unless we're
3255 // in a member pointer.
3256 IsCXXInstanceMethod =
3257 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3258 } else if (D.getContext() == Declarator::LambdaExprContext) {
3259 // This can only be a call operator for a lambda, which is an instance
3260 // method.
3261 IsCXXInstanceMethod = true;
3262 } else {
3263 // We're the innermost decl chunk, so must be a function declarator.
3264 assert(D.isFunctionDeclarator())(static_cast <bool> (D.isFunctionDeclarator()) ? void (
0) : __assert_fail ("D.isFunctionDeclarator()", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 3264, __extension__ __PRETTY_FUNCTION__))
;
3265
3266 // If we're inside a record, we're declaring a method, but it could be
3267 // explicitly or implicitly static.
3268 IsCXXInstanceMethod =
3269 D.isFirstDeclarationOfMember() &&
3270 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3271 !D.isStaticMember();
3272 }
3273 }
3274
3275 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3276 IsCXXInstanceMethod);
3277
3278 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3279 // and AMDGPU targets, hence it cannot be treated as a calling
3280 // convention attribute. This is the simplest place to infer
3281 // calling convention for OpenCL kernels.
3282 if (S.getLangOpts().OpenCL) {
3283 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3284 Attr; Attr = Attr->getNext()) {
3285 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3286 CC = CC_OpenCLKernel;
3287 break;
3288 }
3289 }
3290 }
3291
3292 return CC;
3293}
3294
3295namespace {
3296 /// A simple notion of pointer kinds, which matches up with the various
3297 /// pointer declarators.
3298 enum class SimplePointerKind {
3299 Pointer,
3300 BlockPointer,
3301 MemberPointer,
3302 Array,
3303 };
3304} // end anonymous namespace
3305
3306IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3307 switch (nullability) {
3308 case NullabilityKind::NonNull:
3309 if (!Ident__Nonnull)
3310 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3311 return Ident__Nonnull;
3312
3313 case NullabilityKind::Nullable:
3314 if (!Ident__Nullable)
3315 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3316 return Ident__Nullable;
3317
3318 case NullabilityKind::Unspecified:
3319 if (!Ident__Null_unspecified)
3320 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3321 return Ident__Null_unspecified;
3322 }
3323 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 3323)
;
3324}
3325
3326/// Retrieve the identifier "NSError".
3327IdentifierInfo *Sema::getNSErrorIdent() {
3328 if (!Ident_NSError)
3329 Ident_NSError = PP.getIdentifierInfo("NSError");
3330
3331 return Ident_NSError;
3332}
3333
3334/// Check whether there is a nullability attribute of any kind in the given
3335/// attribute list.
3336static bool hasNullabilityAttr(const AttributeList *attrs) {
3337 for (const AttributeList *attr = attrs; attr;
3338 attr = attr->getNext()) {
3339 if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3340 attr->getKind() == AttributeList::AT_TypeNullable ||
3341 attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3342 return true;
3343 }
3344
3345 return false;
3346}
3347
3348namespace {
3349 /// Describes the kind of a pointer a declarator describes.
3350 enum class PointerDeclaratorKind {
3351 // Not a pointer.
3352 NonPointer,
3353 // Single-level pointer.
3354 SingleLevelPointer,
3355 // Multi-level pointer (of any pointer kind).
3356 MultiLevelPointer,
3357 // CFFooRef*
3358 MaybePointerToCFRef,
3359 // CFErrorRef*
3360 CFErrorRefPointer,
3361 // NSError**
3362 NSErrorPointerPointer,
3363 };
3364
3365 /// Describes a declarator chunk wrapping a pointer that marks inference as
3366 /// unexpected.
3367 // These values must be kept in sync with diagnostics.
3368 enum class PointerWrappingDeclaratorKind {
3369 /// Pointer is top-level.
3370 None = -1,
3371 /// Pointer is an array element.
3372 Array = 0,
3373 /// Pointer is the referent type of a C++ reference.
3374 Reference = 1
3375 };
3376} // end anonymous namespace
3377
3378/// Classify the given declarator, whose type-specified is \c type, based on
3379/// what kind of pointer it refers to.
3380///
3381/// This is used to determine the default nullability.
3382static PointerDeclaratorKind
3383classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3384 PointerWrappingDeclaratorKind &wrappingKind) {
3385 unsigned numNormalPointers = 0;
3386
3387 // For any dependent type, we consider it a non-pointer.
3388 if (type->isDependentType())
3389 return PointerDeclaratorKind::NonPointer;
3390
3391 // Look through the declarator chunks to identify pointers.
3392 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3393 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3394 switch (chunk.Kind) {
3395 case DeclaratorChunk::Array:
3396 if (numNormalPointers == 0)
3397 wrappingKind = PointerWrappingDeclaratorKind::Array;
3398 break;
3399
3400 case DeclaratorChunk::Function:
3401 case DeclaratorChunk::Pipe:
3402 break;
3403
3404 case DeclaratorChunk::BlockPointer:
3405 case DeclaratorChunk::MemberPointer:
3406 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3407 : PointerDeclaratorKind::SingleLevelPointer;
3408
3409 case DeclaratorChunk::Paren:
3410 break;
3411
3412 case DeclaratorChunk::Reference:
3413 if (numNormalPointers == 0)
3414 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3415 break;
3416
3417 case DeclaratorChunk::Pointer:
3418 ++numNormalPointers;
3419 if (numNormalPointers > 2)
3420 return PointerDeclaratorKind::MultiLevelPointer;
3421 break;
3422 }
3423 }
3424
3425 // Then, dig into the type specifier itself.
3426 unsigned numTypeSpecifierPointers = 0;
3427 do {
3428 // Decompose normal pointers.
3429 if (auto ptrType = type->getAs<PointerType>()) {
3430 ++numNormalPointers;
3431
3432 if (numNormalPointers > 2)
3433 return PointerDeclaratorKind::MultiLevelPointer;
3434
3435 type = ptrType->getPointeeType();
3436 ++numTypeSpecifierPointers;
3437 continue;
3438 }
3439
3440 // Decompose block pointers.
3441 if (type->getAs<BlockPointerType>()) {
3442 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3443 : PointerDeclaratorKind::SingleLevelPointer;
3444 }
3445
3446 // Decompose member pointers.
3447 if (type->getAs<MemberPointerType>()) {
3448 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3449 : PointerDeclaratorKind::SingleLevelPointer;
3450 }
3451
3452 // Look at Objective-C object pointers.
3453 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3454 ++numNormalPointers;
3455 ++numTypeSpecifierPointers;
3456
3457 // If this is NSError**, report that.
3458 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3459 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3460 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3461 return PointerDeclaratorKind::NSErrorPointerPointer;
3462 }
3463 }
3464
3465 break;
3466 }
3467
3468 // Look at Objective-C class types.
3469 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3470 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3471 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3472 return PointerDeclaratorKind::NSErrorPointerPointer;
3473 }
3474
3475 break;
3476 }
3477
3478 // If at this point we haven't seen a pointer, we won't see one.
3479 if (numNormalPointers == 0)
3480 return PointerDeclaratorKind::NonPointer;
3481
3482 if (auto recordType = type->getAs<RecordType>()) {
3483 RecordDecl *recordDecl = recordType->getDecl();
3484
3485 bool isCFError = false;
3486 if (S.CFError) {
3487 // If we already know about CFError, test it directly.
3488 isCFError = (S.CFError == recordDecl);
3489 } else {
3490 // Check whether this is CFError, which we identify based on its bridge
3491 // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
3492 // now declared with "objc_bridge_mutable", so look for either one of
3493 // the two attributes.
3494 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3495 IdentifierInfo *bridgedType = nullptr;
3496 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
3497 bridgedType = bridgeAttr->getBridgedType();
3498 else if (auto bridgeAttr =
3499 recordDecl->getAttr<ObjCBridgeMutableAttr>())
3500 bridgedType = bridgeAttr->getBridgedType();
3501
3502 if (bridgedType == S.getNSErrorIdent()) {
3503 S.CFError = recordDecl;
3504 isCFError = true;
3505 }
3506 }
3507 }
3508
3509 // If this is CFErrorRef*, report it as such.
3510 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3511 return PointerDeclaratorKind::CFErrorRefPointer;
3512 }
3513 break;
3514 }
3515
3516 break;
3517 } while (true);
3518
3519 switch (numNormalPointers) {
3520 case 0:
3521 return PointerDeclaratorKind::NonPointer;
3522
3523 case 1:
3524 return PointerDeclaratorKind::SingleLevelPointer;
3525
3526 case 2:
3527 return PointerDeclaratorKind::MaybePointerToCFRef;
3528
3529 default:
3530 return PointerDeclaratorKind::MultiLevelPointer;
3531 }
3532}
3533
3534static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3535 SourceLocation loc) {
3536 // If we're anywhere in a function, method, or closure context, don't perform
3537 // completeness checks.
3538 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3539 if (ctx->isFunctionOrMethod())
3540 return FileID();
3541
3542 if (ctx->isFileContext())
3543 break;
3544 }
3545
3546 // We only care about the expansion location.
3547 loc = S.SourceMgr.getExpansionLoc(loc);
3548 FileID file = S.SourceMgr.getFileID(loc);
3549 if (file.isInvalid())
3550 return FileID();
3551
3552 // Retrieve file information.
3553 bool invalid = false;
3554 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3555 if (invalid || !sloc.isFile())
3556 return FileID();
3557
3558 // We don't want to perform completeness checks on the main file or in
3559 // system headers.
3560 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3561 if (fileInfo.getIncludeLoc().isInvalid())
3562 return FileID();
3563 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3564 S.Diags.getSuppressSystemWarnings()) {
3565 return FileID();
3566 }
3567
3568 return file;
3569}
3570
3571/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3572/// taking into account whitespace before and after.
3573static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
3574 SourceLocation PointerLoc,
3575 NullabilityKind Nullability) {
3576 assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) :
__assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 3576, __extension__ __PRETTY_FUNCTION__))
;
3577 if (PointerLoc.isMacroID())
3578 return;
3579
3580 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3581 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3582 return;
3583
3584 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3585 if (!NextChar)
3586 return;
3587
3588 SmallString<32> InsertionTextBuf{" "};
3589 InsertionTextBuf += getNullabilitySpelling(Nullability);
3590 InsertionTextBuf += " ";
3591 StringRef InsertionText = InsertionTextBuf.str();
3592
3593 if (isWhitespace(*NextChar)) {
3594 InsertionText = InsertionText.drop_back();
3595 } else if (NextChar[-1] == '[') {
3596 if (NextChar[0] == ']')
3597 InsertionText = InsertionText.drop_back().drop_front();
3598 else
3599 InsertionText = InsertionText.drop_front();
3600 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3601 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3602 InsertionText = InsertionText.drop_back().drop_front();
3603 }
3604
3605 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3606}
3607
3608static void emitNullabilityConsistencyWarning(Sema &S,
3609 SimplePointerKind PointerKind,
3610 SourceLocation PointerLoc,
3611 SourceLocation PointerEndLoc) {
3612 assert(PointerLoc.isValid())(static_cast <bool> (PointerLoc.isValid()) ? void (0) :
__assert_fail ("PointerLoc.isValid()", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 3612, __extension__ __PRETTY_FUNCTION__))
;
3613
3614 if (PointerKind == SimplePointerKind::Array) {
3615 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3616 } else {
3617 S.Diag(PointerLoc, diag::warn_nullability_missing)
3618 << static_cast<unsigned>(PointerKind);
3619 }
3620
3621 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
3622 if (FixItLoc.isMacroID())
3623 return;
3624
3625 auto addFixIt = [&](NullabilityKind Nullability) {
3626 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
3627 Diag << static_cast<unsigned>(Nullability);
3628 Diag << static_cast<unsigned>(PointerKind);
3629 fixItNullability(S, Diag, FixItLoc, Nullability);
3630 };
3631 addFixIt(NullabilityKind::Nullable);
3632 addFixIt(NullabilityKind::NonNull);
3633}
3634
3635/// Complains about missing nullability if the file containing \p pointerLoc
3636/// has other uses of nullability (either the keywords or the \c assume_nonnull
3637/// pragma).
3638///
3639/// If the file has \e not seen other uses of nullability, this particular
3640/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3641static void
3642checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
3643 SourceLocation pointerLoc,
3644 SourceLocation pointerEndLoc = SourceLocation()) {
3645 // Determine which file we're performing consistency checking for.
3646 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3647 if (file.isInvalid())
3648 return;
3649
3650 // If we haven't seen any type nullability in this file, we won't warn now
3651 // about anything.
3652 FileNullability &fileNullability = S.NullabilityMap[file];
3653 if (!fileNullability.SawTypeNullability) {
3654 // If this is the first pointer declarator in the file, and the appropriate
3655 // warning is on, record it in case we need to diagnose it retroactively.
3656 diag::kind diagKind;
3657 if (pointerKind == SimplePointerKind::Array)
3658 diagKind = diag::warn_nullability_missing_array;
3659 else
3660 diagKind = diag::warn_nullability_missing;
3661
3662 if (fileNullability.PointerLoc.isInvalid() &&
3663 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3664 fileNullability.PointerLoc = pointerLoc;
3665 fileNullability.PointerEndLoc = pointerEndLoc;
3666 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3667 }
3668
3669 return;
3670 }
3671
3672 // Complain about missing nullability.
3673 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
3674}
3675
3676/// Marks that a nullability feature has been used in the file containing
3677/// \p loc.
3678///
3679/// If this file already had pointer types in it that were missing nullability,
3680/// the first such instance is retroactively diagnosed.
3681///
3682/// \sa checkNullabilityConsistency
3683static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
3684 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
3685 if (file.isInvalid())
3686 return;
3687
3688 FileNullability &fileNullability = S.NullabilityMap[file];
3689 if (fileNullability.SawTypeNullability)
3690 return;
3691 fileNullability.SawTypeNullability = true;
3692
3693 // If we haven't seen any type nullability before, now we have. Retroactively
3694 // diagnose the first unannotated pointer, if there was one.
3695 if (fileNullability.PointerLoc.isInvalid())
3696 return;
3697
3698 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3699 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
3700 fileNullability.PointerEndLoc);
3701}
3702
3703/// Returns true if any of the declarator chunks before \p endIndex include a
3704/// level of indirection: array, pointer, reference, or pointer-to-member.
3705///
3706/// Because declarator chunks are stored in outer-to-inner order, testing
3707/// every chunk before \p endIndex is testing all chunks that embed the current
3708/// chunk as part of their type.
3709///
3710/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3711/// end index, in which case all chunks are tested.
3712static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3713 unsigned i = endIndex;
3714 while (i != 0) {
3715 // Walk outwards along the declarator chunks.
3716 --i;
3717 const DeclaratorChunk &DC = D.getTypeObject(i);
3718 switch (DC.Kind) {
3719 case DeclaratorChunk::Paren:
3720 break;
3721 case DeclaratorChunk::Array:
3722 case DeclaratorChunk::Pointer:
3723 case DeclaratorChunk::Reference:
3724 case DeclaratorChunk::MemberPointer:
3725 return true;
3726 case DeclaratorChunk::Function:
3727 case DeclaratorChunk::BlockPointer:
3728 case DeclaratorChunk::Pipe:
3729 // These are invalid anyway, so just ignore.
3730 break;
3731 }
3732 }
3733 return false;
3734}
3735
3736static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3737 QualType declSpecType,
3738 TypeSourceInfo *TInfo) {
3739 // The TypeSourceInfo that this function returns will not be a null type.
3740 // If there is an error, this function will fill in a dummy type as fallback.
3741 QualType T = declSpecType;
3742 Declarator &D = state.getDeclarator();
3743 Sema &S = state.getSema();
3744 ASTContext &Context = S.Context;
3745 const LangOptions &LangOpts = S.getLangOpts();
3746
3747 // The name we're declaring, if any.
3748 DeclarationName Name;
3749 if (D.getIdentifier())
1
Taking false branch
3750 Name = D.getIdentifier();
3751
3752 // Does this declaration declare a typedef-name?
3753 bool IsTypedefName =
3754 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2
Assuming the condition is false
3755 D.getContext() == Declarator::AliasDeclContext ||
3
Assuming the condition is false
3756 D.getContext() == Declarator::AliasTemplateContext;
4
Assuming the condition is false
3757
3758 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3759 bool IsQualifiedFunction = T->isFunctionProtoType() &&
5
Assuming the condition is false
3760 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3761 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3762
3763 // If T is 'decltype(auto)', the only declarators we can have are parens
3764 // and at most one function declarator if this is a function declaration.
3765 // If T is a deduced class template specialization type, we can have no
3766 // declarator chunks at all.
3767 if (auto *DT = T->getAs<DeducedType>()) {
6
Assuming 'DT' is null
7
Taking false branch
3768 const AutoType *AT = T->getAs<AutoType>();
3769 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3770 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3771 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3772 unsigned Index = E - I - 1;
3773 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3774 unsigned DiagId = IsClassTemplateDeduction
3775 ? diag::err_deduced_class_template_compound_type
3776 : diag::err_decltype_auto_compound_type;
3777 unsigned DiagKind = 0;
3778 switch (DeclChunk.Kind) {
3779 case DeclaratorChunk::Paren:
3780 // FIXME: Rejecting this is a little silly.
3781 if (IsClassTemplateDeduction) {
3782 DiagKind = 4;
3783 break;
3784 }
3785 continue;
3786 case DeclaratorChunk::Function: {
3787 if (IsClassTemplateDeduction) {
3788 DiagKind = 3;
3789 break;
3790 }
3791 unsigned FnIndex;
3792 if (D.isFunctionDeclarationContext() &&
3793 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3794 continue;
3795 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3796 break;
3797 }
3798 case DeclaratorChunk::Pointer:
3799 case DeclaratorChunk::BlockPointer:
3800 case DeclaratorChunk::MemberPointer:
3801 DiagKind = 0;
3802 break;
3803 case DeclaratorChunk::Reference:
3804 DiagKind = 1;
3805 break;
3806 case DeclaratorChunk::Array:
3807 DiagKind = 2;
3808 break;
3809 case DeclaratorChunk::Pipe:
3810 break;
3811 }
3812
3813 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3814 D.setInvalidType(true);
3815 break;
3816 }
3817 }
3818 }
3819
3820 // Determine whether we should infer _Nonnull on pointer types.
3821 Optional<NullabilityKind> inferNullability;
3822 bool inferNullabilityCS = false;
3823 bool inferNullabilityInnerOnly = false;
3824 bool inferNullabilityInnerOnlyComplete = false;
3825
3826 // Are we in an assume-nonnull region?
3827 bool inAssumeNonNullRegion = false;
3828 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
3829 if (assumeNonNullLoc.isValid()) {
8
Taking false branch
3830 inAssumeNonNullRegion = true;
3831 recordNullabilitySeen(S, assumeNonNullLoc);
3832 }
3833
3834 // Whether to complain about missing nullability specifiers or not.
3835 enum {
3836 /// Never complain.
3837 CAMN_No,
3838 /// Complain on the inner pointers (but not the outermost
3839 /// pointer).
3840 CAMN_InnerPointers,
3841 /// Complain about any pointers that don't have nullability
3842 /// specified or inferred.
3843 CAMN_Yes
3844 } complainAboutMissingNullability = CAMN_No;
3845 unsigned NumPointersRemaining = 0;
3846 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
3847
3848 if (IsTypedefName) {
9
Taking false branch
3849 // For typedefs, we do not infer any nullability (the default),
3850 // and we only complain about missing nullability specifiers on
3851 // inner pointers.
3852 complainAboutMissingNullability = CAMN_InnerPointers;
3853
3854 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
3855 !T->getNullability(S.Context)) {
3856 // Note that we allow but don't require nullability on dependent types.
3857 ++NumPointersRemaining;
3858 }
3859
3860 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3861 DeclaratorChunk &chunk = D.getTypeObject(i);
3862 switch (chunk.Kind) {
3863 case DeclaratorChunk::Array:
3864 case DeclaratorChunk::Function:
3865 case DeclaratorChunk::Pipe:
3866 break;
3867
3868 case DeclaratorChunk::BlockPointer:
3869 case DeclaratorChunk::MemberPointer:
3870 ++NumPointersRemaining;
3871 break;
3872
3873 case DeclaratorChunk::Paren:
3874 case DeclaratorChunk::Reference:
3875 continue;
3876
3877 case DeclaratorChunk::Pointer:
3878 ++NumPointersRemaining;
3879 continue;
3880 }
3881 }
3882 } else {
3883 bool isFunctionOrMethod = false;
3884 switch (auto context = state.getDeclarator().getContext()) {
10
Control jumps to 'case BlockContext:' at line 3970
3885 case Declarator::ObjCParameterContext:
3886 case Declarator::ObjCResultContext:
3887 case Declarator::PrototypeContext:
3888 case Declarator::TrailingReturnContext:
3889 isFunctionOrMethod = true;
3890 // fallthrough
3891
3892 case Declarator::MemberContext:
3893 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3894 complainAboutMissingNullability = CAMN_No;
3895 break;
3896 }
3897
3898 // Weak properties are inferred to be nullable.
3899 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3900 inferNullability = NullabilityKind::Nullable;
3901 break;
3902 }
3903
3904 // fallthrough
3905
3906 case Declarator::FileContext:
3907 case Declarator::KNRTypeListContext: {
3908 complainAboutMissingNullability = CAMN_Yes;
3909
3910 // Nullability inference depends on the type and declarator.
3911 auto wrappingKind = PointerWrappingDeclaratorKind::None;
3912 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
3913 case PointerDeclaratorKind::NonPointer:
3914 case PointerDeclaratorKind::MultiLevelPointer:
3915 // Cannot infer nullability.
3916 break;
3917
3918 case PointerDeclaratorKind::SingleLevelPointer:
3919 // Infer _Nonnull if we are in an assumes-nonnull region.
3920 if (inAssumeNonNullRegion) {
3921 complainAboutInferringWithinChunk = wrappingKind;
3922 inferNullability = NullabilityKind::NonNull;
3923 inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3924 context == Declarator::ObjCResultContext);
3925 }
3926 break;
3927
3928 case PointerDeclaratorKind::CFErrorRefPointer:
3929 case PointerDeclaratorKind::NSErrorPointerPointer:
3930 // Within a function or method signature, infer _Nullable at both
3931 // levels.
3932 if (isFunctionOrMethod && inAssumeNonNullRegion)
3933 inferNullability = NullabilityKind::Nullable;
3934 break;
3935
3936 case PointerDeclaratorKind::MaybePointerToCFRef:
3937 if (isFunctionOrMethod) {
3938 // On pointer-to-pointer parameters marked cf_returns_retained or
3939 // cf_returns_not_retained, if the outer pointer is explicit then
3940 // infer the inner pointer as _Nullable.
3941 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3942 while (NextAttr) {
3943 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3944 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3945 return true;
3946 NextAttr = NextAttr->getNext();
3947 }
3948 return false;
3949 };
3950 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3951 if (hasCFReturnsAttr(D.getAttributes()) ||
3952 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3953 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3954 inferNullability = NullabilityKind::Nullable;
3955 inferNullabilityInnerOnly = true;
3956 }
3957 }
3958 }
3959 break;
3960 }
3961 break;
3962 }
3963
3964 case Declarator::ConversionIdContext:
3965 complainAboutMissingNullability = CAMN_Yes;
3966 break;
3967
3968 case Declarator::AliasDeclContext:
3969 case Declarator::AliasTemplateContext:
3970 case Declarator::BlockContext:
3971 case Declarator::BlockLiteralContext:
3972 case Declarator::ConditionContext:
3973 case Declarator::CXXCatchContext:
3974 case Declarator::CXXNewContext:
3975 case Declarator::ForContext:
3976 case Declarator::InitStmtContext:
3977 case Declarator::LambdaExprContext:
3978 case Declarator::LambdaExprParameterContext:
3979 case Declarator::ObjCCatchContext:
3980 case Declarator::TemplateParamContext:
3981 case Declarator::TemplateTypeArgContext:
3982 case Declarator::TypeNameContext:
3983 case Declarator::FunctionalCastContext:
3984 // Don't infer in these contexts.
3985 break;
11
Execution continues on line 3990
3986 }
3987 }
3988
3989 // Local function that returns true if its argument looks like a va_list.
3990 auto isVaList = [&S](QualType T) -> bool {
3991 auto *typedefTy = T->getAs<TypedefType>();
3992 if (!typedefTy)
3993 return false;
3994 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
3995 do {
3996 if (typedefTy->getDecl() == vaListTypedef)
3997 return true;
3998 if (auto *name = typedefTy->getDecl()->getIdentifier())
3999 if (name->isStr("va_list"))
4000 return true;
4001 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4002 } while (typedefTy);
4003 return false;
4004 };
4005
4006 // Local function that checks the nullability for a given pointer declarator.
4007 // Returns true if _Nonnull was inferred.
4008 auto inferPointerNullability = [&](SimplePointerKind pointerKind,
4009 SourceLocation pointerLoc,
4010 SourceLocation pointerEndLoc,
4011 AttributeList *&attrs) -> AttributeList * {
4012 // We've seen a pointer.
4013 if (NumPointersRemaining > 0)
4014 --NumPointersRemaining;
4015
4016 // If a nullability attribute is present, there's nothing to do.
4017 if (hasNullabilityAttr(attrs))
4018 return nullptr;
4019
4020 // If we're supposed to infer nullability, do so now.
4021 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4022 AttributeList::Syntax syntax
4023 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
4024 : AttributeList::AS_Keyword;
4025 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
4026 .create(
4027 S.getNullabilityKeyword(
4028 *inferNullability),
4029 SourceRange(pointerLoc),
4030 nullptr, SourceLocation(),
4031 nullptr, 0, syntax);
4032
4033 spliceAttrIntoList(*nullabilityAttr, attrs);
4034
4035 if (inferNullabilityCS) {
4036 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4037 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4038 }
4039
4040 if (pointerLoc.isValid() &&
4041 complainAboutInferringWithinChunk !=
4042 PointerWrappingDeclaratorKind::None) {
4043 auto Diag =
4044 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4045 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4046 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4047 }
4048
4049 if (inferNullabilityInnerOnly)
4050 inferNullabilityInnerOnlyComplete = true;
4051 return nullabilityAttr;
4052 }
4053
4054 // If we're supposed to complain about missing nullability, do so
4055 // now if it's truly missing.
4056 switch (complainAboutMissingNullability) {
4057 case CAMN_No:
4058 break;
4059
4060 case CAMN_InnerPointers:
4061 if (NumPointersRemaining == 0)
4062 break;
4063 // Fallthrough.
4064
4065 case CAMN_Yes:
4066 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4067 }
4068 return nullptr;
4069 };
4070
4071 // If the type itself could have nullability but does not, infer pointer
4072 // nullability and perform consistency checking.
4073 if (S.CodeSynthesisContexts.empty()) {
12
Taking false branch
4074 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4075 !T->getNullability(S.Context)) {
4076 if (isVaList(T)) {
4077 // Record that we've seen a pointer, but do nothing else.
4078 if (NumPointersRemaining > 0)
4079 --NumPointersRemaining;
4080 } else {
4081 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4082 if (T->isBlockPointerType())
4083 pointerKind = SimplePointerKind::BlockPointer;
4084 else if (T->isMemberPointerType())
4085 pointerKind = SimplePointerKind::MemberPointer;
4086
4087 if (auto *attr = inferPointerNullability(
4088 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4089 D.getDeclSpec().getLocEnd(),
4090 D.getMutableDeclSpec().getAttributes().getListRef())) {
4091 T = Context.getAttributedType(
4092 AttributedType::getNullabilityAttrKind(*inferNullability),T,T);
4093 attr->setUsedAsTypeAttr();
4094 }
4095 }
4096 }
4097
4098 if (complainAboutMissingNullability == CAMN_Yes &&
4099 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4100 D.isPrototypeContext() &&
4101 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4102 checkNullabilityConsistency(S, SimplePointerKind::Array,
4103 D.getDeclSpec().getTypeSpecTypeLoc());
4104 }
4105 }
4106
4107 // Walk the DeclTypeInfo, building the recursive type as we go.
4108 // DeclTypeInfos are ordered from the identifier out, which is
4109 // opposite of what we want :).
4110 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
13
Assuming 'i' is equal to 'e'
14
Loop condition is false. Execution continues on line 4730
4111 unsigned chunkIndex = e - i - 1;
4112 state.setCurrentChunkIndex(chunkIndex);
4113 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4114 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4115 switch (DeclType.Kind) {
4116 case DeclaratorChunk::Paren:
4117 if (i == 0)
4118 warnAboutRedundantParens(S, D, T);
4119 T = S.BuildParenType(T);
4120 break;
4121 case DeclaratorChunk::BlockPointer:
4122 // If blocks are disabled, emit an error.
4123 if (!LangOpts.Blocks)
4124 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4125
4126 // Handle pointer nullability.
4127 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4128 DeclType.EndLoc, DeclType.getAttrListRef());
4129
4130 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4131 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4132 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4133 // qualified with const.
4134 if (LangOpts.OpenCL)
4135 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4136 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4137 }
4138 break;
4139 case DeclaratorChunk::Pointer:
4140 // Verify that we're not building a pointer to pointer to function with
4141 // exception specification.
4142 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4143 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4144 D.setInvalidType(true);
4145 // Build the type anyway.
4146 }
4147
4148 // Handle pointer nullability
4149 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4150 DeclType.EndLoc, DeclType.getAttrListRef());
4151
4152 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
4153 T = Context.getObjCObjectPointerType(T);
4154 if (DeclType.Ptr.TypeQuals)
4155 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4156 break;
4157 }
4158
4159 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4160 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4161 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4162 if (LangOpts.OpenCL) {
4163 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4164 T->isBlockPointerType()) {
4165 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4166 D.setInvalidType(true);
4167 }
4168 }
4169
4170 T = S.BuildPointerType(T, DeclType.Loc, Name);
4171 if (DeclType.Ptr.TypeQuals)
4172 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4173 break;
4174 case DeclaratorChunk::Reference: {
4175 // Verify that we're not building a reference to pointer to function with
4176 // exception specification.
4177 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4178 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4179 D.setInvalidType(true);
4180 // Build the type anyway.
4181 }
4182 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4183
4184 if (DeclType.Ref.HasRestrict)
4185 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4186 break;
4187 }
4188 case DeclaratorChunk::Array: {
4189 // Verify that we're not building an array of pointers to function with
4190 // exception specification.
4191 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4192 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4193 D.setInvalidType(true);
4194 // Build the type anyway.
4195 }
4196 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4197 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4198 ArrayType::ArraySizeModifier ASM;
4199 if (ATI.isStar)
4200 ASM = ArrayType::Star;
4201 else if (ATI.hasStatic)
4202 ASM = ArrayType::Static;
4203 else
4204 ASM = ArrayType::Normal;
4205 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4206 // FIXME: This check isn't quite right: it allows star in prototypes
4207 // for function definitions, and disallows some edge cases detailed
4208 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4209 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4210 ASM = ArrayType::Normal;
4211 D.setInvalidType(true);
4212 }
4213
4214 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4215 // shall appear only in a declaration of a function parameter with an
4216 // array type, ...
4217 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4218 if (!(D.isPrototypeContext() ||
4219 D.getContext() == Declarator::KNRTypeListContext)) {
4220 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4221 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4222 // Remove the 'static' and the type qualifiers.
4223 if (ASM == ArrayType::Static)
4224 ASM = ArrayType::Normal;
4225 ATI.TypeQuals = 0;
4226 D.setInvalidType(true);
4227 }
4228
4229 // C99 6.7.5.2p1: ... and then only in the outermost array type
4230 // derivation.
4231 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4232 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4233 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4234 if (ASM == ArrayType::Static)
4235 ASM = ArrayType::Normal;
4236 ATI.TypeQuals = 0;
4237 D.setInvalidType(true);
4238 }
4239 }
4240 const AutoType *AT = T->getContainedAutoType();
4241 // Allow arrays of auto if we are a generic lambda parameter.
4242 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4243 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
4244 // We've already diagnosed this for decltype(auto).
4245 if (!AT->isDecltypeAuto())
4246 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4247 << getPrintableNameForEntity(Name) << T;
4248 T = QualType();
4249 break;
4250 }
4251
4252 // Array parameters can be marked nullable as well, although it's not
4253 // necessary if they're marked 'static'.
4254 if (complainAboutMissingNullability == CAMN_Yes &&
4255 !hasNullabilityAttr(DeclType.getAttrs()) &&
4256 ASM != ArrayType::Static &&
4257 D.isPrototypeContext() &&
4258 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4259 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4260 }
4261
4262 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4263 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4264 break;
4265 }
4266 case DeclaratorChunk::Function: {
4267 // If the function declarator has a prototype (i.e. it is not () and
4268 // does not have a K&R-style identifier list), then the arguments are part
4269 // of the type, otherwise the argument list is ().
4270 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4271 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
4272
4273 // Check for auto functions and trailing return type and adjust the
4274 // return type accordingly.
4275 if (!D.isInvalidType()) {
4276 // trailing-return-type is only required if we're declaring a function,
4277 // and not, for instance, a pointer to a function.
4278 if (D.getDeclSpec().hasAutoTypeSpec() &&
4279 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
4280 !S.getLangOpts().CPlusPlus14) {
4281 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4282 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4283 ? diag::err_auto_missing_trailing_return
4284 : diag::err_deduced_return_type);
4285 T = Context.IntTy;
4286 D.setInvalidType(true);
4287 } else if (FTI.hasTrailingReturnType()) {
4288 // T must be exactly 'auto' at this point. See CWG issue 681.
4289 if (isa<ParenType>(T)) {
4290 S.Diag(D.getLocStart(),
4291 diag::err_trailing_return_in_parens)
4292 << T << D.getSourceRange();
4293 D.setInvalidType(true);
4294 } else if (D.getName().getKind() ==
4295 UnqualifiedId::IK_DeductionGuideName) {
4296 if (T != Context.DependentTy) {
4297 S.Diag(D.getDeclSpec().getLocStart(),
4298 diag::err_deduction_guide_with_complex_decl)
4299 << D.getSourceRange();
4300 D.setInvalidType(true);
4301 }
4302 } else if (D.getContext() != Declarator::LambdaExprContext &&
4303 (T.hasQualifiers() || !isa<AutoType>(T) ||
4304 cast<AutoType>(T)->getKeyword() !=
4305 AutoTypeKeyword::Auto)) {
4306 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4307 diag::err_trailing_return_without_auto)
4308 << T << D.getDeclSpec().getSourceRange();
4309 D.setInvalidType(true);
4310 }
4311 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4312 if (T.isNull()) {
4313 // An error occurred parsing the trailing return type.
4314 T = Context.IntTy;
4315 D.setInvalidType(true);
4316 }
4317 }
4318 }
4319
4320 // C99 6.7.5.3p1: The return type may not be a function or array type.
4321 // For conversion functions, we'll diagnose this particular error later.
4322 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4323 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
4324 unsigned diagID = diag::err_func_returning_array_function;
4325 // Last processing chunk in block context means this function chunk
4326 // represents the block.
4327 if (chunkIndex == 0 &&
4328 D.getContext() == Declarator::BlockLiteralContext)
4329 diagID = diag::err_block_returning_array_function;
4330 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4331 T = Context.IntTy;
4332 D.setInvalidType(true);
4333 }
4334
4335 // Do not allow returning half FP value.
4336 // FIXME: This really should be in BuildFunctionType.
4337 if (T->isHalfType()) {
4338 if (S.getLangOpts().OpenCL) {
4339 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4340 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4341 << T << 0 /*pointer hint*/;
4342 D.setInvalidType(true);
4343 }
4344 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4345 S.Diag(D.getIdentifierLoc(),
4346 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4347 D.setInvalidType(true);
4348 }
4349 }
4350
4351 if (LangOpts.OpenCL) {
4352 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4353 // function.
4354 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4355 T->isPipeType()) {
4356 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4357 << T << 1 /*hint off*/;
4358 D.setInvalidType(true);
4359 }
4360 // OpenCL doesn't support variadic functions and blocks
4361 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4362 // We also allow here any toolchain reserved identifiers.
4363 if (FTI.isVariadic &&
4364 !(D.getIdentifier() &&
4365 ((D.getIdentifier()->getName() == "printf" &&
4366 LangOpts.OpenCLVersion >= 120) ||
4367 D.getIdentifier()->getName().startswith("__")))) {
4368 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4369 D.setInvalidType(true);
4370 }
4371 }
4372
4373 // Methods cannot return interface types. All ObjC objects are
4374 // passed by reference.
4375 if (T->isObjCObjectType()) {
4376 SourceLocation DiagLoc, FixitLoc;
4377 if (TInfo) {
4378 DiagLoc = TInfo->getTypeLoc().getLocStart();
4379 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4380 } else {
4381 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4382 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4383 }
4384 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4385 << 0 << T
4386 << FixItHint::CreateInsertion(FixitLoc, "*");
4387
4388 T = Context.getObjCObjectPointerType(T);
4389 if (TInfo) {
4390 TypeLocBuilder TLB;
4391 TLB.pushFullCopy(TInfo->getTypeLoc());
4392 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4393 TLoc.setStarLoc(FixitLoc);
4394 TInfo = TLB.getTypeSourceInfo(Context, T);
4395 }
4396
4397 D.setInvalidType(true);
4398 }
4399
4400 // cv-qualifiers on return types are pointless except when the type is a
4401 // class type in C++.
4402 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4403 !(S.getLangOpts().CPlusPlus &&
4404 (T->isDependentType() || T->isRecordType()))) {
4405 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4406 D.getFunctionDefinitionKind() == FDK_Definition) {
4407 // [6.9.1/3] qualified void return is invalid on a C
4408 // function definition. Apparently ok on declarations and
4409 // in C++ though (!)
4410 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4411 } else
4412 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4413 }
4414
4415 // Objective-C ARC ownership qualifiers are ignored on the function
4416 // return type (by type canonicalization). Complain if this attribute
4417 // was written here.
4418 if (T.getQualifiers().hasObjCLifetime()) {
4419 SourceLocation AttrLoc;
4420 if (chunkIndex + 1 < D.getNumTypeObjects()) {
4421 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4422 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4423 Attr; Attr = Attr->getNext()) {
4424 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4425 AttrLoc = Attr->getLoc();
4426 break;
4427 }
4428 }
4429 }
4430 if (AttrLoc.isInvalid()) {
4431 for (const AttributeList *Attr
4432 = D.getDeclSpec().getAttributes().getList();
4433 Attr; Attr = Attr->getNext()) {
4434 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4435 AttrLoc = Attr->getLoc();
4436 break;
4437 }
4438 }
4439 }
4440
4441 if (AttrLoc.isValid()) {
4442 // The ownership attributes are almost always written via
4443 // the predefined
4444 // __strong/__weak/__autoreleasing/__unsafe_unretained.
4445 if (AttrLoc.isMacroID())
4446 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
4447
4448 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4449 << T.getQualifiers().getObjCLifetime();
4450 }
4451 }
4452
4453 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4454 // C++ [dcl.fct]p6:
4455 // Types shall not be defined in return or parameter types.
4456 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4457 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4458 << Context.getTypeDeclType(Tag);
4459 }
4460
4461 // Exception specs are not allowed in typedefs. Complain, but add it
4462 // anyway.
4463 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus1z)
4464 S.Diag(FTI.getExceptionSpecLocBeg(),
4465 diag::err_exception_spec_in_typedef)
4466 << (D.getContext() == Declarator::AliasDeclContext ||
4467 D.getContext() == Declarator::AliasTemplateContext);
4468
4469 // If we see "T var();" or "T var(T());" at block scope, it is probably
4470 // an attempt to initialize a variable, not a function declaration.
4471 if (FTI.isAmbiguous)
4472 warnAboutAmbiguousFunction(S, D, DeclType, T);
4473
4474 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4475
4476 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
4477 && !LangOpts.OpenCL) {
4478 // Simple void foo(), where the incoming T is the result type.
4479 T = Context.getFunctionNoProtoType(T, EI);
4480 } else {
4481 // We allow a zero-parameter variadic function in C if the
4482 // function is marked with the "overloadable" attribute. Scan
4483 // for this attribute now.
4484 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4485 bool Overloadable = false;
4486 for (const AttributeList *Attrs = D.getAttributes();
4487 Attrs; Attrs = Attrs->getNext()) {
4488 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4489 Overloadable = true;
4490 break;
4491 }
4492 }
4493
4494 if (!Overloadable)
4495 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4496 }
4497
4498 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4499 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4500 // definition.
4501 S.Diag(FTI.Params[0].IdentLoc,
4502 diag::err_ident_list_in_fn_declaration);
4503 D.setInvalidType(true);
4504 // Recover by creating a K&R-style function type.
4505 T = Context.getFunctionNoProtoType(T, EI);
4506 break;
4507 }
4508
4509 FunctionProtoType::ExtProtoInfo EPI;
4510 EPI.ExtInfo = EI;
4511 EPI.Variadic = FTI.isVariadic;
4512 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4513 EPI.TypeQuals = FTI.TypeQuals;
4514 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4515 : FTI.RefQualifierIsLValueRef? RQ_LValue
4516 : RQ_RValue;
4517
4518 // Otherwise, we have a function with a parameter list that is
4519 // potentially variadic.
4520 SmallVector<QualType, 16> ParamTys;
4521 ParamTys.reserve(FTI.NumParams);
4522
4523 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4524 ExtParameterInfos(FTI.NumParams);
4525 bool HasAnyInterestingExtParameterInfos = false;
4526
4527 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4528 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4529 QualType ParamTy = Param->getType();
4530 assert(!ParamTy.isNull() && "Couldn't parse type?")(static_cast <bool> (!ParamTy.isNull() && "Couldn't parse type?"
) ? void (0) : __assert_fail ("!ParamTy.isNull() && \"Couldn't parse type?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 4530, __extension__ __PRETTY_FUNCTION__))
;
4531
4532 // Look for 'void'. void is allowed only as a single parameter to a
4533 // function with no other parameters (C99 6.7.5.3p10). We record
4534 // int(void) as a FunctionProtoType with an empty parameter list.
4535 if (ParamTy->isVoidType()) {
4536 // If this is something like 'float(int, void)', reject it. 'void'
4537 // is an incomplete type (C99 6.2.5p19) and function decls cannot
4538 // have parameters of incomplete type.
4539 if (FTI.NumParams != 1 || FTI.isVariadic) {
4540 S.Diag(DeclType.Loc, diag::err_void_only_param);
4541 ParamTy = Context.IntTy;
4542 Param->setType(ParamTy);
4543 } else if (FTI.Params[i].Ident) {
4544 // Reject, but continue to parse 'int(void abc)'.
4545 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4546 ParamTy = Context.IntTy;
4547 Param->setType(ParamTy);
4548 } else {
4549 // Reject, but continue to parse 'float(const void)'.
4550 if (ParamTy.hasQualifiers())
4551 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4552
4553 // Do not add 'void' to the list.
4554 break;
4555 }
4556 } else if (ParamTy->isHalfType()) {
4557 // Disallow half FP parameters.
4558 // FIXME: This really should be in BuildFunctionType.
4559 if (S.getLangOpts().OpenCL) {
4560 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4561 S.Diag(Param->getLocation(),
4562 diag::err_opencl_half_param) << ParamTy;
4563 D.setInvalidType();
4564 Param->setInvalidDecl();
4565 }
4566 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4567 S.Diag(Param->getLocation(),
4568 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4569 D.setInvalidType();
4570 }
4571 } else if (!FTI.hasPrototype) {
4572 if (ParamTy->isPromotableIntegerType()) {
4573 ParamTy = Context.getPromotedIntegerType(ParamTy);
4574 Param->setKNRPromoted(true);
4575 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4576 if (BTy->getKind() == BuiltinType::Float) {
4577 ParamTy = Context.DoubleTy;
4578 Param->setKNRPromoted(true);
4579 }
4580 }
4581 }
4582
4583 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4584 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4585 HasAnyInterestingExtParameterInfos = true;
4586 }
4587
4588 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4589 ExtParameterInfos[i] =
4590 ExtParameterInfos[i].withABI(attr->getABI());
4591 HasAnyInterestingExtParameterInfos = true;
4592 }
4593
4594 if (Param->hasAttr<PassObjectSizeAttr>()) {
4595 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4596 HasAnyInterestingExtParameterInfos = true;
4597 }
4598
4599 if (Param->hasAttr<NoEscapeAttr>()) {
4600 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
4601 HasAnyInterestingExtParameterInfos = true;
4602 }
4603
4604 ParamTys.push_back(ParamTy);
4605 }
4606
4607 if (HasAnyInterestingExtParameterInfos) {
4608 EPI.ExtParameterInfos = ExtParameterInfos.data();
4609 checkExtParameterInfos(S, ParamTys, EPI,
4610 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4611 }
4612
4613 SmallVector<QualType, 4> Exceptions;
4614 SmallVector<ParsedType, 2> DynamicExceptions;
4615 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4616 Expr *NoexceptExpr = nullptr;
4617
4618 if (FTI.getExceptionSpecType() == EST_Dynamic) {
4619 // FIXME: It's rather inefficient to have to split into two vectors
4620 // here.
4621 unsigned N = FTI.getNumExceptions();
4622 DynamicExceptions.reserve(N);
4623 DynamicExceptionRanges.reserve(N);
4624 for (unsigned I = 0; I != N; ++I) {
4625 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4626 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4627 }
4628 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4629 NoexceptExpr = FTI.NoexceptExpr;
4630 }
4631
4632 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4633 FTI.getExceptionSpecType(),
4634 DynamicExceptions,
4635 DynamicExceptionRanges,
4636 NoexceptExpr,
4637 Exceptions,
4638 EPI.ExceptionSpec);
4639
4640 T = Context.getFunctionType(T, ParamTys, EPI);
4641 }
4642 break;
4643 }
4644 case DeclaratorChunk::MemberPointer: {
4645 // The scope spec must refer to a class, or be dependent.
4646 CXXScopeSpec &SS = DeclType.Mem.Scope();
4647 QualType ClsType;
4648
4649 // Handle pointer nullability.
4650 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
4651 DeclType.EndLoc, DeclType.getAttrListRef());
4652
4653 if (SS.isInvalid()) {
4654 // Avoid emitting extra errors if we already errored on the scope.
4655 D.setInvalidType(true);
4656 } else if (S.isDependentScopeSpecifier(SS) ||
4657 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4658 NestedNameSpecifier *NNS = SS.getScopeRep();
4659 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4660 switch (NNS->getKind()) {
4661 case NestedNameSpecifier::Identifier:
4662 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4663 NNS->getAsIdentifier());
4664 break;
4665
4666 case NestedNameSpecifier::Namespace:
4667 case NestedNameSpecifier::NamespaceAlias:
4668 case NestedNameSpecifier::Global:
4669 case NestedNameSpecifier::Super:
4670 llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 4670)
;
4671
4672 case NestedNameSpecifier::TypeSpec:
4673 case NestedNameSpecifier::TypeSpecWithTemplate:
4674 ClsType = QualType(NNS->getAsType(), 0);
4675 // Note: if the NNS has a prefix and ClsType is a nondependent
4676 // TemplateSpecializationType, then the NNS prefix is NOT included
4677 // in ClsType; hence we wrap ClsType into an ElaboratedType.
4678 // NOTE: in particular, no wrap occurs if ClsType already is an
4679 // Elaborated, DependentName, or DependentTemplateSpecialization.
4680 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4681 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4682 break;
4683 }
4684 } else {
4685 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4686 diag::err_illegal_decl_mempointer_in_nonclass)
4687 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4688 << DeclType.Mem.Scope().getRange();
4689 D.setInvalidType(true);
4690 }
4691
4692 if (!ClsType.isNull())
4693 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4694 D.getIdentifier());
4695 if (T.isNull()) {
4696 T = Context.IntTy;
4697 D.setInvalidType(true);
4698 } else if (DeclType.Mem.TypeQuals) {
4699 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4700 }
4701 break;
4702 }
4703
4704 case DeclaratorChunk::Pipe: {
4705 T = S.BuildReadPipeType(T, DeclType.Loc);
4706 processTypeAttrs(state, T, TAL_DeclSpec,
4707 D.getDeclSpec().getAttributes().getList());
4708 break;
4709 }
4710 }
4711
4712 if (T.isNull()) {
4713 D.setInvalidType(true);
4714 T = Context.IntTy;
4715 }
4716
4717 // See if there are any attributes on this declarator chunk.
4718 processTypeAttrs(state, T, TAL_DeclChunk,
4719 const_cast<AttributeList *>(DeclType.getAttrs()));
4720 }
4721
4722 // GNU warning -Wstrict-prototypes
4723 // Warn if a function declaration is without a prototype.
4724 // This warning is issued for all kinds of unprototyped function
4725 // declarations (i.e. function type typedef, function pointer etc.)
4726 // C99 6.7.5.3p14:
4727 // The empty list in a function declarator that is not part of a definition
4728 // of that function specifies that no information about the number or types
4729 // of the parameters is supplied.
4730 if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
15
Assuming the condition is false
4731 bool IsBlock = false;
4732 for (const DeclaratorChunk &DeclType : D.type_objects()) {
4733 switch (DeclType.Kind) {
4734 case DeclaratorChunk::BlockPointer:
4735 IsBlock = true;
4736 break;
4737 case DeclaratorChunk::Function: {
4738 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4739 if (FTI.NumParams == 0)
4740 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4741 << IsBlock
4742 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4743 IsBlock = false;
4744 break;
4745 }
4746 default:
4747 break;
4748 }
4749 }
4750 }
4751
4752 assert(!T.isNull() && "T must not be null after this point")(static_cast <bool> (!T.isNull() && "T must not be null after this point"
) ? void (0) : __assert_fail ("!T.isNull() && \"T must not be null after this point\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 4752, __extension__ __PRETTY_FUNCTION__))
;
4753
4754 if (LangOpts.CPlusPlus && T->isFunctionType()) {
16
Taking false branch
4755 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4756 assert(FnTy && "Why oh why is there not a FunctionProtoType here?")(static_cast <bool> (FnTy && "Why oh why is there not a FunctionProtoType here?"
) ? void (0) : __assert_fail ("FnTy && \"Why oh why is there not a FunctionProtoType here?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 4756, __extension__ __PRETTY_FUNCTION__))
;
4757
4758 // C++ 8.3.5p4:
4759 // A cv-qualifier-seq shall only be part of the function type
4760 // for a nonstatic member function, the function type to which a pointer
4761 // to member refers, or the top-level function type of a function typedef
4762 // declaration.
4763 //
4764 // Core issue 547 also allows cv-qualifiers on function types that are
4765 // top-level template type arguments.
4766 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
4767 if (D.getName().getKind() == UnqualifiedId::IK_DeductionGuideName)
4768 Kind = DeductionGuide;
4769 else if (!D.getCXXScopeSpec().isSet()) {
4770 if ((D.getContext() == Declarator::MemberContext ||
4771 D.getContext() == Declarator::LambdaExprContext) &&
4772 !D.getDeclSpec().isFriendSpecified())
4773 Kind = Member;
4774 } else {
4775 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4776 if (!DC || DC->isRecord())
4777 Kind = Member;
4778 }
4779
4780 // C++11 [dcl.fct]p6 (w/DR1417):
4781 // An attempt to specify a function type with a cv-qualifier-seq or a
4782 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4783 // - the function type for a non-static member function,
4784 // - the function type to which a pointer to member refers,
4785 // - the top-level function type of a function typedef declaration or
4786 // alias-declaration,
4787 // - the type-id in the default argument of a type-parameter, or
4788 // - the type-id of a template-argument for a type-parameter
4789 //
4790 // FIXME: Checking this here is insufficient. We accept-invalid on:
4791 //
4792 // template<typename T> struct S { void f(T); };
4793 // S<int() const> s;
4794 //
4795 // ... for instance.
4796 if (IsQualifiedFunction &&
4797 !(Kind == Member &&
4798 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4799 !IsTypedefName &&
4800 D.getContext() != Declarator::TemplateTypeArgContext) {
4801 SourceLocation Loc = D.getLocStart();
4802 SourceRange RemovalRange;
4803 unsigned I;
4804 if (D.isFunctionDeclarator(I)) {
4805 SmallVector<SourceLocation, 4> RemovalLocs;
4806 const DeclaratorChunk &Chunk = D.getTypeObject(I);
4807 assert(Chunk.Kind == DeclaratorChunk::Function)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Function
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 4807, __extension__ __PRETTY_FUNCTION__))
;
4808 if (Chunk.Fun.hasRefQualifier())
4809 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4810 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4811 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4812 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4813 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4814 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4815 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4816 if (!RemovalLocs.empty()) {
4817 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4818 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4819 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4820 Loc = RemovalLocs.front();
4821 }
4822 }
4823
4824 S.Diag(Loc, diag::err_invalid_qualified_function_type)
4825 << Kind << D.isFunctionDeclarator() << T
4826 << getFunctionQualifiersAsString(FnTy)
4827 << FixItHint::CreateRemoval(RemovalRange);
4828
4829 // Strip the cv-qualifiers and ref-qualifiers from the type.
4830 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4831 EPI.TypeQuals = 0;
4832 EPI.RefQualifier = RQ_None;
4833
4834 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4835 EPI);
4836 // Rebuild any parens around the identifier in the function type.
4837 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4838 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4839 break;
4840 T = S.BuildParenType(T);
4841 }
4842 }
4843 }
4844
4845 // Apply any undistributed attributes from the declarator.
4846 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4847
4848 // Diagnose any ignored type attributes.
4849 state.diagnoseIgnoredTypeAttrs(T);
4850
4851 // C++0x [dcl.constexpr]p9:
4852 // A constexpr specifier used in an object declaration declares the object
4853 // as const.
4854 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
17
Assuming the condition is false
4855 T.addConst();
4856 }
4857
4858 // If there was an ellipsis in the declarator, the declaration declares a
4859 // parameter pack whose type may be a pack expansion type.
4860 if (D.hasEllipsis()) {
18
Taking false branch
4861 // C++0x [dcl.fct]p13:
4862 // A declarator-id or abstract-declarator containing an ellipsis shall
4863 // only be used in a parameter-declaration. Such a parameter-declaration
4864 // is a parameter pack (14.5.3). [...]
4865 switch (D.getContext()) {
4866 case Declarator::PrototypeContext:
4867 case Declarator::LambdaExprParameterContext:
4868 // C++0x [dcl.fct]p13:
4869 // [...] When it is part of a parameter-declaration-clause, the
4870 // parameter pack is a function parameter pack (14.5.3). The type T
4871 // of the declarator-id of the function parameter pack shall contain
4872 // a template parameter pack; each template parameter pack in T is
4873 // expanded by the function parameter pack.
4874 //
4875 // We represent function parameter packs as function parameters whose
4876 // type is a pack expansion.
4877 if (!T->containsUnexpandedParameterPack()) {
4878 S.Diag(D.getEllipsisLoc(),
4879 diag::err_function_parameter_pack_without_parameter_packs)
4880 << T << D.getSourceRange();
4881 D.setEllipsisLoc(SourceLocation());
4882 } else {
4883 T = Context.getPackExpansionType(T, None);
4884 }
4885 break;
4886 case Declarator::TemplateParamContext:
4887 // C++0x [temp.param]p15:
4888 // If a template-parameter is a [...] is a parameter-declaration that
4889 // declares a parameter pack (8.3.5), then the template-parameter is a
4890 // template parameter pack (14.5.3).
4891 //
4892 // Note: core issue 778 clarifies that, if there are any unexpanded
4893 // parameter packs in the type of the non-type template parameter, then
4894 // it expands those parameter packs.
4895 if (T->containsUnexpandedParameterPack())
4896 T = Context.getPackExpansionType(T, None);
4897 else
4898 S.Diag(D.getEllipsisLoc(),
4899 LangOpts.CPlusPlus11
4900 ? diag::warn_cxx98_compat_variadic_templates
4901 : diag::ext_variadic_templates);
4902 break;
4903
4904 case Declarator::FileContext:
4905 case Declarator::KNRTypeListContext:
4906 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
4907 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
4908 case Declarator::TypeNameContext:
4909 case Declarator::FunctionalCastContext:
4910 case Declarator::CXXNewContext:
4911 case Declarator::AliasDeclContext:
4912 case Declarator::AliasTemplateContext:
4913 case Declarator::MemberContext:
4914 case Declarator::BlockContext:
4915 case Declarator::ForContext:
4916 case Declarator::InitStmtContext:
4917 case Declarator::ConditionContext:
4918 case Declarator::CXXCatchContext:
4919 case Declarator::ObjCCatchContext:
4920 case Declarator::BlockLiteralContext:
4921 case Declarator::LambdaExprContext:
4922 case Declarator::ConversionIdContext:
4923 case Declarator::TrailingReturnContext:
4924 case Declarator::TemplateTypeArgContext:
4925 // FIXME: We may want to allow parameter packs in block-literal contexts
4926 // in the future.
4927 S.Diag(D.getEllipsisLoc(),
4928 diag::err_ellipsis_in_declarator_not_parameter);
4929 D.setEllipsisLoc(SourceLocation());
4930 break;
4931 }
4932 }
4933
4934 assert(!T.isNull() && "T must not be null at the end of this function")(static_cast <bool> (!T.isNull() && "T must not be null at the end of this function"
) ? void (0) : __assert_fail ("!T.isNull() && \"T must not be null at the end of this function\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 4934, __extension__ __PRETTY_FUNCTION__))
;
4935 if (D.isInvalidType())
19
Taking false branch
4936 return Context.getTrivialTypeSourceInfo(T);
4937
4938 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
20
Calling 'Sema::GetTypeSourceInfoForDeclarator'
4939}
4940
4941/// GetTypeForDeclarator - Convert the type for the specified
4942/// declarator to Type instances.
4943///
4944/// The result of this call will never be null, but the associated
4945/// type may be a null type if there's an unrecoverable error.
4946TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4947 // Determine the type of the declarator. Not all forms of declarator
4948 // have a type.
4949
4950 TypeProcessingState state(*this, D);
4951
4952 TypeSourceInfo *ReturnTypeInfo = nullptr;
4953 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4954 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4955 inferARCWriteback(state, T);
4956
4957 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4958}
4959
4960static void transferARCOwnershipToDeclSpec(Sema &S,
4961 QualType &declSpecTy,
4962 Qualifiers::ObjCLifetime ownership) {
4963 if (declSpecTy->isObjCRetainableType() &&
4964 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4965 Qualifiers qs;
4966 qs.addObjCLifetime(ownership);
4967 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4968 }
4969}
4970
4971static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4972 Qualifiers::ObjCLifetime ownership,
4973 unsigned chunkIndex) {
4974 Sema &S = state.getSema();
4975 Declarator &D = state.getDeclarator();
4976
4977 // Look for an explicit lifetime attribute.
4978 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4979 for (const AttributeList *attr = chunk.getAttrs(); attr;
4980 attr = attr->getNext())
4981 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4982 return;
4983
4984 const char *attrStr = nullptr;
4985 switch (ownership) {
4986 case Qualifiers::OCL_None: llvm_unreachable("no ownership!")::llvm::llvm_unreachable_internal("no ownership!", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 4986)
;
4987 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4988 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4989 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4990 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4991 }
4992
4993 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4994 Arg->Ident = &S.Context.Idents.get(attrStr);
4995 Arg->Loc = SourceLocation();
4996
4997 ArgsUnion Args(Arg);
4998
4999 // If there wasn't one, add one (with an invalid source location
5000 // so that we don't make an AttributedType for it).
5001 AttributeList *attr = D.getAttributePool()
5002 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
5003 /*scope*/ nullptr, SourceLocation(),
5004 /*args*/ &Args, 1, AttributeList::AS_GNU);
5005 spliceAttrIntoList(*attr, chunk.getAttrListRef());
5006
5007 // TODO: mark whether we did this inference?
5008}
5009
5010/// \brief Used for transferring ownership in casts resulting in l-values.
5011static void transferARCOwnership(TypeProcessingState &state,
5012 QualType &declSpecTy,
5013 Qualifiers::ObjCLifetime ownership) {
5014 Sema &S = state.getSema();
5015 Declarator &D = state.getDeclarator();
5016
5017 int inner = -1;
5018 bool hasIndirection = false;
5019 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5020 DeclaratorChunk &chunk = D.getTypeObject(i);
5021 switch (chunk.Kind) {
5022 case DeclaratorChunk::Paren:
5023 // Ignore parens.
5024 break;
5025
5026 case DeclaratorChunk::Array:
5027 case DeclaratorChunk::Reference:
5028 case DeclaratorChunk::Pointer:
5029 if (inner != -1)
5030 hasIndirection = true;
5031 inner = i;
5032 break;
5033
5034 case DeclaratorChunk::BlockPointer:
5035 if (inner != -1)
5036 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5037 return;
5038
5039 case DeclaratorChunk::Function:
5040 case DeclaratorChunk::MemberPointer:
5041 case DeclaratorChunk::Pipe:
5042 return;
5043 }
5044 }
5045
5046 if (inner == -1)
5047 return;
5048
5049 DeclaratorChunk &chunk = D.getTypeObject(inner);
5050 if (chunk.Kind == DeclaratorChunk::Pointer) {
5051 if (declSpecTy->isObjCRetainableType())
5052 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5053 if (declSpecTy->isObjCObjectType() && hasIndirection)
5054 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5055 } else {
5056 assert(chunk.Kind == DeclaratorChunk::Array ||(static_cast <bool> (chunk.Kind == DeclaratorChunk::Array
|| chunk.Kind == DeclaratorChunk::Reference) ? void (0) : __assert_fail
("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5057, __extension__ __PRETTY_FUNCTION__))
5057 chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (chunk.Kind == DeclaratorChunk::Array
|| chunk.Kind == DeclaratorChunk::Reference) ? void (0) : __assert_fail
("chunk.Kind == DeclaratorChunk::Array || chunk.Kind == DeclaratorChunk::Reference"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5057, __extension__ __PRETTY_FUNCTION__))
;
5058 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5059 }
5060}
5061
5062TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5063 TypeProcessingState state(*this, D);
5064
5065 TypeSourceInfo *ReturnTypeInfo = nullptr;
5066 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5067
5068 if (getLangOpts().ObjC1) {
5069 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5070 if (ownership != Qualifiers::OCL_None)
5071 transferARCOwnership(state, declSpecTy, ownership);
5072 }
5073
5074 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5075}
5076
5077/// Map an AttributedType::Kind to an AttributeList::Kind.
5078static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
5079 switch (kind) {
5080 case AttributedType::attr_address_space:
5081 return AttributeList::AT_AddressSpace;
5082 case AttributedType::attr_regparm:
5083 return AttributeList::AT_Regparm;
5084 case AttributedType::attr_vector_size:
5085 return AttributeList::AT_VectorSize;
5086 case AttributedType::attr_neon_vector_type:
5087 return AttributeList::AT_NeonVectorType;
5088 case AttributedType::attr_neon_polyvector_type:
5089 return AttributeList::AT_NeonPolyVectorType;
5090 case AttributedType::attr_objc_gc:
5091 return AttributeList::AT_ObjCGC;
5092 case AttributedType::attr_objc_ownership:
5093 case AttributedType::attr_objc_inert_unsafe_unretained:
5094 return AttributeList::AT_ObjCOwnership;
5095 case AttributedType::attr_noreturn:
5096 return AttributeList::AT_NoReturn;
5097 case AttributedType::attr_cdecl:
5098 return AttributeList::AT_CDecl;
5099 case AttributedType::attr_fastcall:
5100 return AttributeList::AT_FastCall;
5101 case AttributedType::attr_stdcall:
5102 return AttributeList::AT_StdCall;
5103 case AttributedType::attr_thiscall:
5104 return AttributeList::AT_ThisCall;
5105 case AttributedType::attr_regcall:
5106 return AttributeList::AT_RegCall;
5107 case AttributedType::attr_pascal:
5108 return AttributeList::AT_Pascal;
5109 case AttributedType::attr_swiftcall:
5110 return AttributeList::AT_SwiftCall;
5111 case AttributedType::attr_vectorcall:
5112 return AttributeList::AT_VectorCall;
5113 case AttributedType::attr_pcs:
5114 case AttributedType::attr_pcs_vfp:
5115 return AttributeList::AT_Pcs;
5116 case AttributedType::attr_inteloclbicc:
5117 return AttributeList::AT_IntelOclBicc;
5118 case AttributedType::attr_ms_abi:
5119 return AttributeList::AT_MSABI;
5120 case AttributedType::attr_sysv_abi:
5121 return AttributeList::AT_SysVABI;
5122 case AttributedType::attr_preserve_most:
5123 return AttributeList::AT_PreserveMost;
5124 case AttributedType::attr_preserve_all:
5125 return AttributeList::AT_PreserveAll;
5126 case AttributedType::attr_ptr32:
5127 return AttributeList::AT_Ptr32;
5128 case AttributedType::attr_ptr64:
5129 return AttributeList::AT_Ptr64;
5130 case AttributedType::attr_sptr:
5131 return AttributeList::AT_SPtr;
5132 case AttributedType::attr_uptr:
5133 return AttributeList::AT_UPtr;
5134 case AttributedType::attr_nonnull:
5135 return AttributeList::AT_TypeNonNull;
5136 case AttributedType::attr_nullable:
5137 return AttributeList::AT_TypeNullable;
5138 case AttributedType::attr_null_unspecified:
5139 return AttributeList::AT_TypeNullUnspecified;
5140 case AttributedType::attr_objc_kindof:
5141 return AttributeList::AT_ObjCKindOf;
5142 case AttributedType::attr_ns_returns_retained:
5143 return AttributeList::AT_NSReturnsRetained;
5144 }
5145 llvm_unreachable("unexpected attribute kind!")::llvm::llvm_unreachable_internal("unexpected attribute kind!"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5145)
;
5146}
5147
5148static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5149 const AttributeList *attrs,
5150 const AttributeList *DeclAttrs = nullptr) {
5151 // DeclAttrs and attrs cannot be both empty.
5152 assert((attrs || DeclAttrs) &&(static_cast <bool> ((attrs || DeclAttrs) && "no type attributes in the expected location!"
) ? void (0) : __assert_fail ("(attrs || DeclAttrs) && \"no type attributes in the expected location!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5153, __extension__ __PRETTY_FUNCTION__))
5153 "no type attributes in the expected location!")(static_cast <bool> ((attrs || DeclAttrs) && "no type attributes in the expected location!"
) ? void (0) : __assert_fail ("(attrs || DeclAttrs) && \"no type attributes in the expected location!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5153, __extension__ __PRETTY_FUNCTION__))
;
5154
5155 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
5156 // Try to search for an attribute of matching kind in attrs list.
5157 while (attrs && attrs->getKind() != parsedKind)
5158 attrs = attrs->getNext();
5159 if (!attrs) {
5160 // No matching type attribute in attrs list found.
5161 // Try searching through C++11 attributes in the declarator attribute list.
5162 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
5163 DeclAttrs->getKind() != parsedKind))
5164 DeclAttrs = DeclAttrs->getNext();
5165 attrs = DeclAttrs;
5166 }
5167
5168 assert(attrs && "no matching type attribute in expected location!")(static_cast <bool> (attrs && "no matching type attribute in expected location!"
) ? void (0) : __assert_fail ("attrs && \"no matching type attribute in expected location!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5168, __extension__ __PRETTY_FUNCTION__))
;
5169
5170 TL.setAttrNameLoc(attrs->getLoc());
5171 if (TL.hasAttrExprOperand()) {
5172 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind")(static_cast <bool> (attrs->isArgExpr(0) && "mismatched attribute operand kind"
) ? void (0) : __assert_fail ("attrs->isArgExpr(0) && \"mismatched attribute operand kind\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5172, __extension__ __PRETTY_FUNCTION__))
;
5173 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
5174 } else if (TL.hasAttrEnumOperand()) {
5175 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&(static_cast <bool> ((attrs->isArgIdent(0) || attrs->
isArgExpr(0)) && "unexpected attribute operand kind")
? void (0) : __assert_fail ("(attrs->isArgIdent(0) || attrs->isArgExpr(0)) && \"unexpected attribute operand kind\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5176, __extension__ __PRETTY_FUNCTION__))
5176 "unexpected attribute operand kind")(static_cast <bool> ((attrs->isArgIdent(0) || attrs->
isArgExpr(0)) && "unexpected attribute operand kind")
? void (0) : __assert_fail ("(attrs->isArgIdent(0) || attrs->isArgExpr(0)) && \"unexpected attribute operand kind\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5176, __extension__ __PRETTY_FUNCTION__))
;
5177 if (attrs->isArgIdent(0))
5178 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
5179 else
5180 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
5181 }
5182
5183 // FIXME: preserve this information to here.
5184 if (TL.hasAttrOperand())
5185 TL.setAttrOperandParensRange(SourceRange());
5186}
5187
5188namespace {
5189 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5190 ASTContext &Context;
5191 const DeclSpec &DS;
5192
5193 public:
5194 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
5195 : Context(Context), DS(DS) {}
5196
5197 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5198 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
5199 Visit(TL.getModifiedLoc());
5200 }
5201 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5202 Visit(TL.getUnqualifiedLoc());
5203 }
5204 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5205 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5206 }
5207 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5208 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5209 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5210 // addition field. What we have is good enough for dispay of location
5211 // of 'fixit' on interface name.
5212 TL.setNameEndLoc(DS.getLocEnd());
5213 }
5214 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5215 TypeSourceInfo *RepTInfo = nullptr;
5216 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
29
Calling 'Sema::GetTypeFromParser'
82
Returning from 'Sema::GetTypeFromParser'
5217 TL.copy(RepTInfo->getTypeLoc());
83
Called C++ object pointer is null
5218 }
5219 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5220 TypeSourceInfo *RepTInfo = nullptr;
5221 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5222 TL.copy(RepTInfo->getTypeLoc());
5223 }
5224 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5225 TypeSourceInfo *TInfo = nullptr;
5226 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5227
5228 // If we got no declarator info from previous Sema routines,
5229 // just fill with the typespec loc.
5230 if (!TInfo) {
5231 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5232 return;
5233 }
5234
5235 TypeLoc OldTL = TInfo->getTypeLoc();
5236 if (TInfo->getType()->getAs<ElaboratedType>()) {
5237 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5238 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5239 .castAs<TemplateSpecializationTypeLoc>();
5240 TL.copy(NamedTL);
5241 } else {
5242 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5243 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc())(static_cast <bool> (TL.getRAngleLoc() == OldTL.castAs<
TemplateSpecializationTypeLoc>().getRAngleLoc()) ? void (0
) : __assert_fail ("TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5243, __extension__ __PRETTY_FUNCTION__))
;
5244 }
5245
5246 }
5247 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5248 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_typeofExpr) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofExpr"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5248, __extension__ __PRETTY_FUNCTION__))
;
5249 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5250 TL.setParensRange(DS.getTypeofParensRange());
5251 }
5252 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5253 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_typeofType) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_typeofType"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5253, __extension__ __PRETTY_FUNCTION__))
;
5254 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5255 TL.setParensRange(DS.getTypeofParensRange());
5256 assert(DS.getRepAsType())(static_cast <bool> (DS.getRepAsType()) ? void (0) : __assert_fail
("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5256, __extension__ __PRETTY_FUNCTION__))
;
5257 TypeSourceInfo *TInfo = nullptr;
5258 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5259 TL.setUnderlyingTInfo(TInfo);
5260 }
5261 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5262 // FIXME: This holds only because we only have one unary transform.
5263 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType)(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_underlyingType) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_underlyingType"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5263, __extension__ __PRETTY_FUNCTION__))
;
5264 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5265 TL.setParensRange(DS.getTypeofParensRange());
5266 assert(DS.getRepAsType())(static_cast <bool> (DS.getRepAsType()) ? void (0) : __assert_fail
("DS.getRepAsType()", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5266, __extension__ __PRETTY_FUNCTION__))
;
5267 TypeSourceInfo *TInfo = nullptr;
5268 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5269 TL.setUnderlyingTInfo(TInfo);
5270 }
5271 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5272 // By default, use the source location of the type specifier.
5273 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5274 if (TL.needsExtraLocalData()) {
5275 // Set info for the written builtin specifiers.
5276 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5277 // Try to have a meaningful source location.
5278 if (TL.getWrittenSignSpec() != TSS_unspecified)
5279 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5280 if (TL.getWrittenWidthSpec() != TSW_unspecified)
5281 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5282 }
5283 }
5284 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5285 ElaboratedTypeKeyword Keyword
5286 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5287 if (DS.getTypeSpecType() == TST_typename) {
5288 TypeSourceInfo *TInfo = nullptr;
5289 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5290 if (TInfo) {
5291 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5292 return;
5293 }
5294 }
5295 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5296 ? DS.getTypeSpecTypeLoc()
5297 : SourceLocation());
5298 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5299 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5300 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5301 }
5302 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5303 assert(DS.getTypeSpecType() == TST_typename)(static_cast <bool> (DS.getTypeSpecType() == TST_typename
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5303, __extension__ __PRETTY_FUNCTION__))
;
5304 TypeSourceInfo *TInfo = nullptr;
5305 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5306 assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail (
"TInfo", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5306, __extension__ __PRETTY_FUNCTION__))
;
5307 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5308 }
5309 void VisitDependentTemplateSpecializationTypeLoc(
5310 DependentTemplateSpecializationTypeLoc TL) {
5311 assert(DS.getTypeSpecType() == TST_typename)(static_cast <bool> (DS.getTypeSpecType() == TST_typename
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == TST_typename"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5311, __extension__ __PRETTY_FUNCTION__))
;
5312 TypeSourceInfo *TInfo = nullptr;
5313 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5314 assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail (
"TInfo", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5314, __extension__ __PRETTY_FUNCTION__))
;
5315 TL.copy(
5316 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5317 }
5318 void VisitTagTypeLoc(TagTypeLoc TL) {
5319 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5320 }
5321 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5322 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5323 // or an _Atomic qualifier.
5324 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5325 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5326 TL.setParensRange(DS.getTypeofParensRange());
5327
5328 TypeSourceInfo *TInfo = nullptr;
5329 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5330 assert(TInfo)(static_cast <bool> (TInfo) ? void (0) : __assert_fail (
"TInfo", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5330, __extension__ __PRETTY_FUNCTION__))
;
5331 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5332 } else {
5333 TL.setKWLoc(DS.getAtomicSpecLoc());
5334 // No parens, to indicate this was spelled as an _Atomic qualifier.
5335 TL.setParensRange(SourceRange());
5336 Visit(TL.getValueLoc());
5337 }
5338 }
5339
5340 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5341 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5342
5343 TypeSourceInfo *TInfo = nullptr;
5344 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5345 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5346 }
5347
5348 void VisitTypeLoc(TypeLoc TL) {
5349 // FIXME: add other typespec types and change this to an assert.
5350 TL.initialize(Context, DS.getTypeSpecTypeLoc());
5351 }
5352 };
5353
5354 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5355 ASTContext &Context;
5356 const DeclaratorChunk &Chunk;
5357
5358 public:
5359 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
5360 : Context(Context), Chunk(Chunk) {}
5361
5362 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5363 llvm_unreachable("qualified type locs not expected here!")::llvm::llvm_unreachable_internal("qualified type locs not expected here!"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5363)
;
5364 }
5365 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5366 llvm_unreachable("decayed type locs not expected here!")::llvm::llvm_unreachable_internal("decayed type locs not expected here!"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5366)
;
5367 }
5368
5369 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5370 fillAttributedTypeLoc(TL, Chunk.getAttrs());
5371 }
5372 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5373 // nothing
5374 }
5375 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5376 assert(Chunk.Kind == DeclaratorChunk::BlockPointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::BlockPointer
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::BlockPointer"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5376, __extension__ __PRETTY_FUNCTION__))
;
5377 TL.setCaretLoc(Chunk.Loc);
5378 }
5379 void VisitPointerTypeLoc(PointerTypeLoc TL) {
5380 assert(Chunk.Kind == DeclaratorChunk::Pointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pointer
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5380, __extension__ __PRETTY_FUNCTION__))
;
5381 TL.setStarLoc(Chunk.Loc);
5382 }
5383 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5384 assert(Chunk.Kind == DeclaratorChunk::Pointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pointer
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pointer"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5384, __extension__ __PRETTY_FUNCTION__))
;
5385 TL.setStarLoc(Chunk.Loc);
5386 }
5387 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5388 assert(Chunk.Kind == DeclaratorChunk::MemberPointer)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::MemberPointer
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::MemberPointer"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5388, __extension__ __PRETTY_FUNCTION__))
;
5389 const CXXScopeSpec& SS = Chunk.Mem.Scope();
5390 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5391
5392 const Type* ClsTy = TL.getClass();
5393 QualType ClsQT = QualType(ClsTy, 0);
5394 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5395 // Now copy source location info into the type loc component.
5396 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5397 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5398 case NestedNameSpecifier::Identifier:
5399 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc")(static_cast <bool> (isa<DependentNameType>(ClsTy
) && "Unexpected TypeLoc") ? void (0) : __assert_fail
("isa<DependentNameType>(ClsTy) && \"Unexpected TypeLoc\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5399, __extension__ __PRETTY_FUNCTION__))
;
5400 {
5401 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5402 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5403 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5404 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5405 }
5406 break;
5407
5408 case NestedNameSpecifier::TypeSpec:
5409 case NestedNameSpecifier::TypeSpecWithTemplate:
5410 if (isa<ElaboratedType>(ClsTy)) {
5411 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5412 ETLoc.setElaboratedKeywordLoc(SourceLocation());
5413 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5414 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5415 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5416 } else {
5417 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5418 }
5419 break;
5420
5421 case NestedNameSpecifier::Namespace:
5422 case NestedNameSpecifier::NamespaceAlias:
5423 case NestedNameSpecifier::Global:
5424 case NestedNameSpecifier::Super:
5425 llvm_unreachable("Nested-name-specifier must name a type")::llvm::llvm_unreachable_internal("Nested-name-specifier must name a type"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5425)
;
5426 }
5427
5428 // Finally fill in MemberPointerLocInfo fields.
5429 TL.setStarLoc(Chunk.Loc);
5430 TL.setClassTInfo(ClsTInfo);
5431 }
5432 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5433 assert(Chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Reference
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5433, __extension__ __PRETTY_FUNCTION__))
;
5434 // 'Amp' is misleading: this might have been originally
5435 /// spelled with AmpAmp.
5436 TL.setAmpLoc(Chunk.Loc);
5437 }
5438 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5439 assert(Chunk.Kind == DeclaratorChunk::Reference)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Reference
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Reference"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5439, __extension__ __PRETTY_FUNCTION__))
;
5440 assert(!Chunk.Ref.LValueRef)(static_cast <bool> (!Chunk.Ref.LValueRef) ? void (0) :
__assert_fail ("!Chunk.Ref.LValueRef", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5440, __extension__ __PRETTY_FUNCTION__))
;
5441 TL.setAmpAmpLoc(Chunk.Loc);
5442 }
5443 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5444 assert(Chunk.Kind == DeclaratorChunk::Array)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Array
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Array"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5444, __extension__ __PRETTY_FUNCTION__))
;
5445 TL.setLBracketLoc(Chunk.Loc);
5446 TL.setRBracketLoc(Chunk.EndLoc);
5447 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5448 }
5449 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5450 assert(Chunk.Kind == DeclaratorChunk::Function)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Function
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Function"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5450, __extension__ __PRETTY_FUNCTION__))
;
5451 TL.setLocalRangeBegin(Chunk.Loc);
5452 TL.setLocalRangeEnd(Chunk.EndLoc);
5453
5454 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5455 TL.setLParenLoc(FTI.getLParenLoc());
5456 TL.setRParenLoc(FTI.getRParenLoc());
5457 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5458 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5459 TL.setParam(tpi++, Param);
5460 }
5461 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5462 }
5463 void VisitParenTypeLoc(ParenTypeLoc TL) {
5464 assert(Chunk.Kind == DeclaratorChunk::Paren)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Paren
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Paren"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5464, __extension__ __PRETTY_FUNCTION__))
;
5465 TL.setLParenLoc(Chunk.Loc);
5466 TL.setRParenLoc(Chunk.EndLoc);
5467 }
5468 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5469 assert(Chunk.Kind == DeclaratorChunk::Pipe)(static_cast <bool> (Chunk.Kind == DeclaratorChunk::Pipe
) ? void (0) : __assert_fail ("Chunk.Kind == DeclaratorChunk::Pipe"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5469, __extension__ __PRETTY_FUNCTION__))
;
5470 TL.setKWLoc(Chunk.Loc);
5471 }
5472
5473 void VisitTypeLoc(TypeLoc TL) {
5474 llvm_unreachable("unsupported TypeLoc kind in declarator!")::llvm::llvm_unreachable_internal("unsupported TypeLoc kind in declarator!"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5474)
;
5475 }
5476 };
5477} // end anonymous namespace
5478
5479static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5480 SourceLocation Loc;
5481 switch (Chunk.Kind) {
5482 case DeclaratorChunk::Function:
5483 case DeclaratorChunk::Array:
5484 case DeclaratorChunk::Paren:
5485 case DeclaratorChunk::Pipe:
5486 llvm_unreachable("cannot be _Atomic qualified")::llvm::llvm_unreachable_internal("cannot be _Atomic qualified"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5486)
;
5487
5488 case DeclaratorChunk::Pointer:
5489 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5490 break;
5491
5492 case DeclaratorChunk::BlockPointer:
5493 case DeclaratorChunk::Reference:
5494 case DeclaratorChunk::MemberPointer:
5495 // FIXME: Provide a source location for the _Atomic keyword.
5496 break;
5497 }
5498
5499 ATL.setKWLoc(Loc);
5500 ATL.setParensRange(SourceRange());
5501}
5502
5503static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
5504 const AttributeList *Attrs) {
5505 while (Attrs && Attrs->getKind() != AttributeList::AT_AddressSpace)
5506 Attrs = Attrs->getNext();
5507
5508 assert(Attrs && "no address_space attribute found at the expected location!")(static_cast <bool> (Attrs && "no address_space attribute found at the expected location!"
) ? void (0) : __assert_fail ("Attrs && \"no address_space attribute found at the expected location!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5508, __extension__ __PRETTY_FUNCTION__))
;
5509
5510 DASTL.setAttrNameLoc(Attrs->getLoc());
5511 DASTL.setAttrExprOperand(Attrs->getArgAsExpr(0));
5512 DASTL.setAttrOperandParensRange(SourceRange());
5513}
5514
5515/// \brief Create and instantiate a TypeSourceInfo with type source information.
5516///
5517/// \param T QualType referring to the type as written in source code.
5518///
5519/// \param ReturnTypeInfo For declarators whose return type does not show
5520/// up in the normal place in the declaration specifiers (such as a C++
5521/// conversion function), this pointer will refer to a type source information
5522/// for that return type.
5523TypeSourceInfo *
5524Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5525 TypeSourceInfo *ReturnTypeInfo) {
5526 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5527 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5528 const AttributeList *DeclAttrs = D.getAttributes();
5529
5530 // Handle parameter packs whose type is a pack expansion.
5531 if (isa<PackExpansionType>(T)) {
21
Taking false branch
5532 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5533 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5534 }
5535
5536 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
22
Assuming 'i' is equal to 'e'
23
Loop condition is false. Execution continues on line 5566
5537
5538 if (DependentAddressSpaceTypeLoc DASTL =
5539 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
5540 fillDependentAddressSpaceTypeLoc(DASTL, D.getTypeObject(i).getAttrs());
5541 CurrTL = DASTL.getPointeeTypeLoc().getUnqualifiedLoc();
5542 }
5543
5544 // An AtomicTypeLoc might be produced by an atomic qualifier in this
5545 // declarator chunk.
5546 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5547 fillAtomicQualLoc(ATL, D.getTypeObject(i));
5548 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5549 }
5550
5551 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5552 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
5553 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5554 }
5555
5556 // FIXME: Ordering here?
5557 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5558 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5559
5560 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5561 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5562 }
5563
5564 // If we have different source information for the return type, use
5565 // that. This really only applies to C++ conversion functions.
5566 if (ReturnTypeInfo) {
24
Assuming 'ReturnTypeInfo' is null
25
Taking false branch
5567 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5568 assert(TL.getFullDataSize() == CurrTL.getFullDataSize())(static_cast <bool> (TL.getFullDataSize() == CurrTL.getFullDataSize
()) ? void (0) : __assert_fail ("TL.getFullDataSize() == CurrTL.getFullDataSize()"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5568, __extension__ __PRETTY_FUNCTION__))
;
5569 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5570 } else {
5571 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
26
Calling 'TypeLocVisitor::Visit'
5572 }
5573
5574 return TInfo;
5575}
5576
5577/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5578ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5579 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5580 // and Sema during declaration parsing. Try deallocating/caching them when
5581 // it's appropriate, instead of allocating them and keeping them around.
5582 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5583 TypeAlignment);
5584 new (LocT) LocInfoType(T, TInfo);
5585 assert(LocT->getTypeClass() != T->getTypeClass() &&(static_cast <bool> (LocT->getTypeClass() != T->getTypeClass
() && "LocInfoType's TypeClass conflicts with an existing Type class"
) ? void (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5586, __extension__ __PRETTY_FUNCTION__))
5586 "LocInfoType's TypeClass conflicts with an existing Type class")(static_cast <bool> (LocT->getTypeClass() != T->getTypeClass
() && "LocInfoType's TypeClass conflicts with an existing Type class"
) ? void (0) : __assert_fail ("LocT->getTypeClass() != T->getTypeClass() && \"LocInfoType's TypeClass conflicts with an existing Type class\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5586, __extension__ __PRETTY_FUNCTION__))
;
5587 return ParsedType::make(QualType(LocT, 0));
5588}
5589
5590void LocInfoType::getAsStringInternal(std::string &Str,
5591 const PrintingPolicy &Policy) const {
5592 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*"
" was used directly instead of getting the QualType through"
" GetTypeFromParser", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5594)
5593 " was used directly instead of getting the QualType through"::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*"
" was used directly instead of getting the QualType through"
" GetTypeFromParser", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5594)
5594 " GetTypeFromParser")::llvm::llvm_unreachable_internal("LocInfoType leaked into the type system; an opaque TypeTy*"
" was used directly instead of getting the QualType through"
" GetTypeFromParser", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5594)
;
5595}
5596
5597TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5598 // C99 6.7.6: Type names have no identifier. This is already validated by
5599 // the parser.
5600 assert(D.getIdentifier() == nullptr &&(static_cast <bool> (D.getIdentifier() == nullptr &&
"Type name should have no identifier!") ? void (0) : __assert_fail
("D.getIdentifier() == nullptr && \"Type name should have no identifier!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5601, __extension__ __PRETTY_FUNCTION__))
5601 "Type name should have no identifier!")(static_cast <bool> (D.getIdentifier() == nullptr &&
"Type name should have no identifier!") ? void (0) : __assert_fail
("D.getIdentifier() == nullptr && \"Type name should have no identifier!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5601, __extension__ __PRETTY_FUNCTION__))
;
5602
5603 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5604 QualType T = TInfo->getType();
5605 if (D.isInvalidType())
5606 return true;
5607
5608 // Make sure there are no unused decl attributes on the declarator.
5609 // We don't want to do this for ObjC parameters because we're going
5610 // to apply them to the actual parameter declaration.
5611 // Likewise, we don't want to do this for alias declarations, because
5612 // we are actually going to build a declaration from this eventually.
5613 if (D.getContext() != Declarator::ObjCParameterContext &&
5614 D.getContext() != Declarator::AliasDeclContext &&
5615 D.getContext() != Declarator::AliasTemplateContext)
5616 checkUnusedDeclAttributes(D);
5617
5618 if (getLangOpts().CPlusPlus) {
5619 // Check that there are no default arguments (C++ only).
5620 CheckExtraCXXDefaultArguments(D);
5621 }
5622
5623 return CreateParsedType(T, TInfo);
5624}
5625
5626ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5627 QualType T = Context.getObjCInstanceType();
5628 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5629 return CreateParsedType(T, TInfo);
5630}
5631
5632//===----------------------------------------------------------------------===//
5633// Type Attribute Processing
5634//===----------------------------------------------------------------------===//
5635
5636/// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
5637/// is uninstantiated. If instantiated it will apply the appropriate address space
5638/// to the type. This function allows dependent template variables to be used in
5639/// conjunction with the address_space attribute
5640QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
5641 SourceLocation AttrLoc) {
5642 if (!AddrSpace->isValueDependent()) {
5643
5644 // If this type is already address space qualified, reject it.
5645 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
5646 // by qualifiers for two or more different address spaces."
5647 if (T.getAddressSpace() != LangAS::Default) {
5648 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5649 return QualType();
5650 }
5651
5652 llvm::APSInt addrSpace(32);
5653 if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) {
5654 Diag(AttrLoc, diag::err_attribute_argument_type)
5655 << "'address_space'" << AANT_ArgumentIntegerConstant
5656 << AddrSpace->getSourceRange();
5657 return QualType();
5658 }
5659
5660 // Bounds checking.
5661 if (addrSpace.isSigned()) {
5662 if (addrSpace.isNegative()) {
5663 Diag(AttrLoc, diag::err_attribute_address_space_negative)
5664 << AddrSpace->getSourceRange();
5665 return QualType();
5666 }
5667 addrSpace.setIsSigned(false);
5668 }
5669
5670 llvm::APSInt max(addrSpace.getBitWidth());
5671 max =
5672 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
5673 if (addrSpace > max) {
5674 Diag(AttrLoc, diag::err_attribute_address_space_too_high)
5675 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
5676 return QualType();
5677 }
5678
5679 LangAS ASIdx =
5680 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
5681
5682 return Context.getAddrSpaceQualType(T, ASIdx);
5683 }
5684
5685 // A check with similar intentions as checking if a type already has an
5686 // address space except for on a dependent types, basically if the
5687 // current type is already a DependentAddressSpaceType then its already
5688 // lined up to have another address space on it and we can't have
5689 // multiple address spaces on the one pointer indirection
5690 if (T->getAs<DependentAddressSpaceType>()) {
5691 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5692 return QualType();
5693 }
5694
5695 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
5696}
5697
5698/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5699/// specified type. The attribute contains 1 argument, the id of the address
5700/// space for the type.
5701static void HandleAddressSpaceTypeAttribute(QualType &Type,
5702 const AttributeList &Attr, Sema &S){
5703 // If this type is already address space qualified, reject it.
5704 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5705 // qualifiers for two or more different address spaces."
5706 if (Type.getAddressSpace() != LangAS::Default) {
5707 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5708 Attr.setInvalid();
5709 return;
5710 }
5711
5712 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5713 // qualified by an address-space qualifier."
5714 if (Type->isFunctionType()) {
5715 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5716 Attr.setInvalid();
5717 return;
5718 }
5719
5720 LangAS ASIdx;
5721 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5722
5723 // Check the attribute arguments.
5724 if (Attr.getNumArgs() != 1) {
5725 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5726 << Attr.getName() << 1;
5727 Attr.setInvalid();
5728 return;
5729 }
5730
5731 Expr *ASArgExpr;
5732 if (Attr.isArgIdent(0)) {
5733 // Special case where the argument is a template id.
5734 CXXScopeSpec SS;
5735 SourceLocation TemplateKWLoc;
5736 UnqualifiedId id;
5737 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
5738
5739 ExprResult AddrSpace = S.ActOnIdExpression(
5740 S.getCurScope(), SS, TemplateKWLoc, id, false, false);
5741 if (AddrSpace.isInvalid())
5742 return;
5743
5744 ASArgExpr = static_cast<Expr *>(AddrSpace.get());
5745 } else {
5746 ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5747 }
5748
5749 // Create the DependentAddressSpaceType or append an address space onto
5750 // the type.
5751 QualType T = S.BuildAddressSpaceAttr(Type, ASArgExpr, Attr.getLoc());
5752
5753 if (!T.isNull())
5754 Type = T;
5755 else
5756 Attr.setInvalid();
5757 } else {
5758 // The keyword-based type attributes imply which address space to use.
5759 switch (Attr.getKind()) {
5760 case AttributeList::AT_OpenCLGlobalAddressSpace:
5761 ASIdx = LangAS::opencl_global; break;
5762 case AttributeList::AT_OpenCLLocalAddressSpace:
5763 ASIdx = LangAS::opencl_local; break;
5764 case AttributeList::AT_OpenCLConstantAddressSpace:
5765 ASIdx = LangAS::opencl_constant; break;
5766 case AttributeList::AT_OpenCLGenericAddressSpace:
5767 ASIdx = LangAS::opencl_generic; break;
5768 case AttributeList::AT_OpenCLPrivateAddressSpace:
5769 ASIdx = LangAS::opencl_private; break;
5770 default:
5771 llvm_unreachable("Invalid address space")::llvm::llvm_unreachable_internal("Invalid address space", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5771)
;
5772 }
5773
5774 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5775 }
5776}
5777
5778/// Does this type have a "direct" ownership qualifier? That is,
5779/// is it written like "__strong id", as opposed to something like
5780/// "typeof(foo)", where that happens to be strong?
5781static bool hasDirectOwnershipQualifier(QualType type) {
5782 // Fast path: no qualifier at all.
5783 assert(type.getQualifiers().hasObjCLifetime())(static_cast <bool> (type.getQualifiers().hasObjCLifetime
()) ? void (0) : __assert_fail ("type.getQualifiers().hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 5783, __extension__ __PRETTY_FUNCTION__))
;
5784
5785 while (true) {
5786 // __strong id
5787 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5788 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5789 return true;
5790
5791 type = attr->getModifiedType();
5792
5793 // X *__strong (...)
5794 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5795 type = paren->getInnerType();
5796
5797 // That's it for things we want to complain about. In particular,
5798 // we do not want to look through typedefs, typeof(expr),
5799 // typeof(type), or any other way that the type is somehow
5800 // abstracted.
5801 } else {
5802
5803 return false;
5804 }
5805 }
5806}
5807
5808/// handleObjCOwnershipTypeAttr - Process an objc_ownership
5809/// attribute on the specified type.
5810///
5811/// Returns 'true' if the attribute was handled.
5812static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5813 AttributeList &attr,
5814 QualType &type) {
5815 bool NonObjCPointer = false;
5816
5817 if (!type->isDependentType() && !type->isUndeducedType()) {
5818 if (const PointerType *ptr = type->getAs<PointerType>()) {
5819 QualType pointee = ptr->getPointeeType();
5820 if (pointee->isObjCRetainableType() || pointee->isPointerType())
5821 return false;
5822 // It is important not to lose the source info that there was an attribute
5823 // applied to non-objc pointer. We will create an attributed type but
5824 // its type will be the same as the original type.
5825 NonObjCPointer = true;
5826 } else if (!type->isObjCRetainableType()) {
5827 return false;
5828 }
5829
5830 // Don't accept an ownership attribute in the declspec if it would
5831 // just be the return type of a block pointer.
5832 if (state.isProcessingDeclSpec()) {
5833 Declarator &D = state.getDeclarator();
5834 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5835 /*onlyBlockPointers=*/true))
5836 return false;
5837 }
5838 }
5839
5840 Sema &S = state.getSema();
5841 SourceLocation AttrLoc = attr.getLoc();
5842 if (AttrLoc.isMacroID())
5843 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5844
5845 if (!attr.isArgIdent(0)) {
5846 S.Diag(AttrLoc, diag::err_attribute_argument_type)
5847 << attr.getName() << AANT_ArgumentString;
5848 attr.setInvalid();
5849 return true;
5850 }
5851
5852 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5853 Qualifiers::ObjCLifetime lifetime;
5854 if (II->isStr("none"))
5855 lifetime = Qualifiers::OCL_ExplicitNone;
5856 else if (II->isStr("strong"))
5857 lifetime = Qualifiers::OCL_Strong;
5858 else if (II->isStr("weak"))
5859 lifetime = Qualifiers::OCL_Weak;
5860 else if (II->isStr("autoreleasing"))
5861 lifetime = Qualifiers::OCL_Autoreleasing;
5862 else {
5863 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5864 << attr.getName() << II;
5865 attr.setInvalid();
5866 return true;
5867 }
5868
5869 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5870 // outside of ARC mode.
5871 if (!S.getLangOpts().ObjCAutoRefCount &&
5872 lifetime != Qualifiers::OCL_Weak &&
5873 lifetime != Qualifiers::OCL_ExplicitNone) {
5874 return true;
5875 }
5876
5877 SplitQualType underlyingType = type.split();
5878
5879 // Check for redundant/conflicting ownership qualifiers.
5880 if (Qualifiers::ObjCLifetime previousLifetime
5881 = type.getQualifiers().getObjCLifetime()) {
5882 // If it's written directly, that's an error.
5883 if (hasDirectOwnershipQualifier(type)) {
5884 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5885 << type;
5886 return true;
5887 }
5888
5889 // Otherwise, if the qualifiers actually conflict, pull sugar off
5890 // and remove the ObjCLifetime qualifiers.
5891 if (previousLifetime != lifetime) {
5892 // It's possible to have multiple local ObjCLifetime qualifiers. We
5893 // can't stop after we reach a type that is directly qualified.
5894 const Type *prevTy = nullptr;
5895 while (!prevTy || prevTy != underlyingType.Ty) {
5896 prevTy = underlyingType.Ty;
5897 underlyingType = underlyingType.getSingleStepDesugaredType();
5898 }
5899 underlyingType.Quals.removeObjCLifetime();
5900 }
5901 }
5902
5903 underlyingType.Quals.addObjCLifetime(lifetime);
5904
5905 if (NonObjCPointer) {
5906 StringRef name = attr.getName()->getName();
5907 switch (lifetime) {
5908 case Qualifiers::OCL_None:
5909 case Qualifiers::OCL_ExplicitNone:
5910 break;
5911 case Qualifiers::OCL_Strong: name = "__strong"; break;
5912 case Qualifiers::OCL_Weak: name = "__weak"; break;
5913 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5914 }
5915 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5916 << TDS_ObjCObjOrBlock << type;
5917 }
5918
5919 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5920 // because having both 'T' and '__unsafe_unretained T' exist in the type
5921 // system causes unfortunate widespread consistency problems. (For example,
5922 // they're not considered compatible types, and we mangle them identicially
5923 // as template arguments.) These problems are all individually fixable,
5924 // but it's easier to just not add the qualifier and instead sniff it out
5925 // in specific places using isObjCInertUnsafeUnretainedType().
5926 //
5927 // Doing this does means we miss some trivial consistency checks that
5928 // would've triggered in ARC, but that's better than trying to solve all
5929 // the coexistence problems with __unsafe_unretained.
5930 if (!S.getLangOpts().ObjCAutoRefCount &&
5931 lifetime == Qualifiers::OCL_ExplicitNone) {
5932 type = S.Context.getAttributedType(
5933 AttributedType::attr_objc_inert_unsafe_unretained,
5934 type, type);
5935 return true;
5936 }
5937
5938 QualType origType = type;
5939 if (!NonObjCPointer)
5940 type = S.Context.getQualifiedType(underlyingType);
5941
5942 // If we have a valid source location for the attribute, use an
5943 // AttributedType instead.
5944 if (AttrLoc.isValid())
5945 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5946 origType, type);
5947
5948 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5949 unsigned diagnostic, QualType type) {
5950 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5951 S.DelayedDiagnostics.add(
5952 sema::DelayedDiagnostic::makeForbiddenType(
5953 S.getSourceManager().getExpansionLoc(loc),
5954 diagnostic, type, /*ignored*/ 0));
5955 } else {
5956 S.Diag(loc, diagnostic);
5957 }
5958 };
5959
5960 // Sometimes, __weak isn't allowed.
5961 if (lifetime == Qualifiers::OCL_Weak &&
5962 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5963
5964 // Use a specialized diagnostic if the runtime just doesn't support them.
5965 unsigned diagnostic =
5966 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5967 : diag::err_arc_weak_no_runtime);
5968
5969 // In any case, delay the diagnostic until we know what we're parsing.
5970 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5971
5972 attr.setInvalid();
5973 return true;
5974 }
5975
5976 // Forbid __weak for class objects marked as
5977 // objc_arc_weak_reference_unavailable
5978 if (lifetime == Qualifiers::OCL_Weak) {
5979 if (const ObjCObjectPointerType *ObjT =
5980 type->getAs<ObjCObjectPointerType>()) {
5981 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5982 if (Class->isArcWeakrefUnavailable()) {
5983 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5984 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5985 diag::note_class_declared);
5986 }
5987 }
5988 }
5989 }
5990
5991 return true;
5992}
5993
5994/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5995/// attribute on the specified type. Returns true to indicate that
5996/// the attribute was handled, false to indicate that the type does
5997/// not permit the attribute.
5998static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5999 AttributeList &attr,
6000 QualType &type) {
6001 Sema &S = state.getSema();
6002
6003 // Delay if this isn't some kind of pointer.
6004 if (!type->isPointerType() &&
6005 !type->isObjCObjectPointerType() &&
6006 !type->isBlockPointerType())
6007 return false;
6008
6009 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6010 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6011 attr.setInvalid();
6012 return true;
6013 }
6014
6015 // Check the attribute arguments.
6016 if (!attr.isArgIdent(0)) {
6017 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6018 << attr.getName() << AANT_ArgumentString;
6019 attr.setInvalid();
6020 return true;
6021 }
6022 Qualifiers::GC GCAttr;
6023 if (attr.getNumArgs() > 1) {
6024 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6025 << attr.getName() << 1;
6026 attr.setInvalid();
6027 return true;
6028 }
6029
6030 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6031 if (II->isStr("weak"))
6032 GCAttr = Qualifiers::Weak;
6033 else if (II->isStr("strong"))
6034 GCAttr = Qualifiers::Strong;
6035 else {
6036 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6037 << attr.getName() << II;
6038 attr.setInvalid();
6039 return true;
6040 }
6041
6042 QualType origType = type;
6043 type = S.Context.getObjCGCQualType(origType, GCAttr);
6044
6045 // Make an attributed type to preserve the source information.
6046 if (attr.getLoc().isValid())
6047 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
6048 origType, type);
6049
6050 return true;
6051}
6052
6053namespace {
6054 /// A helper class to unwrap a type down to a function for the
6055 /// purposes of applying attributes there.
6056 ///
6057 /// Use:
6058 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
6059 /// if (unwrapped.isFunctionType()) {
6060 /// const FunctionType *fn = unwrapped.get();
6061 /// // change fn somehow
6062 /// T = unwrapped.wrap(fn);
6063 /// }
6064 struct FunctionTypeUnwrapper {
6065 enum WrapKind {
6066 Desugar,
6067 Attributed,
6068 Parens,
6069 Pointer,
6070 BlockPointer,
6071 Reference,
6072 MemberPointer
6073 };
6074
6075 QualType Original;
6076 const FunctionType *Fn;
6077 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6078
6079 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6080 while (true) {
6081 const Type *Ty = T.getTypePtr();
6082 if (isa<FunctionType>(Ty)) {
6083 Fn = cast<FunctionType>(Ty);
6084 return;
6085 } else if (isa<ParenType>(Ty)) {
6086 T = cast<ParenType>(Ty)->getInnerType();
6087 Stack.push_back(Parens);
6088 } else if (isa<PointerType>(Ty)) {
6089 T = cast<PointerType>(Ty)->getPointeeType();
6090 Stack.push_back(Pointer);
6091 } else if (isa<BlockPointerType>(Ty)) {
6092 T = cast<BlockPointerType>(Ty)->getPointeeType();
6093 Stack.push_back(BlockPointer);
6094 } else if (isa<MemberPointerType>(Ty)) {
6095 T = cast<MemberPointerType>(Ty)->getPointeeType();
6096 Stack.push_back(MemberPointer);
6097 } else if (isa<ReferenceType>(Ty)) {
6098 T = cast<ReferenceType>(Ty)->getPointeeType();
6099 Stack.push_back(Reference);
6100 } else if (isa<AttributedType>(Ty)) {
6101 T = cast<AttributedType>(Ty)->getEquivalentType();
6102 Stack.push_back(Attributed);
6103 } else {
6104 const Type *DTy = Ty->getUnqualifiedDesugaredType();
6105 if (Ty == DTy) {
6106 Fn = nullptr;
6107 return;
6108 }
6109
6110 T = QualType(DTy, 0);
6111 Stack.push_back(Desugar);
6112 }
6113 }
6114 }
6115
6116 bool isFunctionType() const { return (Fn != nullptr); }
6117 const FunctionType *get() const { return Fn; }
6118
6119 QualType wrap(Sema &S, const FunctionType *New) {
6120 // If T wasn't modified from the unwrapped type, do nothing.
6121 if (New == get()) return Original;
6122
6123 Fn = New;
6124 return wrap(S.Context, Original, 0);
6125 }
6126
6127 private:
6128 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6129 if (I == Stack.size())
6130 return C.getQualifiedType(Fn, Old.getQualifiers());
6131
6132 // Build up the inner type, applying the qualifiers from the old
6133 // type to the new type.
6134 SplitQualType SplitOld = Old.split();
6135
6136 // As a special case, tail-recurse if there are no qualifiers.
6137 if (SplitOld.Quals.empty())
6138 return wrap(C, SplitOld.Ty, I);
6139 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6140 }
6141
6142 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6143 if (I == Stack.size()) return QualType(Fn, 0);
6144
6145 switch (static_cast<WrapKind>(Stack[I++])) {
6146 case Desugar:
6147 // This is the point at which we potentially lose source
6148 // information.
6149 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6150
6151 case Attributed:
6152 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6153
6154 case Parens: {
6155 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
6156 return C.getParenType(New);
6157 }
6158
6159 case Pointer: {
6160 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
6161 return C.getPointerType(New);
6162 }
6163
6164 case BlockPointer: {
6165 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
6166 return C.getBlockPointerType(New);
6167 }
6168
6169 case MemberPointer: {
6170 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
6171 QualType New = wrap(C, OldMPT->getPointeeType(), I);
6172 return C.getMemberPointerType(New, OldMPT->getClass());
6173 }
6174
6175 case Reference: {
6176 const ReferenceType *OldRef = cast<ReferenceType>(Old);
6177 QualType New = wrap(C, OldRef->getPointeeType(), I);
6178 if (isa<LValueReferenceType>(OldRef))
6179 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
6180 else
6181 return C.getRValueReferenceType(New);
6182 }
6183 }
6184
6185 llvm_unreachable("unknown wrapping kind")::llvm::llvm_unreachable_internal("unknown wrapping kind", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 6185)
;
6186 }
6187 };
6188} // end anonymous namespace
6189
6190static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
6191 AttributeList &Attr,
6192 QualType &Type) {
6193 Sema &S = State.getSema();
6194
6195 AttributeList::Kind Kind = Attr.getKind();
6196 QualType Desugared = Type;
6197 const AttributedType *AT = dyn_cast<AttributedType>(Type);
6198 while (AT) {
6199 AttributedType::Kind CurAttrKind = AT->getAttrKind();
6200
6201 // You cannot specify duplicate type attributes, so if the attribute has
6202 // already been applied, flag it.
6203 if (getAttrListKind(CurAttrKind) == Kind) {
6204 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
6205 << Attr.getName();
6206 return true;
6207 }
6208
6209 // You cannot have both __sptr and __uptr on the same type, nor can you
6210 // have __ptr32 and __ptr64.
6211 if ((CurAttrKind == AttributedType::attr_ptr32 &&
6212 Kind == AttributeList::AT_Ptr64) ||
6213 (CurAttrKind == AttributedType::attr_ptr64 &&
6214 Kind == AttributeList::AT_Ptr32)) {
6215 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6216 << "'__ptr32'" << "'__ptr64'";
6217 return true;
6218 } else if ((CurAttrKind == AttributedType::attr_sptr &&
6219 Kind == AttributeList::AT_UPtr) ||
6220 (CurAttrKind == AttributedType::attr_uptr &&
6221 Kind == AttributeList::AT_SPtr)) {
6222 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6223 << "'__sptr'" << "'__uptr'";
6224 return true;
6225 }
6226
6227 Desugared = AT->getEquivalentType();
6228 AT = dyn_cast<AttributedType>(Desugared);
6229 }
6230
6231 // Pointer type qualifiers can only operate on pointer types, but not
6232 // pointer-to-member types.
6233 if (!isa<PointerType>(Desugared)) {
6234 if (Type->isMemberPointerType())
6235 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
6236 << Attr.getName();
6237 else
6238 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
6239 << Attr.getName() << 0;
6240 return true;
6241 }
6242
6243 AttributedType::Kind TAK;
6244 switch (Kind) {
6245 default: llvm_unreachable("Unknown attribute kind")::llvm::llvm_unreachable_internal("Unknown attribute kind", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 6245)
;
6246 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
6247 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
6248 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
6249 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
6250 }
6251
6252 Type = S.Context.getAttributedType(TAK, Type, Type);
6253 return false;
6254}
6255
6256bool Sema::checkNullabilityTypeSpecifier(QualType &type,
6257 NullabilityKind nullability,
6258 SourceLocation nullabilityLoc,
6259 bool isContextSensitive,
6260 bool allowOnArrayType) {
6261 recordNullabilitySeen(*this, nullabilityLoc);
6262
6263 // Check for existing nullability attributes on the type.
6264 QualType desugared = type;
6265 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6266 // Check whether there is already a null
6267 if (auto existingNullability = attributed->getImmediateNullability()) {
6268 // Duplicated nullability.
6269 if (nullability == *existingNullability) {
6270 Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6271 << DiagNullabilityKind(nullability, isContextSensitive)
6272 << FixItHint::CreateRemoval(nullabilityLoc);
6273
6274 break;
6275 }
6276
6277 // Conflicting nullability.
6278 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6279 << DiagNullabilityKind(nullability, isContextSensitive)
6280 << DiagNullabilityKind(*existingNullability, false);
6281 return true;
6282 }
6283
6284 desugared = attributed->getModifiedType();
6285 }
6286
6287 // If there is already a different nullability specifier, complain.
6288 // This (unlike the code above) looks through typedefs that might
6289 // have nullability specifiers on them, which means we cannot
6290 // provide a useful Fix-It.
6291 if (auto existingNullability = desugared->getNullability(Context)) {
6292 if (nullability != *existingNullability) {
6293 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6294 << DiagNullabilityKind(nullability, isContextSensitive)
6295 << DiagNullabilityKind(*existingNullability, false);
6296
6297 // Try to find the typedef with the existing nullability specifier.
6298 if (auto typedefType = desugared->getAs<TypedefType>()) {
6299 TypedefNameDecl *typedefDecl = typedefType->getDecl();
6300 QualType underlyingType = typedefDecl->getUnderlyingType();
6301 if (auto typedefNullability
6302 = AttributedType::stripOuterNullability(underlyingType)) {
6303 if (*typedefNullability == *existingNullability) {
6304 Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6305 << DiagNullabilityKind(*existingNullability, false);
6306 }
6307 }
6308 }
6309
6310 return true;
6311 }
6312 }
6313
6314 // If this definitely isn't a pointer type, reject the specifier.
6315 if (!desugared->canHaveNullability() &&
6316 !(allowOnArrayType && desugared->isArrayType())) {
6317 Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6318 << DiagNullabilityKind(nullability, isContextSensitive) << type;
6319 return true;
6320 }
6321
6322 // For the context-sensitive keywords/Objective-C property
6323 // attributes, require that the type be a single-level pointer.
6324 if (isContextSensitive) {
6325 // Make sure that the pointee isn't itself a pointer type.
6326 const Type *pointeeType;
6327 if (desugared->isArrayType())
6328 pointeeType = desugared->getArrayElementTypeNoTypeQual();
6329 else
6330 pointeeType = desugared->getPointeeType().getTypePtr();
6331
6332 if (pointeeType->isAnyPointerType() ||
6333 pointeeType->isObjCObjectPointerType() ||
6334 pointeeType->isMemberPointerType()) {
6335 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6336 << DiagNullabilityKind(nullability, true)
6337 << type;
6338 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6339 << DiagNullabilityKind(nullability, false)
6340 << type
6341 << FixItHint::CreateReplacement(nullabilityLoc,
6342 getNullabilitySpelling(nullability));
6343 return true;
6344 }
6345 }
6346
6347 // Form the attributed type.
6348 type = Context.getAttributedType(
6349 AttributedType::getNullabilityAttrKind(nullability), type, type);
6350 return false;
6351}
6352
6353bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
6354 if (isa<ObjCTypeParamType>(type)) {
6355 // Build the attributed type to record where __kindof occurred.
6356 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6357 type, type);
6358 return false;
6359 }
6360
6361 // Find out if it's an Objective-C object or object pointer type;
6362 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6363 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6364 : type->getAs<ObjCObjectType>();
6365
6366 // If not, we can't apply __kindof.
6367 if (!objType) {
6368 // FIXME: Handle dependent types that aren't yet object types.
6369 Diag(loc, diag::err_objc_kindof_nonobject)
6370 << type;
6371 return true;
6372 }
6373
6374 // Rebuild the "equivalent" type, which pushes __kindof down into
6375 // the object type.
6376 // There is no need to apply kindof on an unqualified id type.
6377 QualType equivType = Context.getObjCObjectType(
6378 objType->getBaseType(), objType->getTypeArgsAsWritten(),
6379 objType->getProtocols(),
6380 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6381
6382 // If we started with an object pointer type, rebuild it.
6383 if (ptrType) {
6384 equivType = Context.getObjCObjectPointerType(equivType);
6385 if (auto nullability = type->getNullability(Context)) {
6386 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
6387 equivType = Context.getAttributedType(attrKind, equivType, equivType);
6388 }
6389 }
6390
6391 // Build the attributed type to record where __kindof occurred.
6392 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6393 type,
6394 equivType);
6395
6396 return false;
6397}
6398
6399/// Map a nullability attribute kind to a nullability kind.
6400static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
6401 switch (kind) {
6402 case AttributeList::AT_TypeNonNull:
6403 return NullabilityKind::NonNull;
6404
6405 case AttributeList::AT_TypeNullable:
6406 return NullabilityKind::Nullable;
6407
6408 case AttributeList::AT_TypeNullUnspecified:
6409 return NullabilityKind::Unspecified;
6410
6411 default:
6412 llvm_unreachable("not a nullability attribute kind")::llvm::llvm_unreachable_internal("not a nullability attribute kind"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 6412)
;
6413 }
6414}
6415
6416/// Distribute a nullability type attribute that cannot be applied to
6417/// the type specifier to a pointer, block pointer, or member pointer
6418/// declarator, complaining if necessary.
6419///
6420/// \returns true if the nullability annotation was distributed, false
6421/// otherwise.
6422static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6423 QualType type,
6424 AttributeList &attr) {
6425 Declarator &declarator = state.getDeclarator();
6426
6427 /// Attempt to move the attribute to the specified chunk.
6428 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6429 // If there is already a nullability attribute there, don't add
6430 // one.
6431 if (hasNullabilityAttr(chunk.getAttrListRef()))
6432 return false;
6433
6434 // Complain about the nullability qualifier being in the wrong
6435 // place.
6436 enum {
6437 PK_Pointer,
6438 PK_BlockPointer,
6439 PK_MemberPointer,
6440 PK_FunctionPointer,
6441 PK_MemberFunctionPointer,
6442 } pointerKind
6443 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6444 : PK_Pointer)
6445 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6446 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6447
6448 auto diag = state.getSema().Diag(attr.getLoc(),
6449 diag::warn_nullability_declspec)
6450 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6451 attr.isContextSensitiveKeywordAttribute())
6452 << type
6453 << static_cast<unsigned>(pointerKind);
6454
6455 // FIXME: MemberPointer chunks don't carry the location of the *.
6456 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6457 diag << FixItHint::CreateRemoval(attr.getLoc())
6458 << FixItHint::CreateInsertion(
6459 state.getSema().getPreprocessor()
6460 .getLocForEndOfToken(chunk.Loc),
6461 " " + attr.getName()->getName().str() + " ");
6462 }
6463
6464 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
6465 chunk.getAttrListRef());
6466 return true;
6467 };
6468
6469 // Move it to the outermost pointer, member pointer, or block
6470 // pointer declarator.
6471 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6472 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6473 switch (chunk.Kind) {
6474 case DeclaratorChunk::Pointer:
6475 case DeclaratorChunk::BlockPointer:
6476 case DeclaratorChunk::MemberPointer:
6477 return moveToChunk(chunk, false);
6478
6479 case DeclaratorChunk::Paren:
6480 case DeclaratorChunk::Array:
6481 continue;
6482
6483 case DeclaratorChunk::Function:
6484 // Try to move past the return type to a function/block/member
6485 // function pointer.
6486 if (DeclaratorChunk *dest = maybeMovePastReturnType(
6487 declarator, i,
6488 /*onlyBlockPointers=*/false)) {
6489 return moveToChunk(*dest, true);
6490 }
6491
6492 return false;
6493
6494 // Don't walk through these.
6495 case DeclaratorChunk::Reference:
6496 case DeclaratorChunk::Pipe:
6497 return false;
6498 }
6499 }
6500
6501 return false;
6502}
6503
6504static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6505 assert(!Attr.isInvalid())(static_cast <bool> (!Attr.isInvalid()) ? void (0) : __assert_fail
("!Attr.isInvalid()", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 6505, __extension__ __PRETTY_FUNCTION__))
;
6506 switch (Attr.getKind()) {
6507 default:
6508 llvm_unreachable("not a calling convention attribute")::llvm::llvm_unreachable_internal("not a calling convention attribute"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 6508)
;
6509 case AttributeList::AT_CDecl:
6510 return AttributedType::attr_cdecl;
6511 case AttributeList::AT_FastCall:
6512 return AttributedType::attr_fastcall;
6513 case AttributeList::AT_StdCall:
6514 return AttributedType::attr_stdcall;
6515 case AttributeList::AT_ThisCall:
6516 return AttributedType::attr_thiscall;
6517 case AttributeList::AT_RegCall:
6518 return AttributedType::attr_regcall;
6519 case AttributeList::AT_Pascal:
6520 return AttributedType::attr_pascal;
6521 case AttributeList::AT_SwiftCall:
6522 return AttributedType::attr_swiftcall;
6523 case AttributeList::AT_VectorCall:
6524 return AttributedType::attr_vectorcall;
6525 case AttributeList::AT_Pcs: {
6526 // The attribute may have had a fixit applied where we treated an
6527 // identifier as a string literal. The contents of the string are valid,
6528 // but the form may not be.
6529 StringRef Str;
6530 if (Attr.isArgExpr(0))
6531 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6532 else
6533 Str = Attr.getArgAsIdent(0)->Ident->getName();
6534 return llvm::StringSwitch<AttributedType::Kind>(Str)
6535 .Case("aapcs", AttributedType::attr_pcs)
6536 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6537 }
6538 case AttributeList::AT_IntelOclBicc:
6539 return AttributedType::attr_inteloclbicc;
6540 case AttributeList::AT_MSABI:
6541 return AttributedType::attr_ms_abi;
6542 case AttributeList::AT_SysVABI:
6543 return AttributedType::attr_sysv_abi;
6544 case AttributeList::AT_PreserveMost:
6545 return AttributedType::attr_preserve_most;
6546 case AttributeList::AT_PreserveAll:
6547 return AttributedType::attr_preserve_all;
6548 }
6549 llvm_unreachable("unexpected attribute kind!")::llvm::llvm_unreachable_internal("unexpected attribute kind!"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 6549)
;
6550}
6551
6552/// Process an individual function attribute. Returns true to
6553/// indicate that the attribute was handled, false if it wasn't.
6554static bool handleFunctionTypeAttr(TypeProcessingState &state,
6555 AttributeList &attr,
6556 QualType &type) {
6557 Sema &S = state.getSema();
6558
6559 FunctionTypeUnwrapper unwrapped(S, type);
6560
6561 if (attr.getKind() == AttributeList::AT_NoReturn) {
6562 if (S.CheckNoReturnAttr(attr))
6563 return true;
6564
6565 // Delay if this is not a function type.
6566 if (!unwrapped.isFunctionType())
6567 return false;
6568
6569 // Otherwise we can process right away.
6570 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6571 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6572 return true;
6573 }
6574
6575 // ns_returns_retained is not always a type attribute, but if we got
6576 // here, we're treating it as one right now.
6577 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6578 if (attr.getNumArgs()) return true;
6579
6580 // Delay if this is not a function type.
6581 if (!unwrapped.isFunctionType())
6582 return false;
6583
6584 // Check whether the return type is reasonable.
6585 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
6586 unwrapped.get()->getReturnType()))
6587 return true;
6588
6589 // Only actually change the underlying type in ARC builds.
6590 QualType origType = type;
6591 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
6592 FunctionType::ExtInfo EI
6593 = unwrapped.get()->getExtInfo().withProducesResult(true);
6594 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6595 }
6596 type = S.Context.getAttributedType(AttributedType::attr_ns_returns_retained,
6597 origType, type);
6598 return true;
6599 }
6600
6601 if (attr.getKind() == AttributeList::AT_AnyX86NoCallerSavedRegisters) {
6602 if (S.CheckNoCallerSavedRegsAttr(attr))
6603 return true;
6604
6605 // Delay if this is not a function type.
6606 if (!unwrapped.isFunctionType())
6607 return false;
6608
6609 FunctionType::ExtInfo EI =
6610 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
6611 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6612 return true;
6613 }
6614
6615 if (attr.getKind() == AttributeList::AT_Regparm) {
6616 unsigned value;
6617 if (S.CheckRegparmAttr(attr, value))
6618 return true;
6619
6620 // Delay if this is not a function type.
6621 if (!unwrapped.isFunctionType())
6622 return false;
6623
6624 // Diagnose regparm with fastcall.
6625 const FunctionType *fn = unwrapped.get();
6626 CallingConv CC = fn->getCallConv();
6627 if (CC == CC_X86FastCall) {
6628 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6629 << FunctionType::getNameForCallConv(CC)
6630 << "regparm";
6631 attr.setInvalid();
6632 return true;
6633 }
6634
6635 FunctionType::ExtInfo EI =
6636 unwrapped.get()->getExtInfo().withRegParm(value);
6637 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6638 return true;
6639 }
6640
6641 // Delay if the type didn't work out to a function.
6642 if (!unwrapped.isFunctionType()) return false;
6643
6644 // Otherwise, a calling convention.
6645 CallingConv CC;
6646 if (S.CheckCallingConvAttr(attr, CC))
6647 return true;
6648
6649 const FunctionType *fn = unwrapped.get();
6650 CallingConv CCOld = fn->getCallConv();
6651 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6652
6653 if (CCOld != CC) {
6654 // Error out on when there's already an attribute on the type
6655 // and the CCs don't match.
6656 const AttributedType *AT = S.getCallingConvAttributedType(type);
6657 if (AT && AT->getAttrKind() != CCAttrKind) {
6658 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6659 << FunctionType::getNameForCallConv(CC)
6660 << FunctionType::getNameForCallConv(CCOld);
6661 attr.setInvalid();
6662 return true;
6663 }
6664 }
6665
6666 // Diagnose use of variadic functions with calling conventions that
6667 // don't support them (e.g. because they're callee-cleanup).
6668 // We delay warning about this on unprototyped function declarations
6669 // until after redeclaration checking, just in case we pick up a
6670 // prototype that way. And apparently we also "delay" warning about
6671 // unprototyped function types in general, despite not necessarily having
6672 // much ability to diagnose it later.
6673 if (!supportsVariadicCall(CC)) {
6674 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6675 if (FnP && FnP->isVariadic()) {
6676 unsigned DiagID = diag::err_cconv_varargs;
6677
6678 // stdcall and fastcall are ignored with a warning for GCC and MS
6679 // compatibility.
6680 bool IsInvalid = true;
6681 if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6682 DiagID = diag::warn_cconv_varargs;
6683 IsInvalid = false;
6684 }
6685
6686 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6687 if (IsInvalid) attr.setInvalid();
6688 return true;
6689 }
6690 }
6691
6692 // Also diagnose fastcall with regparm.
6693 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6694 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6695 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6696 attr.setInvalid();
6697 return true;
6698 }
6699
6700 // Modify the CC from the wrapped function type, wrap it all back, and then
6701 // wrap the whole thing in an AttributedType as written. The modified type
6702 // might have a different CC if we ignored the attribute.
6703 QualType Equivalent;
6704 if (CCOld == CC) {
6705 Equivalent = type;
6706 } else {
6707 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6708 Equivalent =
6709 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6710 }
6711 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6712 return true;
6713}
6714
6715bool Sema::hasExplicitCallingConv(QualType &T) {
6716 QualType R = T.IgnoreParens();
6717 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6718 if (AT->isCallingConv())
6719 return true;
6720 R = AT->getModifiedType().IgnoreParens();
6721 }
6722 return false;
6723}
6724
6725void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6726 SourceLocation Loc) {
6727 FunctionTypeUnwrapper Unwrapped(*this, T);
6728 const FunctionType *FT = Unwrapped.get();
6729 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6730 cast<FunctionProtoType>(FT)->isVariadic());
6731 CallingConv CurCC = FT->getCallConv();
6732 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6733
6734 if (CurCC == ToCC)
6735 return;
6736
6737 // MS compiler ignores explicit calling convention attributes on structors. We
6738 // should do the same.
6739 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6740 // Issue a warning on ignored calling convention -- except of __stdcall.
6741 // Again, this is what MS compiler does.
6742 if (CurCC != CC_X86StdCall)
6743 Diag(Loc, diag::warn_cconv_structors)
6744 << FunctionType::getNameForCallConv(CurCC);
6745 // Default adjustment.
6746 } else {
6747 // Only adjust types with the default convention. For example, on Windows
6748 // we should adjust a __cdecl type to __thiscall for instance methods, and a
6749 // __thiscall type to __cdecl for static methods.
6750 CallingConv DefaultCC =
6751 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6752
6753 if (CurCC != DefaultCC || DefaultCC == ToCC)
6754 return;
6755
6756 if (hasExplicitCallingConv(T))
6757 return;
6758 }
6759
6760 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6761 QualType Wrapped = Unwrapped.wrap(*this, FT);
6762 T = Context.getAdjustedType(T, Wrapped);
6763}
6764
6765/// HandleVectorSizeAttribute - this attribute is only applicable to integral
6766/// and float scalars, although arrays, pointers, and function return values are
6767/// allowed in conjunction with this construct. Aggregates with this attribute
6768/// are invalid, even if they are of the same size as a corresponding scalar.
6769/// The raw attribute should contain precisely 1 argument, the vector size for
6770/// the variable, measured in bytes. If curType and rawAttr are well formed,
6771/// this routine will return a new vector type.
6772static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6773 Sema &S) {
6774 // Check the attribute arguments.
6775 if (Attr.getNumArgs() != 1) {
6776 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6777 << Attr.getName() << 1;
6778 Attr.setInvalid();
6779 return;
6780 }
6781 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6782 llvm::APSInt vecSize(32);
6783 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6784 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6785 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6786 << Attr.getName() << AANT_ArgumentIntegerConstant
6787 << sizeExpr->getSourceRange();
6788 Attr.setInvalid();
6789 return;
6790 }
6791 // The base type must be integer (not Boolean or enumeration) or float, and
6792 // can't already be a vector.
6793 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6794 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6795 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6796 Attr.setInvalid();
6797 return;
6798 }
6799 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6800 // vecSize is specified in bytes - convert to bits.
6801 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6802
6803 // the vector size needs to be an integral multiple of the type size.
6804 if (vectorSize % typeSize) {
6805 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6806 << sizeExpr->getSourceRange();
6807 Attr.setInvalid();
6808 return;
6809 }
6810 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6811 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6812 << sizeExpr->getSourceRange();
6813 Attr.setInvalid();
6814 return;
6815 }
6816 if (vectorSize == 0) {
6817 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6818 << sizeExpr->getSourceRange();
6819 Attr.setInvalid();
6820 return;
6821 }
6822
6823 // Success! Instantiate the vector type, the number of elements is > 0, and
6824 // not required to be a power of 2, unlike GCC.
6825 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6826 VectorType::GenericVector);
6827}
6828
6829/// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6830/// a type.
6831static void HandleExtVectorTypeAttr(QualType &CurType,
6832 const AttributeList &Attr,
6833 Sema &S) {
6834 // check the attribute arguments.
6835 if (Attr.getNumArgs() != 1) {
6836 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6837 << Attr.getName() << 1;
6838 return;
6839 }
6840
6841 Expr *sizeExpr;
6842
6843 // Special case where the argument is a template id.
6844 if (Attr.isArgIdent(0)) {
6845 CXXScopeSpec SS;
6846 SourceLocation TemplateKWLoc;
6847 UnqualifiedId id;
6848 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6849
6850 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6851 id, false, false);
6852 if (Size.isInvalid())
6853 return;
6854
6855 sizeExpr = Size.get();
6856 } else {
6857 sizeExpr = Attr.getArgAsExpr(0);
6858 }
6859
6860 // Create the vector type.
6861 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6862 if (!T.isNull())
6863 CurType = T;
6864}
6865
6866static bool isPermittedNeonBaseType(QualType &Ty,
6867 VectorType::VectorKind VecKind, Sema &S) {
6868 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6869 if (!BTy)
6870 return false;
6871
6872 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6873
6874 // Signed poly is mathematically wrong, but has been baked into some ABIs by
6875 // now.
6876 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6877 Triple.getArch() == llvm::Triple::aarch64_be;
6878 if (VecKind == VectorType::NeonPolyVector) {
6879 if (IsPolyUnsigned) {
6880 // AArch64 polynomial vectors are unsigned and support poly64.
6881 return BTy->getKind() == BuiltinType::UChar ||
6882 BTy->getKind() == BuiltinType::UShort ||
6883 BTy->getKind() == BuiltinType::ULong ||
6884 BTy->getKind() == BuiltinType::ULongLong;
6885 } else {
6886 // AArch32 polynomial vector are signed.
6887 return BTy->getKind() == BuiltinType::SChar ||
6888 BTy->getKind() == BuiltinType::Short;
6889 }
6890 }
6891
6892 // Non-polynomial vector types: the usual suspects are allowed, as well as
6893 // float64_t on AArch64.
6894 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6895 Triple.getArch() == llvm::Triple::aarch64_be;
6896
6897 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6898 return true;
6899
6900 return BTy->getKind() == BuiltinType::SChar ||
6901 BTy->getKind() == BuiltinType::UChar ||
6902 BTy->getKind() == BuiltinType::Short ||
6903 BTy->getKind() == BuiltinType::UShort ||
6904 BTy->getKind() == BuiltinType::Int ||
6905 BTy->getKind() == BuiltinType::UInt ||
6906 BTy->getKind() == BuiltinType::Long ||
6907 BTy->getKind() == BuiltinType::ULong ||
6908 BTy->getKind() == BuiltinType::LongLong ||
6909 BTy->getKind() == BuiltinType::ULongLong ||
6910 BTy->getKind() == BuiltinType::Float ||
6911 BTy->getKind() == BuiltinType::Half;
6912}
6913
6914/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6915/// "neon_polyvector_type" attributes are used to create vector types that
6916/// are mangled according to ARM's ABI. Otherwise, these types are identical
6917/// to those created with the "vector_size" attribute. Unlike "vector_size"
6918/// the argument to these Neon attributes is the number of vector elements,
6919/// not the vector size in bytes. The vector width and element type must
6920/// match one of the standard Neon vector types.
6921static void HandleNeonVectorTypeAttr(QualType& CurType,
6922 const AttributeList &Attr, Sema &S,
6923 VectorType::VectorKind VecKind) {
6924 // Target must have NEON
6925 if (!S.Context.getTargetInfo().hasFeature("neon")) {
6926 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6927 Attr.setInvalid();
6928 return;
6929 }
6930 // Check the attribute arguments.
6931 if (Attr.getNumArgs() != 1) {
6932 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6933 << Attr.getName() << 1;
6934 Attr.setInvalid();
6935 return;
6936 }
6937 // The number of elements must be an ICE.
6938 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6939 llvm::APSInt numEltsInt(32);
6940 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6941 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6942 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6943 << Attr.getName() << AANT_ArgumentIntegerConstant
6944 << numEltsExpr->getSourceRange();
6945 Attr.setInvalid();
6946 return;
6947 }
6948 // Only certain element types are supported for Neon vectors.
6949 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6950 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6951 Attr.setInvalid();
6952 return;
6953 }
6954
6955 // The total size of the vector must be 64 or 128 bits.
6956 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6957 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6958 unsigned vecSize = typeSize * numElts;
6959 if (vecSize != 64 && vecSize != 128) {
6960 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6961 Attr.setInvalid();
6962 return;
6963 }
6964
6965 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6966}
6967
6968/// Handle OpenCL Access Qualifier Attribute.
6969static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
6970 Sema &S) {
6971 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
6972 if (!(CurType->isImageType() || CurType->isPipeType())) {
6973 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
6974 Attr.setInvalid();
6975 return;
6976 }
6977
6978 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
6979 QualType PointeeTy = TypedefTy->desugar();
6980 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
6981
6982 std::string PrevAccessQual;
6983 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
6984 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6985 case BuiltinType::Id: \
6986 PrevAccessQual = #Access; \
6987 break;
6988 #include "clang/Basic/OpenCLImageTypes.def"
6989 default:
6990 assert(0 && "Unable to find corresponding image type.")(static_cast <bool> (0 && "Unable to find corresponding image type."
) ? void (0) : __assert_fail ("0 && \"Unable to find corresponding image type.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 6990, __extension__ __PRETTY_FUNCTION__))
;
6991 }
6992
6993 S.Diag(TypedefTy->getDecl()->getLocStart(),
6994 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
6995 } else if (CurType->isPipeType()) {
6996 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
6997 QualType ElemType = CurType->getAs<PipeType>()->getElementType();
6998 CurType = S.Context.getWritePipeType(ElemType);
6999 }
7000 }
7001}
7002
7003static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State,
7004 QualType &T, TypeAttrLocation TAL) {
7005 Declarator &D = State.getDeclarator();
7006
7007 // Handle the cases where address space should not be deduced.
7008 //
7009 // The pointee type of a pointer type is alwasy deduced since a pointer always
7010 // points to some memory location which should has an address space.
7011 //
7012 // There are situations that at the point of certain declarations, the address
7013 // space may be unknown and better to be left as default. For example, when
7014 // definining a typedef or struct type, they are not associated with any
7015 // specific address space. Later on, they may be used with any address space
7016 // to declare a variable.
7017 //
7018 // The return value of a function is r-value, therefore should not have
7019 // address space.
7020 //
7021 // The void type does not occupy memory, therefore should not have address
7022 // space, except when it is used as a pointee type.
7023 //
7024 // Since LLVM assumes function type is in default address space, it should not
7025 // have address space.
7026 auto ChunkIndex = State.getCurrentChunkIndex();
7027 bool IsPointee =
7028 ChunkIndex > 0 &&
7029 (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer ||
7030 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer);
7031 bool IsFuncReturnType =
7032 ChunkIndex > 0 &&
7033 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function;
7034 bool IsFuncType =
7035 ChunkIndex < D.getNumTypeObjects() &&
7036 D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function;
7037 if ( // Do not deduce addr space for function return type and function type,
7038 // otherwise it will fail some sema check.
7039 IsFuncReturnType || IsFuncType ||
7040 // Do not deduce addr space for member types of struct, except the pointee
7041 // type of a pointer member type.
7042 (D.getContext() == Declarator::MemberContext && !IsPointee) ||
7043 // Do not deduce addr space for types used to define a typedef and the
7044 // typedef itself, except the pointee type of a pointer type which is used
7045 // to define the typedef.
7046 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef &&
7047 !IsPointee) ||
7048 // Do not deduce addr space of the void type, e.g. in f(void), otherwise
7049 // it will fail some sema check.
7050 (T->isVoidType() && !IsPointee))
7051 return;
7052
7053 LangAS ImpAddr;
7054 // Put OpenCL automatic variable in private address space.
7055 // OpenCL v1.2 s6.5:
7056 // The default address space name for arguments to a function in a
7057 // program, or local variables of a function is __private. All function
7058 // arguments shall be in the __private address space.
7059 if (State.getSema().getLangOpts().OpenCLVersion <= 120) {
7060 ImpAddr = LangAS::opencl_private;
7061 } else {
7062 // If address space is not set, OpenCL 2.0 defines non private default
7063 // address spaces for some cases:
7064 // OpenCL 2.0, section 6.5:
7065 // The address space for a variable at program scope or a static variable
7066 // inside a function can either be __global or __constant, but defaults to
7067 // __global if not specified.
7068 // (...)
7069 // Pointers that are declared without pointing to a named address space
7070 // point to the generic address space.
7071 if (IsPointee) {
7072 ImpAddr = LangAS::opencl_generic;
7073 } else {
7074 if (D.getContext() == Declarator::FileContext) {
7075 ImpAddr = LangAS::opencl_global;
7076 } else {
7077 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
7078 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) {
7079 ImpAddr = LangAS::opencl_global;
7080 } else {
7081 ImpAddr = LangAS::opencl_private;
7082 }
7083 }
7084 }
7085 }
7086 T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr);
7087}
7088
7089static void processTypeAttrs(TypeProcessingState &state, QualType &type,
7090 TypeAttrLocation TAL, AttributeList *attrs) {
7091 // Scan through and apply attributes to this type where it makes sense. Some
7092 // attributes (such as __address_space__, __vector_size__, etc) apply to the
7093 // type, but others can be present in the type specifiers even though they
7094 // apply to the decl. Here we apply type attributes and ignore the rest.
7095
7096 while (attrs) {
7097 AttributeList &attr = *attrs;
7098 attrs = attr.getNext(); // reset to the next here due to early loop continue
7099 // stmts
7100
7101 // Skip attributes that were marked to be invalid.
7102 if (attr.isInvalid())
7103 continue;
7104
7105 if (attr.isCXX11Attribute()) {
7106 // [[gnu::...]] attributes are treated as declaration attributes, so may
7107 // not appertain to a DeclaratorChunk, even if we handle them as type
7108 // attributes.
7109 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
7110 if (TAL == TAL_DeclChunk) {
7111 state.getSema().Diag(attr.getLoc(),
7112 diag::warn_cxx11_gnu_attribute_on_type)
7113 << attr.getName();
7114 continue;
7115 }
7116 } else if (TAL != TAL_DeclChunk) {
7117 // Otherwise, only consider type processing for a C++11 attribute if
7118 // it's actually been applied to a type.
7119 continue;
7120 }
7121 }
7122
7123 // If this is an attribute we can handle, do so now,
7124 // otherwise, add it to the FnAttrs list for rechaining.
7125 switch (attr.getKind()) {
7126 default:
7127 // A C++11 attribute on a declarator chunk must appertain to a type.
7128 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
7129 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
7130 << attr.getName();
7131 attr.setUsedAsTypeAttr();
7132 }
7133 break;
7134
7135 case AttributeList::UnknownAttribute:
7136 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
7137 state.getSema().Diag(attr.getLoc(),
7138 diag::warn_unknown_attribute_ignored)
7139 << attr.getName();
7140 break;
7141
7142 case AttributeList::IgnoredAttribute:
7143 break;
7144
7145 case AttributeList::AT_MayAlias:
7146 // FIXME: This attribute needs to actually be handled, but if we ignore
7147 // it it breaks large amounts of Linux software.
7148 attr.setUsedAsTypeAttr();
7149 break;
7150 case AttributeList::AT_OpenCLPrivateAddressSpace:
7151 case AttributeList::AT_OpenCLGlobalAddressSpace:
7152 case AttributeList::AT_OpenCLLocalAddressSpace:
7153 case AttributeList::AT_OpenCLConstantAddressSpace:
7154 case AttributeList::AT_OpenCLGenericAddressSpace:
7155 case AttributeList::AT_AddressSpace:
7156 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
7157 attr.setUsedAsTypeAttr();
7158 break;
7159 OBJC_POINTER_TYPE_ATTRS_CASELISTcase AttributeList::AT_ObjCGC: case AttributeList::AT_ObjCOwnership:
7160 if (!handleObjCPointerTypeAttr(state, attr, type))
7161 distributeObjCPointerTypeAttr(state, attr, type);
7162 attr.setUsedAsTypeAttr();
7163 break;
7164 case AttributeList::AT_VectorSize:
7165 HandleVectorSizeAttr(type, attr, state.getSema());
7166 attr.setUsedAsTypeAttr();
7167 break;
7168 case AttributeList::AT_ExtVectorType:
7169 HandleExtVectorTypeAttr(type, attr, state.getSema());
7170 attr.setUsedAsTypeAttr();
7171 break;
7172 case AttributeList::AT_NeonVectorType:
7173 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7174 VectorType::NeonVector);
7175 attr.setUsedAsTypeAttr();
7176 break;
7177 case AttributeList::AT_NeonPolyVectorType:
7178 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7179 VectorType::NeonPolyVector);
7180 attr.setUsedAsTypeAttr();
7181 break;
7182 case AttributeList::AT_OpenCLAccess:
7183 HandleOpenCLAccessAttr(type, attr, state.getSema());
7184 attr.setUsedAsTypeAttr();
7185 break;
7186
7187 MS_TYPE_ATTRS_CASELISTcase AttributeList::AT_Ptr32: case AttributeList::AT_Ptr64: case
AttributeList::AT_SPtr: case AttributeList::AT_UPtr
:
7188 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
7189 attr.setUsedAsTypeAttr();
7190 break;
7191
7192
7193 NULLABILITY_TYPE_ATTRS_CASELISTcase AttributeList::AT_TypeNonNull: case AttributeList::AT_TypeNullable
: case AttributeList::AT_TypeNullUnspecified
:
7194 // Either add nullability here or try to distribute it. We
7195 // don't want to distribute the nullability specifier past any
7196 // dependent type, because that complicates the user model.
7197 if (type->canHaveNullability() || type->isDependentType() ||
7198 type->isArrayType() ||
7199 !distributeNullabilityTypeAttr(state, type, attr)) {
7200 unsigned endIndex;
7201 if (TAL == TAL_DeclChunk)
7202 endIndex = state.getCurrentChunkIndex();
7203 else
7204 endIndex = state.getDeclarator().getNumTypeObjects();
7205 bool allowOnArrayType =
7206 state.getDeclarator().isPrototypeContext() &&
7207 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
7208 if (state.getSema().checkNullabilityTypeSpecifier(
7209 type,
7210 mapNullabilityAttrKind(attr.getKind()),
7211 attr.getLoc(),
7212 attr.isContextSensitiveKeywordAttribute(),
7213 allowOnArrayType)) {
7214 attr.setInvalid();
7215 }
7216
7217 attr.setUsedAsTypeAttr();
7218 }
7219 break;
7220
7221 case AttributeList::AT_ObjCKindOf:
7222 // '__kindof' must be part of the decl-specifiers.
7223 switch (TAL) {
7224 case TAL_DeclSpec:
7225 break;
7226
7227 case TAL_DeclChunk:
7228 case TAL_DeclName:
7229 state.getSema().Diag(attr.getLoc(),
7230 diag::err_objc_kindof_wrong_position)
7231 << FixItHint::CreateRemoval(attr.getLoc())
7232 << FixItHint::CreateInsertion(
7233 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
7234 break;
7235 }
7236
7237 // Apply it regardless.
7238 if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
7239 attr.setInvalid();
7240 attr.setUsedAsTypeAttr();
7241 break;
7242
7243 FUNCTION_TYPE_ATTRS_CASELISTcase AttributeList::AT_NSReturnsRetained: case AttributeList::
AT_NoReturn: case AttributeList::AT_Regparm: case AttributeList
::AT_AnyX86NoCallerSavedRegisters: case AttributeList::AT_CDecl
: case AttributeList::AT_FastCall: case AttributeList::AT_StdCall
: case AttributeList::AT_ThisCall: case AttributeList::AT_RegCall
: case AttributeList::AT_Pascal: case AttributeList::AT_SwiftCall
: case AttributeList::AT_VectorCall: case AttributeList::AT_MSABI
: case AttributeList::AT_SysVABI: case AttributeList::AT_Pcs:
case AttributeList::AT_IntelOclBicc: case AttributeList::AT_PreserveMost
: case AttributeList::AT_PreserveAll
:
7244 attr.setUsedAsTypeAttr();
7245
7246 // Never process function type attributes as part of the
7247 // declaration-specifiers.
7248 if (TAL == TAL_DeclSpec)
7249 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
7250
7251 // Otherwise, handle the possible delays.
7252 else if (!handleFunctionTypeAttr(state, attr, type))
7253 distributeFunctionTypeAttr(state, attr, type);
7254 break;
7255 }
7256 }
7257
7258 if (!state.getSema().getLangOpts().OpenCL ||
7259 type.getAddressSpace() != LangAS::Default)
7260 return;
7261
7262 deduceOpenCLImplicitAddrSpace(state, type, TAL);
7263}
7264
7265void Sema::completeExprArrayBound(Expr *E) {
7266 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7267 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7268 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
7269 SourceLocation PointOfInstantiation = E->getExprLoc();
7270
7271 if (MemberSpecializationInfo *MSInfo =
7272 Var->getMemberSpecializationInfo()) {
7273 // If we don't already have a point of instantiation, this is it.
7274 if (MSInfo->getPointOfInstantiation().isInvalid()) {
7275 MSInfo->setPointOfInstantiation(PointOfInstantiation);
7276
7277 // This is a modification of an existing AST node. Notify
7278 // listeners.
7279 if (ASTMutationListener *L = getASTMutationListener())
7280 L->StaticDataMemberInstantiated(Var);
7281 }
7282 } else {
7283 VarTemplateSpecializationDecl *VarSpec =
7284 cast<VarTemplateSpecializationDecl>(Var);
7285 if (VarSpec->getPointOfInstantiation().isInvalid())
7286 VarSpec->setPointOfInstantiation(PointOfInstantiation);
7287 }
7288
7289 InstantiateVariableDefinition(PointOfInstantiation, Var);
7290
7291 // Update the type to the newly instantiated definition's type both
7292 // here and within the expression.
7293 if (VarDecl *Def = Var->getDefinition()) {
7294 DRE->setDecl(Def);
7295 QualType T = Def->getType();
7296 DRE->setType(T);
7297 // FIXME: Update the type on all intervening expressions.
7298 E->setType(T);
7299 }
7300
7301 // We still go on to try to complete the type independently, as it
7302 // may also require instantiations or diagnostics if it remains
7303 // incomplete.
7304 }
7305 }
7306 }
7307}
7308
7309/// \brief Ensure that the type of the given expression is complete.
7310///
7311/// This routine checks whether the expression \p E has a complete type. If the
7312/// expression refers to an instantiable construct, that instantiation is
7313/// performed as needed to complete its type. Furthermore
7314/// Sema::RequireCompleteType is called for the expression's type (or in the
7315/// case of a reference type, the referred-to type).
7316///
7317/// \param E The expression whose type is required to be complete.
7318/// \param Diagnoser The object that will emit a diagnostic if the type is
7319/// incomplete.
7320///
7321/// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7322/// otherwise.
7323bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
7324 QualType T = E->getType();
7325
7326 // Incomplete array types may be completed by the initializer attached to
7327 // their definitions. For static data members of class templates and for
7328 // variable templates, we need to instantiate the definition to get this
7329 // initializer and complete the type.
7330 if (T->isIncompleteArrayType()) {
7331 completeExprArrayBound(E);
7332 T = E->getType();
7333 }
7334
7335 // FIXME: Are there other cases which require instantiating something other
7336 // than the type to complete the type of an expression?
7337
7338 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7339}
7340
7341bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7342 BoundTypeDiagnoser<> Diagnoser(DiagID);
7343 return RequireCompleteExprType(E, Diagnoser);
7344}
7345
7346/// @brief Ensure that the type T is a complete type.
7347///
7348/// This routine checks whether the type @p T is complete in any
7349/// context where a complete type is required. If @p T is a complete
7350/// type, returns false. If @p T is a class template specialization,
7351/// this routine then attempts to perform class template
7352/// instantiation. If instantiation fails, or if @p T is incomplete
7353/// and cannot be completed, issues the diagnostic @p diag (giving it
7354/// the type @p T) and returns true.
7355///
7356/// @param Loc The location in the source that the incomplete type
7357/// diagnostic should refer to.
7358///
7359/// @param T The type that this routine is examining for completeness.
7360///
7361/// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7362/// @c false otherwise.
7363bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7364 TypeDiagnoser &Diagnoser) {
7365 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7366 return true;
7367 if (const TagType *Tag = T->getAs<TagType>()) {
7368 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7369 Tag->getDecl()->setCompleteDefinitionRequired();
7370 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7371 }
7372 }
7373 return false;
7374}
7375
7376bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
7377 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
7378 if (!Suggested)
7379 return false;
7380
7381 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
7382 // and isolate from other C++ specific checks.
7383 StructuralEquivalenceContext Ctx(
7384 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
7385 false /*StrictTypeSpelling*/, true /*Complain*/,
7386 true /*ErrorOnTagTypeMismatch*/);
7387 return Ctx.IsStructurallyEquivalent(D, Suggested);
7388}
7389
7390/// \brief Determine whether there is any declaration of \p D that was ever a
7391/// definition (perhaps before module merging) and is currently visible.
7392/// \param D The definition of the entity.
7393/// \param Suggested Filled in with the declaration that should be made visible
7394/// in order to provide a definition of this entity.
7395/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7396/// not defined. This only matters for enums with a fixed underlying
7397/// type, since in all other cases, a type is complete if and only if it
7398/// is defined.
7399bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7400 bool OnlyNeedComplete) {
7401 // Easy case: if we don't have modules, all declarations are visible.
7402 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7403 return true;
7404
7405 // If this definition was instantiated from a template, map back to the
7406 // pattern from which it was instantiated.
7407 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7408 // We're in the middle of defining it; this definition should be treated
7409 // as visible.
7410 return true;
7411 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7412 if (auto *Pattern = RD->getTemplateInstantiationPattern())
7413 RD = Pattern;
7414 D = RD->getDefinition();
7415 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7416 if (auto *Pattern = ED->getTemplateInstantiationPattern())
7417 ED = Pattern;
7418 if (OnlyNeedComplete && ED->isFixed()) {
7419 // If the enum has a fixed underlying type, and we're only looking for a
7420 // complete type (not a definition), any visible declaration of it will
7421 // do.
7422 *Suggested = nullptr;
7423 for (auto *Redecl : ED->redecls()) {
7424 if (isVisible(Redecl))
7425 return true;
7426 if (Redecl->isThisDeclarationADefinition() ||
7427 (Redecl->isCanonicalDecl() && !*Suggested))
7428 *Suggested = Redecl;
7429 }
7430 return false;
7431 }
7432 D = ED->getDefinition();
7433 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7434 if (auto *Pattern = FD->getTemplateInstantiationPattern())
7435 FD = Pattern;
7436 D = FD->getDefinition();
7437 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7438 if (auto *Pattern = VD->getTemplateInstantiationPattern())
7439 VD = Pattern;
7440 D = VD->getDefinition();
7441 }
7442 assert(D && "missing definition for pattern of instantiated definition")(static_cast <bool> (D && "missing definition for pattern of instantiated definition"
) ? void (0) : __assert_fail ("D && \"missing definition for pattern of instantiated definition\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 7442, __extension__ __PRETTY_FUNCTION__))
;
7443
7444 *Suggested = D;
7445 if (isVisible(D))
7446 return true;
7447
7448 // The external source may have additional definitions of this entity that are
7449 // visible, so complete the redeclaration chain now and ask again.
7450 if (auto *Source = Context.getExternalSource()) {
7451 Source->CompleteRedeclChain(D);
7452 return isVisible(D);
7453 }
7454
7455 return false;
7456}
7457
7458/// Locks in the inheritance model for the given class and all of its bases.
7459static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7460 RD = RD->getMostRecentDecl();
7461 if (!RD->hasAttr<MSInheritanceAttr>()) {
7462 MSInheritanceAttr::Spelling IM;
7463
7464 switch (S.MSPointerToMemberRepresentationMethod) {
7465 case LangOptions::PPTMK_BestCase:
7466 IM = RD->calculateInheritanceModel();
7467 break;
7468 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7469 IM = MSInheritanceAttr::Keyword_single_inheritance;
7470 break;
7471 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7472 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7473 break;
7474 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7475 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7476 break;
7477 }
7478
7479 RD->addAttr(MSInheritanceAttr::CreateImplicit(
7480 S.getASTContext(), IM,
7481 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7482 LangOptions::PPTMK_BestCase,
7483 S.ImplicitMSInheritanceAttrLoc.isValid()
7484 ? S.ImplicitMSInheritanceAttrLoc
7485 : RD->getSourceRange()));
7486 S.Consumer.AssignInheritanceModel(RD);
7487 }
7488}
7489
7490/// \brief The implementation of RequireCompleteType
7491bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7492 TypeDiagnoser *Diagnoser) {
7493 // FIXME: Add this assertion to make sure we always get instantiation points.
7494 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7495 // FIXME: Add this assertion to help us flush out problems with
7496 // checking for dependent types and type-dependent expressions.
7497 //
7498 // assert(!T->isDependentType() &&
7499 // "Can't ask whether a dependent type is complete");
7500
7501 // We lock in the inheritance model once somebody has asked us to ensure
7502 // that a pointer-to-member type is complete.
7503 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7504 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7505 if (!MPTy->getClass()->isDependentType()) {
7506 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7507 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7508 }
7509 }
7510 }
7511
7512 NamedDecl *Def = nullptr;
7513 bool Incomplete = T->isIncompleteType(&Def);
7514
7515 // Check that any necessary explicit specializations are visible. For an
7516 // enum, we just need the declaration, so don't check this.
7517 if (Def && !isa<EnumDecl>(Def))
7518 checkSpecializationVisibility(Loc, Def);
7519
7520 // If we have a complete type, we're done.
7521 if (!Incomplete) {
7522 // If we know about the definition but it is not visible, complain.
7523 NamedDecl *SuggestedDef = nullptr;
7524 if (Def &&
7525 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7526 // If the user is going to see an error here, recover by making the
7527 // definition visible.
7528 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7529 if (Diagnoser)
7530 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7531 /*Recover*/TreatAsComplete);
7532 return !TreatAsComplete;
7533 }
7534
7535 return false;
7536 }
7537
7538 const TagType *Tag = T->getAs<TagType>();
7539 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
7540
7541 // If there's an unimported definition of this type in a module (for
7542 // instance, because we forward declared it, then imported the definition),
7543 // import that definition now.
7544 //
7545 // FIXME: What about other cases where an import extends a redeclaration
7546 // chain for a declaration that can be accessed through a mechanism other
7547 // than name lookup (eg, referenced in a template, or a variable whose type
7548 // could be completed by the module)?
7549 //
7550 // FIXME: Should we map through to the base array element type before
7551 // checking for a tag type?
7552 if (Tag || IFace) {
7553 NamedDecl *D =
7554 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
7555
7556 // Avoid diagnosing invalid decls as incomplete.
7557 if (D->isInvalidDecl())
7558 return true;
7559
7560 // Give the external AST source a chance to complete the type.
7561 if (auto *Source = Context.getExternalSource()) {
7562 if (Tag) {
7563 TagDecl *TagD = Tag->getDecl();
7564 if (TagD->hasExternalLexicalStorage())
7565 Source->CompleteType(TagD);
7566 } else {
7567 ObjCInterfaceDecl *IFaceD = IFace->getDecl();
7568 if (IFaceD->hasExternalLexicalStorage())
7569 Source->CompleteType(IFace->getDecl());
7570 }
7571 // If the external source completed the type, go through the motions
7572 // again to ensure we're allowed to use the completed type.
7573 if (!T->isIncompleteType())
7574 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7575 }
7576 }
7577
7578 // If we have a class template specialization or a class member of a
7579 // class template specialization, or an array with known size of such,
7580 // try to instantiate it.
7581 QualType MaybeTemplate = T;
7582 while (const ConstantArrayType *Array
7583 = Context.getAsConstantArrayType(MaybeTemplate))
7584 MaybeTemplate = Array->getElementType();
7585 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7586 bool Instantiated = false;
7587 bool Diagnosed = false;
7588 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7589 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7590 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7591 Diagnosed = InstantiateClassTemplateSpecialization(
7592 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7593 /*Complain=*/Diagnoser);
7594 Instantiated = true;
7595 }
7596 } else if (CXXRecordDecl *Rec
7597 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7598 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7599 if (!Rec->isBeingDefined() && Pattern) {
7600 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7601 assert(MSI && "Missing member specialization information?")(static_cast <bool> (MSI && "Missing member specialization information?"
) ? void (0) : __assert_fail ("MSI && \"Missing member specialization information?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 7601, __extension__ __PRETTY_FUNCTION__))
;
7602 // This record was instantiated from a class within a template.
7603 if (MSI->getTemplateSpecializationKind() !=
7604 TSK_ExplicitSpecialization) {
7605 Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7606 getTemplateInstantiationArgs(Rec),
7607 TSK_ImplicitInstantiation,
7608 /*Complain=*/Diagnoser);
7609 Instantiated = true;
7610 }
7611 }
7612 }
7613
7614 if (Instantiated) {
7615 // Instantiate* might have already complained that the template is not
7616 // defined, if we asked it to.
7617 if (Diagnoser && Diagnosed)
7618 return true;
7619 // If we instantiated a definition, check that it's usable, even if
7620 // instantiation produced an error, so that repeated calls to this
7621 // function give consistent answers.
7622 if (!T->isIncompleteType())
7623 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7624 }
7625 }
7626
7627 // FIXME: If we didn't instantiate a definition because of an explicit
7628 // specialization declaration, check that it's visible.
7629
7630 if (!Diagnoser)
7631 return true;
7632
7633 Diagnoser->diagnose(*this, Loc, T);
7634
7635 // If the type was a forward declaration of a class/struct/union
7636 // type, produce a note.
7637 if (Tag && !Tag->getDecl()->isInvalidDecl())
7638 Diag(Tag->getDecl()->getLocation(),
7639 Tag->isBeingDefined() ? diag::note_type_being_defined
7640 : diag::note_forward_declaration)
7641 << QualType(Tag, 0);
7642
7643 // If the Objective-C class was a forward declaration, produce a note.
7644 if (IFace && !IFace->getDecl()->isInvalidDecl())
7645 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7646
7647 // If we have external information that we can use to suggest a fix,
7648 // produce a note.
7649 if (ExternalSource)
7650 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7651
7652 return true;
7653}
7654
7655bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7656 unsigned DiagID) {
7657 BoundTypeDiagnoser<> Diagnoser(DiagID);
7658 return RequireCompleteType(Loc, T, Diagnoser);
7659}
7660
7661/// \brief Get diagnostic %select index for tag kind for
7662/// literal type diagnostic message.
7663/// WARNING: Indexes apply to particular diagnostics only!
7664///
7665/// \returns diagnostic %select index.
7666static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7667 switch (Tag) {
7668 case TTK_Struct: return 0;
7669 case TTK_Interface: return 1;
7670 case TTK_Class: return 2;
7671 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for literal type diagnostic!"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 7671)
;
7672 }
7673}
7674
7675/// @brief Ensure that the type T is a literal type.
7676///
7677/// This routine checks whether the type @p T is a literal type. If @p T is an
7678/// incomplete type, an attempt is made to complete it. If @p T is a literal
7679/// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7680/// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7681/// it the type @p T), along with notes explaining why the type is not a
7682/// literal type, and returns true.
7683///
7684/// @param Loc The location in the source that the non-literal type
7685/// diagnostic should refer to.
7686///
7687/// @param T The type that this routine is examining for literalness.
7688///
7689/// @param Diagnoser Emits a diagnostic if T is not a literal type.
7690///
7691/// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7692/// @c false otherwise.
7693bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7694 TypeDiagnoser &Diagnoser) {
7695 assert(!T->isDependentType() && "type should not be dependent")(static_cast <bool> (!T->isDependentType() &&
"type should not be dependent") ? void (0) : __assert_fail (
"!T->isDependentType() && \"type should not be dependent\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 7695, __extension__ __PRETTY_FUNCTION__))
;
7696
7697 QualType ElemType = Context.getBaseElementType(T);
7698 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7699 T->isLiteralType(Context))
7700 return false;
7701
7702 Diagnoser.diagnose(*this, Loc, T);
7703
7704 if (T->isVariableArrayType())
7705 return true;
7706
7707 const RecordType *RT = ElemType->getAs<RecordType>();
7708 if (!RT)
7709 return true;
7710
7711 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7712
7713 // A partially-defined class type can't be a literal type, because a literal
7714 // class type must have a trivial destructor (which can't be checked until
7715 // the class definition is complete).
7716 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7717 return true;
7718
7719 // If the class has virtual base classes, then it's not an aggregate, and
7720 // cannot have any constexpr constructors or a trivial default constructor,
7721 // so is non-literal. This is better to diagnose than the resulting absence
7722 // of constexpr constructors.
7723 if (RD->getNumVBases()) {
7724 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7725 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7726 for (const auto &I : RD->vbases())
7727 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7728 << I.getSourceRange();
7729 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7730 !RD->hasTrivialDefaultConstructor()) {
7731 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7732 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7733 for (const auto &I : RD->bases()) {
7734 if (!I.getType()->isLiteralType(Context)) {
7735 Diag(I.getLocStart(),
7736 diag::note_non_literal_base_class)
7737 << RD << I.getType() << I.getSourceRange();
7738 return true;
7739 }
7740 }
7741 for (const auto *I : RD->fields()) {
7742 if (!I->getType()->isLiteralType(Context) ||
7743 I->getType().isVolatileQualified()) {
7744 Diag(I->getLocation(), diag::note_non_literal_field)
7745 << RD << I << I->getType()
7746 << I->getType().isVolatileQualified();
7747 return true;
7748 }
7749 }
7750 } else if (!RD->hasTrivialDestructor()) {
7751 // All fields and bases are of literal types, so have trivial destructors.
7752 // If this class's destructor is non-trivial it must be user-declared.
7753 CXXDestructorDecl *Dtor = RD->getDestructor();
7754 assert(Dtor && "class has literal fields and bases but no dtor?")(static_cast <bool> (Dtor && "class has literal fields and bases but no dtor?"
) ? void (0) : __assert_fail ("Dtor && \"class has literal fields and bases but no dtor?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/SemaType.cpp"
, 7754, __extension__ __PRETTY_FUNCTION__))
;
7755 if (!Dtor)
7756 return true;
7757
7758 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7759 diag::note_non_literal_user_provided_dtor :
7760 diag::note_non_literal_nontrivial_dtor) << RD;
7761 if (!Dtor->isUserProvided())
7762 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
7763 }
7764
7765 return true;
7766}
7767
7768bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7769 BoundTypeDiagnoser<> Diagnoser(DiagID);
7770 return RequireLiteralType(Loc, T, Diagnoser);
7771}
7772
7773/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
7774/// and qualified by the nested-name-specifier contained in SS.
7775QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7776 const CXXScopeSpec &SS, QualType T) {
7777 if (T.isNull())
7778 return T;
7779 NestedNameSpecifier *NNS;
7780 if (SS.isValid())
7781 NNS = SS.getScopeRep();
7782 else {
7783 if (Keyword == ETK_None)
7784 return T;
7785 NNS = nullptr;
7786 }
7787 return Context.getElaboratedType(Keyword, NNS, T);
7788}
7789
7790QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7791 ExprResult ER = CheckPlaceholderExpr(E);
7792 if (ER.isInvalid()) return QualType();
7793 E = ER.get();
7794
7795 if (!getLangOpts().CPlusPlus && E->refersToBitField())
7796 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7797
7798 if (!E->isTypeDependent()) {
7799 QualType T = E->getType();
7800 if (const TagType *TT = T->getAs<TagType>())
7801 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7802 }
7803 return Context.getTypeOfExprType(E);
7804}
7805
7806/// getDecltypeForExpr - Given an expr, will return the decltype for
7807/// that expression, according to the rules in C++11
7808/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7809static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7810 if (E->isTypeDependent())
7811 return S.Context.DependentTy;
7812
7813 // C++11 [dcl.type.simple]p4:
7814 // The type denoted by decltype(e) is defined as follows:
7815 //
7816 // - if e is an unparenthesized id-expression or an unparenthesized class
7817 // member access (5.2.5), decltype(e) is the type of the entity named
7818 // by e. If there is no such entity, or if e names a set of overloaded
7819 // functions, the program is ill-formed;
7820 //
7821 // We apply the same rules for Objective-C ivar and property references.
7822 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7823 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
7824 return VD->getType();
7825 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7826 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
7827 return FD->getType();
7828 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7829 return IR->getDecl()->getType();
7830 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7831 if (PR->isExplicitProperty())
7832 return PR->getExplicitProperty()->getType();
7833 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7834