Bug Summary

File:tools/clang/lib/Sema/SemaType.cpp
Warning:line 5292, column 14
Access to field 'Ident' results in a dereference of a null pointer (loaded from variable 'Arg')

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