Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaType.cpp

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