Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-19-134126-35450-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/lib/Sema/SemaType.cpp

/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/lib/Sema/SemaType.cpp

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