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