Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaType.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include -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-13/lib/clang/13.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 -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-07-26-235520-9401-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaType.cpp

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaType.cpp

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