Bug Summary

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