Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaType.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325874/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn325874/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn325874/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325874/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325874/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325874/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn325874/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-23-163436-368-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325874/tools/clang/lib/Sema/SemaType.cpp

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