Bug Summary

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