Bug Summary

File:clang/lib/Sema/SemaType.cpp
Warning:line 959, 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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5=. -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 -o /tmp/scan-build-2021-01-16-002530-32805-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/Sema/SemaType.cpp

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