Bug Summary

File:tools/clang/lib/Sema/SemaType.cpp
Warning:line 5275, 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~svn329677/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/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~svn329677/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-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaType.cpp

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