Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaType.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/include -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/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~++20201026111116+d3205bbca3e/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e=. -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-2020-10-27-053609-25509-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/Sema/SemaType.cpp

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