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/Decl.h" |
20 | #include "clang/AST/DeclObjC.h" |
21 | #include "clang/AST/DeclTemplate.h" |
22 | #include "clang/AST/Expr.h" |
23 | #include "clang/AST/Type.h" |
24 | #include "clang/AST/TypeLoc.h" |
25 | #include "clang/AST/TypeLocVisitor.h" |
26 | #include "clang/Basic/PartialDiagnostic.h" |
27 | #include "clang/Basic/SourceLocation.h" |
28 | #include "clang/Basic/Specifiers.h" |
29 | #include "clang/Basic/TargetInfo.h" |
30 | #include "clang/Lex/Preprocessor.h" |
31 | #include "clang/Sema/DeclSpec.h" |
32 | #include "clang/Sema/DelayedDiagnostic.h" |
33 | #include "clang/Sema/Lookup.h" |
34 | #include "clang/Sema/ParsedTemplate.h" |
35 | #include "clang/Sema/ScopeInfo.h" |
36 | #include "clang/Sema/SemaInternal.h" |
37 | #include "clang/Sema/Template.h" |
38 | #include "clang/Sema/TemplateInstCallback.h" |
39 | #include "llvm/ADT/ArrayRef.h" |
40 | #include "llvm/ADT/SmallPtrSet.h" |
41 | #include "llvm/ADT/SmallString.h" |
42 | #include "llvm/ADT/StringExtras.h" |
43 | #include "llvm/IR/DerivedTypes.h" |
44 | #include "llvm/Support/Casting.h" |
45 | #include "llvm/Support/ErrorHandling.h" |
46 | #include <bitset> |
47 | #include <optional> |
48 | |
49 | using namespace clang; |
50 | |
51 | enum TypeDiagSelector { |
52 | TDS_Function, |
53 | TDS_Pointer, |
54 | TDS_ObjCObjOrBlock |
55 | }; |
56 | |
57 | /// isOmittedBlockReturnType - Return true if this declarator is missing a |
58 | /// return type because this is a omitted return type on a block literal. |
59 | static bool isOmittedBlockReturnType(const Declarator &D) { |
60 | if (D.getContext() != DeclaratorContext::BlockLiteral || |
61 | D.getDeclSpec().hasTypeSpecifier()) |
62 | return false; |
63 | |
64 | if (D.getNumTypeObjects() == 0) |
65 | return true; // ^{ ... } |
66 | |
67 | if (D.getNumTypeObjects() == 1 && |
68 | D.getTypeObject(i: 0).Kind == DeclaratorChunk::Function) |
69 | return true; // ^(int X, float Y) { ... } |
70 | |
71 | return false; |
72 | } |
73 | |
74 | /// diagnoseBadTypeAttribute - Diagnoses a type attribute which |
75 | /// doesn't apply to the given type. |
76 | static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, |
77 | QualType type) { |
78 | TypeDiagSelector WhichType; |
79 | bool useExpansionLoc = true; |
80 | switch (attr.getKind()) { |
81 | case ParsedAttr::AT_ObjCGC: |
82 | WhichType = TDS_Pointer; |
83 | break; |
84 | case ParsedAttr::AT_ObjCOwnership: |
85 | WhichType = TDS_ObjCObjOrBlock; |
86 | break; |
87 | default: |
88 | // Assume everything else was a function attribute. |
89 | WhichType = TDS_Function; |
90 | useExpansionLoc = false; |
91 | break; |
92 | } |
93 | |
94 | SourceLocation loc = attr.getLoc(); |
95 | StringRef name = attr.getAttrName()->getName(); |
96 | |
97 | // The GC attributes are usually written with macros; special-case them. |
98 | IdentifierInfo *II = attr.isArgIdent(Arg: 0) ? attr.getArgAsIdent(Arg: 0)->Ident |
99 | : nullptr; |
100 | if (useExpansionLoc && loc.isMacroID() && II) { |
101 | if (II->isStr(Str: "strong" )) { |
102 | if (S.findMacroSpelling(loc, name: "__strong" )) name = "__strong" ; |
103 | } else if (II->isStr(Str: "weak" )) { |
104 | if (S.findMacroSpelling(loc, name: "__weak" )) name = "__weak" ; |
105 | } |
106 | } |
107 | |
108 | S.Diag(loc, attr.isRegularKeywordAttribute() |
109 | ? diag::err_type_attribute_wrong_type |
110 | : diag::warn_type_attribute_wrong_type) |
111 | << name << WhichType << type; |
112 | } |
113 | |
114 | // objc_gc applies to Objective-C pointers or, otherwise, to the |
115 | // smallest available pointer type (i.e. 'void*' in 'void**'). |
116 | #define OBJC_POINTER_TYPE_ATTRS_CASELIST \ |
117 | case ParsedAttr::AT_ObjCGC: \ |
118 | case ParsedAttr::AT_ObjCOwnership |
119 | |
120 | // Calling convention attributes. |
121 | #define CALLING_CONV_ATTRS_CASELIST \ |
122 | case ParsedAttr::AT_CDecl: \ |
123 | case ParsedAttr::AT_FastCall: \ |
124 | case ParsedAttr::AT_StdCall: \ |
125 | case ParsedAttr::AT_ThisCall: \ |
126 | case ParsedAttr::AT_RegCall: \ |
127 | case ParsedAttr::AT_Pascal: \ |
128 | case ParsedAttr::AT_SwiftCall: \ |
129 | case ParsedAttr::AT_SwiftAsyncCall: \ |
130 | case ParsedAttr::AT_VectorCall: \ |
131 | case ParsedAttr::AT_AArch64VectorPcs: \ |
132 | case ParsedAttr::AT_AArch64SVEPcs: \ |
133 | case ParsedAttr::AT_AMDGPUKernelCall: \ |
134 | case ParsedAttr::AT_MSABI: \ |
135 | case ParsedAttr::AT_SysVABI: \ |
136 | case ParsedAttr::AT_Pcs: \ |
137 | case ParsedAttr::AT_IntelOclBicc: \ |
138 | case ParsedAttr::AT_PreserveMost: \ |
139 | case ParsedAttr::AT_PreserveAll: \ |
140 | case ParsedAttr::AT_M68kRTD: \ |
141 | case ParsedAttr::AT_PreserveNone |
142 | |
143 | // Function type attributes. |
144 | #define FUNCTION_TYPE_ATTRS_CASELIST \ |
145 | case ParsedAttr::AT_NSReturnsRetained: \ |
146 | case ParsedAttr::AT_NoReturn: \ |
147 | case ParsedAttr::AT_Regparm: \ |
148 | case ParsedAttr::AT_CmseNSCall: \ |
149 | case ParsedAttr::AT_ArmStreaming: \ |
150 | case ParsedAttr::AT_ArmStreamingCompatible: \ |
151 | case ParsedAttr::AT_ArmPreserves: \ |
152 | case ParsedAttr::AT_ArmIn: \ |
153 | case ParsedAttr::AT_ArmOut: \ |
154 | case ParsedAttr::AT_ArmInOut: \ |
155 | case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \ |
156 | case ParsedAttr::AT_AnyX86NoCfCheck: \ |
157 | CALLING_CONV_ATTRS_CASELIST |
158 | |
159 | // Microsoft-specific type qualifiers. |
160 | #define MS_TYPE_ATTRS_CASELIST \ |
161 | case ParsedAttr::AT_Ptr32: \ |
162 | case ParsedAttr::AT_Ptr64: \ |
163 | case ParsedAttr::AT_SPtr: \ |
164 | case ParsedAttr::AT_UPtr |
165 | |
166 | // Nullability qualifiers. |
167 | #define NULLABILITY_TYPE_ATTRS_CASELIST \ |
168 | case ParsedAttr::AT_TypeNonNull: \ |
169 | case ParsedAttr::AT_TypeNullable: \ |
170 | case ParsedAttr::AT_TypeNullableResult: \ |
171 | case ParsedAttr::AT_TypeNullUnspecified |
172 | |
173 | namespace { |
174 | /// An object which stores processing state for the entire |
175 | /// GetTypeForDeclarator process. |
176 | class TypeProcessingState { |
177 | Sema &sema; |
178 | |
179 | /// The declarator being processed. |
180 | Declarator &declarator; |
181 | |
182 | /// The index of the declarator chunk we're currently processing. |
183 | /// May be the total number of valid chunks, indicating the |
184 | /// DeclSpec. |
185 | unsigned chunkIndex; |
186 | |
187 | /// The original set of attributes on the DeclSpec. |
188 | SmallVector<ParsedAttr *, 2> savedAttrs; |
189 | |
190 | /// A list of attributes to diagnose the uselessness of when the |
191 | /// processing is complete. |
192 | SmallVector<ParsedAttr *, 2> ignoredTypeAttrs; |
193 | |
194 | /// Attributes corresponding to AttributedTypeLocs that we have not yet |
195 | /// populated. |
196 | // FIXME: The two-phase mechanism by which we construct Types and fill |
197 | // their TypeLocs makes it hard to correctly assign these. We keep the |
198 | // attributes in creation order as an attempt to make them line up |
199 | // properly. |
200 | using TypeAttrPair = std::pair<const AttributedType*, const Attr*>; |
201 | SmallVector<TypeAttrPair, 8> AttrsForTypes; |
202 | bool AttrsForTypesSorted = true; |
203 | |
204 | /// MacroQualifiedTypes mapping to macro expansion locations that will be |
205 | /// stored in a MacroQualifiedTypeLoc. |
206 | llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros; |
207 | |
208 | /// Flag to indicate we parsed a noderef attribute. This is used for |
209 | /// validating that noderef was used on a pointer or array. |
210 | bool parsedNoDeref; |
211 | |
212 | public: |
213 | TypeProcessingState(Sema &sema, Declarator &declarator) |
214 | : sema(sema), declarator(declarator), |
215 | chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {} |
216 | |
217 | Sema &getSema() const { |
218 | return sema; |
219 | } |
220 | |
221 | Declarator &getDeclarator() const { |
222 | return declarator; |
223 | } |
224 | |
225 | bool isProcessingDeclSpec() const { |
226 | return chunkIndex == declarator.getNumTypeObjects(); |
227 | } |
228 | |
229 | unsigned getCurrentChunkIndex() const { |
230 | return chunkIndex; |
231 | } |
232 | |
233 | void setCurrentChunkIndex(unsigned idx) { |
234 | assert(idx <= declarator.getNumTypeObjects()); |
235 | chunkIndex = idx; |
236 | } |
237 | |
238 | ParsedAttributesView &getCurrentAttributes() const { |
239 | if (isProcessingDeclSpec()) |
240 | return getMutableDeclSpec().getAttributes(); |
241 | return declarator.getTypeObject(i: chunkIndex).getAttrs(); |
242 | } |
243 | |
244 | /// Save the current set of attributes on the DeclSpec. |
245 | void saveDeclSpecAttrs() { |
246 | // Don't try to save them multiple times. |
247 | if (!savedAttrs.empty()) |
248 | return; |
249 | |
250 | DeclSpec &spec = getMutableDeclSpec(); |
251 | llvm::append_range(C&: savedAttrs, |
252 | R: llvm::make_pointer_range(Range&: spec.getAttributes())); |
253 | } |
254 | |
255 | /// Record that we had nowhere to put the given type attribute. |
256 | /// We will diagnose such attributes later. |
257 | void addIgnoredTypeAttr(ParsedAttr &attr) { |
258 | ignoredTypeAttrs.push_back(Elt: &attr); |
259 | } |
260 | |
261 | /// Diagnose all the ignored type attributes, given that the |
262 | /// declarator worked out to the given type. |
263 | void diagnoseIgnoredTypeAttrs(QualType type) const { |
264 | for (auto *Attr : ignoredTypeAttrs) |
265 | diagnoseBadTypeAttribute(S&: getSema(), attr: *Attr, type); |
266 | } |
267 | |
268 | /// Get an attributed type for the given attribute, and remember the Attr |
269 | /// object so that we can attach it to the AttributedTypeLoc. |
270 | QualType getAttributedType(Attr *A, QualType ModifiedType, |
271 | QualType EquivType) { |
272 | QualType T = |
273 | sema.Context.getAttributedType(attrKind: A->getKind(), modifiedType: ModifiedType, equivalentType: EquivType); |
274 | AttrsForTypes.push_back(Elt: {cast<AttributedType>(Val: T.getTypePtr()), A}); |
275 | AttrsForTypesSorted = false; |
276 | return T; |
277 | } |
278 | |
279 | /// Get a BTFTagAttributed type for the btf_type_tag attribute. |
280 | QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, |
281 | QualType WrappedType) { |
282 | return sema.Context.getBTFTagAttributedType(BTFAttr, Wrapped: WrappedType); |
283 | } |
284 | |
285 | /// Completely replace the \c auto in \p TypeWithAuto by |
286 | /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if |
287 | /// necessary. |
288 | QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) { |
289 | QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement); |
290 | if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) { |
291 | // Attributed type still should be an attributed type after replacement. |
292 | auto *NewAttrTy = cast<AttributedType>(Val: T.getTypePtr()); |
293 | for (TypeAttrPair &A : AttrsForTypes) { |
294 | if (A.first == AttrTy) |
295 | A.first = NewAttrTy; |
296 | } |
297 | AttrsForTypesSorted = false; |
298 | } |
299 | return T; |
300 | } |
301 | |
302 | /// Extract and remove the Attr* for a given attributed type. |
303 | const Attr *takeAttrForAttributedType(const AttributedType *AT) { |
304 | if (!AttrsForTypesSorted) { |
305 | llvm::stable_sort(Range&: AttrsForTypes, C: llvm::less_first()); |
306 | AttrsForTypesSorted = true; |
307 | } |
308 | |
309 | // FIXME: This is quadratic if we have lots of reuses of the same |
310 | // attributed type. |
311 | for (auto It = std::partition_point( |
312 | first: AttrsForTypes.begin(), last: AttrsForTypes.end(), |
313 | pred: [=](const TypeAttrPair &A) { return A.first < AT; }); |
314 | It != AttrsForTypes.end() && It->first == AT; ++It) { |
315 | if (It->second) { |
316 | const Attr *Result = It->second; |
317 | It->second = nullptr; |
318 | return Result; |
319 | } |
320 | } |
321 | |
322 | llvm_unreachable("no Attr* for AttributedType*" ); |
323 | } |
324 | |
325 | SourceLocation |
326 | getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const { |
327 | auto FoundLoc = LocsForMacros.find(Val: MQT); |
328 | assert(FoundLoc != LocsForMacros.end() && |
329 | "Unable to find macro expansion location for MacroQualifedType" ); |
330 | return FoundLoc->second; |
331 | } |
332 | |
333 | void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT, |
334 | SourceLocation Loc) { |
335 | LocsForMacros[MQT] = Loc; |
336 | } |
337 | |
338 | void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; } |
339 | |
340 | bool didParseNoDeref() const { return parsedNoDeref; } |
341 | |
342 | ~TypeProcessingState() { |
343 | if (savedAttrs.empty()) |
344 | return; |
345 | |
346 | getMutableDeclSpec().getAttributes().clearListOnly(); |
347 | for (ParsedAttr *AL : savedAttrs) |
348 | getMutableDeclSpec().getAttributes().addAtEnd(newAttr: AL); |
349 | } |
350 | |
351 | private: |
352 | DeclSpec &getMutableDeclSpec() const { |
353 | return const_cast<DeclSpec&>(declarator.getDeclSpec()); |
354 | } |
355 | }; |
356 | } // end anonymous namespace |
357 | |
358 | static void moveAttrFromListToList(ParsedAttr &attr, |
359 | ParsedAttributesView &fromList, |
360 | ParsedAttributesView &toList) { |
361 | fromList.remove(ToBeRemoved: &attr); |
362 | toList.addAtEnd(newAttr: &attr); |
363 | } |
364 | |
365 | /// The location of a type attribute. |
366 | enum TypeAttrLocation { |
367 | /// The attribute is in the decl-specifier-seq. |
368 | TAL_DeclSpec, |
369 | /// The attribute is part of a DeclaratorChunk. |
370 | TAL_DeclChunk, |
371 | /// The attribute is immediately after the declaration's name. |
372 | TAL_DeclName |
373 | }; |
374 | |
375 | static void |
376 | processTypeAttrs(TypeProcessingState &state, QualType &type, |
377 | TypeAttrLocation TAL, const ParsedAttributesView &attrs, |
378 | Sema::CUDAFunctionTarget CFT = Sema::CFT_HostDevice); |
379 | |
380 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, |
381 | QualType &type, |
382 | Sema::CUDAFunctionTarget CFT); |
383 | |
384 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, |
385 | ParsedAttr &attr, QualType &type); |
386 | |
387 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, |
388 | QualType &type); |
389 | |
390 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, |
391 | ParsedAttr &attr, QualType &type); |
392 | |
393 | static bool handleObjCPointerTypeAttr(TypeProcessingState &state, |
394 | ParsedAttr &attr, QualType &type) { |
395 | if (attr.getKind() == ParsedAttr::AT_ObjCGC) |
396 | return handleObjCGCTypeAttr(state, attr, type); |
397 | assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership); |
398 | return handleObjCOwnershipTypeAttr(state, attr, type); |
399 | } |
400 | |
401 | /// Given the index of a declarator chunk, check whether that chunk |
402 | /// directly specifies the return type of a function and, if so, find |
403 | /// an appropriate place for it. |
404 | /// |
405 | /// \param i - a notional index which the search will start |
406 | /// immediately inside |
407 | /// |
408 | /// \param onlyBlockPointers Whether we should only look into block |
409 | /// pointer types (vs. all pointer types). |
410 | static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator, |
411 | unsigned i, |
412 | bool onlyBlockPointers) { |
413 | assert(i <= declarator.getNumTypeObjects()); |
414 | |
415 | DeclaratorChunk *result = nullptr; |
416 | |
417 | // First, look inwards past parens for a function declarator. |
418 | for (; i != 0; --i) { |
419 | DeclaratorChunk &fnChunk = declarator.getTypeObject(i: i-1); |
420 | switch (fnChunk.Kind) { |
421 | case DeclaratorChunk::Paren: |
422 | continue; |
423 | |
424 | // If we find anything except a function, bail out. |
425 | case DeclaratorChunk::Pointer: |
426 | case DeclaratorChunk::BlockPointer: |
427 | case DeclaratorChunk::Array: |
428 | case DeclaratorChunk::Reference: |
429 | case DeclaratorChunk::MemberPointer: |
430 | case DeclaratorChunk::Pipe: |
431 | return result; |
432 | |
433 | // If we do find a function declarator, scan inwards from that, |
434 | // looking for a (block-)pointer declarator. |
435 | case DeclaratorChunk::Function: |
436 | for (--i; i != 0; --i) { |
437 | DeclaratorChunk &ptrChunk = declarator.getTypeObject(i: i-1); |
438 | switch (ptrChunk.Kind) { |
439 | case DeclaratorChunk::Paren: |
440 | case DeclaratorChunk::Array: |
441 | case DeclaratorChunk::Function: |
442 | case DeclaratorChunk::Reference: |
443 | case DeclaratorChunk::Pipe: |
444 | continue; |
445 | |
446 | case DeclaratorChunk::MemberPointer: |
447 | case DeclaratorChunk::Pointer: |
448 | if (onlyBlockPointers) |
449 | continue; |
450 | |
451 | [[fallthrough]]; |
452 | |
453 | case DeclaratorChunk::BlockPointer: |
454 | result = &ptrChunk; |
455 | goto continue_outer; |
456 | } |
457 | llvm_unreachable("bad declarator chunk kind" ); |
458 | } |
459 | |
460 | // If we run out of declarators doing that, we're done. |
461 | return result; |
462 | } |
463 | llvm_unreachable("bad declarator chunk kind" ); |
464 | |
465 | // Okay, reconsider from our new point. |
466 | continue_outer: ; |
467 | } |
468 | |
469 | // Ran out of chunks, bail out. |
470 | return result; |
471 | } |
472 | |
473 | /// Given that an objc_gc attribute was written somewhere on a |
474 | /// declaration *other* than on the declarator itself (for which, use |
475 | /// distributeObjCPointerTypeAttrFromDeclarator), and given that it |
476 | /// didn't apply in whatever position it was written in, try to move |
477 | /// it to a more appropriate position. |
478 | static void distributeObjCPointerTypeAttr(TypeProcessingState &state, |
479 | ParsedAttr &attr, QualType type) { |
480 | Declarator &declarator = state.getDeclarator(); |
481 | |
482 | // Move it to the outermost normal or block pointer declarator. |
483 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { |
484 | DeclaratorChunk &chunk = declarator.getTypeObject(i: i-1); |
485 | switch (chunk.Kind) { |
486 | case DeclaratorChunk::Pointer: |
487 | case DeclaratorChunk::BlockPointer: { |
488 | // But don't move an ARC ownership attribute to the return type |
489 | // of a block. |
490 | DeclaratorChunk *destChunk = nullptr; |
491 | if (state.isProcessingDeclSpec() && |
492 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) |
493 | destChunk = maybeMovePastReturnType(declarator, i: i - 1, |
494 | /*onlyBlockPointers=*/true); |
495 | if (!destChunk) destChunk = &chunk; |
496 | |
497 | moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(), |
498 | toList&: destChunk->getAttrs()); |
499 | return; |
500 | } |
501 | |
502 | case DeclaratorChunk::Paren: |
503 | case DeclaratorChunk::Array: |
504 | continue; |
505 | |
506 | // We may be starting at the return type of a block. |
507 | case DeclaratorChunk::Function: |
508 | if (state.isProcessingDeclSpec() && |
509 | attr.getKind() == ParsedAttr::AT_ObjCOwnership) { |
510 | if (DeclaratorChunk *dest = maybeMovePastReturnType( |
511 | declarator, i, |
512 | /*onlyBlockPointers=*/true)) { |
513 | moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(), |
514 | toList&: dest->getAttrs()); |
515 | return; |
516 | } |
517 | } |
518 | goto error; |
519 | |
520 | // Don't walk through these. |
521 | case DeclaratorChunk::Reference: |
522 | case DeclaratorChunk::MemberPointer: |
523 | case DeclaratorChunk::Pipe: |
524 | goto error; |
525 | } |
526 | } |
527 | error: |
528 | |
529 | diagnoseBadTypeAttribute(S&: state.getSema(), attr, type); |
530 | } |
531 | |
532 | /// Distribute an objc_gc type attribute that was written on the |
533 | /// declarator. |
534 | static void distributeObjCPointerTypeAttrFromDeclarator( |
535 | TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) { |
536 | Declarator &declarator = state.getDeclarator(); |
537 | |
538 | // objc_gc goes on the innermost pointer to something that's not a |
539 | // pointer. |
540 | unsigned innermost = -1U; |
541 | bool considerDeclSpec = true; |
542 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { |
543 | DeclaratorChunk &chunk = declarator.getTypeObject(i); |
544 | switch (chunk.Kind) { |
545 | case DeclaratorChunk::Pointer: |
546 | case DeclaratorChunk::BlockPointer: |
547 | innermost = i; |
548 | continue; |
549 | |
550 | case DeclaratorChunk::Reference: |
551 | case DeclaratorChunk::MemberPointer: |
552 | case DeclaratorChunk::Paren: |
553 | case DeclaratorChunk::Array: |
554 | case DeclaratorChunk::Pipe: |
555 | continue; |
556 | |
557 | case DeclaratorChunk::Function: |
558 | considerDeclSpec = false; |
559 | goto done; |
560 | } |
561 | } |
562 | done: |
563 | |
564 | // That might actually be the decl spec if we weren't blocked by |
565 | // anything in the declarator. |
566 | if (considerDeclSpec) { |
567 | if (handleObjCPointerTypeAttr(state, attr, type&: declSpecType)) { |
568 | // Splice the attribute into the decl spec. Prevents the |
569 | // attribute from being applied multiple times and gives |
570 | // the source-location-filler something to work with. |
571 | state.saveDeclSpecAttrs(); |
572 | declarator.getMutableDeclSpec().getAttributes().takeOneFrom( |
573 | Other&: declarator.getAttributes(), PA: &attr); |
574 | return; |
575 | } |
576 | } |
577 | |
578 | // Otherwise, if we found an appropriate chunk, splice the attribute |
579 | // into it. |
580 | if (innermost != -1U) { |
581 | moveAttrFromListToList(attr, fromList&: declarator.getAttributes(), |
582 | toList&: declarator.getTypeObject(i: innermost).getAttrs()); |
583 | return; |
584 | } |
585 | |
586 | // Otherwise, diagnose when we're done building the type. |
587 | declarator.getAttributes().remove(ToBeRemoved: &attr); |
588 | state.addIgnoredTypeAttr(attr); |
589 | } |
590 | |
591 | /// A function type attribute was written somewhere in a declaration |
592 | /// *other* than on the declarator itself or in the decl spec. Given |
593 | /// that it didn't apply in whatever position it was written in, try |
594 | /// to move it to a more appropriate position. |
595 | static void distributeFunctionTypeAttr(TypeProcessingState &state, |
596 | ParsedAttr &attr, QualType type) { |
597 | Declarator &declarator = state.getDeclarator(); |
598 | |
599 | // Try to push the attribute from the return type of a function to |
600 | // the function itself. |
601 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { |
602 | DeclaratorChunk &chunk = declarator.getTypeObject(i: i-1); |
603 | switch (chunk.Kind) { |
604 | case DeclaratorChunk::Function: |
605 | moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(), |
606 | toList&: chunk.getAttrs()); |
607 | return; |
608 | |
609 | case DeclaratorChunk::Paren: |
610 | case DeclaratorChunk::Pointer: |
611 | case DeclaratorChunk::BlockPointer: |
612 | case DeclaratorChunk::Array: |
613 | case DeclaratorChunk::Reference: |
614 | case DeclaratorChunk::MemberPointer: |
615 | case DeclaratorChunk::Pipe: |
616 | continue; |
617 | } |
618 | } |
619 | |
620 | diagnoseBadTypeAttribute(S&: state.getSema(), attr, type); |
621 | } |
622 | |
623 | /// Try to distribute a function type attribute to the innermost |
624 | /// function chunk or type. Returns true if the attribute was |
625 | /// distributed, false if no location was found. |
626 | static bool distributeFunctionTypeAttrToInnermost( |
627 | TypeProcessingState &state, ParsedAttr &attr, |
628 | ParsedAttributesView &attrList, QualType &declSpecType, |
629 | Sema::CUDAFunctionTarget CFT) { |
630 | Declarator &declarator = state.getDeclarator(); |
631 | |
632 | // Put it on the innermost function chunk, if there is one. |
633 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { |
634 | DeclaratorChunk &chunk = declarator.getTypeObject(i); |
635 | if (chunk.Kind != DeclaratorChunk::Function) continue; |
636 | |
637 | moveAttrFromListToList(attr, fromList&: attrList, toList&: chunk.getAttrs()); |
638 | return true; |
639 | } |
640 | |
641 | return handleFunctionTypeAttr(state, attr, type&: declSpecType, CFT); |
642 | } |
643 | |
644 | /// A function type attribute was written in the decl spec. Try to |
645 | /// apply it somewhere. |
646 | static void |
647 | distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, |
648 | ParsedAttr &attr, QualType &declSpecType, |
649 | Sema::CUDAFunctionTarget CFT) { |
650 | state.saveDeclSpecAttrs(); |
651 | |
652 | // Try to distribute to the innermost. |
653 | if (distributeFunctionTypeAttrToInnermost( |
654 | state, attr, attrList&: state.getCurrentAttributes(), declSpecType, CFT)) |
655 | return; |
656 | |
657 | // If that failed, diagnose the bad attribute when the declarator is |
658 | // fully built. |
659 | state.addIgnoredTypeAttr(attr); |
660 | } |
661 | |
662 | /// A function type attribute was written on the declarator or declaration. |
663 | /// Try to apply it somewhere. |
664 | /// `Attrs` is the attribute list containing the declaration (either of the |
665 | /// declarator or the declaration). |
666 | static void distributeFunctionTypeAttrFromDeclarator( |
667 | TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType, |
668 | Sema::CUDAFunctionTarget CFT) { |
669 | Declarator &declarator = state.getDeclarator(); |
670 | |
671 | // Try to distribute to the innermost. |
672 | if (distributeFunctionTypeAttrToInnermost( |
673 | state, attr, attrList&: declarator.getAttributes(), declSpecType, CFT)) |
674 | return; |
675 | |
676 | // If that failed, diagnose the bad attribute when the declarator is |
677 | // fully built. |
678 | declarator.getAttributes().remove(ToBeRemoved: &attr); |
679 | state.addIgnoredTypeAttr(attr); |
680 | } |
681 | |
682 | /// Given that there are attributes written on the declarator or declaration |
683 | /// itself, try to distribute any type attributes to the appropriate |
684 | /// declarator chunk. |
685 | /// |
686 | /// These are attributes like the following: |
687 | /// int f ATTR; |
688 | /// int (f ATTR)(); |
689 | /// but not necessarily this: |
690 | /// int f() ATTR; |
691 | /// |
692 | /// `Attrs` is the attribute list containing the declaration (either of the |
693 | /// declarator or the declaration). |
694 | static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, |
695 | QualType &declSpecType, |
696 | Sema::CUDAFunctionTarget CFT) { |
697 | // The called functions in this loop actually remove things from the current |
698 | // list, so iterating over the existing list isn't possible. Instead, make a |
699 | // non-owning copy and iterate over that. |
700 | ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()}; |
701 | for (ParsedAttr &attr : AttrsCopy) { |
702 | // Do not distribute [[]] attributes. They have strict rules for what |
703 | // they appertain to. |
704 | if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) |
705 | continue; |
706 | |
707 | switch (attr.getKind()) { |
708 | OBJC_POINTER_TYPE_ATTRS_CASELIST: |
709 | distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType); |
710 | break; |
711 | |
712 | FUNCTION_TYPE_ATTRS_CASELIST: |
713 | distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT); |
714 | break; |
715 | |
716 | MS_TYPE_ATTRS_CASELIST: |
717 | // Microsoft type attributes cannot go after the declarator-id. |
718 | continue; |
719 | |
720 | NULLABILITY_TYPE_ATTRS_CASELIST: |
721 | // Nullability specifiers cannot go after the declarator-id. |
722 | |
723 | // Objective-C __kindof does not get distributed. |
724 | case ParsedAttr::AT_ObjCKindOf: |
725 | continue; |
726 | |
727 | default: |
728 | break; |
729 | } |
730 | } |
731 | } |
732 | |
733 | /// Add a synthetic '()' to a block-literal declarator if it is |
734 | /// required, given the return type. |
735 | static void maybeSynthesizeBlockSignature(TypeProcessingState &state, |
736 | QualType declSpecType) { |
737 | Declarator &declarator = state.getDeclarator(); |
738 | |
739 | // First, check whether the declarator would produce a function, |
740 | // i.e. whether the innermost semantic chunk is a function. |
741 | if (declarator.isFunctionDeclarator()) { |
742 | // If so, make that declarator a prototyped declarator. |
743 | declarator.getFunctionTypeInfo().hasPrototype = true; |
744 | return; |
745 | } |
746 | |
747 | // If there are any type objects, the type as written won't name a |
748 | // function, regardless of the decl spec type. This is because a |
749 | // block signature declarator is always an abstract-declarator, and |
750 | // abstract-declarators can't just be parentheses chunks. Therefore |
751 | // we need to build a function chunk unless there are no type |
752 | // objects and the decl spec type is a function. |
753 | if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType()) |
754 | return; |
755 | |
756 | // Note that there *are* cases with invalid declarators where |
757 | // declarators consist solely of parentheses. In general, these |
758 | // occur only in failed efforts to make function declarators, so |
759 | // faking up the function chunk is still the right thing to do. |
760 | |
761 | // Otherwise, we need to fake up a function declarator. |
762 | SourceLocation loc = declarator.getBeginLoc(); |
763 | |
764 | // ...and *prepend* it to the declarator. |
765 | SourceLocation NoLoc; |
766 | declarator.AddInnermostTypeInfo(TI: DeclaratorChunk::getFunction( |
767 | /*HasProto=*/true, |
768 | /*IsAmbiguous=*/false, |
769 | /*LParenLoc=*/NoLoc, |
770 | /*ArgInfo=*/Params: nullptr, |
771 | /*NumParams=*/0, |
772 | /*EllipsisLoc=*/NoLoc, |
773 | /*RParenLoc=*/NoLoc, |
774 | /*RefQualifierIsLvalueRef=*/true, |
775 | /*RefQualifierLoc=*/NoLoc, |
776 | /*MutableLoc=*/NoLoc, ESpecType: EST_None, |
777 | /*ESpecRange=*/SourceRange(), |
778 | /*Exceptions=*/nullptr, |
779 | /*ExceptionRanges=*/nullptr, |
780 | /*NumExceptions=*/0, |
781 | /*NoexceptExpr=*/nullptr, |
782 | /*ExceptionSpecTokens=*/nullptr, |
783 | /*DeclsInPrototype=*/std::nullopt, LocalRangeBegin: loc, LocalRangeEnd: loc, TheDeclarator&: declarator)); |
784 | |
785 | // For consistency, make sure the state still has us as processing |
786 | // the decl spec. |
787 | assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1); |
788 | state.setCurrentChunkIndex(declarator.getNumTypeObjects()); |
789 | } |
790 | |
791 | static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, |
792 | unsigned &TypeQuals, |
793 | QualType TypeSoFar, |
794 | unsigned RemoveTQs, |
795 | unsigned DiagID) { |
796 | // If this occurs outside a template instantiation, warn the user about |
797 | // it; they probably didn't mean to specify a redundant qualifier. |
798 | typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc; |
799 | for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()), |
800 | QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()), |
801 | QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()), |
802 | QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) { |
803 | if (!(RemoveTQs & Qual.first)) |
804 | continue; |
805 | |
806 | if (!S.inTemplateInstantiation()) { |
807 | if (TypeQuals & Qual.first) |
808 | S.Diag(Loc: Qual.second, DiagID) |
809 | << DeclSpec::getSpecifierName(Q: Qual.first) << TypeSoFar |
810 | << FixItHint::CreateRemoval(RemoveRange: Qual.second); |
811 | } |
812 | |
813 | TypeQuals &= ~Qual.first; |
814 | } |
815 | } |
816 | |
817 | /// Return true if this is omitted block return type. Also check type |
818 | /// attributes and type qualifiers when returning true. |
819 | static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, |
820 | QualType Result) { |
821 | if (!isOmittedBlockReturnType(D: declarator)) |
822 | return false; |
823 | |
824 | // Warn if we see type attributes for omitted return type on a block literal. |
825 | SmallVector<ParsedAttr *, 2> ToBeRemoved; |
826 | for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) { |
827 | if (AL.isInvalid() || !AL.isTypeAttr()) |
828 | continue; |
829 | S.Diag(AL.getLoc(), |
830 | diag::warn_block_literal_attributes_on_omitted_return_type) |
831 | << AL; |
832 | ToBeRemoved.push_back(Elt: &AL); |
833 | } |
834 | // Remove bad attributes from the list. |
835 | for (ParsedAttr *AL : ToBeRemoved) |
836 | declarator.getMutableDeclSpec().getAttributes().remove(ToBeRemoved: AL); |
837 | |
838 | // Warn if we see type qualifiers for omitted return type on a block literal. |
839 | const DeclSpec &DS = declarator.getDeclSpec(); |
840 | unsigned TypeQuals = DS.getTypeQualifiers(); |
841 | diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1, |
842 | diag::warn_block_literal_qualifiers_on_omitted_return_type); |
843 | declarator.getMutableDeclSpec().ClearTypeQualifiers(); |
844 | |
845 | return true; |
846 | } |
847 | |
848 | /// Apply Objective-C type arguments to the given type. |
849 | static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, |
850 | ArrayRef<TypeSourceInfo *> typeArgs, |
851 | SourceRange typeArgsRange, bool failOnError, |
852 | bool rebuilding) { |
853 | // We can only apply type arguments to an Objective-C class type. |
854 | const auto *objcObjectType = type->getAs<ObjCObjectType>(); |
855 | if (!objcObjectType || !objcObjectType->getInterface()) { |
856 | S.Diag(loc, diag::err_objc_type_args_non_class) |
857 | << type |
858 | << typeArgsRange; |
859 | |
860 | if (failOnError) |
861 | return QualType(); |
862 | return type; |
863 | } |
864 | |
865 | // The class type must be parameterized. |
866 | ObjCInterfaceDecl *objcClass = objcObjectType->getInterface(); |
867 | ObjCTypeParamList *typeParams = objcClass->getTypeParamList(); |
868 | if (!typeParams) { |
869 | S.Diag(loc, diag::err_objc_type_args_non_parameterized_class) |
870 | << objcClass->getDeclName() |
871 | << FixItHint::CreateRemoval(typeArgsRange); |
872 | |
873 | if (failOnError) |
874 | return QualType(); |
875 | |
876 | return type; |
877 | } |
878 | |
879 | // The type must not already be specialized. |
880 | if (objcObjectType->isSpecialized()) { |
881 | S.Diag(loc, diag::err_objc_type_args_specialized_class) |
882 | << type |
883 | << FixItHint::CreateRemoval(typeArgsRange); |
884 | |
885 | if (failOnError) |
886 | return QualType(); |
887 | |
888 | return type; |
889 | } |
890 | |
891 | // Check the type arguments. |
892 | SmallVector<QualType, 4> finalTypeArgs; |
893 | unsigned numTypeParams = typeParams->size(); |
894 | bool anyPackExpansions = false; |
895 | for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) { |
896 | TypeSourceInfo *typeArgInfo = typeArgs[i]; |
897 | QualType typeArg = typeArgInfo->getType(); |
898 | |
899 | // Type arguments cannot have explicit qualifiers or nullability. |
900 | // We ignore indirect sources of these, e.g. behind typedefs or |
901 | // template arguments. |
902 | if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) { |
903 | bool diagnosed = false; |
904 | SourceRange rangeToRemove; |
905 | if (auto attr = qual.getAs<AttributedTypeLoc>()) { |
906 | rangeToRemove = attr.getLocalSourceRange(); |
907 | if (attr.getTypePtr()->getImmediateNullability()) { |
908 | typeArg = attr.getTypePtr()->getModifiedType(); |
909 | S.Diag(attr.getBeginLoc(), |
910 | diag::err_objc_type_arg_explicit_nullability) |
911 | << typeArg << FixItHint::CreateRemoval(rangeToRemove); |
912 | diagnosed = true; |
913 | } |
914 | } |
915 | |
916 | // When rebuilding, qualifiers might have gotten here through a |
917 | // final substitution. |
918 | if (!rebuilding && !diagnosed) { |
919 | S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified) |
920 | << typeArg << typeArg.getQualifiers().getAsString() |
921 | << FixItHint::CreateRemoval(rangeToRemove); |
922 | } |
923 | } |
924 | |
925 | // Remove qualifiers even if they're non-local. |
926 | typeArg = typeArg.getUnqualifiedType(); |
927 | |
928 | finalTypeArgs.push_back(Elt: typeArg); |
929 | |
930 | if (typeArg->getAs<PackExpansionType>()) |
931 | anyPackExpansions = true; |
932 | |
933 | // Find the corresponding type parameter, if there is one. |
934 | ObjCTypeParamDecl *typeParam = nullptr; |
935 | if (!anyPackExpansions) { |
936 | if (i < numTypeParams) { |
937 | typeParam = typeParams->begin()[i]; |
938 | } else { |
939 | // Too many arguments. |
940 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) |
941 | << false |
942 | << objcClass->getDeclName() |
943 | << (unsigned)typeArgs.size() |
944 | << numTypeParams; |
945 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) |
946 | << objcClass; |
947 | |
948 | if (failOnError) |
949 | return QualType(); |
950 | |
951 | return type; |
952 | } |
953 | } |
954 | |
955 | // Objective-C object pointer types must be substitutable for the bounds. |
956 | if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) { |
957 | // If we don't have a type parameter to match against, assume |
958 | // everything is fine. There was a prior pack expansion that |
959 | // means we won't be able to match anything. |
960 | if (!typeParam) { |
961 | assert(anyPackExpansions && "Too many arguments?" ); |
962 | continue; |
963 | } |
964 | |
965 | // Retrieve the bound. |
966 | QualType bound = typeParam->getUnderlyingType(); |
967 | const auto *boundObjC = bound->castAs<ObjCObjectPointerType>(); |
968 | |
969 | // Determine whether the type argument is substitutable for the bound. |
970 | if (typeArgObjC->isObjCIdType()) { |
971 | // When the type argument is 'id', the only acceptable type |
972 | // parameter bound is 'id'. |
973 | if (boundObjC->isObjCIdType()) |
974 | continue; |
975 | } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) { |
976 | // Otherwise, we follow the assignability rules. |
977 | continue; |
978 | } |
979 | |
980 | // Diagnose the mismatch. |
981 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), |
982 | diag::err_objc_type_arg_does_not_match_bound) |
983 | << typeArg << bound << typeParam->getDeclName(); |
984 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) |
985 | << typeParam->getDeclName(); |
986 | |
987 | if (failOnError) |
988 | return QualType(); |
989 | |
990 | return type; |
991 | } |
992 | |
993 | // Block pointer types are permitted for unqualified 'id' bounds. |
994 | if (typeArg->isBlockPointerType()) { |
995 | // If we don't have a type parameter to match against, assume |
996 | // everything is fine. There was a prior pack expansion that |
997 | // means we won't be able to match anything. |
998 | if (!typeParam) { |
999 | assert(anyPackExpansions && "Too many arguments?" ); |
1000 | continue; |
1001 | } |
1002 | |
1003 | // Retrieve the bound. |
1004 | QualType bound = typeParam->getUnderlyingType(); |
1005 | if (bound->isBlockCompatibleObjCPointerType(ctx&: S.Context)) |
1006 | continue; |
1007 | |
1008 | // Diagnose the mismatch. |
1009 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), |
1010 | diag::err_objc_type_arg_does_not_match_bound) |
1011 | << typeArg << bound << typeParam->getDeclName(); |
1012 | S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here) |
1013 | << typeParam->getDeclName(); |
1014 | |
1015 | if (failOnError) |
1016 | return QualType(); |
1017 | |
1018 | return type; |
1019 | } |
1020 | |
1021 | // Dependent types will be checked at instantiation time. |
1022 | if (typeArg->isDependentType()) { |
1023 | continue; |
1024 | } |
1025 | |
1026 | // Diagnose non-id-compatible type arguments. |
1027 | S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(), |
1028 | diag::err_objc_type_arg_not_id_compatible) |
1029 | << typeArg << typeArgInfo->getTypeLoc().getSourceRange(); |
1030 | |
1031 | if (failOnError) |
1032 | return QualType(); |
1033 | |
1034 | return type; |
1035 | } |
1036 | |
1037 | // Make sure we didn't have the wrong number of arguments. |
1038 | if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) { |
1039 | S.Diag(loc, diag::err_objc_type_args_wrong_arity) |
1040 | << (typeArgs.size() < typeParams->size()) |
1041 | << objcClass->getDeclName() |
1042 | << (unsigned)finalTypeArgs.size() |
1043 | << (unsigned)numTypeParams; |
1044 | S.Diag(objcClass->getLocation(), diag::note_previous_decl) |
1045 | << objcClass; |
1046 | |
1047 | if (failOnError) |
1048 | return QualType(); |
1049 | |
1050 | return type; |
1051 | } |
1052 | |
1053 | // Success. Form the specialized type. |
1054 | return S.Context.getObjCObjectType(Base: type, typeArgs: finalTypeArgs, protocols: { }, isKindOf: false); |
1055 | } |
1056 | |
1057 | QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, |
1058 | SourceLocation ProtocolLAngleLoc, |
1059 | ArrayRef<ObjCProtocolDecl *> Protocols, |
1060 | ArrayRef<SourceLocation> ProtocolLocs, |
1061 | SourceLocation ProtocolRAngleLoc, |
1062 | bool FailOnError) { |
1063 | QualType Result = QualType(Decl->getTypeForDecl(), 0); |
1064 | if (!Protocols.empty()) { |
1065 | bool HasError; |
1066 | Result = Context.applyObjCProtocolQualifiers(type: Result, protocols: Protocols, |
1067 | hasError&: HasError); |
1068 | if (HasError) { |
1069 | Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers) |
1070 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); |
1071 | if (FailOnError) Result = QualType(); |
1072 | } |
1073 | if (FailOnError && Result.isNull()) |
1074 | return QualType(); |
1075 | } |
1076 | |
1077 | return Result; |
1078 | } |
1079 | |
1080 | QualType Sema::BuildObjCObjectType( |
1081 | QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, |
1082 | ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, |
1083 | SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, |
1084 | ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, |
1085 | bool FailOnError, bool Rebuilding) { |
1086 | QualType Result = BaseType; |
1087 | if (!TypeArgs.empty()) { |
1088 | Result = |
1089 | applyObjCTypeArgs(S&: *this, loc: Loc, type: Result, typeArgs: TypeArgs, |
1090 | typeArgsRange: SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc), |
1091 | failOnError: FailOnError, rebuilding: Rebuilding); |
1092 | if (FailOnError && Result.isNull()) |
1093 | return QualType(); |
1094 | } |
1095 | |
1096 | if (!Protocols.empty()) { |
1097 | bool HasError; |
1098 | Result = Context.applyObjCProtocolQualifiers(type: Result, protocols: Protocols, |
1099 | hasError&: HasError); |
1100 | if (HasError) { |
1101 | Diag(Loc, diag::err_invalid_protocol_qualifiers) |
1102 | << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc); |
1103 | if (FailOnError) Result = QualType(); |
1104 | } |
1105 | if (FailOnError && Result.isNull()) |
1106 | return QualType(); |
1107 | } |
1108 | |
1109 | return Result; |
1110 | } |
1111 | |
1112 | TypeResult Sema::actOnObjCProtocolQualifierType( |
1113 | SourceLocation lAngleLoc, |
1114 | ArrayRef<Decl *> protocols, |
1115 | ArrayRef<SourceLocation> protocolLocs, |
1116 | SourceLocation rAngleLoc) { |
1117 | // Form id<protocol-list>. |
1118 | QualType Result = Context.getObjCObjectType( |
1119 | Context.ObjCBuiltinIdTy, {}, |
1120 | llvm::ArrayRef((ObjCProtocolDecl *const *)protocols.data(), |
1121 | protocols.size()), |
1122 | false); |
1123 | Result = Context.getObjCObjectPointerType(OIT: Result); |
1124 | |
1125 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(T: Result); |
1126 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); |
1127 | |
1128 | auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>(); |
1129 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit |
1130 | |
1131 | auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc() |
1132 | .castAs<ObjCObjectTypeLoc>(); |
1133 | ObjCObjectTL.setHasBaseTypeAsWritten(false); |
1134 | ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation()); |
1135 | |
1136 | // No type arguments. |
1137 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); |
1138 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); |
1139 | |
1140 | // Fill in protocol qualifiers. |
1141 | ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc); |
1142 | ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc); |
1143 | for (unsigned i = 0, n = protocols.size(); i != n; ++i) |
1144 | ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]); |
1145 | |
1146 | // We're done. Return the completed type to the parser. |
1147 | return CreateParsedType(T: Result, TInfo: ResultTInfo); |
1148 | } |
1149 | |
1150 | TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers( |
1151 | Scope *S, |
1152 | SourceLocation Loc, |
1153 | ParsedType BaseType, |
1154 | SourceLocation TypeArgsLAngleLoc, |
1155 | ArrayRef<ParsedType> TypeArgs, |
1156 | SourceLocation TypeArgsRAngleLoc, |
1157 | SourceLocation ProtocolLAngleLoc, |
1158 | ArrayRef<Decl *> Protocols, |
1159 | ArrayRef<SourceLocation> ProtocolLocs, |
1160 | SourceLocation ProtocolRAngleLoc) { |
1161 | TypeSourceInfo *BaseTypeInfo = nullptr; |
1162 | QualType T = GetTypeFromParser(Ty: BaseType, TInfo: &BaseTypeInfo); |
1163 | if (T.isNull()) |
1164 | return true; |
1165 | |
1166 | // Handle missing type-source info. |
1167 | if (!BaseTypeInfo) |
1168 | BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc); |
1169 | |
1170 | // Extract type arguments. |
1171 | SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos; |
1172 | for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) { |
1173 | TypeSourceInfo *TypeArgInfo = nullptr; |
1174 | QualType TypeArg = GetTypeFromParser(Ty: TypeArgs[i], TInfo: &TypeArgInfo); |
1175 | if (TypeArg.isNull()) { |
1176 | ActualTypeArgInfos.clear(); |
1177 | break; |
1178 | } |
1179 | |
1180 | assert(TypeArgInfo && "No type source info?" ); |
1181 | ActualTypeArgInfos.push_back(Elt: TypeArgInfo); |
1182 | } |
1183 | |
1184 | // Build the object type. |
1185 | QualType Result = BuildObjCObjectType( |
1186 | BaseType: T, Loc: BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(), |
1187 | TypeArgsLAngleLoc, TypeArgs: ActualTypeArgInfos, TypeArgsRAngleLoc, |
1188 | ProtocolLAngleLoc, |
1189 | Protocols: llvm::ArrayRef((ObjCProtocolDecl *const *)Protocols.data(), |
1190 | Protocols.size()), |
1191 | ProtocolLocs, ProtocolRAngleLoc, |
1192 | /*FailOnError=*/false, |
1193 | /*Rebuilding=*/false); |
1194 | |
1195 | if (Result == T) |
1196 | return BaseType; |
1197 | |
1198 | // Create source information for this type. |
1199 | TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(T: Result); |
1200 | TypeLoc ResultTL = ResultTInfo->getTypeLoc(); |
1201 | |
1202 | // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an |
1203 | // object pointer type. Fill in source information for it. |
1204 | if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) { |
1205 | // The '*' is implicit. |
1206 | ObjCObjectPointerTL.setStarLoc(SourceLocation()); |
1207 | ResultTL = ObjCObjectPointerTL.getPointeeLoc(); |
1208 | } |
1209 | |
1210 | if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) { |
1211 | // Protocol qualifier information. |
1212 | if (OTPTL.getNumProtocols() > 0) { |
1213 | assert(OTPTL.getNumProtocols() == Protocols.size()); |
1214 | OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc); |
1215 | OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc); |
1216 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) |
1217 | OTPTL.setProtocolLoc(i, Loc: ProtocolLocs[i]); |
1218 | } |
1219 | |
1220 | // We're done. Return the completed type to the parser. |
1221 | return CreateParsedType(T: Result, TInfo: ResultTInfo); |
1222 | } |
1223 | |
1224 | auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>(); |
1225 | |
1226 | // Type argument information. |
1227 | if (ObjCObjectTL.getNumTypeArgs() > 0) { |
1228 | assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size()); |
1229 | ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc); |
1230 | ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc); |
1231 | for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i) |
1232 | ObjCObjectTL.setTypeArgTInfo(i, TInfo: ActualTypeArgInfos[i]); |
1233 | } else { |
1234 | ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation()); |
1235 | ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation()); |
1236 | } |
1237 | |
1238 | // Protocol qualifier information. |
1239 | if (ObjCObjectTL.getNumProtocols() > 0) { |
1240 | assert(ObjCObjectTL.getNumProtocols() == Protocols.size()); |
1241 | ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc); |
1242 | ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc); |
1243 | for (unsigned i = 0, n = Protocols.size(); i != n; ++i) |
1244 | ObjCObjectTL.setProtocolLoc(i, Loc: ProtocolLocs[i]); |
1245 | } else { |
1246 | ObjCObjectTL.setProtocolLAngleLoc(SourceLocation()); |
1247 | ObjCObjectTL.setProtocolRAngleLoc(SourceLocation()); |
1248 | } |
1249 | |
1250 | // Base type. |
1251 | ObjCObjectTL.setHasBaseTypeAsWritten(true); |
1252 | if (ObjCObjectTL.getType() == T) |
1253 | ObjCObjectTL.getBaseLoc().initializeFullCopy(Other: BaseTypeInfo->getTypeLoc()); |
1254 | else |
1255 | ObjCObjectTL.getBaseLoc().initialize(Context, Loc); |
1256 | |
1257 | // We're done. Return the completed type to the parser. |
1258 | return CreateParsedType(T: Result, TInfo: ResultTInfo); |
1259 | } |
1260 | |
1261 | static OpenCLAccessAttr::Spelling |
1262 | getImageAccess(const ParsedAttributesView &Attrs) { |
1263 | for (const ParsedAttr &AL : Attrs) |
1264 | if (AL.getKind() == ParsedAttr::AT_OpenCLAccess) |
1265 | return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling()); |
1266 | return OpenCLAccessAttr::Keyword_read_only; |
1267 | } |
1268 | |
1269 | static UnaryTransformType::UTTKind |
1270 | TSTToUnaryTransformType(DeclSpec::TST SwitchTST) { |
1271 | switch (SwitchTST) { |
1272 | #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \ |
1273 | case TST_##Trait: \ |
1274 | return UnaryTransformType::Enum; |
1275 | #include "clang/Basic/TransformTypeTraits.def" |
1276 | default: |
1277 | llvm_unreachable("attempted to parse a non-unary transform builtin" ); |
1278 | } |
1279 | } |
1280 | |
1281 | /// Convert the specified declspec to the appropriate type |
1282 | /// object. |
1283 | /// \param state Specifies the declarator containing the declaration specifier |
1284 | /// to be converted, along with other associated processing state. |
1285 | /// \returns The type described by the declaration specifiers. This function |
1286 | /// never returns null. |
1287 | static QualType ConvertDeclSpecToType(TypeProcessingState &state) { |
1288 | // FIXME: Should move the logic from DeclSpec::Finish to here for validity |
1289 | // checking. |
1290 | |
1291 | Sema &S = state.getSema(); |
1292 | Declarator &declarator = state.getDeclarator(); |
1293 | DeclSpec &DS = declarator.getMutableDeclSpec(); |
1294 | SourceLocation DeclLoc = declarator.getIdentifierLoc(); |
1295 | if (DeclLoc.isInvalid()) |
1296 | DeclLoc = DS.getBeginLoc(); |
1297 | |
1298 | ASTContext &Context = S.Context; |
1299 | |
1300 | QualType Result; |
1301 | switch (DS.getTypeSpecType()) { |
1302 | case DeclSpec::TST_void: |
1303 | Result = Context.VoidTy; |
1304 | break; |
1305 | case DeclSpec::TST_char: |
1306 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) |
1307 | Result = Context.CharTy; |
1308 | else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) |
1309 | Result = Context.SignedCharTy; |
1310 | else { |
1311 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && |
1312 | "Unknown TSS value" ); |
1313 | Result = Context.UnsignedCharTy; |
1314 | } |
1315 | break; |
1316 | case DeclSpec::TST_wchar: |
1317 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified) |
1318 | Result = Context.WCharTy; |
1319 | else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) { |
1320 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) |
1321 | << DS.getSpecifierName(DS.getTypeSpecType(), |
1322 | Context.getPrintingPolicy()); |
1323 | Result = Context.getSignedWCharType(); |
1324 | } else { |
1325 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned && |
1326 | "Unknown TSS value" ); |
1327 | S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec) |
1328 | << DS.getSpecifierName(DS.getTypeSpecType(), |
1329 | Context.getPrintingPolicy()); |
1330 | Result = Context.getUnsignedWCharType(); |
1331 | } |
1332 | break; |
1333 | case DeclSpec::TST_char8: |
1334 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && |
1335 | "Unknown TSS value" ); |
1336 | Result = Context.Char8Ty; |
1337 | break; |
1338 | case DeclSpec::TST_char16: |
1339 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && |
1340 | "Unknown TSS value" ); |
1341 | Result = Context.Char16Ty; |
1342 | break; |
1343 | case DeclSpec::TST_char32: |
1344 | assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && |
1345 | "Unknown TSS value" ); |
1346 | Result = Context.Char32Ty; |
1347 | break; |
1348 | case DeclSpec::TST_unspecified: |
1349 | // If this is a missing declspec in a block literal return context, then it |
1350 | // is inferred from the return statements inside the block. |
1351 | // The declspec is always missing in a lambda expr context; it is either |
1352 | // specified with a trailing return type or inferred. |
1353 | if (S.getLangOpts().CPlusPlus14 && |
1354 | declarator.getContext() == DeclaratorContext::LambdaExpr) { |
1355 | // In C++1y, a lambda's implicit return type is 'auto'. |
1356 | Result = Context.getAutoDeductType(); |
1357 | break; |
1358 | } else if (declarator.getContext() == DeclaratorContext::LambdaExpr || |
1359 | checkOmittedBlockReturnType(S, declarator, |
1360 | Context.DependentTy)) { |
1361 | Result = Context.DependentTy; |
1362 | break; |
1363 | } |
1364 | |
1365 | // Unspecified typespec defaults to int in C90. However, the C90 grammar |
1366 | // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, |
1367 | // type-qualifier, or storage-class-specifier. If not, emit an extwarn. |
1368 | // Note that the one exception to this is function definitions, which are |
1369 | // allowed to be completely missing a declspec. This is handled in the |
1370 | // parser already though by it pretending to have seen an 'int' in this |
1371 | // case. |
1372 | if (S.getLangOpts().isImplicitIntRequired()) { |
1373 | S.Diag(DeclLoc, diag::warn_missing_type_specifier) |
1374 | << DS.getSourceRange() |
1375 | << FixItHint::CreateInsertion(DS.getBeginLoc(), "int" ); |
1376 | } else if (!DS.hasTypeSpecifier()) { |
1377 | // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: |
1378 | // "At least one type specifier shall be given in the declaration |
1379 | // specifiers in each declaration, and in the specifier-qualifier list in |
1380 | // each struct declaration and type name." |
1381 | if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) { |
1382 | S.Diag(DeclLoc, diag::err_missing_type_specifier) |
1383 | << DS.getSourceRange(); |
1384 | |
1385 | // When this occurs, often something is very broken with the value |
1386 | // being declared, poison it as invalid so we don't get chains of |
1387 | // errors. |
1388 | declarator.setInvalidType(true); |
1389 | } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 && |
1390 | DS.isTypeSpecPipe()) { |
1391 | S.Diag(DeclLoc, diag::err_missing_actual_pipe_type) |
1392 | << DS.getSourceRange(); |
1393 | declarator.setInvalidType(true); |
1394 | } else { |
1395 | assert(S.getLangOpts().isImplicitIntAllowed() && |
1396 | "implicit int is disabled?" ); |
1397 | S.Diag(DeclLoc, diag::ext_missing_type_specifier) |
1398 | << DS.getSourceRange() |
1399 | << FixItHint::CreateInsertion(DS.getBeginLoc(), "int" ); |
1400 | } |
1401 | } |
1402 | |
1403 | [[fallthrough]]; |
1404 | case DeclSpec::TST_int: { |
1405 | if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) { |
1406 | switch (DS.getTypeSpecWidth()) { |
1407 | case TypeSpecifierWidth::Unspecified: |
1408 | Result = Context.IntTy; |
1409 | break; |
1410 | case TypeSpecifierWidth::Short: |
1411 | Result = Context.ShortTy; |
1412 | break; |
1413 | case TypeSpecifierWidth::Long: |
1414 | Result = Context.LongTy; |
1415 | break; |
1416 | case TypeSpecifierWidth::LongLong: |
1417 | Result = Context.LongLongTy; |
1418 | |
1419 | // 'long long' is a C99 or C++11 feature. |
1420 | if (!S.getLangOpts().C99) { |
1421 | if (S.getLangOpts().CPlusPlus) |
1422 | S.Diag(DS.getTypeSpecWidthLoc(), |
1423 | S.getLangOpts().CPlusPlus11 ? |
1424 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); |
1425 | else |
1426 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); |
1427 | } |
1428 | break; |
1429 | } |
1430 | } else { |
1431 | switch (DS.getTypeSpecWidth()) { |
1432 | case TypeSpecifierWidth::Unspecified: |
1433 | Result = Context.UnsignedIntTy; |
1434 | break; |
1435 | case TypeSpecifierWidth::Short: |
1436 | Result = Context.UnsignedShortTy; |
1437 | break; |
1438 | case TypeSpecifierWidth::Long: |
1439 | Result = Context.UnsignedLongTy; |
1440 | break; |
1441 | case TypeSpecifierWidth::LongLong: |
1442 | Result = Context.UnsignedLongLongTy; |
1443 | |
1444 | // 'long long' is a C99 or C++11 feature. |
1445 | if (!S.getLangOpts().C99) { |
1446 | if (S.getLangOpts().CPlusPlus) |
1447 | S.Diag(DS.getTypeSpecWidthLoc(), |
1448 | S.getLangOpts().CPlusPlus11 ? |
1449 | diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); |
1450 | else |
1451 | S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong); |
1452 | } |
1453 | break; |
1454 | } |
1455 | } |
1456 | break; |
1457 | } |
1458 | case DeclSpec::TST_bitint: { |
1459 | if (!S.Context.getTargetInfo().hasBitIntType()) |
1460 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt" ; |
1461 | Result = |
1462 | S.BuildBitIntType(IsUnsigned: DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned, |
1463 | BitWidth: DS.getRepAsExpr(), Loc: DS.getBeginLoc()); |
1464 | if (Result.isNull()) { |
1465 | Result = Context.IntTy; |
1466 | declarator.setInvalidType(true); |
1467 | } |
1468 | break; |
1469 | } |
1470 | case DeclSpec::TST_accum: { |
1471 | switch (DS.getTypeSpecWidth()) { |
1472 | case TypeSpecifierWidth::Short: |
1473 | Result = Context.ShortAccumTy; |
1474 | break; |
1475 | case TypeSpecifierWidth::Unspecified: |
1476 | Result = Context.AccumTy; |
1477 | break; |
1478 | case TypeSpecifierWidth::Long: |
1479 | Result = Context.LongAccumTy; |
1480 | break; |
1481 | case TypeSpecifierWidth::LongLong: |
1482 | llvm_unreachable("Unable to specify long long as _Accum width" ); |
1483 | } |
1484 | |
1485 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) |
1486 | Result = Context.getCorrespondingUnsignedType(T: Result); |
1487 | |
1488 | if (DS.isTypeSpecSat()) |
1489 | Result = Context.getCorrespondingSaturatedType(Ty: Result); |
1490 | |
1491 | break; |
1492 | } |
1493 | case DeclSpec::TST_fract: { |
1494 | switch (DS.getTypeSpecWidth()) { |
1495 | case TypeSpecifierWidth::Short: |
1496 | Result = Context.ShortFractTy; |
1497 | break; |
1498 | case TypeSpecifierWidth::Unspecified: |
1499 | Result = Context.FractTy; |
1500 | break; |
1501 | case TypeSpecifierWidth::Long: |
1502 | Result = Context.LongFractTy; |
1503 | break; |
1504 | case TypeSpecifierWidth::LongLong: |
1505 | llvm_unreachable("Unable to specify long long as _Fract width" ); |
1506 | } |
1507 | |
1508 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) |
1509 | Result = Context.getCorrespondingUnsignedType(T: Result); |
1510 | |
1511 | if (DS.isTypeSpecSat()) |
1512 | Result = Context.getCorrespondingSaturatedType(Ty: Result); |
1513 | |
1514 | break; |
1515 | } |
1516 | case DeclSpec::TST_int128: |
1517 | if (!S.Context.getTargetInfo().hasInt128Type() && |
1518 | !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice || |
1519 | (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))) |
1520 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) |
1521 | << "__int128" ; |
1522 | if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned) |
1523 | Result = Context.UnsignedInt128Ty; |
1524 | else |
1525 | Result = Context.Int128Ty; |
1526 | break; |
1527 | case DeclSpec::TST_float16: |
1528 | // CUDA host and device may have different _Float16 support, therefore |
1529 | // do not diagnose _Float16 usage to avoid false alarm. |
1530 | // ToDo: more precise diagnostics for CUDA. |
1531 | if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA && |
1532 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)) |
1533 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) |
1534 | << "_Float16" ; |
1535 | Result = Context.Float16Ty; |
1536 | break; |
1537 | case DeclSpec::TST_half: Result = Context.HalfTy; break; |
1538 | case DeclSpec::TST_BFloat16: |
1539 | if (!S.Context.getTargetInfo().hasBFloat16Type() && |
1540 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) && |
1541 | !S.getLangOpts().SYCLIsDevice) |
1542 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16" ; |
1543 | Result = Context.BFloat16Ty; |
1544 | break; |
1545 | case DeclSpec::TST_float: Result = Context.FloatTy; break; |
1546 | case DeclSpec::TST_double: |
1547 | if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long) |
1548 | Result = Context.LongDoubleTy; |
1549 | else |
1550 | Result = Context.DoubleTy; |
1551 | if (S.getLangOpts().OpenCL) { |
1552 | if (!S.getOpenCLOptions().isSupported("cl_khr_fp64" , S.getLangOpts())) |
1553 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) |
1554 | << 0 << Result |
1555 | << (S.getLangOpts().getOpenCLCompatibleVersion() == 300 |
1556 | ? "cl_khr_fp64 and __opencl_c_fp64" |
1557 | : "cl_khr_fp64" ); |
1558 | else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64" , S.getLangOpts())) |
1559 | S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma); |
1560 | } |
1561 | break; |
1562 | case DeclSpec::TST_float128: |
1563 | if (!S.Context.getTargetInfo().hasFloat128Type() && |
1564 | !S.getLangOpts().SYCLIsDevice && |
1565 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)) |
1566 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) |
1567 | << "__float128" ; |
1568 | Result = Context.Float128Ty; |
1569 | break; |
1570 | case DeclSpec::TST_ibm128: |
1571 | if (!S.Context.getTargetInfo().hasIbm128Type() && |
1572 | !S.getLangOpts().SYCLIsDevice && |
1573 | !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)) |
1574 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128" ; |
1575 | Result = Context.Ibm128Ty; |
1576 | break; |
1577 | case DeclSpec::TST_bool: |
1578 | Result = Context.BoolTy; // _Bool or bool |
1579 | break; |
1580 | case DeclSpec::TST_decimal32: // _Decimal32 |
1581 | case DeclSpec::TST_decimal64: // _Decimal64 |
1582 | case DeclSpec::TST_decimal128: // _Decimal128 |
1583 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); |
1584 | Result = Context.IntTy; |
1585 | declarator.setInvalidType(true); |
1586 | break; |
1587 | case DeclSpec::TST_class: |
1588 | case DeclSpec::TST_enum: |
1589 | case DeclSpec::TST_union: |
1590 | case DeclSpec::TST_struct: |
1591 | case DeclSpec::TST_interface: { |
1592 | TagDecl *D = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl()); |
1593 | if (!D) { |
1594 | // This can happen in C++ with ambiguous lookups. |
1595 | Result = Context.IntTy; |
1596 | declarator.setInvalidType(true); |
1597 | break; |
1598 | } |
1599 | |
1600 | // If the type is deprecated or unavailable, diagnose it. |
1601 | S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc()); |
1602 | |
1603 | assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && |
1604 | DS.getTypeSpecComplex() == 0 && |
1605 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && |
1606 | "No qualifiers on tag names!" ); |
1607 | |
1608 | // TypeQuals handled by caller. |
1609 | Result = Context.getTypeDeclType(D); |
1610 | |
1611 | // In both C and C++, make an ElaboratedType. |
1612 | ElaboratedTypeKeyword Keyword |
1613 | = ElaboratedType::getKeywordForTypeSpec(TypeSpec: DS.getTypeSpecType()); |
1614 | Result = S.getElaboratedType(Keyword, SS: DS.getTypeSpecScope(), T: Result, |
1615 | OwnedTagDecl: DS.isTypeSpecOwned() ? D : nullptr); |
1616 | break; |
1617 | } |
1618 | case DeclSpec::TST_typename: { |
1619 | assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified && |
1620 | DS.getTypeSpecComplex() == 0 && |
1621 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && |
1622 | "Can't handle qualifiers on typedef names yet!" ); |
1623 | Result = S.GetTypeFromParser(Ty: DS.getRepAsType()); |
1624 | if (Result.isNull()) { |
1625 | declarator.setInvalidType(true); |
1626 | } |
1627 | |
1628 | // TypeQuals handled by caller. |
1629 | break; |
1630 | } |
1631 | case DeclSpec::TST_typeof_unqualType: |
1632 | case DeclSpec::TST_typeofType: |
1633 | // FIXME: Preserve type source info. |
1634 | Result = S.GetTypeFromParser(Ty: DS.getRepAsType()); |
1635 | assert(!Result.isNull() && "Didn't get a type for typeof?" ); |
1636 | if (!Result->isDependentType()) |
1637 | if (const TagType *TT = Result->getAs<TagType>()) |
1638 | S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc()); |
1639 | // TypeQuals handled by caller. |
1640 | Result = Context.getTypeOfType( |
1641 | QT: Result, Kind: DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType |
1642 | ? TypeOfKind::Unqualified |
1643 | : TypeOfKind::Qualified); |
1644 | break; |
1645 | case DeclSpec::TST_typeof_unqualExpr: |
1646 | case DeclSpec::TST_typeofExpr: { |
1647 | Expr *E = DS.getRepAsExpr(); |
1648 | assert(E && "Didn't get an expression for typeof?" ); |
1649 | // TypeQuals handled by caller. |
1650 | Result = S.BuildTypeofExprType(E, Kind: DS.getTypeSpecType() == |
1651 | DeclSpec::TST_typeof_unqualExpr |
1652 | ? TypeOfKind::Unqualified |
1653 | : TypeOfKind::Qualified); |
1654 | if (Result.isNull()) { |
1655 | Result = Context.IntTy; |
1656 | declarator.setInvalidType(true); |
1657 | } |
1658 | break; |
1659 | } |
1660 | case DeclSpec::TST_decltype: { |
1661 | Expr *E = DS.getRepAsExpr(); |
1662 | assert(E && "Didn't get an expression for decltype?" ); |
1663 | // TypeQuals handled by caller. |
1664 | Result = S.BuildDecltypeType(E); |
1665 | if (Result.isNull()) { |
1666 | Result = Context.IntTy; |
1667 | declarator.setInvalidType(true); |
1668 | } |
1669 | break; |
1670 | } |
1671 | case DeclSpec::TST_typename_pack_indexing: { |
1672 | Expr *E = DS.getPackIndexingExpr(); |
1673 | assert(E && "Didn't get an expression for pack indexing" ); |
1674 | QualType Pattern = S.GetTypeFromParser(Ty: DS.getRepAsType()); |
1675 | Result = S.BuildPackIndexingType(Pattern, IndexExpr: E, Loc: DS.getBeginLoc(), |
1676 | EllipsisLoc: DS.getEllipsisLoc()); |
1677 | if (Result.isNull()) { |
1678 | declarator.setInvalidType(true); |
1679 | Result = Context.IntTy; |
1680 | } |
1681 | break; |
1682 | } |
1683 | |
1684 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait: |
1685 | #include "clang/Basic/TransformTypeTraits.def" |
1686 | Result = S.GetTypeFromParser(Ty: DS.getRepAsType()); |
1687 | assert(!Result.isNull() && "Didn't get a type for the transformation?" ); |
1688 | Result = S.BuildUnaryTransformType( |
1689 | BaseType: Result, UKind: TSTToUnaryTransformType(SwitchTST: DS.getTypeSpecType()), |
1690 | Loc: DS.getTypeSpecTypeLoc()); |
1691 | if (Result.isNull()) { |
1692 | Result = Context.IntTy; |
1693 | declarator.setInvalidType(true); |
1694 | } |
1695 | break; |
1696 | |
1697 | case DeclSpec::TST_auto: |
1698 | case DeclSpec::TST_decltype_auto: { |
1699 | auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto |
1700 | ? AutoTypeKeyword::DecltypeAuto |
1701 | : AutoTypeKeyword::Auto; |
1702 | |
1703 | ConceptDecl *TypeConstraintConcept = nullptr; |
1704 | llvm::SmallVector<TemplateArgument, 8> TemplateArgs; |
1705 | if (DS.isConstrainedAuto()) { |
1706 | if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) { |
1707 | TypeConstraintConcept = |
1708 | cast<ConceptDecl>(Val: TemplateId->Template.get().getAsTemplateDecl()); |
1709 | TemplateArgumentListInfo TemplateArgsInfo; |
1710 | TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc); |
1711 | TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc); |
1712 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
1713 | TemplateId->NumArgs); |
1714 | S.translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgsInfo); |
1715 | for (const auto &ArgLoc : TemplateArgsInfo.arguments()) |
1716 | TemplateArgs.push_back(Elt: ArgLoc.getArgument()); |
1717 | } else { |
1718 | declarator.setInvalidType(true); |
1719 | } |
1720 | } |
1721 | Result = S.Context.getAutoType(DeducedType: QualType(), Keyword: AutoKW, |
1722 | /*IsDependent*/ false, /*IsPack=*/false, |
1723 | TypeConstraintConcept, TypeConstraintArgs: TemplateArgs); |
1724 | break; |
1725 | } |
1726 | |
1727 | case DeclSpec::TST_auto_type: |
1728 | Result = Context.getAutoType(DeducedType: QualType(), Keyword: AutoTypeKeyword::GNUAutoType, IsDependent: false); |
1729 | break; |
1730 | |
1731 | case DeclSpec::TST_unknown_anytype: |
1732 | Result = Context.UnknownAnyTy; |
1733 | break; |
1734 | |
1735 | case DeclSpec::TST_atomic: |
1736 | Result = S.GetTypeFromParser(Ty: DS.getRepAsType()); |
1737 | assert(!Result.isNull() && "Didn't get a type for _Atomic?" ); |
1738 | Result = S.BuildAtomicType(T: Result, Loc: DS.getTypeSpecTypeLoc()); |
1739 | if (Result.isNull()) { |
1740 | Result = Context.IntTy; |
1741 | declarator.setInvalidType(true); |
1742 | } |
1743 | break; |
1744 | |
1745 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ |
1746 | case DeclSpec::TST_##ImgType##_t: \ |
1747 | switch (getImageAccess(DS.getAttributes())) { \ |
1748 | case OpenCLAccessAttr::Keyword_write_only: \ |
1749 | Result = Context.Id##WOTy; \ |
1750 | break; \ |
1751 | case OpenCLAccessAttr::Keyword_read_write: \ |
1752 | Result = Context.Id##RWTy; \ |
1753 | break; \ |
1754 | case OpenCLAccessAttr::Keyword_read_only: \ |
1755 | Result = Context.Id##ROTy; \ |
1756 | break; \ |
1757 | case OpenCLAccessAttr::SpellingNotCalculated: \ |
1758 | llvm_unreachable("Spelling not yet calculated"); \ |
1759 | } \ |
1760 | break; |
1761 | #include "clang/Basic/OpenCLImageTypes.def" |
1762 | |
1763 | case DeclSpec::TST_error: |
1764 | Result = Context.IntTy; |
1765 | declarator.setInvalidType(true); |
1766 | break; |
1767 | } |
1768 | |
1769 | // FIXME: we want resulting declarations to be marked invalid, but claiming |
1770 | // the type is invalid is too strong - e.g. it causes ActOnTypeName to return |
1771 | // a null type. |
1772 | if (Result->containsErrors()) |
1773 | declarator.setInvalidType(); |
1774 | |
1775 | if (S.getLangOpts().OpenCL) { |
1776 | const auto &OpenCLOptions = S.getOpenCLOptions(); |
1777 | bool IsOpenCLC30Compatible = |
1778 | S.getLangOpts().getOpenCLCompatibleVersion() == 300; |
1779 | // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images |
1780 | // support. |
1781 | // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support |
1782 | // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the |
1783 | // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices |
1784 | // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and |
1785 | // only when the optional feature is supported |
1786 | if ((Result->isImageType() || Result->isSamplerT()) && |
1787 | (IsOpenCLC30Compatible && |
1788 | !OpenCLOptions.isSupported(Ext: "__opencl_c_images" , LO: S.getLangOpts()))) { |
1789 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) |
1790 | << 0 << Result << "__opencl_c_images" ; |
1791 | declarator.setInvalidType(); |
1792 | } else if (Result->isOCLImage3dWOType() && |
1793 | !OpenCLOptions.isSupported(Ext: "cl_khr_3d_image_writes" , |
1794 | LO: S.getLangOpts())) { |
1795 | S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension) |
1796 | << 0 << Result |
1797 | << (IsOpenCLC30Compatible |
1798 | ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes" |
1799 | : "cl_khr_3d_image_writes" ); |
1800 | declarator.setInvalidType(); |
1801 | } |
1802 | } |
1803 | |
1804 | bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum || |
1805 | DS.getTypeSpecType() == DeclSpec::TST_fract; |
1806 | |
1807 | // Only fixed point types can be saturated |
1808 | if (DS.isTypeSpecSat() && !IsFixedPointType) |
1809 | S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec) |
1810 | << DS.getSpecifierName(DS.getTypeSpecType(), |
1811 | Context.getPrintingPolicy()); |
1812 | |
1813 | // Handle complex types. |
1814 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { |
1815 | if (S.getLangOpts().Freestanding) |
1816 | S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); |
1817 | Result = Context.getComplexType(T: Result); |
1818 | } else if (DS.isTypeAltiVecVector()) { |
1819 | unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(T: Result)); |
1820 | assert(typeSize > 0 && "type size for vector must be greater than 0 bits" ); |
1821 | VectorKind VecKind = VectorKind::AltiVecVector; |
1822 | if (DS.isTypeAltiVecPixel()) |
1823 | VecKind = VectorKind::AltiVecPixel; |
1824 | else if (DS.isTypeAltiVecBool()) |
1825 | VecKind = VectorKind::AltiVecBool; |
1826 | Result = Context.getVectorType(VectorType: Result, NumElts: 128/typeSize, VecKind); |
1827 | } |
1828 | |
1829 | // FIXME: Imaginary. |
1830 | if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary) |
1831 | S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported); |
1832 | |
1833 | // Before we process any type attributes, synthesize a block literal |
1834 | // function declarator if necessary. |
1835 | if (declarator.getContext() == DeclaratorContext::BlockLiteral) |
1836 | maybeSynthesizeBlockSignature(state, declSpecType: Result); |
1837 | |
1838 | // Apply any type attributes from the decl spec. This may cause the |
1839 | // list of type attributes to be temporarily saved while the type |
1840 | // attributes are pushed around. |
1841 | // pipe attributes will be handled later ( at GetFullTypeForDeclarator ) |
1842 | if (!DS.isTypeSpecPipe()) { |
1843 | // We also apply declaration attributes that "slide" to the decl spec. |
1844 | // Ordering can be important for attributes. The decalaration attributes |
1845 | // come syntactically before the decl spec attributes, so we process them |
1846 | // in that order. |
1847 | ParsedAttributesView SlidingAttrs; |
1848 | for (ParsedAttr &AL : declarator.getDeclarationAttributes()) { |
1849 | if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) { |
1850 | SlidingAttrs.addAtEnd(newAttr: &AL); |
1851 | |
1852 | // For standard syntax attributes, which would normally appertain to the |
1853 | // declaration here, suggest moving them to the type instead. But only |
1854 | // do this for our own vendor attributes; moving other vendors' |
1855 | // attributes might hurt portability. |
1856 | // There's one special case that we need to deal with here: The |
1857 | // `MatrixType` attribute may only be used in a typedef declaration. If |
1858 | // it's being used anywhere else, don't output the warning as |
1859 | // ProcessDeclAttributes() will output an error anyway. |
1860 | if (AL.isStandardAttributeSyntax() && AL.isClangScope() && |
1861 | !(AL.getKind() == ParsedAttr::AT_MatrixType && |
1862 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) { |
1863 | S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl) |
1864 | << AL; |
1865 | } |
1866 | } |
1867 | } |
1868 | // During this call to processTypeAttrs(), |
1869 | // TypeProcessingState::getCurrentAttributes() will erroneously return a |
1870 | // reference to the DeclSpec attributes, rather than the declaration |
1871 | // attributes. However, this doesn't matter, as getCurrentAttributes() |
1872 | // is only called when distributing attributes from one attribute list |
1873 | // to another. Declaration attributes are always C++11 attributes, and these |
1874 | // are never distributed. |
1875 | processTypeAttrs(state, type&: Result, TAL: TAL_DeclSpec, attrs: SlidingAttrs); |
1876 | processTypeAttrs(state, type&: Result, TAL: TAL_DeclSpec, attrs: DS.getAttributes()); |
1877 | } |
1878 | |
1879 | // Apply const/volatile/restrict qualifiers to T. |
1880 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { |
1881 | // Warn about CV qualifiers on function types. |
1882 | // C99 6.7.3p8: |
1883 | // If the specification of a function type includes any type qualifiers, |
1884 | // the behavior is undefined. |
1885 | // C++11 [dcl.fct]p7: |
1886 | // The effect of a cv-qualifier-seq in a function declarator is not the |
1887 | // same as adding cv-qualification on top of the function type. In the |
1888 | // latter case, the cv-qualifiers are ignored. |
1889 | if (Result->isFunctionType()) { |
1890 | diagnoseAndRemoveTypeQualifiers( |
1891 | S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile, |
1892 | S.getLangOpts().CPlusPlus |
1893 | ? diag::warn_typecheck_function_qualifiers_ignored |
1894 | : diag::warn_typecheck_function_qualifiers_unspecified); |
1895 | // No diagnostic for 'restrict' or '_Atomic' applied to a |
1896 | // function type; we'll diagnose those later, in BuildQualifiedType. |
1897 | } |
1898 | |
1899 | // C++11 [dcl.ref]p1: |
1900 | // Cv-qualified references are ill-formed except when the |
1901 | // cv-qualifiers are introduced through the use of a typedef-name |
1902 | // or decltype-specifier, in which case the cv-qualifiers are ignored. |
1903 | // |
1904 | // There don't appear to be any other contexts in which a cv-qualified |
1905 | // reference type could be formed, so the 'ill-formed' clause here appears |
1906 | // to never happen. |
1907 | if (TypeQuals && Result->isReferenceType()) { |
1908 | diagnoseAndRemoveTypeQualifiers( |
1909 | S, DS, TypeQuals, Result, |
1910 | DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic, |
1911 | diag::warn_typecheck_reference_qualifiers); |
1912 | } |
1913 | |
1914 | // C90 6.5.3 constraints: "The same type qualifier shall not appear more |
1915 | // than once in the same specifier-list or qualifier-list, either directly |
1916 | // or via one or more typedefs." |
1917 | if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus |
1918 | && TypeQuals & Result.getCVRQualifiers()) { |
1919 | if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) { |
1920 | S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec) |
1921 | << "const" ; |
1922 | } |
1923 | |
1924 | if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) { |
1925 | S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec) |
1926 | << "volatile" ; |
1927 | } |
1928 | |
1929 | // C90 doesn't have restrict nor _Atomic, so it doesn't force us to |
1930 | // produce a warning in this case. |
1931 | } |
1932 | |
1933 | QualType Qualified = S.BuildQualifiedType(T: Result, Loc: DeclLoc, CVRA: TypeQuals, DS: &DS); |
1934 | |
1935 | // If adding qualifiers fails, just use the unqualified type. |
1936 | if (Qualified.isNull()) |
1937 | declarator.setInvalidType(true); |
1938 | else |
1939 | Result = Qualified; |
1940 | } |
1941 | |
1942 | assert(!Result.isNull() && "This function should not return a null type" ); |
1943 | return Result; |
1944 | } |
1945 | |
1946 | static std::string getPrintableNameForEntity(DeclarationName Entity) { |
1947 | if (Entity) |
1948 | return Entity.getAsString(); |
1949 | |
1950 | return "type name" ; |
1951 | } |
1952 | |
1953 | static bool isDependentOrGNUAutoType(QualType T) { |
1954 | if (T->isDependentType()) |
1955 | return true; |
1956 | |
1957 | const auto *AT = dyn_cast<AutoType>(Val&: T); |
1958 | return AT && AT->isGNUAutoType(); |
1959 | } |
1960 | |
1961 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, |
1962 | Qualifiers Qs, const DeclSpec *DS) { |
1963 | if (T.isNull()) |
1964 | return QualType(); |
1965 | |
1966 | // Ignore any attempt to form a cv-qualified reference. |
1967 | if (T->isReferenceType()) { |
1968 | Qs.removeConst(); |
1969 | Qs.removeVolatile(); |
1970 | } |
1971 | |
1972 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from |
1973 | // object or incomplete types shall not be restrict-qualified." |
1974 | if (Qs.hasRestrict()) { |
1975 | unsigned DiagID = 0; |
1976 | QualType ProblemTy; |
1977 | |
1978 | if (T->isAnyPointerType() || T->isReferenceType() || |
1979 | T->isMemberPointerType()) { |
1980 | QualType EltTy; |
1981 | if (T->isObjCObjectPointerType()) |
1982 | EltTy = T; |
1983 | else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>()) |
1984 | EltTy = PTy->getPointeeType(); |
1985 | else |
1986 | EltTy = T->getPointeeType(); |
1987 | |
1988 | // If we have a pointer or reference, the pointee must have an object |
1989 | // incomplete type. |
1990 | if (!EltTy->isIncompleteOrObjectType()) { |
1991 | DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee; |
1992 | ProblemTy = EltTy; |
1993 | } |
1994 | } else if (!isDependentOrGNUAutoType(T)) { |
1995 | // For an __auto_type variable, we may not have seen the initializer yet |
1996 | // and so have no idea whether the underlying type is a pointer type or |
1997 | // not. |
1998 | DiagID = diag::err_typecheck_invalid_restrict_not_pointer; |
1999 | ProblemTy = T; |
2000 | } |
2001 | |
2002 | if (DiagID) { |
2003 | Diag(Loc: DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy; |
2004 | Qs.removeRestrict(); |
2005 | } |
2006 | } |
2007 | |
2008 | return Context.getQualifiedType(T, Qs); |
2009 | } |
2010 | |
2011 | QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, |
2012 | unsigned CVRAU, const DeclSpec *DS) { |
2013 | if (T.isNull()) |
2014 | return QualType(); |
2015 | |
2016 | // Ignore any attempt to form a cv-qualified reference. |
2017 | if (T->isReferenceType()) |
2018 | CVRAU &= |
2019 | ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic); |
2020 | |
2021 | // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and |
2022 | // TQ_unaligned; |
2023 | unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned); |
2024 | |
2025 | // C11 6.7.3/5: |
2026 | // If the same qualifier appears more than once in the same |
2027 | // specifier-qualifier-list, either directly or via one or more typedefs, |
2028 | // the behavior is the same as if it appeared only once. |
2029 | // |
2030 | // It's not specified what happens when the _Atomic qualifier is applied to |
2031 | // a type specified with the _Atomic specifier, but we assume that this |
2032 | // should be treated as if the _Atomic qualifier appeared multiple times. |
2033 | if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) { |
2034 | // C11 6.7.3/5: |
2035 | // If other qualifiers appear along with the _Atomic qualifier in a |
2036 | // specifier-qualifier-list, the resulting type is the so-qualified |
2037 | // atomic type. |
2038 | // |
2039 | // Don't need to worry about array types here, since _Atomic can't be |
2040 | // applied to such types. |
2041 | SplitQualType Split = T.getSplitUnqualifiedType(); |
2042 | T = BuildAtomicType(T: QualType(Split.Ty, 0), |
2043 | Loc: DS ? DS->getAtomicSpecLoc() : Loc); |
2044 | if (T.isNull()) |
2045 | return T; |
2046 | Split.Quals.addCVRQualifiers(mask: CVR); |
2047 | return BuildQualifiedType(T, Loc, Qs: Split.Quals); |
2048 | } |
2049 | |
2050 | Qualifiers Q = Qualifiers::fromCVRMask(CVR); |
2051 | Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned); |
2052 | return BuildQualifiedType(T, Loc, Qs: Q, DS); |
2053 | } |
2054 | |
2055 | /// Build a paren type including \p T. |
2056 | QualType Sema::BuildParenType(QualType T) { |
2057 | return Context.getParenType(NamedType: T); |
2058 | } |
2059 | |
2060 | /// Given that we're building a pointer or reference to the given |
2061 | static QualType inferARCLifetimeForPointee(Sema &S, QualType type, |
2062 | SourceLocation loc, |
2063 | bool isReference) { |
2064 | // Bail out if retention is unrequired or already specified. |
2065 | if (!type->isObjCLifetimeType() || |
2066 | type.getObjCLifetime() != Qualifiers::OCL_None) |
2067 | return type; |
2068 | |
2069 | Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None; |
2070 | |
2071 | // If the object type is const-qualified, we can safely use |
2072 | // __unsafe_unretained. This is safe (because there are no read |
2073 | // barriers), and it'll be safe to coerce anything but __weak* to |
2074 | // the resulting type. |
2075 | if (type.isConstQualified()) { |
2076 | implicitLifetime = Qualifiers::OCL_ExplicitNone; |
2077 | |
2078 | // Otherwise, check whether the static type does not require |
2079 | // retaining. This currently only triggers for Class (possibly |
2080 | // protocol-qualifed, and arrays thereof). |
2081 | } else if (type->isObjCARCImplicitlyUnretainedType()) { |
2082 | implicitLifetime = Qualifiers::OCL_ExplicitNone; |
2083 | |
2084 | // If we are in an unevaluated context, like sizeof, skip adding a |
2085 | // qualification. |
2086 | } else if (S.isUnevaluatedContext()) { |
2087 | return type; |
2088 | |
2089 | // If that failed, give an error and recover using __strong. __strong |
2090 | // is the option most likely to prevent spurious second-order diagnostics, |
2091 | // like when binding a reference to a field. |
2092 | } else { |
2093 | // These types can show up in private ivars in system headers, so |
2094 | // we need this to not be an error in those cases. Instead we |
2095 | // want to delay. |
2096 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { |
2097 | S.DelayedDiagnostics.add( |
2098 | sema::DelayedDiagnostic::makeForbiddenType(loc, |
2099 | diag::err_arc_indirect_no_ownership, type, isReference)); |
2100 | } else { |
2101 | S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference; |
2102 | } |
2103 | implicitLifetime = Qualifiers::OCL_Strong; |
2104 | } |
2105 | assert(implicitLifetime && "didn't infer any lifetime!" ); |
2106 | |
2107 | Qualifiers qs; |
2108 | qs.addObjCLifetime(type: implicitLifetime); |
2109 | return S.Context.getQualifiedType(T: type, Qs: qs); |
2110 | } |
2111 | |
2112 | static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){ |
2113 | std::string Quals = FnTy->getMethodQuals().getAsString(); |
2114 | |
2115 | switch (FnTy->getRefQualifier()) { |
2116 | case RQ_None: |
2117 | break; |
2118 | |
2119 | case RQ_LValue: |
2120 | if (!Quals.empty()) |
2121 | Quals += ' '; |
2122 | Quals += '&'; |
2123 | break; |
2124 | |
2125 | case RQ_RValue: |
2126 | if (!Quals.empty()) |
2127 | Quals += ' '; |
2128 | Quals += "&&" ; |
2129 | break; |
2130 | } |
2131 | |
2132 | return Quals; |
2133 | } |
2134 | |
2135 | namespace { |
2136 | /// Kinds of declarator that cannot contain a qualified function type. |
2137 | /// |
2138 | /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: |
2139 | /// a function type with a cv-qualifier or a ref-qualifier can only appear |
2140 | /// at the topmost level of a type. |
2141 | /// |
2142 | /// Parens and member pointers are permitted. We don't diagnose array and |
2143 | /// function declarators, because they don't allow function types at all. |
2144 | /// |
2145 | /// The values of this enum are used in diagnostics. |
2146 | enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference }; |
2147 | } // end anonymous namespace |
2148 | |
2149 | /// Check whether the type T is a qualified function type, and if it is, |
2150 | /// diagnose that it cannot be contained within the given kind of declarator. |
2151 | static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, |
2152 | QualifiedFunctionKind QFK) { |
2153 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? |
2154 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); |
2155 | if (!FPT || |
2156 | (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) |
2157 | return false; |
2158 | |
2159 | S.Diag(Loc, diag::err_compound_qualified_function_type) |
2160 | << QFK << isa<FunctionType>(T.IgnoreParens()) << T |
2161 | << getFunctionQualifiersAsString(FPT); |
2162 | return true; |
2163 | } |
2164 | |
2165 | bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) { |
2166 | const FunctionProtoType *FPT = T->getAs<FunctionProtoType>(); |
2167 | if (!FPT || |
2168 | (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None)) |
2169 | return false; |
2170 | |
2171 | Diag(Loc, diag::err_qualified_function_typeid) |
2172 | << T << getFunctionQualifiersAsString(FPT); |
2173 | return true; |
2174 | } |
2175 | |
2176 | // Helper to deduce addr space of a pointee type in OpenCL mode. |
2177 | static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) { |
2178 | if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() && |
2179 | !PointeeType->isSamplerT() && |
2180 | !PointeeType.hasAddressSpace()) |
2181 | PointeeType = S.getASTContext().getAddrSpaceQualType( |
2182 | T: PointeeType, AddressSpace: S.getASTContext().getDefaultOpenCLPointeeAddrSpace()); |
2183 | return PointeeType; |
2184 | } |
2185 | |
2186 | /// Build a pointer type. |
2187 | /// |
2188 | /// \param T The type to which we'll be building a pointer. |
2189 | /// |
2190 | /// \param Loc The location of the entity whose type involves this |
2191 | /// pointer type or, if there is no such entity, the location of the |
2192 | /// type that will have pointer type. |
2193 | /// |
2194 | /// \param Entity The name of the entity that involves the pointer |
2195 | /// type, if known. |
2196 | /// |
2197 | /// \returns A suitable pointer type, if there are no |
2198 | /// errors. Otherwise, returns a NULL type. |
2199 | QualType Sema::BuildPointerType(QualType T, |
2200 | SourceLocation Loc, DeclarationName Entity) { |
2201 | if (T->isReferenceType()) { |
2202 | // C++ 8.3.2p4: There shall be no ... pointers to references ... |
2203 | Diag(Loc, diag::err_illegal_decl_pointer_to_reference) |
2204 | << getPrintableNameForEntity(Entity) << T; |
2205 | return QualType(); |
2206 | } |
2207 | |
2208 | if (T->isFunctionType() && getLangOpts().OpenCL && |
2209 | !getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers" , |
2210 | LO: getLangOpts())) { |
2211 | Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0; |
2212 | return QualType(); |
2213 | } |
2214 | |
2215 | if (getLangOpts().HLSL && Loc.isValid()) { |
2216 | Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0; |
2217 | return QualType(); |
2218 | } |
2219 | |
2220 | if (checkQualifiedFunction(S&: *this, T, Loc, QFK: QFK_Pointer)) |
2221 | return QualType(); |
2222 | |
2223 | assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType" ); |
2224 | |
2225 | // In ARC, it is forbidden to build pointers to unqualified pointers. |
2226 | if (getLangOpts().ObjCAutoRefCount) |
2227 | T = inferARCLifetimeForPointee(S&: *this, type: T, loc: Loc, /*reference*/ isReference: false); |
2228 | |
2229 | if (getLangOpts().OpenCL) |
2230 | T = deduceOpenCLPointeeAddrSpace(S&: *this, PointeeType: T); |
2231 | |
2232 | // In WebAssembly, pointers to reference types and pointers to tables are |
2233 | // illegal. |
2234 | if (getASTContext().getTargetInfo().getTriple().isWasm()) { |
2235 | if (T.isWebAssemblyReferenceType()) { |
2236 | Diag(Loc, diag::err_wasm_reference_pr) << 0; |
2237 | return QualType(); |
2238 | } |
2239 | |
2240 | // We need to desugar the type here in case T is a ParenType. |
2241 | if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) { |
2242 | Diag(Loc, diag::err_wasm_table_pr) << 0; |
2243 | return QualType(); |
2244 | } |
2245 | } |
2246 | |
2247 | // Build the pointer type. |
2248 | return Context.getPointerType(T); |
2249 | } |
2250 | |
2251 | /// Build a reference type. |
2252 | /// |
2253 | /// \param T The type to which we'll be building a reference. |
2254 | /// |
2255 | /// \param Loc The location of the entity whose type involves this |
2256 | /// reference type or, if there is no such entity, the location of the |
2257 | /// type that will have reference type. |
2258 | /// |
2259 | /// \param Entity The name of the entity that involves the reference |
2260 | /// type, if known. |
2261 | /// |
2262 | /// \returns A suitable reference type, if there are no |
2263 | /// errors. Otherwise, returns a NULL type. |
2264 | QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, |
2265 | SourceLocation Loc, |
2266 | DeclarationName Entity) { |
2267 | assert(Context.getCanonicalType(T) != Context.OverloadTy && |
2268 | "Unresolved overloaded function type" ); |
2269 | |
2270 | // C++0x [dcl.ref]p6: |
2271 | // If a typedef (7.1.3), a type template-parameter (14.3.1), or a |
2272 | // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a |
2273 | // type T, an attempt to create the type "lvalue reference to cv TR" creates |
2274 | // the type "lvalue reference to T", while an attempt to create the type |
2275 | // "rvalue reference to cv TR" creates the type TR. |
2276 | bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); |
2277 | |
2278 | // C++ [dcl.ref]p4: There shall be no references to references. |
2279 | // |
2280 | // According to C++ DR 106, references to references are only |
2281 | // diagnosed when they are written directly (e.g., "int & &"), |
2282 | // but not when they happen via a typedef: |
2283 | // |
2284 | // typedef int& intref; |
2285 | // typedef intref& intref2; |
2286 | // |
2287 | // Parser::ParseDeclaratorInternal diagnoses the case where |
2288 | // references are written directly; here, we handle the |
2289 | // collapsing of references-to-references as described in C++0x. |
2290 | // DR 106 and 540 introduce reference-collapsing into C++98/03. |
2291 | |
2292 | // C++ [dcl.ref]p1: |
2293 | // A declarator that specifies the type "reference to cv void" |
2294 | // is ill-formed. |
2295 | if (T->isVoidType()) { |
2296 | Diag(Loc, diag::err_reference_to_void); |
2297 | return QualType(); |
2298 | } |
2299 | |
2300 | if (getLangOpts().HLSL && Loc.isValid()) { |
2301 | Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1; |
2302 | return QualType(); |
2303 | } |
2304 | |
2305 | if (checkQualifiedFunction(S&: *this, T, Loc, QFK: QFK_Reference)) |
2306 | return QualType(); |
2307 | |
2308 | if (T->isFunctionType() && getLangOpts().OpenCL && |
2309 | !getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers" , |
2310 | LO: getLangOpts())) { |
2311 | Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1; |
2312 | return QualType(); |
2313 | } |
2314 | |
2315 | // In ARC, it is forbidden to build references to unqualified pointers. |
2316 | if (getLangOpts().ObjCAutoRefCount) |
2317 | T = inferARCLifetimeForPointee(S&: *this, type: T, loc: Loc, /*reference*/ isReference: true); |
2318 | |
2319 | if (getLangOpts().OpenCL) |
2320 | T = deduceOpenCLPointeeAddrSpace(S&: *this, PointeeType: T); |
2321 | |
2322 | // In WebAssembly, references to reference types and tables are illegal. |
2323 | if (getASTContext().getTargetInfo().getTriple().isWasm() && |
2324 | T.isWebAssemblyReferenceType()) { |
2325 | Diag(Loc, diag::err_wasm_reference_pr) << 1; |
2326 | return QualType(); |
2327 | } |
2328 | if (T->isWebAssemblyTableType()) { |
2329 | Diag(Loc, diag::err_wasm_table_pr) << 1; |
2330 | return QualType(); |
2331 | } |
2332 | |
2333 | // Handle restrict on references. |
2334 | if (LValueRef) |
2335 | return Context.getLValueReferenceType(T, SpelledAsLValue); |
2336 | return Context.getRValueReferenceType(T); |
2337 | } |
2338 | |
2339 | /// Build a Read-only Pipe type. |
2340 | /// |
2341 | /// \param T The type to which we'll be building a Pipe. |
2342 | /// |
2343 | /// \param Loc We do not use it for now. |
2344 | /// |
2345 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a |
2346 | /// NULL type. |
2347 | QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) { |
2348 | return Context.getReadPipeType(T); |
2349 | } |
2350 | |
2351 | /// Build a Write-only Pipe type. |
2352 | /// |
2353 | /// \param T The type to which we'll be building a Pipe. |
2354 | /// |
2355 | /// \param Loc We do not use it for now. |
2356 | /// |
2357 | /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a |
2358 | /// NULL type. |
2359 | QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) { |
2360 | return Context.getWritePipeType(T); |
2361 | } |
2362 | |
2363 | /// Build a bit-precise integer type. |
2364 | /// |
2365 | /// \param IsUnsigned Boolean representing the signedness of the type. |
2366 | /// |
2367 | /// \param BitWidth Size of this int type in bits, or an expression representing |
2368 | /// that. |
2369 | /// |
2370 | /// \param Loc Location of the keyword. |
2371 | QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth, |
2372 | SourceLocation Loc) { |
2373 | if (BitWidth->isInstantiationDependent()) |
2374 | return Context.getDependentBitIntType(Unsigned: IsUnsigned, BitsExpr: BitWidth); |
2375 | |
2376 | llvm::APSInt Bits(32); |
2377 | ExprResult ICE = |
2378 | VerifyIntegerConstantExpression(E: BitWidth, Result: &Bits, /*FIXME*/ CanFold: AllowFold); |
2379 | |
2380 | if (ICE.isInvalid()) |
2381 | return QualType(); |
2382 | |
2383 | size_t NumBits = Bits.getZExtValue(); |
2384 | if (!IsUnsigned && NumBits < 2) { |
2385 | Diag(Loc, diag::err_bit_int_bad_size) << 0; |
2386 | return QualType(); |
2387 | } |
2388 | |
2389 | if (IsUnsigned && NumBits < 1) { |
2390 | Diag(Loc, diag::err_bit_int_bad_size) << 1; |
2391 | return QualType(); |
2392 | } |
2393 | |
2394 | const TargetInfo &TI = getASTContext().getTargetInfo(); |
2395 | if (NumBits > TI.getMaxBitIntWidth()) { |
2396 | Diag(Loc, diag::err_bit_int_max_size) |
2397 | << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth()); |
2398 | return QualType(); |
2399 | } |
2400 | |
2401 | return Context.getBitIntType(Unsigned: IsUnsigned, NumBits); |
2402 | } |
2403 | |
2404 | /// Check whether the specified array bound can be evaluated using the relevant |
2405 | /// language rules. If so, returns the possibly-converted expression and sets |
2406 | /// SizeVal to the size. If not, but the expression might be a VLA bound, |
2407 | /// returns ExprResult(). Otherwise, produces a diagnostic and returns |
2408 | /// ExprError(). |
2409 | static ExprResult checkArraySize(Sema &S, Expr *&ArraySize, |
2410 | llvm::APSInt &SizeVal, unsigned VLADiag, |
2411 | bool VLAIsError) { |
2412 | if (S.getLangOpts().CPlusPlus14 && |
2413 | (VLAIsError || |
2414 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) { |
2415 | // C++14 [dcl.array]p1: |
2416 | // The constant-expression shall be a converted constant expression of |
2417 | // type std::size_t. |
2418 | // |
2419 | // Don't apply this rule if we might be forming a VLA: in that case, we |
2420 | // allow non-constant expressions and constant-folding. We only need to use |
2421 | // the converted constant expression rules (to properly convert the source) |
2422 | // when the source expression is of class type. |
2423 | return S.CheckConvertedConstantExpression( |
2424 | From: ArraySize, T: S.Context.getSizeType(), Value&: SizeVal, CCE: Sema::CCEK_ArrayBound); |
2425 | } |
2426 | |
2427 | // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode |
2428 | // (like gnu99, but not c99) accept any evaluatable value as an extension. |
2429 | class VLADiagnoser : public Sema::VerifyICEDiagnoser { |
2430 | public: |
2431 | unsigned VLADiag; |
2432 | bool VLAIsError; |
2433 | bool IsVLA = false; |
2434 | |
2435 | VLADiagnoser(unsigned VLADiag, bool VLAIsError) |
2436 | : VLADiag(VLADiag), VLAIsError(VLAIsError) {} |
2437 | |
2438 | Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, |
2439 | QualType T) override { |
2440 | return S.Diag(Loc, diag::err_array_size_non_int) << T; |
2441 | } |
2442 | |
2443 | Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, |
2444 | SourceLocation Loc) override { |
2445 | IsVLA = !VLAIsError; |
2446 | return S.Diag(Loc, DiagID: VLADiag); |
2447 | } |
2448 | |
2449 | Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S, |
2450 | SourceLocation Loc) override { |
2451 | return S.Diag(Loc, diag::ext_vla_folded_to_constant); |
2452 | } |
2453 | } Diagnoser(VLADiag, VLAIsError); |
2454 | |
2455 | ExprResult R = |
2456 | S.VerifyIntegerConstantExpression(E: ArraySize, Result: &SizeVal, Diagnoser); |
2457 | if (Diagnoser.IsVLA) |
2458 | return ExprResult(); |
2459 | return R; |
2460 | } |
2461 | |
2462 | bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) { |
2463 | EltTy = Context.getBaseElementType(QT: EltTy); |
2464 | if (EltTy->isIncompleteType() || EltTy->isDependentType() || |
2465 | EltTy->isUndeducedType()) |
2466 | return true; |
2467 | |
2468 | CharUnits Size = Context.getTypeSizeInChars(T: EltTy); |
2469 | CharUnits Alignment = Context.getTypeAlignInChars(T: EltTy); |
2470 | |
2471 | if (Size.isMultipleOf(N: Alignment)) |
2472 | return true; |
2473 | |
2474 | Diag(Loc, diag::err_array_element_alignment) |
2475 | << EltTy << Size.getQuantity() << Alignment.getQuantity(); |
2476 | return false; |
2477 | } |
2478 | |
2479 | /// Build an array type. |
2480 | /// |
2481 | /// \param T The type of each element in the array. |
2482 | /// |
2483 | /// \param ASM C99 array size modifier (e.g., '*', 'static'). |
2484 | /// |
2485 | /// \param ArraySize Expression describing the size of the array. |
2486 | /// |
2487 | /// \param Brackets The range from the opening '[' to the closing ']'. |
2488 | /// |
2489 | /// \param Entity The name of the entity that involves the array |
2490 | /// type, if known. |
2491 | /// |
2492 | /// \returns A suitable array type, if there are no errors. Otherwise, |
2493 | /// returns a NULL type. |
2494 | QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM, |
2495 | Expr *ArraySize, unsigned Quals, |
2496 | SourceRange Brackets, DeclarationName Entity) { |
2497 | |
2498 | SourceLocation Loc = Brackets.getBegin(); |
2499 | if (getLangOpts().CPlusPlus) { |
2500 | // C++ [dcl.array]p1: |
2501 | // T is called the array element type; this type shall not be a reference |
2502 | // type, the (possibly cv-qualified) type void, a function type or an |
2503 | // abstract class type. |
2504 | // |
2505 | // C++ [dcl.array]p3: |
2506 | // When several "array of" specifications are adjacent, [...] only the |
2507 | // first of the constant expressions that specify the bounds of the arrays |
2508 | // may be omitted. |
2509 | // |
2510 | // Note: function types are handled in the common path with C. |
2511 | if (T->isReferenceType()) { |
2512 | Diag(Loc, diag::err_illegal_decl_array_of_references) |
2513 | << getPrintableNameForEntity(Entity) << T; |
2514 | return QualType(); |
2515 | } |
2516 | |
2517 | if (T->isVoidType() || T->isIncompleteArrayType()) { |
2518 | Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T; |
2519 | return QualType(); |
2520 | } |
2521 | |
2522 | if (RequireNonAbstractType(Brackets.getBegin(), T, |
2523 | diag::err_array_of_abstract_type)) |
2524 | return QualType(); |
2525 | |
2526 | // Mentioning a member pointer type for an array type causes us to lock in |
2527 | // an inheritance model, even if it's inside an unused typedef. |
2528 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) |
2529 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) |
2530 | if (!MPTy->getClass()->isDependentType()) |
2531 | (void)isCompleteType(Loc, T); |
2532 | |
2533 | } else { |
2534 | // C99 6.7.5.2p1: If the element type is an incomplete or function type, |
2535 | // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) |
2536 | if (!T.isWebAssemblyReferenceType() && |
2537 | RequireCompleteSizedType(Loc, T, |
2538 | diag::err_array_incomplete_or_sizeless_type)) |
2539 | return QualType(); |
2540 | } |
2541 | |
2542 | // Multi-dimensional arrays of WebAssembly references are not allowed. |
2543 | if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) { |
2544 | const auto *ATy = dyn_cast<ArrayType>(Val&: T); |
2545 | if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) { |
2546 | Diag(Loc, diag::err_wasm_reftype_multidimensional_array); |
2547 | return QualType(); |
2548 | } |
2549 | } |
2550 | |
2551 | if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) { |
2552 | Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T; |
2553 | return QualType(); |
2554 | } |
2555 | |
2556 | if (T->isFunctionType()) { |
2557 | Diag(Loc, diag::err_illegal_decl_array_of_functions) |
2558 | << getPrintableNameForEntity(Entity) << T; |
2559 | return QualType(); |
2560 | } |
2561 | |
2562 | if (const RecordType *EltTy = T->getAs<RecordType>()) { |
2563 | // If the element type is a struct or union that contains a variadic |
2564 | // array, accept it as a GNU extension: C99 6.7.2.1p2. |
2565 | if (EltTy->getDecl()->hasFlexibleArrayMember()) |
2566 | Diag(Loc, diag::ext_flexible_array_in_array) << T; |
2567 | } else if (T->isObjCObjectType()) { |
2568 | Diag(Loc, diag::err_objc_array_of_interfaces) << T; |
2569 | return QualType(); |
2570 | } |
2571 | |
2572 | if (!checkArrayElementAlignment(EltTy: T, Loc)) |
2573 | return QualType(); |
2574 | |
2575 | // Do placeholder conversions on the array size expression. |
2576 | if (ArraySize && ArraySize->hasPlaceholderType()) { |
2577 | ExprResult Result = CheckPlaceholderExpr(E: ArraySize); |
2578 | if (Result.isInvalid()) return QualType(); |
2579 | ArraySize = Result.get(); |
2580 | } |
2581 | |
2582 | // Do lvalue-to-rvalue conversions on the array size expression. |
2583 | if (ArraySize && !ArraySize->isPRValue()) { |
2584 | ExprResult Result = DefaultLvalueConversion(E: ArraySize); |
2585 | if (Result.isInvalid()) |
2586 | return QualType(); |
2587 | |
2588 | ArraySize = Result.get(); |
2589 | } |
2590 | |
2591 | // C99 6.7.5.2p1: The size expression shall have integer type. |
2592 | // C++11 allows contextual conversions to such types. |
2593 | if (!getLangOpts().CPlusPlus11 && |
2594 | ArraySize && !ArraySize->isTypeDependent() && |
2595 | !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) { |
2596 | Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int) |
2597 | << ArraySize->getType() << ArraySize->getSourceRange(); |
2598 | return QualType(); |
2599 | } |
2600 | |
2601 | auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) { |
2602 | if (!ArraySize) |
2603 | return false; |
2604 | |
2605 | // If the array size expression is a conditional expression whose branches |
2606 | // are both integer constant expressions, one negative and one positive, |
2607 | // then it's assumed to be like an old-style static assertion. e.g., |
2608 | // int old_style_assert[expr ? 1 : -1]; |
2609 | // We will accept any integer constant expressions instead of assuming the |
2610 | // values 1 and -1 are always used. |
2611 | if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>( |
2612 | Val: ArraySize->IgnoreParenImpCasts())) { |
2613 | std::optional<llvm::APSInt> LHS = |
2614 | CondExpr->getLHS()->getIntegerConstantExpr(Ctx: Context); |
2615 | std::optional<llvm::APSInt> RHS = |
2616 | CondExpr->getRHS()->getIntegerConstantExpr(Ctx: Context); |
2617 | return LHS && RHS && LHS->isNegative() != RHS->isNegative(); |
2618 | } |
2619 | return false; |
2620 | }; |
2621 | |
2622 | // VLAs always produce at least a -Wvla diagnostic, sometimes an error. |
2623 | unsigned VLADiag; |
2624 | bool VLAIsError; |
2625 | if (getLangOpts().OpenCL) { |
2626 | // OpenCL v1.2 s6.9.d: variable length arrays are not supported. |
2627 | VLADiag = diag::err_opencl_vla; |
2628 | VLAIsError = true; |
2629 | } else if (getLangOpts().C99) { |
2630 | VLADiag = diag::warn_vla_used; |
2631 | VLAIsError = false; |
2632 | } else if (isSFINAEContext()) { |
2633 | VLADiag = diag::err_vla_in_sfinae; |
2634 | VLAIsError = true; |
2635 | } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) { |
2636 | VLADiag = diag::err_openmp_vla_in_task_untied; |
2637 | VLAIsError = true; |
2638 | } else if (getLangOpts().CPlusPlus) { |
2639 | if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context)) |
2640 | VLADiag = getLangOpts().GNUMode |
2641 | ? diag::ext_vla_cxx_in_gnu_mode_static_assert |
2642 | : diag::ext_vla_cxx_static_assert; |
2643 | else |
2644 | VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode |
2645 | : diag::ext_vla_cxx; |
2646 | VLAIsError = false; |
2647 | } else { |
2648 | VLADiag = diag::ext_vla; |
2649 | VLAIsError = false; |
2650 | } |
2651 | |
2652 | llvm::APSInt ConstVal(Context.getTypeSize(T: Context.getSizeType())); |
2653 | if (!ArraySize) { |
2654 | if (ASM == ArraySizeModifier::Star) { |
2655 | Diag(Loc, DiagID: VLADiag); |
2656 | if (VLAIsError) |
2657 | return QualType(); |
2658 | |
2659 | T = Context.getVariableArrayType(EltTy: T, NumElts: nullptr, ASM, IndexTypeQuals: Quals, Brackets); |
2660 | } else { |
2661 | T = Context.getIncompleteArrayType(EltTy: T, ASM, IndexTypeQuals: Quals); |
2662 | } |
2663 | } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) { |
2664 | T = Context.getDependentSizedArrayType(EltTy: T, NumElts: ArraySize, ASM, IndexTypeQuals: Quals, Brackets); |
2665 | } else { |
2666 | ExprResult R = |
2667 | checkArraySize(S&: *this, ArraySize, SizeVal&: ConstVal, VLADiag, VLAIsError); |
2668 | if (R.isInvalid()) |
2669 | return QualType(); |
2670 | |
2671 | if (!R.isUsable()) { |
2672 | // C99: an array with a non-ICE size is a VLA. We accept any expression |
2673 | // that we can fold to a non-zero positive value as a non-VLA as an |
2674 | // extension. |
2675 | T = Context.getVariableArrayType(EltTy: T, NumElts: ArraySize, ASM, IndexTypeQuals: Quals, Brackets); |
2676 | } else if (!T->isDependentType() && !T->isIncompleteType() && |
2677 | !T->isConstantSizeType()) { |
2678 | // C99: an array with an element type that has a non-constant-size is a |
2679 | // VLA. |
2680 | // FIXME: Add a note to explain why this isn't a VLA. |
2681 | Diag(Loc, DiagID: VLADiag); |
2682 | if (VLAIsError) |
2683 | return QualType(); |
2684 | T = Context.getVariableArrayType(EltTy: T, NumElts: ArraySize, ASM, IndexTypeQuals: Quals, Brackets); |
2685 | } else { |
2686 | // C99 6.7.5.2p1: If the expression is a constant expression, it shall |
2687 | // have a value greater than zero. |
2688 | // In C++, this follows from narrowing conversions being disallowed. |
2689 | if (ConstVal.isSigned() && ConstVal.isNegative()) { |
2690 | if (Entity) |
2691 | Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size) |
2692 | << getPrintableNameForEntity(Entity) |
2693 | << ArraySize->getSourceRange(); |
2694 | else |
2695 | Diag(ArraySize->getBeginLoc(), |
2696 | diag::err_typecheck_negative_array_size) |
2697 | << ArraySize->getSourceRange(); |
2698 | return QualType(); |
2699 | } |
2700 | if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) { |
2701 | // GCC accepts zero sized static arrays. We allow them when |
2702 | // we're not in a SFINAE context. |
2703 | Diag(ArraySize->getBeginLoc(), |
2704 | isSFINAEContext() ? diag::err_typecheck_zero_array_size |
2705 | : diag::ext_typecheck_zero_array_size) |
2706 | << 0 << ArraySize->getSourceRange(); |
2707 | } |
2708 | |
2709 | // Is the array too large? |
2710 | unsigned ActiveSizeBits = |
2711 | (!T->isDependentType() && !T->isVariablyModifiedType() && |
2712 | !T->isIncompleteType() && !T->isUndeducedType()) |
2713 | ? ConstantArrayType::getNumAddressingBits(Context, ElementType: T, NumElements: ConstVal) |
2714 | : ConstVal.getActiveBits(); |
2715 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { |
2716 | Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) |
2717 | << toString(ConstVal, 10) << ArraySize->getSourceRange(); |
2718 | return QualType(); |
2719 | } |
2720 | |
2721 | T = Context.getConstantArrayType(EltTy: T, ArySize: ConstVal, SizeExpr: ArraySize, ASM, IndexTypeQuals: Quals); |
2722 | } |
2723 | } |
2724 | |
2725 | if (T->isVariableArrayType()) { |
2726 | if (!Context.getTargetInfo().isVLASupported()) { |
2727 | // CUDA device code and some other targets don't support VLAs. |
2728 | bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice); |
2729 | targetDiag(Loc, |
2730 | IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported) |
2731 | << (IsCUDADevice ? CurrentCUDATarget() : 0); |
2732 | } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) { |
2733 | // VLAs are supported on this target, but we may need to do delayed |
2734 | // checking that the VLA is not being used within a coroutine. |
2735 | FSI->setHasVLA(Loc); |
2736 | } |
2737 | } |
2738 | |
2739 | // If this is not C99, diagnose array size modifiers on non-VLAs. |
2740 | if (!getLangOpts().C99 && !T->isVariableArrayType() && |
2741 | (ASM != ArraySizeModifier::Normal || Quals != 0)) { |
2742 | Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx |
2743 | : diag::ext_c99_array_usage) |
2744 | << llvm::to_underlying(ASM); |
2745 | } |
2746 | |
2747 | // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported. |
2748 | // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported. |
2749 | // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported. |
2750 | if (getLangOpts().OpenCL) { |
2751 | const QualType ArrType = Context.getBaseElementType(QT: T); |
2752 | if (ArrType->isBlockPointerType() || ArrType->isPipeType() || |
2753 | ArrType->isSamplerT() || ArrType->isImageType()) { |
2754 | Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType; |
2755 | return QualType(); |
2756 | } |
2757 | } |
2758 | |
2759 | return T; |
2760 | } |
2761 | |
2762 | QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr, |
2763 | SourceLocation AttrLoc) { |
2764 | // The base type must be integer (not Boolean or enumeration) or float, and |
2765 | // can't already be a vector. |
2766 | if ((!CurType->isDependentType() && |
2767 | (!CurType->isBuiltinType() || CurType->isBooleanType() || |
2768 | (!CurType->isIntegerType() && !CurType->isRealFloatingType())) && |
2769 | !CurType->isBitIntType()) || |
2770 | CurType->isArrayType()) { |
2771 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType; |
2772 | return QualType(); |
2773 | } |
2774 | // Only support _BitInt elements with byte-sized power of 2 NumBits. |
2775 | if (const auto *BIT = CurType->getAs<BitIntType>()) { |
2776 | unsigned NumBits = BIT->getNumBits(); |
2777 | if (!llvm::isPowerOf2_32(Value: NumBits) || NumBits < 8) { |
2778 | Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type) |
2779 | << (NumBits < 8); |
2780 | return QualType(); |
2781 | } |
2782 | } |
2783 | |
2784 | if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent()) |
2785 | return Context.getDependentVectorType(VectorType: CurType, SizeExpr, AttrLoc, |
2786 | VecKind: VectorKind::Generic); |
2787 | |
2788 | std::optional<llvm::APSInt> VecSize = |
2789 | SizeExpr->getIntegerConstantExpr(Ctx: Context); |
2790 | if (!VecSize) { |
2791 | Diag(AttrLoc, diag::err_attribute_argument_type) |
2792 | << "vector_size" << AANT_ArgumentIntegerConstant |
2793 | << SizeExpr->getSourceRange(); |
2794 | return QualType(); |
2795 | } |
2796 | |
2797 | if (CurType->isDependentType()) |
2798 | return Context.getDependentVectorType(VectorType: CurType, SizeExpr, AttrLoc, |
2799 | VecKind: VectorKind::Generic); |
2800 | |
2801 | // vecSize is specified in bytes - convert to bits. |
2802 | if (!VecSize->isIntN(N: 61)) { |
2803 | // Bit size will overflow uint64. |
2804 | Diag(AttrLoc, diag::err_attribute_size_too_large) |
2805 | << SizeExpr->getSourceRange() << "vector" ; |
2806 | return QualType(); |
2807 | } |
2808 | uint64_t VectorSizeBits = VecSize->getZExtValue() * 8; |
2809 | unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(T: CurType)); |
2810 | |
2811 | if (VectorSizeBits == 0) { |
2812 | Diag(AttrLoc, diag::err_attribute_zero_size) |
2813 | << SizeExpr->getSourceRange() << "vector" ; |
2814 | return QualType(); |
2815 | } |
2816 | |
2817 | if (!TypeSize || VectorSizeBits % TypeSize) { |
2818 | Diag(AttrLoc, diag::err_attribute_invalid_size) |
2819 | << SizeExpr->getSourceRange(); |
2820 | return QualType(); |
2821 | } |
2822 | |
2823 | if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) { |
2824 | Diag(AttrLoc, diag::err_attribute_size_too_large) |
2825 | << SizeExpr->getSourceRange() << "vector" ; |
2826 | return QualType(); |
2827 | } |
2828 | |
2829 | return Context.getVectorType(VectorType: CurType, NumElts: VectorSizeBits / TypeSize, |
2830 | VecKind: VectorKind::Generic); |
2831 | } |
2832 | |
2833 | /// Build an ext-vector type. |
2834 | /// |
2835 | /// Run the required checks for the extended vector type. |
2836 | QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize, |
2837 | SourceLocation AttrLoc) { |
2838 | // Unlike gcc's vector_size attribute, we do not allow vectors to be defined |
2839 | // in conjunction with complex types (pointers, arrays, functions, etc.). |
2840 | // |
2841 | // Additionally, OpenCL prohibits vectors of booleans (they're considered a |
2842 | // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects |
2843 | // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors |
2844 | // of bool aren't allowed. |
2845 | // |
2846 | // We explictly allow bool elements in ext_vector_type for C/C++. |
2847 | bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus; |
2848 | if ((!T->isDependentType() && !T->isIntegerType() && |
2849 | !T->isRealFloatingType()) || |
2850 | (IsNoBoolVecLang && T->isBooleanType())) { |
2851 | Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; |
2852 | return QualType(); |
2853 | } |
2854 | |
2855 | // Only support _BitInt elements with byte-sized power of 2 NumBits. |
2856 | if (T->isBitIntType()) { |
2857 | unsigned NumBits = T->castAs<BitIntType>()->getNumBits(); |
2858 | if (!llvm::isPowerOf2_32(Value: NumBits) || NumBits < 8) { |
2859 | Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type) |
2860 | << (NumBits < 8); |
2861 | return QualType(); |
2862 | } |
2863 | } |
2864 | |
2865 | if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) { |
2866 | std::optional<llvm::APSInt> vecSize = |
2867 | ArraySize->getIntegerConstantExpr(Ctx: Context); |
2868 | if (!vecSize) { |
2869 | Diag(AttrLoc, diag::err_attribute_argument_type) |
2870 | << "ext_vector_type" << AANT_ArgumentIntegerConstant |
2871 | << ArraySize->getSourceRange(); |
2872 | return QualType(); |
2873 | } |
2874 | |
2875 | if (!vecSize->isIntN(N: 32)) { |
2876 | Diag(AttrLoc, diag::err_attribute_size_too_large) |
2877 | << ArraySize->getSourceRange() << "vector" ; |
2878 | return QualType(); |
2879 | } |
2880 | // Unlike gcc's vector_size attribute, the size is specified as the |
2881 | // number of elements, not the number of bytes. |
2882 | unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue()); |
2883 | |
2884 | if (vectorSize == 0) { |
2885 | Diag(AttrLoc, diag::err_attribute_zero_size) |
2886 | << ArraySize->getSourceRange() << "vector" ; |
2887 | return QualType(); |
2888 | } |
2889 | |
2890 | return Context.getExtVectorType(VectorType: T, NumElts: vectorSize); |
2891 | } |
2892 | |
2893 | return Context.getDependentSizedExtVectorType(VectorType: T, SizeExpr: ArraySize, AttrLoc); |
2894 | } |
2895 | |
2896 | QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols, |
2897 | SourceLocation AttrLoc) { |
2898 | assert(Context.getLangOpts().MatrixTypes && |
2899 | "Should never build a matrix type when it is disabled" ); |
2900 | |
2901 | // Check element type, if it is not dependent. |
2902 | if (!ElementTy->isDependentType() && |
2903 | !MatrixType::isValidElementType(T: ElementTy)) { |
2904 | Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy; |
2905 | return QualType(); |
2906 | } |
2907 | |
2908 | if (NumRows->isTypeDependent() || NumCols->isTypeDependent() || |
2909 | NumRows->isValueDependent() || NumCols->isValueDependent()) |
2910 | return Context.getDependentSizedMatrixType(ElementType: ElementTy, RowExpr: NumRows, ColumnExpr: NumCols, |
2911 | AttrLoc); |
2912 | |
2913 | std::optional<llvm::APSInt> ValueRows = |
2914 | NumRows->getIntegerConstantExpr(Ctx: Context); |
2915 | std::optional<llvm::APSInt> ValueColumns = |
2916 | NumCols->getIntegerConstantExpr(Ctx: Context); |
2917 | |
2918 | auto const RowRange = NumRows->getSourceRange(); |
2919 | auto const ColRange = NumCols->getSourceRange(); |
2920 | |
2921 | // Both are row and column expressions are invalid. |
2922 | if (!ValueRows && !ValueColumns) { |
2923 | Diag(AttrLoc, diag::err_attribute_argument_type) |
2924 | << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange |
2925 | << ColRange; |
2926 | return QualType(); |
2927 | } |
2928 | |
2929 | // Only the row expression is invalid. |
2930 | if (!ValueRows) { |
2931 | Diag(AttrLoc, diag::err_attribute_argument_type) |
2932 | << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange; |
2933 | return QualType(); |
2934 | } |
2935 | |
2936 | // Only the column expression is invalid. |
2937 | if (!ValueColumns) { |
2938 | Diag(AttrLoc, diag::err_attribute_argument_type) |
2939 | << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange; |
2940 | return QualType(); |
2941 | } |
2942 | |
2943 | // Check the matrix dimensions. |
2944 | unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue()); |
2945 | unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue()); |
2946 | if (MatrixRows == 0 && MatrixColumns == 0) { |
2947 | Diag(AttrLoc, diag::err_attribute_zero_size) |
2948 | << "matrix" << RowRange << ColRange; |
2949 | return QualType(); |
2950 | } |
2951 | if (MatrixRows == 0) { |
2952 | Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange; |
2953 | return QualType(); |
2954 | } |
2955 | if (MatrixColumns == 0) { |
2956 | Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange; |
2957 | return QualType(); |
2958 | } |
2959 | if (!ConstantMatrixType::isDimensionValid(NumElements: MatrixRows)) { |
2960 | Diag(AttrLoc, diag::err_attribute_size_too_large) |
2961 | << RowRange << "matrix row" ; |
2962 | return QualType(); |
2963 | } |
2964 | if (!ConstantMatrixType::isDimensionValid(NumElements: MatrixColumns)) { |
2965 | Diag(AttrLoc, diag::err_attribute_size_too_large) |
2966 | << ColRange << "matrix column" ; |
2967 | return QualType(); |
2968 | } |
2969 | return Context.getConstantMatrixType(ElementType: ElementTy, NumRows: MatrixRows, NumColumns: MatrixColumns); |
2970 | } |
2971 | |
2972 | bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) { |
2973 | if (T->isArrayType() || T->isFunctionType()) { |
2974 | Diag(Loc, diag::err_func_returning_array_function) |
2975 | << T->isFunctionType() << T; |
2976 | return true; |
2977 | } |
2978 | |
2979 | // Functions cannot return half FP. |
2980 | if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns && |
2981 | !Context.getTargetInfo().allowHalfArgsAndReturns()) { |
2982 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 << |
2983 | FixItHint::CreateInsertion(Loc, "*" ); |
2984 | return true; |
2985 | } |
2986 | |
2987 | // Methods cannot return interface types. All ObjC objects are |
2988 | // passed by reference. |
2989 | if (T->isObjCObjectType()) { |
2990 | Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) |
2991 | << 0 << T << FixItHint::CreateInsertion(Loc, "*" ); |
2992 | return true; |
2993 | } |
2994 | |
2995 | if (T.hasNonTrivialToPrimitiveDestructCUnion() || |
2996 | T.hasNonTrivialToPrimitiveCopyCUnion()) |
2997 | checkNonTrivialCUnion(QT: T, Loc, UseContext: NTCUC_FunctionReturn, |
2998 | NonTrivialKind: NTCUK_Destruct|NTCUK_Copy); |
2999 | |
3000 | // C++2a [dcl.fct]p12: |
3001 | // A volatile-qualified return type is deprecated |
3002 | if (T.isVolatileQualified() && getLangOpts().CPlusPlus20) |
3003 | Diag(Loc, diag::warn_deprecated_volatile_return) << T; |
3004 | |
3005 | if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL) |
3006 | return true; |
3007 | return false; |
3008 | } |
3009 | |
3010 | /// Check the extended parameter information. Most of the necessary |
3011 | /// checking should occur when applying the parameter attribute; the |
3012 | /// only other checks required are positional restrictions. |
3013 | static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes, |
3014 | const FunctionProtoType::ExtProtoInfo &EPI, |
3015 | llvm::function_ref<SourceLocation(unsigned)> getParamLoc) { |
3016 | assert(EPI.ExtParameterInfos && "shouldn't get here without param infos" ); |
3017 | |
3018 | bool emittedError = false; |
3019 | auto actualCC = EPI.ExtInfo.getCC(); |
3020 | enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync }; |
3021 | auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) { |
3022 | bool isCompatible = |
3023 | (required == RequiredCC::OnlySwift) |
3024 | ? (actualCC == CC_Swift) |
3025 | : (actualCC == CC_Swift || actualCC == CC_SwiftAsync); |
3026 | if (isCompatible || emittedError) |
3027 | return; |
3028 | S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall) |
3029 | << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI()) |
3030 | << (required == RequiredCC::OnlySwift); |
3031 | emittedError = true; |
3032 | }; |
3033 | for (size_t paramIndex = 0, numParams = paramTypes.size(); |
3034 | paramIndex != numParams; ++paramIndex) { |
3035 | switch (EPI.ExtParameterInfos[paramIndex].getABI()) { |
3036 | // Nothing interesting to check for orindary-ABI parameters. |
3037 | case ParameterABI::Ordinary: |
3038 | continue; |
3039 | |
3040 | // swift_indirect_result parameters must be a prefix of the function |
3041 | // arguments. |
3042 | case ParameterABI::SwiftIndirectResult: |
3043 | checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync); |
3044 | if (paramIndex != 0 && |
3045 | EPI.ExtParameterInfos[paramIndex - 1].getABI() |
3046 | != ParameterABI::SwiftIndirectResult) { |
3047 | S.Diag(getParamLoc(paramIndex), |
3048 | diag::err_swift_indirect_result_not_first); |
3049 | } |
3050 | continue; |
3051 | |
3052 | case ParameterABI::SwiftContext: |
3053 | checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync); |
3054 | continue; |
3055 | |
3056 | // SwiftAsyncContext is not limited to swiftasynccall functions. |
3057 | case ParameterABI::SwiftAsyncContext: |
3058 | continue; |
3059 | |
3060 | // swift_error parameters must be preceded by a swift_context parameter. |
3061 | case ParameterABI::SwiftErrorResult: |
3062 | checkCompatible(paramIndex, RequiredCC::OnlySwift); |
3063 | if (paramIndex == 0 || |
3064 | EPI.ExtParameterInfos[paramIndex - 1].getABI() != |
3065 | ParameterABI::SwiftContext) { |
3066 | S.Diag(getParamLoc(paramIndex), |
3067 | diag::err_swift_error_result_not_after_swift_context); |
3068 | } |
3069 | continue; |
3070 | } |
3071 | llvm_unreachable("bad ABI kind" ); |
3072 | } |
3073 | } |
3074 | |
3075 | QualType Sema::BuildFunctionType(QualType T, |
3076 | MutableArrayRef<QualType> ParamTypes, |
3077 | SourceLocation Loc, DeclarationName Entity, |
3078 | const FunctionProtoType::ExtProtoInfo &EPI) { |
3079 | bool Invalid = false; |
3080 | |
3081 | Invalid |= CheckFunctionReturnType(T, Loc); |
3082 | |
3083 | for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) { |
3084 | // FIXME: Loc is too inprecise here, should use proper locations for args. |
3085 | QualType ParamType = Context.getAdjustedParameterType(T: ParamTypes[Idx]); |
3086 | if (ParamType->isVoidType()) { |
3087 | Diag(Loc, diag::err_param_with_void_type); |
3088 | Invalid = true; |
3089 | } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns && |
3090 | !Context.getTargetInfo().allowHalfArgsAndReturns()) { |
3091 | // Disallow half FP arguments. |
3092 | Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 << |
3093 | FixItHint::CreateInsertion(Loc, "*" ); |
3094 | Invalid = true; |
3095 | } else if (ParamType->isWebAssemblyTableType()) { |
3096 | Diag(Loc, diag::err_wasm_table_as_function_parameter); |
3097 | Invalid = true; |
3098 | } |
3099 | |
3100 | // C++2a [dcl.fct]p4: |
3101 | // A parameter with volatile-qualified type is deprecated |
3102 | if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20) |
3103 | Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType; |
3104 | |
3105 | ParamTypes[Idx] = ParamType; |
3106 | } |
3107 | |
3108 | if (EPI.ExtParameterInfos) { |
3109 | checkExtParameterInfos(S&: *this, paramTypes: ParamTypes, EPI, |
3110 | getParamLoc: [=](unsigned i) { return Loc; }); |
3111 | } |
3112 | |
3113 | if (EPI.ExtInfo.getProducesResult()) { |
3114 | // This is just a warning, so we can't fail to build if we see it. |
3115 | checkNSReturnsRetainedReturnType(loc: Loc, type: T); |
3116 | } |
3117 | |
3118 | if (Invalid) |
3119 | return QualType(); |
3120 | |
3121 | return Context.getFunctionType(ResultTy: T, Args: ParamTypes, EPI); |
3122 | } |
3123 | |
3124 | /// Build a member pointer type \c T Class::*. |
3125 | /// |
3126 | /// \param T the type to which the member pointer refers. |
3127 | /// \param Class the class type into which the member pointer points. |
3128 | /// \param Loc the location where this type begins |
3129 | /// \param Entity the name of the entity that will have this member pointer type |
3130 | /// |
3131 | /// \returns a member pointer type, if successful, or a NULL type if there was |
3132 | /// an error. |
3133 | QualType Sema::BuildMemberPointerType(QualType T, QualType Class, |
3134 | SourceLocation Loc, |
3135 | DeclarationName Entity) { |
3136 | // Verify that we're not building a pointer to pointer to function with |
3137 | // exception specification. |
3138 | if (CheckDistantExceptionSpec(T)) { |
3139 | Diag(Loc, diag::err_distant_exception_spec); |
3140 | return QualType(); |
3141 | } |
3142 | |
3143 | // C++ 8.3.3p3: A pointer to member shall not point to ... a member |
3144 | // with reference type, or "cv void." |
3145 | if (T->isReferenceType()) { |
3146 | Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) |
3147 | << getPrintableNameForEntity(Entity) << T; |
3148 | return QualType(); |
3149 | } |
3150 | |
3151 | if (T->isVoidType()) { |
3152 | Diag(Loc, diag::err_illegal_decl_mempointer_to_void) |
3153 | << getPrintableNameForEntity(Entity); |
3154 | return QualType(); |
3155 | } |
3156 | |
3157 | if (!Class->isDependentType() && !Class->isRecordType()) { |
3158 | Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; |
3159 | return QualType(); |
3160 | } |
3161 | |
3162 | if (T->isFunctionType() && getLangOpts().OpenCL && |
3163 | !getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers" , |
3164 | LO: getLangOpts())) { |
3165 | Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0; |
3166 | return QualType(); |
3167 | } |
3168 | |
3169 | if (getLangOpts().HLSL && Loc.isValid()) { |
3170 | Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0; |
3171 | return QualType(); |
3172 | } |
3173 | |
3174 | // Adjust the default free function calling convention to the default method |
3175 | // calling convention. |
3176 | bool IsCtorOrDtor = |
3177 | (Entity.getNameKind() == DeclarationName::CXXConstructorName) || |
3178 | (Entity.getNameKind() == DeclarationName::CXXDestructorName); |
3179 | if (T->isFunctionType()) |
3180 | adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc); |
3181 | |
3182 | return Context.getMemberPointerType(T, Cls: Class.getTypePtr()); |
3183 | } |
3184 | |
3185 | /// Build a block pointer type. |
3186 | /// |
3187 | /// \param T The type to which we'll be building a block pointer. |
3188 | /// |
3189 | /// \param Loc The source location, used for diagnostics. |
3190 | /// |
3191 | /// \param Entity The name of the entity that involves the block pointer |
3192 | /// type, if known. |
3193 | /// |
3194 | /// \returns A suitable block pointer type, if there are no |
3195 | /// errors. Otherwise, returns a NULL type. |
3196 | QualType Sema::BuildBlockPointerType(QualType T, |
3197 | SourceLocation Loc, |
3198 | DeclarationName Entity) { |
3199 | if (!T->isFunctionType()) { |
3200 | Diag(Loc, diag::err_nonfunction_block_type); |
3201 | return QualType(); |
3202 | } |
3203 | |
3204 | if (checkQualifiedFunction(S&: *this, T, Loc, QFK: QFK_BlockPointer)) |
3205 | return QualType(); |
3206 | |
3207 | if (getLangOpts().OpenCL) |
3208 | T = deduceOpenCLPointeeAddrSpace(S&: *this, PointeeType: T); |
3209 | |
3210 | return Context.getBlockPointerType(T); |
3211 | } |
3212 | |
3213 | QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) { |
3214 | QualType QT = Ty.get(); |
3215 | if (QT.isNull()) { |
3216 | if (TInfo) *TInfo = nullptr; |
3217 | return QualType(); |
3218 | } |
3219 | |
3220 | TypeSourceInfo *DI = nullptr; |
3221 | if (const LocInfoType *LIT = dyn_cast<LocInfoType>(Val&: QT)) { |
3222 | QT = LIT->getType(); |
3223 | DI = LIT->getTypeSourceInfo(); |
3224 | } |
3225 | |
3226 | if (TInfo) *TInfo = DI; |
3227 | return QT; |
3228 | } |
3229 | |
3230 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, |
3231 | Qualifiers::ObjCLifetime ownership, |
3232 | unsigned chunkIndex); |
3233 | |
3234 | /// Given that this is the declaration of a parameter under ARC, |
3235 | /// attempt to infer attributes and such for pointer-to-whatever |
3236 | /// types. |
3237 | static void inferARCWriteback(TypeProcessingState &state, |
3238 | QualType &declSpecType) { |
3239 | Sema &S = state.getSema(); |
3240 | Declarator &declarator = state.getDeclarator(); |
3241 | |
3242 | // TODO: should we care about decl qualifiers? |
3243 | |
3244 | // Check whether the declarator has the expected form. We walk |
3245 | // from the inside out in order to make the block logic work. |
3246 | unsigned outermostPointerIndex = 0; |
3247 | bool isBlockPointer = false; |
3248 | unsigned numPointers = 0; |
3249 | for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) { |
3250 | unsigned chunkIndex = i; |
3251 | DeclaratorChunk &chunk = declarator.getTypeObject(i: chunkIndex); |
3252 | switch (chunk.Kind) { |
3253 | case DeclaratorChunk::Paren: |
3254 | // Ignore parens. |
3255 | break; |
3256 | |
3257 | case DeclaratorChunk::Reference: |
3258 | case DeclaratorChunk::Pointer: |
3259 | // Count the number of pointers. Treat references |
3260 | // interchangeably as pointers; if they're mis-ordered, normal |
3261 | // type building will discover that. |
3262 | outermostPointerIndex = chunkIndex; |
3263 | numPointers++; |
3264 | break; |
3265 | |
3266 | case DeclaratorChunk::BlockPointer: |
3267 | // If we have a pointer to block pointer, that's an acceptable |
3268 | // indirect reference; anything else is not an application of |
3269 | // the rules. |
3270 | if (numPointers != 1) return; |
3271 | numPointers++; |
3272 | outermostPointerIndex = chunkIndex; |
3273 | isBlockPointer = true; |
3274 | |
3275 | // We don't care about pointer structure in return values here. |
3276 | goto done; |
3277 | |
3278 | case DeclaratorChunk::Array: // suppress if written (id[])? |
3279 | case DeclaratorChunk::Function: |
3280 | case DeclaratorChunk::MemberPointer: |
3281 | case DeclaratorChunk::Pipe: |
3282 | return; |
3283 | } |
3284 | } |
3285 | done: |
3286 | |
3287 | // If we have *one* pointer, then we want to throw the qualifier on |
3288 | // the declaration-specifiers, which means that it needs to be a |
3289 | // retainable object type. |
3290 | if (numPointers == 1) { |
3291 | // If it's not a retainable object type, the rule doesn't apply. |
3292 | if (!declSpecType->isObjCRetainableType()) return; |
3293 | |
3294 | // If it already has lifetime, don't do anything. |
3295 | if (declSpecType.getObjCLifetime()) return; |
3296 | |
3297 | // Otherwise, modify the type in-place. |
3298 | Qualifiers qs; |
3299 | |
3300 | if (declSpecType->isObjCARCImplicitlyUnretainedType()) |
3301 | qs.addObjCLifetime(type: Qualifiers::OCL_ExplicitNone); |
3302 | else |
3303 | qs.addObjCLifetime(type: Qualifiers::OCL_Autoreleasing); |
3304 | declSpecType = S.Context.getQualifiedType(T: declSpecType, Qs: qs); |
3305 | |
3306 | // If we have *two* pointers, then we want to throw the qualifier on |
3307 | // the outermost pointer. |
3308 | } else if (numPointers == 2) { |
3309 | // If we don't have a block pointer, we need to check whether the |
3310 | // declaration-specifiers gave us something that will turn into a |
3311 | // retainable object pointer after we slap the first pointer on it. |
3312 | if (!isBlockPointer && !declSpecType->isObjCObjectType()) |
3313 | return; |
3314 | |
3315 | // Look for an explicit lifetime attribute there. |
3316 | DeclaratorChunk &chunk = declarator.getTypeObject(i: outermostPointerIndex); |
3317 | if (chunk.Kind != DeclaratorChunk::Pointer && |
3318 | chunk.Kind != DeclaratorChunk::BlockPointer) |
3319 | return; |
3320 | for (const ParsedAttr &AL : chunk.getAttrs()) |
3321 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) |
3322 | return; |
3323 | |
3324 | transferARCOwnershipToDeclaratorChunk(state, ownership: Qualifiers::OCL_Autoreleasing, |
3325 | chunkIndex: outermostPointerIndex); |
3326 | |
3327 | // Any other number of pointers/references does not trigger the rule. |
3328 | } else return; |
3329 | |
3330 | // TODO: mark whether we did this inference? |
3331 | } |
3332 | |
3333 | void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, |
3334 | SourceLocation FallbackLoc, |
3335 | SourceLocation ConstQualLoc, |
3336 | SourceLocation VolatileQualLoc, |
3337 | SourceLocation RestrictQualLoc, |
3338 | SourceLocation AtomicQualLoc, |
3339 | SourceLocation UnalignedQualLoc) { |
3340 | if (!Quals) |
3341 | return; |
3342 | |
3343 | struct Qual { |
3344 | const char *Name; |
3345 | unsigned Mask; |
3346 | SourceLocation Loc; |
3347 | } const QualKinds[5] = { |
3348 | { .Name: "const" , .Mask: DeclSpec::TQ_const, .Loc: ConstQualLoc }, |
3349 | { .Name: "volatile" , .Mask: DeclSpec::TQ_volatile, .Loc: VolatileQualLoc }, |
3350 | { .Name: "restrict" , .Mask: DeclSpec::TQ_restrict, .Loc: RestrictQualLoc }, |
3351 | { .Name: "__unaligned" , .Mask: DeclSpec::TQ_unaligned, .Loc: UnalignedQualLoc }, |
3352 | { .Name: "_Atomic" , .Mask: DeclSpec::TQ_atomic, .Loc: AtomicQualLoc } |
3353 | }; |
3354 | |
3355 | SmallString<32> QualStr; |
3356 | unsigned NumQuals = 0; |
3357 | SourceLocation Loc; |
3358 | FixItHint FixIts[5]; |
3359 | |
3360 | // Build a string naming the redundant qualifiers. |
3361 | for (auto &E : QualKinds) { |
3362 | if (Quals & E.Mask) { |
3363 | if (!QualStr.empty()) QualStr += ' '; |
3364 | QualStr += E.Name; |
3365 | |
3366 | // If we have a location for the qualifier, offer a fixit. |
3367 | SourceLocation QualLoc = E.Loc; |
3368 | if (QualLoc.isValid()) { |
3369 | FixIts[NumQuals] = FixItHint::CreateRemoval(RemoveRange: QualLoc); |
3370 | if (Loc.isInvalid() || |
3371 | getSourceManager().isBeforeInTranslationUnit(LHS: QualLoc, RHS: Loc)) |
3372 | Loc = QualLoc; |
3373 | } |
3374 | |
3375 | ++NumQuals; |
3376 | } |
3377 | } |
3378 | |
3379 | Diag(Loc: Loc.isInvalid() ? FallbackLoc : Loc, DiagID) |
3380 | << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3]; |
3381 | } |
3382 | |
3383 | // Diagnose pointless type qualifiers on the return type of a function. |
3384 | static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, |
3385 | Declarator &D, |
3386 | unsigned FunctionChunkIndex) { |
3387 | const DeclaratorChunk::FunctionTypeInfo &FTI = |
3388 | D.getTypeObject(i: FunctionChunkIndex).Fun; |
3389 | if (FTI.hasTrailingReturnType()) { |
3390 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, |
3391 | RetTy.getLocalCVRQualifiers(), |
3392 | FTI.getTrailingReturnTypeLoc()); |
3393 | return; |
3394 | } |
3395 | |
3396 | for (unsigned OuterChunkIndex = FunctionChunkIndex + 1, |
3397 | End = D.getNumTypeObjects(); |
3398 | OuterChunkIndex != End; ++OuterChunkIndex) { |
3399 | DeclaratorChunk &OuterChunk = D.getTypeObject(i: OuterChunkIndex); |
3400 | switch (OuterChunk.Kind) { |
3401 | case DeclaratorChunk::Paren: |
3402 | continue; |
3403 | |
3404 | case DeclaratorChunk::Pointer: { |
3405 | DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr; |
3406 | S.diagnoseIgnoredQualifiers( |
3407 | diag::warn_qual_return_type, |
3408 | PTI.TypeQuals, |
3409 | SourceLocation(), |
3410 | PTI.ConstQualLoc, |
3411 | PTI.VolatileQualLoc, |
3412 | PTI.RestrictQualLoc, |
3413 | PTI.AtomicQualLoc, |
3414 | PTI.UnalignedQualLoc); |
3415 | return; |
3416 | } |
3417 | |
3418 | case DeclaratorChunk::Function: |
3419 | case DeclaratorChunk::BlockPointer: |
3420 | case DeclaratorChunk::Reference: |
3421 | case DeclaratorChunk::Array: |
3422 | case DeclaratorChunk::MemberPointer: |
3423 | case DeclaratorChunk::Pipe: |
3424 | // FIXME: We can't currently provide an accurate source location and a |
3425 | // fix-it hint for these. |
3426 | unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0; |
3427 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, |
3428 | RetTy.getCVRQualifiers() | AtomicQual, |
3429 | D.getIdentifierLoc()); |
3430 | return; |
3431 | } |
3432 | |
3433 | llvm_unreachable("unknown declarator chunk kind" ); |
3434 | } |
3435 | |
3436 | // If the qualifiers come from a conversion function type, don't diagnose |
3437 | // them -- they're not necessarily redundant, since such a conversion |
3438 | // operator can be explicitly called as "x.operator const int()". |
3439 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) |
3440 | return; |
3441 | |
3442 | // Just parens all the way out to the decl specifiers. Diagnose any qualifiers |
3443 | // which are present there. |
3444 | S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type, |
3445 | D.getDeclSpec().getTypeQualifiers(), |
3446 | D.getIdentifierLoc(), |
3447 | D.getDeclSpec().getConstSpecLoc(), |
3448 | D.getDeclSpec().getVolatileSpecLoc(), |
3449 | D.getDeclSpec().getRestrictSpecLoc(), |
3450 | D.getDeclSpec().getAtomicSpecLoc(), |
3451 | D.getDeclSpec().getUnalignedSpecLoc()); |
3452 | } |
3453 | |
3454 | static std::pair<QualType, TypeSourceInfo *> |
3455 | InventTemplateParameter(TypeProcessingState &state, QualType T, |
3456 | TypeSourceInfo *TrailingTSI, AutoType *Auto, |
3457 | InventedTemplateParameterInfo &Info) { |
3458 | Sema &S = state.getSema(); |
3459 | Declarator &D = state.getDeclarator(); |
3460 | |
3461 | const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth; |
3462 | const unsigned AutoParameterPosition = Info.TemplateParams.size(); |
3463 | const bool IsParameterPack = D.hasEllipsis(); |
3464 | |
3465 | // If auto is mentioned in a lambda parameter or abbreviated function |
3466 | // template context, convert it to a template parameter type. |
3467 | |
3468 | // Create the TemplateTypeParmDecl here to retrieve the corresponding |
3469 | // template parameter type. Template parameters are temporarily added |
3470 | // to the TU until the associated TemplateDecl is created. |
3471 | TemplateTypeParmDecl *InventedTemplateParam = |
3472 | TemplateTypeParmDecl::Create( |
3473 | S.Context, S.Context.getTranslationUnitDecl(), |
3474 | /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(), |
3475 | /*NameLoc=*/D.getIdentifierLoc(), |
3476 | TemplateParameterDepth, AutoParameterPosition, |
3477 | S.InventAbbreviatedTemplateParameterTypeName( |
3478 | ParamName: D.getIdentifier(), Index: AutoParameterPosition), false, |
3479 | IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained()); |
3480 | InventedTemplateParam->setImplicit(); |
3481 | Info.TemplateParams.push_back(InventedTemplateParam); |
3482 | |
3483 | // Attach type constraints to the new parameter. |
3484 | if (Auto->isConstrained()) { |
3485 | if (TrailingTSI) { |
3486 | // The 'auto' appears in a trailing return type we've already built; |
3487 | // extract its type constraints to attach to the template parameter. |
3488 | AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc(); |
3489 | TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc()); |
3490 | bool Invalid = false; |
3491 | for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) { |
3492 | if (D.getEllipsisLoc().isInvalid() && !Invalid && |
3493 | S.DiagnoseUnexpandedParameterPack(Arg: AutoLoc.getArgLoc(i: Idx), |
3494 | UPPC: Sema::UPPC_TypeConstraint)) |
3495 | Invalid = true; |
3496 | TAL.addArgument(Loc: AutoLoc.getArgLoc(i: Idx)); |
3497 | } |
3498 | |
3499 | if (!Invalid) { |
3500 | S.AttachTypeConstraint( |
3501 | NS: AutoLoc.getNestedNameSpecifierLoc(), NameInfo: AutoLoc.getConceptNameInfo(), |
3502 | NamedConcept: AutoLoc.getNamedConcept(), |
3503 | TemplateArgs: AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr, |
3504 | ConstrainedParameter: InventedTemplateParam, EllipsisLoc: D.getEllipsisLoc()); |
3505 | } |
3506 | } else { |
3507 | // The 'auto' appears in the decl-specifiers; we've not finished forming |
3508 | // TypeSourceInfo for it yet. |
3509 | TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId(); |
3510 | TemplateArgumentListInfo TemplateArgsInfo; |
3511 | bool Invalid = false; |
3512 | if (TemplateId->LAngleLoc.isValid()) { |
3513 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
3514 | TemplateId->NumArgs); |
3515 | S.translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgsInfo); |
3516 | |
3517 | if (D.getEllipsisLoc().isInvalid()) { |
3518 | for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) { |
3519 | if (S.DiagnoseUnexpandedParameterPack(Arg, |
3520 | UPPC: Sema::UPPC_TypeConstraint)) { |
3521 | Invalid = true; |
3522 | break; |
3523 | } |
3524 | } |
3525 | } |
3526 | } |
3527 | if (!Invalid) { |
3528 | S.AttachTypeConstraint( |
3529 | NS: D.getDeclSpec().getTypeSpecScope().getWithLocInContext(Context&: S.Context), |
3530 | NameInfo: DeclarationNameInfo(DeclarationName(TemplateId->Name), |
3531 | TemplateId->TemplateNameLoc), |
3532 | NamedConcept: cast<ConceptDecl>(Val: TemplateId->Template.get().getAsTemplateDecl()), |
3533 | TemplateArgs: TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr, |
3534 | ConstrainedParameter: InventedTemplateParam, EllipsisLoc: D.getEllipsisLoc()); |
3535 | } |
3536 | } |
3537 | } |
3538 | |
3539 | // Replace the 'auto' in the function parameter with this invented |
3540 | // template type parameter. |
3541 | // FIXME: Retain some type sugar to indicate that this was written |
3542 | // as 'auto'? |
3543 | QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0); |
3544 | QualType NewT = state.ReplaceAutoType(TypeWithAuto: T, Replacement); |
3545 | TypeSourceInfo *NewTSI = |
3546 | TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TypeWithAuto: TrailingTSI, Replacement) |
3547 | : nullptr; |
3548 | return {NewT, NewTSI}; |
3549 | } |
3550 | |
3551 | static TypeSourceInfo * |
3552 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, |
3553 | QualType T, TypeSourceInfo *ReturnTypeInfo); |
3554 | |
3555 | static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, |
3556 | TypeSourceInfo *&ReturnTypeInfo) { |
3557 | Sema &SemaRef = state.getSema(); |
3558 | Declarator &D = state.getDeclarator(); |
3559 | QualType T; |
3560 | ReturnTypeInfo = nullptr; |
3561 | |
3562 | // The TagDecl owned by the DeclSpec. |
3563 | TagDecl *OwnedTagDecl = nullptr; |
3564 | |
3565 | switch (D.getName().getKind()) { |
3566 | case UnqualifiedIdKind::IK_ImplicitSelfParam: |
3567 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
3568 | case UnqualifiedIdKind::IK_Identifier: |
3569 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
3570 | case UnqualifiedIdKind::IK_TemplateId: |
3571 | T = ConvertDeclSpecToType(state); |
3572 | |
3573 | if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { |
3574 | OwnedTagDecl = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl()); |
3575 | // Owned declaration is embedded in declarator. |
3576 | OwnedTagDecl->setEmbeddedInDeclarator(true); |
3577 | } |
3578 | break; |
3579 | |
3580 | case UnqualifiedIdKind::IK_ConstructorName: |
3581 | case UnqualifiedIdKind::IK_ConstructorTemplateId: |
3582 | case UnqualifiedIdKind::IK_DestructorName: |
3583 | // Constructors and destructors don't have return types. Use |
3584 | // "void" instead. |
3585 | T = SemaRef.Context.VoidTy; |
3586 | processTypeAttrs(state, type&: T, TAL: TAL_DeclSpec, |
3587 | attrs: D.getMutableDeclSpec().getAttributes()); |
3588 | break; |
3589 | |
3590 | case UnqualifiedIdKind::IK_DeductionGuideName: |
3591 | // Deduction guides have a trailing return type and no type in their |
3592 | // decl-specifier sequence. Use a placeholder return type for now. |
3593 | T = SemaRef.Context.DependentTy; |
3594 | break; |
3595 | |
3596 | case UnqualifiedIdKind::IK_ConversionFunctionId: |
3597 | // The result type of a conversion function is the type that it |
3598 | // converts to. |
3599 | T = SemaRef.GetTypeFromParser(Ty: D.getName().ConversionFunctionId, |
3600 | TInfo: &ReturnTypeInfo); |
3601 | break; |
3602 | } |
3603 | |
3604 | // Note: We don't need to distribute declaration attributes (i.e. |
3605 | // D.getDeclarationAttributes()) because those are always C++11 attributes, |
3606 | // and those don't get distributed. |
3607 | distributeTypeAttrsFromDeclarator( |
3608 | state, declSpecType&: T, CFT: SemaRef.IdentifyCUDATarget(Attrs: D.getAttributes())); |
3609 | |
3610 | // Find the deduced type in this type. Look in the trailing return type if we |
3611 | // have one, otherwise in the DeclSpec type. |
3612 | // FIXME: The standard wording doesn't currently describe this. |
3613 | DeducedType *Deduced = T->getContainedDeducedType(); |
3614 | bool DeducedIsTrailingReturnType = false; |
3615 | if (Deduced && isa<AutoType>(Val: Deduced) && D.hasTrailingReturnType()) { |
3616 | QualType T = SemaRef.GetTypeFromParser(Ty: D.getTrailingReturnType()); |
3617 | Deduced = T.isNull() ? nullptr : T->getContainedDeducedType(); |
3618 | DeducedIsTrailingReturnType = true; |
3619 | } |
3620 | |
3621 | // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context. |
3622 | if (Deduced) { |
3623 | AutoType *Auto = dyn_cast<AutoType>(Val: Deduced); |
3624 | int Error = -1; |
3625 | |
3626 | // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or |
3627 | // class template argument deduction)? |
3628 | bool IsCXXAutoType = |
3629 | (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType); |
3630 | bool IsDeducedReturnType = false; |
3631 | |
3632 | switch (D.getContext()) { |
3633 | case DeclaratorContext::LambdaExpr: |
3634 | // Declared return type of a lambda-declarator is implicit and is always |
3635 | // 'auto'. |
3636 | break; |
3637 | case DeclaratorContext::ObjCParameter: |
3638 | case DeclaratorContext::ObjCResult: |
3639 | Error = 0; |
3640 | break; |
3641 | case DeclaratorContext::RequiresExpr: |
3642 | Error = 22; |
3643 | break; |
3644 | case DeclaratorContext::Prototype: |
3645 | case DeclaratorContext::LambdaExprParameter: { |
3646 | InventedTemplateParameterInfo *Info = nullptr; |
3647 | if (D.getContext() == DeclaratorContext::Prototype) { |
3648 | // With concepts we allow 'auto' in function parameters. |
3649 | if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto || |
3650 | Auto->getKeyword() != AutoTypeKeyword::Auto) { |
3651 | Error = 0; |
3652 | break; |
3653 | } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) { |
3654 | Error = 21; |
3655 | break; |
3656 | } |
3657 | |
3658 | Info = &SemaRef.InventedParameterInfos.back(); |
3659 | } else { |
3660 | // In C++14, generic lambdas allow 'auto' in their parameters. |
3661 | if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto || |
3662 | Auto->getKeyword() != AutoTypeKeyword::Auto) { |
3663 | Error = 16; |
3664 | break; |
3665 | } |
3666 | Info = SemaRef.getCurLambda(); |
3667 | assert(Info && "No LambdaScopeInfo on the stack!" ); |
3668 | } |
3669 | |
3670 | // We'll deal with inventing template parameters for 'auto' in trailing |
3671 | // return types when we pick up the trailing return type when processing |
3672 | // the function chunk. |
3673 | if (!DeducedIsTrailingReturnType) |
3674 | T = InventTemplateParameter(state, T, TrailingTSI: nullptr, Auto, Info&: *Info).first; |
3675 | break; |
3676 | } |
3677 | case DeclaratorContext::Member: { |
3678 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || |
3679 | D.isFunctionDeclarator()) |
3680 | break; |
3681 | bool Cxx = SemaRef.getLangOpts().CPlusPlus; |
3682 | if (isa<ObjCContainerDecl>(Val: SemaRef.CurContext)) { |
3683 | Error = 6; // Interface member. |
3684 | } else { |
3685 | switch (cast<TagDecl>(Val: SemaRef.CurContext)->getTagKind()) { |
3686 | case TagTypeKind::Enum: |
3687 | llvm_unreachable("unhandled tag kind" ); |
3688 | case TagTypeKind::Struct: |
3689 | Error = Cxx ? 1 : 2; /* Struct member */ |
3690 | break; |
3691 | case TagTypeKind::Union: |
3692 | Error = Cxx ? 3 : 4; /* Union member */ |
3693 | break; |
3694 | case TagTypeKind::Class: |
3695 | Error = 5; /* Class member */ |
3696 | break; |
3697 | case TagTypeKind::Interface: |
3698 | Error = 6; /* Interface member */ |
3699 | break; |
3700 | } |
3701 | } |
3702 | if (D.getDeclSpec().isFriendSpecified()) |
3703 | Error = 20; // Friend type |
3704 | break; |
3705 | } |
3706 | case DeclaratorContext::CXXCatch: |
3707 | case DeclaratorContext::ObjCCatch: |
3708 | Error = 7; // Exception declaration |
3709 | break; |
3710 | case DeclaratorContext::TemplateParam: |
3711 | if (isa<DeducedTemplateSpecializationType>(Val: Deduced) && |
3712 | !SemaRef.getLangOpts().CPlusPlus20) |
3713 | Error = 19; // Template parameter (until C++20) |
3714 | else if (!SemaRef.getLangOpts().CPlusPlus17) |
3715 | Error = 8; // Template parameter (until C++17) |
3716 | break; |
3717 | case DeclaratorContext::BlockLiteral: |
3718 | Error = 9; // Block literal |
3719 | break; |
3720 | case DeclaratorContext::TemplateArg: |
3721 | // Within a template argument list, a deduced template specialization |
3722 | // type will be reinterpreted as a template template argument. |
3723 | if (isa<DeducedTemplateSpecializationType>(Val: Deduced) && |
3724 | !D.getNumTypeObjects() && |
3725 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier) |
3726 | break; |
3727 | [[fallthrough]]; |
3728 | case DeclaratorContext::TemplateTypeArg: |
3729 | Error = 10; // Template type argument |
3730 | break; |
3731 | case DeclaratorContext::AliasDecl: |
3732 | case DeclaratorContext::AliasTemplate: |
3733 | Error = 12; // Type alias |
3734 | break; |
3735 | case DeclaratorContext::TrailingReturn: |
3736 | case DeclaratorContext::TrailingReturnVar: |
3737 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) |
3738 | Error = 13; // Function return type |
3739 | IsDeducedReturnType = true; |
3740 | break; |
3741 | case DeclaratorContext::ConversionId: |
3742 | if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType) |
3743 | Error = 14; // conversion-type-id |
3744 | IsDeducedReturnType = true; |
3745 | break; |
3746 | case DeclaratorContext::FunctionalCast: |
3747 | if (isa<DeducedTemplateSpecializationType>(Val: Deduced)) |
3748 | break; |
3749 | if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType && |
3750 | !Auto->isDecltypeAuto()) |
3751 | break; // auto(x) |
3752 | [[fallthrough]]; |
3753 | case DeclaratorContext::TypeName: |
3754 | case DeclaratorContext::Association: |
3755 | Error = 15; // Generic |
3756 | break; |
3757 | case DeclaratorContext::File: |
3758 | case DeclaratorContext::Block: |
3759 | case DeclaratorContext::ForInit: |
3760 | case DeclaratorContext::SelectionInit: |
3761 | case DeclaratorContext::Condition: |
3762 | // FIXME: P0091R3 (erroneously) does not permit class template argument |
3763 | // deduction in conditions, for-init-statements, and other declarations |
3764 | // that are not simple-declarations. |
3765 | break; |
3766 | case DeclaratorContext::CXXNew: |
3767 | // FIXME: P0091R3 does not permit class template argument deduction here, |
3768 | // but we follow GCC and allow it anyway. |
3769 | if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Val: Deduced)) |
3770 | Error = 17; // 'new' type |
3771 | break; |
3772 | case DeclaratorContext::KNRTypeList: |
3773 | Error = 18; // K&R function parameter |
3774 | break; |
3775 | } |
3776 | |
3777 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) |
3778 | Error = 11; |
3779 | |
3780 | // In Objective-C it is an error to use 'auto' on a function declarator |
3781 | // (and everywhere for '__auto_type'). |
3782 | if (D.isFunctionDeclarator() && |
3783 | (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType)) |
3784 | Error = 13; |
3785 | |
3786 | SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc(); |
3787 | if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId) |
3788 | AutoRange = D.getName().getSourceRange(); |
3789 | |
3790 | if (Error != -1) { |
3791 | unsigned Kind; |
3792 | if (Auto) { |
3793 | switch (Auto->getKeyword()) { |
3794 | case AutoTypeKeyword::Auto: Kind = 0; break; |
3795 | case AutoTypeKeyword::DecltypeAuto: Kind = 1; break; |
3796 | case AutoTypeKeyword::GNUAutoType: Kind = 2; break; |
3797 | } |
3798 | } else { |
3799 | assert(isa<DeducedTemplateSpecializationType>(Deduced) && |
3800 | "unknown auto type" ); |
3801 | Kind = 3; |
3802 | } |
3803 | |
3804 | auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Val: Deduced); |
3805 | TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName(); |
3806 | |
3807 | SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed) |
3808 | << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN) |
3809 | << QualType(Deduced, 0) << AutoRange; |
3810 | if (auto *TD = TN.getAsTemplateDecl()) |
3811 | SemaRef.NoteTemplateLocation(Decl: *TD); |
3812 | |
3813 | T = SemaRef.Context.IntTy; |
3814 | D.setInvalidType(true); |
3815 | } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) { |
3816 | // If there was a trailing return type, we already got |
3817 | // warn_cxx98_compat_trailing_return_type in the parser. |
3818 | SemaRef.Diag(AutoRange.getBegin(), |
3819 | D.getContext() == DeclaratorContext::LambdaExprParameter |
3820 | ? diag::warn_cxx11_compat_generic_lambda |
3821 | : IsDeducedReturnType |
3822 | ? diag::warn_cxx11_compat_deduced_return_type |
3823 | : diag::warn_cxx98_compat_auto_type_specifier) |
3824 | << AutoRange; |
3825 | } |
3826 | } |
3827 | |
3828 | if (SemaRef.getLangOpts().CPlusPlus && |
3829 | OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) { |
3830 | // Check the contexts where C++ forbids the declaration of a new class |
3831 | // or enumeration in a type-specifier-seq. |
3832 | unsigned DiagID = 0; |
3833 | switch (D.getContext()) { |
3834 | case DeclaratorContext::TrailingReturn: |
3835 | case DeclaratorContext::TrailingReturnVar: |
3836 | // Class and enumeration definitions are syntactically not allowed in |
3837 | // trailing return types. |
3838 | llvm_unreachable("parser should not have allowed this" ); |
3839 | break; |
3840 | case DeclaratorContext::File: |
3841 | case DeclaratorContext::Member: |
3842 | case DeclaratorContext::Block: |
3843 | case DeclaratorContext::ForInit: |
3844 | case DeclaratorContext::SelectionInit: |
3845 | case DeclaratorContext::BlockLiteral: |
3846 | case DeclaratorContext::LambdaExpr: |
3847 | // C++11 [dcl.type]p3: |
3848 | // A type-specifier-seq shall not define a class or enumeration unless |
3849 | // it appears in the type-id of an alias-declaration (7.1.3) that is not |
3850 | // the declaration of a template-declaration. |
3851 | case DeclaratorContext::AliasDecl: |
3852 | break; |
3853 | case DeclaratorContext::AliasTemplate: |
3854 | DiagID = diag::err_type_defined_in_alias_template; |
3855 | break; |
3856 | case DeclaratorContext::TypeName: |
3857 | case DeclaratorContext::FunctionalCast: |
3858 | case DeclaratorContext::ConversionId: |
3859 | case DeclaratorContext::TemplateParam: |
3860 | case DeclaratorContext::CXXNew: |
3861 | case DeclaratorContext::CXXCatch: |
3862 | case DeclaratorContext::ObjCCatch: |
3863 | case DeclaratorContext::TemplateArg: |
3864 | case DeclaratorContext::TemplateTypeArg: |
3865 | case DeclaratorContext::Association: |
3866 | DiagID = diag::err_type_defined_in_type_specifier; |
3867 | break; |
3868 | case DeclaratorContext::Prototype: |
3869 | case DeclaratorContext::LambdaExprParameter: |
3870 | case DeclaratorContext::ObjCParameter: |
3871 | case DeclaratorContext::ObjCResult: |
3872 | case DeclaratorContext::KNRTypeList: |
3873 | case DeclaratorContext::RequiresExpr: |
3874 | // C++ [dcl.fct]p6: |
3875 | // Types shall not be defined in return or parameter types. |
3876 | DiagID = diag::err_type_defined_in_param_type; |
3877 | break; |
3878 | case DeclaratorContext::Condition: |
3879 | // C++ 6.4p2: |
3880 | // The type-specifier-seq shall not contain typedef and shall not declare |
3881 | // a new class or enumeration. |
3882 | DiagID = diag::err_type_defined_in_condition; |
3883 | break; |
3884 | } |
3885 | |
3886 | if (DiagID != 0) { |
3887 | SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID) |
3888 | << SemaRef.Context.getTypeDeclType(OwnedTagDecl); |
3889 | D.setInvalidType(true); |
3890 | } |
3891 | } |
3892 | |
3893 | assert(!T.isNull() && "This function should not return a null type" ); |
3894 | return T; |
3895 | } |
3896 | |
3897 | /// Produce an appropriate diagnostic for an ambiguity between a function |
3898 | /// declarator and a C++ direct-initializer. |
3899 | static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, |
3900 | DeclaratorChunk &DeclType, QualType RT) { |
3901 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; |
3902 | assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity" ); |
3903 | |
3904 | // If the return type is void there is no ambiguity. |
3905 | if (RT->isVoidType()) |
3906 | return; |
3907 | |
3908 | // An initializer for a non-class type can have at most one argument. |
3909 | if (!RT->isRecordType() && FTI.NumParams > 1) |
3910 | return; |
3911 | |
3912 | // An initializer for a reference must have exactly one argument. |
3913 | if (RT->isReferenceType() && FTI.NumParams != 1) |
3914 | return; |
3915 | |
3916 | // Only warn if this declarator is declaring a function at block scope, and |
3917 | // doesn't have a storage class (such as 'extern') specified. |
3918 | if (!D.isFunctionDeclarator() || |
3919 | D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration || |
3920 | !S.CurContext->isFunctionOrMethod() || |
3921 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified) |
3922 | return; |
3923 | |
3924 | // Inside a condition, a direct initializer is not permitted. We allow one to |
3925 | // be parsed in order to give better diagnostics in condition parsing. |
3926 | if (D.getContext() == DeclaratorContext::Condition) |
3927 | return; |
3928 | |
3929 | SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc); |
3930 | |
3931 | S.Diag(DeclType.Loc, |
3932 | FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration |
3933 | : diag::warn_empty_parens_are_function_decl) |
3934 | << ParenRange; |
3935 | |
3936 | // If the declaration looks like: |
3937 | // T var1, |
3938 | // f(); |
3939 | // and name lookup finds a function named 'f', then the ',' was |
3940 | // probably intended to be a ';'. |
3941 | if (!D.isFirstDeclarator() && D.getIdentifier()) { |
3942 | FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr); |
3943 | FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr); |
3944 | if (Comma.getFileID() != Name.getFileID() || |
3945 | Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { |
3946 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), |
3947 | Sema::LookupOrdinaryName); |
3948 | if (S.LookupName(Result, S.getCurScope())) |
3949 | S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) |
3950 | << FixItHint::CreateReplacement(D.getCommaLoc(), ";" ) |
3951 | << D.getIdentifier(); |
3952 | Result.suppressDiagnostics(); |
3953 | } |
3954 | } |
3955 | |
3956 | if (FTI.NumParams > 0) { |
3957 | // For a declaration with parameters, eg. "T var(T());", suggest adding |
3958 | // parens around the first parameter to turn the declaration into a |
3959 | // variable declaration. |
3960 | SourceRange Range = FTI.Params[0].Param->getSourceRange(); |
3961 | SourceLocation B = Range.getBegin(); |
3962 | SourceLocation E = S.getLocForEndOfToken(Loc: Range.getEnd()); |
3963 | // FIXME: Maybe we should suggest adding braces instead of parens |
3964 | // in C++11 for classes that don't have an initializer_list constructor. |
3965 | S.Diag(B, diag::note_additional_parens_for_variable_declaration) |
3966 | << FixItHint::CreateInsertion(B, "(" ) |
3967 | << FixItHint::CreateInsertion(E, ")" ); |
3968 | } else { |
3969 | // For a declaration without parameters, eg. "T var();", suggest replacing |
3970 | // the parens with an initializer to turn the declaration into a variable |
3971 | // declaration. |
3972 | const CXXRecordDecl *RD = RT->getAsCXXRecordDecl(); |
3973 | |
3974 | // Empty parens mean value-initialization, and no parens mean |
3975 | // default initialization. These are equivalent if the default |
3976 | // constructor is user-provided or if zero-initialization is a |
3977 | // no-op. |
3978 | if (RD && RD->hasDefinition() && |
3979 | (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) |
3980 | S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor) |
3981 | << FixItHint::CreateRemoval(ParenRange); |
3982 | else { |
3983 | std::string Init = |
3984 | S.getFixItZeroInitializerForType(T: RT, Loc: ParenRange.getBegin()); |
3985 | if (Init.empty() && S.LangOpts.CPlusPlus11) |
3986 | Init = "{}" ; |
3987 | if (!Init.empty()) |
3988 | S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize) |
3989 | << FixItHint::CreateReplacement(ParenRange, Init); |
3990 | } |
3991 | } |
3992 | } |
3993 | |
3994 | /// Produce an appropriate diagnostic for a declarator with top-level |
3995 | /// parentheses. |
3996 | static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) { |
3997 | DeclaratorChunk &Paren = D.getTypeObject(i: D.getNumTypeObjects() - 1); |
3998 | assert(Paren.Kind == DeclaratorChunk::Paren && |
3999 | "do not have redundant top-level parentheses" ); |
4000 | |
4001 | // This is a syntactic check; we're not interested in cases that arise |
4002 | // during template instantiation. |
4003 | if (S.inTemplateInstantiation()) |
4004 | return; |
4005 | |
4006 | // Check whether this could be intended to be a construction of a temporary |
4007 | // object in C++ via a function-style cast. |
4008 | bool CouldBeTemporaryObject = |
4009 | S.getLangOpts().CPlusPlus && D.isExpressionContext() && |
4010 | !D.isInvalidType() && D.getIdentifier() && |
4011 | D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && |
4012 | (T->isRecordType() || T->isDependentType()) && |
4013 | D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator(); |
4014 | |
4015 | bool StartsWithDeclaratorId = true; |
4016 | for (auto &C : D.type_objects()) { |
4017 | switch (C.Kind) { |
4018 | case DeclaratorChunk::Paren: |
4019 | if (&C == &Paren) |
4020 | continue; |
4021 | [[fallthrough]]; |
4022 | case DeclaratorChunk::Pointer: |
4023 | StartsWithDeclaratorId = false; |
4024 | continue; |
4025 | |
4026 | case DeclaratorChunk::Array: |
4027 | if (!C.Arr.NumElts) |
4028 | CouldBeTemporaryObject = false; |
4029 | continue; |
4030 | |
4031 | case DeclaratorChunk::Reference: |
4032 | // FIXME: Suppress the warning here if there is no initializer; we're |
4033 | // going to give an error anyway. |
4034 | // We assume that something like 'T (&x) = y;' is highly likely to not |
4035 | // be intended to be a temporary object. |
4036 | CouldBeTemporaryObject = false; |
4037 | StartsWithDeclaratorId = false; |
4038 | continue; |
4039 | |
4040 | case DeclaratorChunk::Function: |
4041 | // In a new-type-id, function chunks require parentheses. |
4042 | if (D.getContext() == DeclaratorContext::CXXNew) |
4043 | return; |
4044 | // FIXME: "A(f())" deserves a vexing-parse warning, not just a |
4045 | // redundant-parens warning, but we don't know whether the function |
4046 | // chunk was syntactically valid as an expression here. |
4047 | CouldBeTemporaryObject = false; |
4048 | continue; |
4049 | |
4050 | case DeclaratorChunk::BlockPointer: |
4051 | case DeclaratorChunk::MemberPointer: |
4052 | case DeclaratorChunk::Pipe: |
4053 | // These cannot appear in expressions. |
4054 | CouldBeTemporaryObject = false; |
4055 | StartsWithDeclaratorId = false; |
4056 | continue; |
4057 | } |
4058 | } |
4059 | |
4060 | // FIXME: If there is an initializer, assume that this is not intended to be |
4061 | // a construction of a temporary object. |
4062 | |
4063 | // Check whether the name has already been declared; if not, this is not a |
4064 | // function-style cast. |
4065 | if (CouldBeTemporaryObject) { |
4066 | LookupResult Result(S, D.getIdentifier(), SourceLocation(), |
4067 | Sema::LookupOrdinaryName); |
4068 | if (!S.LookupName(R&: Result, S: S.getCurScope())) |
4069 | CouldBeTemporaryObject = false; |
4070 | Result.suppressDiagnostics(); |
4071 | } |
4072 | |
4073 | SourceRange ParenRange(Paren.Loc, Paren.EndLoc); |
4074 | |
4075 | if (!CouldBeTemporaryObject) { |
4076 | // If we have A (::B), the parentheses affect the meaning of the program. |
4077 | // Suppress the warning in that case. Don't bother looking at the DeclSpec |
4078 | // here: even (e.g.) "int ::x" is visually ambiguous even though it's |
4079 | // formally unambiguous. |
4080 | if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) { |
4081 | for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS; |
4082 | NNS = NNS->getPrefix()) { |
4083 | if (NNS->getKind() == NestedNameSpecifier::Global) |
4084 | return; |
4085 | } |
4086 | } |
4087 | |
4088 | S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator) |
4089 | << ParenRange << FixItHint::CreateRemoval(Paren.Loc) |
4090 | << FixItHint::CreateRemoval(Paren.EndLoc); |
4091 | return; |
4092 | } |
4093 | |
4094 | S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration) |
4095 | << ParenRange << D.getIdentifier(); |
4096 | auto *RD = T->getAsCXXRecordDecl(); |
4097 | if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor()) |
4098 | S.Diag(Paren.Loc, diag::note_raii_guard_add_name) |
4099 | << FixItHint::CreateInsertion(Paren.Loc, " varname" ) << T |
4100 | << D.getIdentifier(); |
4101 | // FIXME: A cast to void is probably a better suggestion in cases where it's |
4102 | // valid (when there is no initializer and we're not in a condition). |
4103 | S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses) |
4104 | << FixItHint::CreateInsertion(D.getBeginLoc(), "(" ) |
4105 | << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")" ); |
4106 | S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration) |
4107 | << FixItHint::CreateRemoval(Paren.Loc) |
4108 | << FixItHint::CreateRemoval(Paren.EndLoc); |
4109 | } |
4110 | |
4111 | /// Helper for figuring out the default CC for a function declarator type. If |
4112 | /// this is the outermost chunk, then we can determine the CC from the |
4113 | /// declarator context. If not, then this could be either a member function |
4114 | /// type or normal function type. |
4115 | static CallingConv getCCForDeclaratorChunk( |
4116 | Sema &S, Declarator &D, const ParsedAttributesView &AttrList, |
4117 | const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) { |
4118 | assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function); |
4119 | |
4120 | // Check for an explicit CC attribute. |
4121 | for (const ParsedAttr &AL : AttrList) { |
4122 | switch (AL.getKind()) { |
4123 | CALLING_CONV_ATTRS_CASELIST : { |
4124 | // Ignore attributes that don't validate or can't apply to the |
4125 | // function type. We'll diagnose the failure to apply them in |
4126 | // handleFunctionTypeAttr. |
4127 | CallingConv CC; |
4128 | if (!S.CheckCallingConvAttr(attr: AL, CC, /*FunctionDecl=*/FD: nullptr, |
4129 | CFT: S.IdentifyCUDATarget(Attrs: D.getAttributes())) && |
4130 | (!FTI.isVariadic || supportsVariadicCall(CC))) { |
4131 | return CC; |
4132 | } |
4133 | break; |
4134 | } |
4135 | |
4136 | default: |
4137 | break; |
4138 | } |
4139 | } |
4140 | |
4141 | bool IsCXXInstanceMethod = false; |
4142 | |
4143 | if (S.getLangOpts().CPlusPlus) { |
4144 | // Look inwards through parentheses to see if this chunk will form a |
4145 | // member pointer type or if we're the declarator. Any type attributes |
4146 | // between here and there will override the CC we choose here. |
4147 | unsigned I = ChunkIndex; |
4148 | bool FoundNonParen = false; |
4149 | while (I && !FoundNonParen) { |
4150 | --I; |
4151 | if (D.getTypeObject(i: I).Kind != DeclaratorChunk::Paren) |
4152 | FoundNonParen = true; |
4153 | } |
4154 | |
4155 | if (FoundNonParen) { |
4156 | // If we're not the declarator, we're a regular function type unless we're |
4157 | // in a member pointer. |
4158 | IsCXXInstanceMethod = |
4159 | D.getTypeObject(i: I).Kind == DeclaratorChunk::MemberPointer; |
4160 | } else if (D.getContext() == DeclaratorContext::LambdaExpr) { |
4161 | // This can only be a call operator for a lambda, which is an instance |
4162 | // method, unless explicitly specified as 'static'. |
4163 | IsCXXInstanceMethod = |
4164 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static; |
4165 | } else { |
4166 | // We're the innermost decl chunk, so must be a function declarator. |
4167 | assert(D.isFunctionDeclarator()); |
4168 | |
4169 | // If we're inside a record, we're declaring a method, but it could be |
4170 | // explicitly or implicitly static. |
4171 | IsCXXInstanceMethod = |
4172 | D.isFirstDeclarationOfMember() && |
4173 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && |
4174 | !D.isStaticMember(); |
4175 | } |
4176 | } |
4177 | |
4178 | CallingConv CC = S.Context.getDefaultCallingConvention(IsVariadic: FTI.isVariadic, |
4179 | IsCXXMethod: IsCXXInstanceMethod); |
4180 | |
4181 | // Attribute AT_OpenCLKernel affects the calling convention for SPIR |
4182 | // and AMDGPU targets, hence it cannot be treated as a calling |
4183 | // convention attribute. This is the simplest place to infer |
4184 | // calling convention for OpenCL kernels. |
4185 | if (S.getLangOpts().OpenCL) { |
4186 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { |
4187 | if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) { |
4188 | CC = CC_OpenCLKernel; |
4189 | break; |
4190 | } |
4191 | } |
4192 | } else if (S.getLangOpts().CUDA) { |
4193 | // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make |
4194 | // sure the kernels will be marked with the right calling convention so that |
4195 | // they will be visible by the APIs that ingest SPIR-V. |
4196 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); |
4197 | if (Triple.getArch() == llvm::Triple::spirv32 || |
4198 | Triple.getArch() == llvm::Triple::spirv64) { |
4199 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { |
4200 | if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) { |
4201 | CC = CC_OpenCLKernel; |
4202 | break; |
4203 | } |
4204 | } |
4205 | } |
4206 | } |
4207 | |
4208 | return CC; |
4209 | } |
4210 | |
4211 | namespace { |
4212 | /// A simple notion of pointer kinds, which matches up with the various |
4213 | /// pointer declarators. |
4214 | enum class SimplePointerKind { |
4215 | Pointer, |
4216 | BlockPointer, |
4217 | MemberPointer, |
4218 | Array, |
4219 | }; |
4220 | } // end anonymous namespace |
4221 | |
4222 | IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) { |
4223 | switch (nullability) { |
4224 | case NullabilityKind::NonNull: |
4225 | if (!Ident__Nonnull) |
4226 | Ident__Nonnull = PP.getIdentifierInfo(Name: "_Nonnull" ); |
4227 | return Ident__Nonnull; |
4228 | |
4229 | case NullabilityKind::Nullable: |
4230 | if (!Ident__Nullable) |
4231 | Ident__Nullable = PP.getIdentifierInfo(Name: "_Nullable" ); |
4232 | return Ident__Nullable; |
4233 | |
4234 | case NullabilityKind::NullableResult: |
4235 | if (!Ident__Nullable_result) |
4236 | Ident__Nullable_result = PP.getIdentifierInfo(Name: "_Nullable_result" ); |
4237 | return Ident__Nullable_result; |
4238 | |
4239 | case NullabilityKind::Unspecified: |
4240 | if (!Ident__Null_unspecified) |
4241 | Ident__Null_unspecified = PP.getIdentifierInfo(Name: "_Null_unspecified" ); |
4242 | return Ident__Null_unspecified; |
4243 | } |
4244 | llvm_unreachable("Unknown nullability kind." ); |
4245 | } |
4246 | |
4247 | /// Retrieve the identifier "NSError". |
4248 | IdentifierInfo *Sema::getNSErrorIdent() { |
4249 | if (!Ident_NSError) |
4250 | Ident_NSError = PP.getIdentifierInfo(Name: "NSError" ); |
4251 | |
4252 | return Ident_NSError; |
4253 | } |
4254 | |
4255 | /// Check whether there is a nullability attribute of any kind in the given |
4256 | /// attribute list. |
4257 | static bool hasNullabilityAttr(const ParsedAttributesView &attrs) { |
4258 | for (const ParsedAttr &AL : attrs) { |
4259 | if (AL.getKind() == ParsedAttr::AT_TypeNonNull || |
4260 | AL.getKind() == ParsedAttr::AT_TypeNullable || |
4261 | AL.getKind() == ParsedAttr::AT_TypeNullableResult || |
4262 | AL.getKind() == ParsedAttr::AT_TypeNullUnspecified) |
4263 | return true; |
4264 | } |
4265 | |
4266 | return false; |
4267 | } |
4268 | |
4269 | namespace { |
4270 | /// Describes the kind of a pointer a declarator describes. |
4271 | enum class PointerDeclaratorKind { |
4272 | // Not a pointer. |
4273 | NonPointer, |
4274 | // Single-level pointer. |
4275 | SingleLevelPointer, |
4276 | // Multi-level pointer (of any pointer kind). |
4277 | MultiLevelPointer, |
4278 | // CFFooRef* |
4279 | MaybePointerToCFRef, |
4280 | // CFErrorRef* |
4281 | CFErrorRefPointer, |
4282 | // NSError** |
4283 | NSErrorPointerPointer, |
4284 | }; |
4285 | |
4286 | /// Describes a declarator chunk wrapping a pointer that marks inference as |
4287 | /// unexpected. |
4288 | // These values must be kept in sync with diagnostics. |
4289 | enum class PointerWrappingDeclaratorKind { |
4290 | /// Pointer is top-level. |
4291 | None = -1, |
4292 | /// Pointer is an array element. |
4293 | Array = 0, |
4294 | /// Pointer is the referent type of a C++ reference. |
4295 | Reference = 1 |
4296 | }; |
4297 | } // end anonymous namespace |
4298 | |
4299 | /// Classify the given declarator, whose type-specified is \c type, based on |
4300 | /// what kind of pointer it refers to. |
4301 | /// |
4302 | /// This is used to determine the default nullability. |
4303 | static PointerDeclaratorKind |
4304 | classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, |
4305 | PointerWrappingDeclaratorKind &wrappingKind) { |
4306 | unsigned numNormalPointers = 0; |
4307 | |
4308 | // For any dependent type, we consider it a non-pointer. |
4309 | if (type->isDependentType()) |
4310 | return PointerDeclaratorKind::NonPointer; |
4311 | |
4312 | // Look through the declarator chunks to identify pointers. |
4313 | for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) { |
4314 | DeclaratorChunk &chunk = declarator.getTypeObject(i); |
4315 | switch (chunk.Kind) { |
4316 | case DeclaratorChunk::Array: |
4317 | if (numNormalPointers == 0) |
4318 | wrappingKind = PointerWrappingDeclaratorKind::Array; |
4319 | break; |
4320 | |
4321 | case DeclaratorChunk::Function: |
4322 | case DeclaratorChunk::Pipe: |
4323 | break; |
4324 | |
4325 | case DeclaratorChunk::BlockPointer: |
4326 | case DeclaratorChunk::MemberPointer: |
4327 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer |
4328 | : PointerDeclaratorKind::SingleLevelPointer; |
4329 | |
4330 | case DeclaratorChunk::Paren: |
4331 | break; |
4332 | |
4333 | case DeclaratorChunk::Reference: |
4334 | if (numNormalPointers == 0) |
4335 | wrappingKind = PointerWrappingDeclaratorKind::Reference; |
4336 | break; |
4337 | |
4338 | case DeclaratorChunk::Pointer: |
4339 | ++numNormalPointers; |
4340 | if (numNormalPointers > 2) |
4341 | return PointerDeclaratorKind::MultiLevelPointer; |
4342 | break; |
4343 | } |
4344 | } |
4345 | |
4346 | // Then, dig into the type specifier itself. |
4347 | unsigned numTypeSpecifierPointers = 0; |
4348 | do { |
4349 | // Decompose normal pointers. |
4350 | if (auto ptrType = type->getAs<PointerType>()) { |
4351 | ++numNormalPointers; |
4352 | |
4353 | if (numNormalPointers > 2) |
4354 | return PointerDeclaratorKind::MultiLevelPointer; |
4355 | |
4356 | type = ptrType->getPointeeType(); |
4357 | ++numTypeSpecifierPointers; |
4358 | continue; |
4359 | } |
4360 | |
4361 | // Decompose block pointers. |
4362 | if (type->getAs<BlockPointerType>()) { |
4363 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer |
4364 | : PointerDeclaratorKind::SingleLevelPointer; |
4365 | } |
4366 | |
4367 | // Decompose member pointers. |
4368 | if (type->getAs<MemberPointerType>()) { |
4369 | return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer |
4370 | : PointerDeclaratorKind::SingleLevelPointer; |
4371 | } |
4372 | |
4373 | // Look at Objective-C object pointers. |
4374 | if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) { |
4375 | ++numNormalPointers; |
4376 | ++numTypeSpecifierPointers; |
4377 | |
4378 | // If this is NSError**, report that. |
4379 | if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) { |
4380 | if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() && |
4381 | numNormalPointers == 2 && numTypeSpecifierPointers < 2) { |
4382 | return PointerDeclaratorKind::NSErrorPointerPointer; |
4383 | } |
4384 | } |
4385 | |
4386 | break; |
4387 | } |
4388 | |
4389 | // Look at Objective-C class types. |
4390 | if (auto objcClass = type->getAs<ObjCInterfaceType>()) { |
4391 | if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) { |
4392 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2) |
4393 | return PointerDeclaratorKind::NSErrorPointerPointer; |
4394 | } |
4395 | |
4396 | break; |
4397 | } |
4398 | |
4399 | // If at this point we haven't seen a pointer, we won't see one. |
4400 | if (numNormalPointers == 0) |
4401 | return PointerDeclaratorKind::NonPointer; |
4402 | |
4403 | if (auto recordType = type->getAs<RecordType>()) { |
4404 | RecordDecl *recordDecl = recordType->getDecl(); |
4405 | |
4406 | // If this is CFErrorRef*, report it as such. |
4407 | if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 && |
4408 | S.isCFError(D: recordDecl)) { |
4409 | return PointerDeclaratorKind::CFErrorRefPointer; |
4410 | } |
4411 | break; |
4412 | } |
4413 | |
4414 | break; |
4415 | } while (true); |
4416 | |
4417 | switch (numNormalPointers) { |
4418 | case 0: |
4419 | return PointerDeclaratorKind::NonPointer; |
4420 | |
4421 | case 1: |
4422 | return PointerDeclaratorKind::SingleLevelPointer; |
4423 | |
4424 | case 2: |
4425 | return PointerDeclaratorKind::MaybePointerToCFRef; |
4426 | |
4427 | default: |
4428 | return PointerDeclaratorKind::MultiLevelPointer; |
4429 | } |
4430 | } |
4431 | |
4432 | bool Sema::isCFError(RecordDecl *RD) { |
4433 | // If we already know about CFError, test it directly. |
4434 | if (CFError) |
4435 | return CFError == RD; |
4436 | |
4437 | // Check whether this is CFError, which we identify based on its bridge to |
4438 | // NSError. CFErrorRef used to be declared with "objc_bridge" but is now |
4439 | // declared with "objc_bridge_mutable", so look for either one of the two |
4440 | // attributes. |
4441 | if (RD->getTagKind() == TagTypeKind::Struct) { |
4442 | IdentifierInfo *bridgedType = nullptr; |
4443 | if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>()) |
4444 | bridgedType = bridgeAttr->getBridgedType(); |
4445 | else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>()) |
4446 | bridgedType = bridgeAttr->getBridgedType(); |
4447 | |
4448 | if (bridgedType == getNSErrorIdent()) { |
4449 | CFError = RD; |
4450 | return true; |
4451 | } |
4452 | } |
4453 | |
4454 | return false; |
4455 | } |
4456 | |
4457 | static FileID getNullabilityCompletenessCheckFileID(Sema &S, |
4458 | SourceLocation loc) { |
4459 | // If we're anywhere in a function, method, or closure context, don't perform |
4460 | // completeness checks. |
4461 | for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) { |
4462 | if (ctx->isFunctionOrMethod()) |
4463 | return FileID(); |
4464 | |
4465 | if (ctx->isFileContext()) |
4466 | break; |
4467 | } |
4468 | |
4469 | // We only care about the expansion location. |
4470 | loc = S.SourceMgr.getExpansionLoc(Loc: loc); |
4471 | FileID file = S.SourceMgr.getFileID(SpellingLoc: loc); |
4472 | if (file.isInvalid()) |
4473 | return FileID(); |
4474 | |
4475 | // Retrieve file information. |
4476 | bool invalid = false; |
4477 | const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(FID: file, Invalid: &invalid); |
4478 | if (invalid || !sloc.isFile()) |
4479 | return FileID(); |
4480 | |
4481 | // We don't want to perform completeness checks on the main file or in |
4482 | // system headers. |
4483 | const SrcMgr::FileInfo &fileInfo = sloc.getFile(); |
4484 | if (fileInfo.getIncludeLoc().isInvalid()) |
4485 | return FileID(); |
4486 | if (fileInfo.getFileCharacteristic() != SrcMgr::C_User && |
4487 | S.Diags.getSuppressSystemWarnings()) { |
4488 | return FileID(); |
4489 | } |
4490 | |
4491 | return file; |
4492 | } |
4493 | |
4494 | /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc, |
4495 | /// taking into account whitespace before and after. |
4496 | template <typename DiagBuilderT> |
4497 | static void fixItNullability(Sema &S, DiagBuilderT &Diag, |
4498 | SourceLocation PointerLoc, |
4499 | NullabilityKind Nullability) { |
4500 | assert(PointerLoc.isValid()); |
4501 | if (PointerLoc.isMacroID()) |
4502 | return; |
4503 | |
4504 | SourceLocation FixItLoc = S.getLocForEndOfToken(Loc: PointerLoc); |
4505 | if (!FixItLoc.isValid() || FixItLoc == PointerLoc) |
4506 | return; |
4507 | |
4508 | const char *NextChar = S.SourceMgr.getCharacterData(SL: FixItLoc); |
4509 | if (!NextChar) |
4510 | return; |
4511 | |
4512 | SmallString<32> InsertionTextBuf{" " }; |
4513 | InsertionTextBuf += getNullabilitySpelling(kind: Nullability); |
4514 | InsertionTextBuf += " " ; |
4515 | StringRef InsertionText = InsertionTextBuf.str(); |
4516 | |
4517 | if (isWhitespace(c: *NextChar)) { |
4518 | InsertionText = InsertionText.drop_back(); |
4519 | } else if (NextChar[-1] == '[') { |
4520 | if (NextChar[0] == ']') |
4521 | InsertionText = InsertionText.drop_back().drop_front(); |
4522 | else |
4523 | InsertionText = InsertionText.drop_front(); |
4524 | } else if (!isAsciiIdentifierContinue(c: NextChar[0], /*allow dollar*/ AllowDollar: true) && |
4525 | !isAsciiIdentifierContinue(c: NextChar[-1], /*allow dollar*/ AllowDollar: true)) { |
4526 | InsertionText = InsertionText.drop_back().drop_front(); |
4527 | } |
4528 | |
4529 | Diag << FixItHint::CreateInsertion(InsertionLoc: FixItLoc, Code: InsertionText); |
4530 | } |
4531 | |
4532 | static void emitNullabilityConsistencyWarning(Sema &S, |
4533 | SimplePointerKind PointerKind, |
4534 | SourceLocation PointerLoc, |
4535 | SourceLocation PointerEndLoc) { |
4536 | assert(PointerLoc.isValid()); |
4537 | |
4538 | if (PointerKind == SimplePointerKind::Array) { |
4539 | S.Diag(PointerLoc, diag::warn_nullability_missing_array); |
4540 | } else { |
4541 | S.Diag(PointerLoc, diag::warn_nullability_missing) |
4542 | << static_cast<unsigned>(PointerKind); |
4543 | } |
4544 | |
4545 | auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc; |
4546 | if (FixItLoc.isMacroID()) |
4547 | return; |
4548 | |
4549 | auto addFixIt = [&](NullabilityKind Nullability) { |
4550 | auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it); |
4551 | Diag << static_cast<unsigned>(Nullability); |
4552 | Diag << static_cast<unsigned>(PointerKind); |
4553 | fixItNullability(S, Diag, FixItLoc, Nullability); |
4554 | }; |
4555 | addFixIt(NullabilityKind::Nullable); |
4556 | addFixIt(NullabilityKind::NonNull); |
4557 | } |
4558 | |
4559 | /// Complains about missing nullability if the file containing \p pointerLoc |
4560 | /// has other uses of nullability (either the keywords or the \c assume_nonnull |
4561 | /// pragma). |
4562 | /// |
4563 | /// If the file has \e not seen other uses of nullability, this particular |
4564 | /// pointer is saved for possible later diagnosis. See recordNullabilitySeen(). |
4565 | static void |
4566 | checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, |
4567 | SourceLocation pointerLoc, |
4568 | SourceLocation pointerEndLoc = SourceLocation()) { |
4569 | // Determine which file we're performing consistency checking for. |
4570 | FileID file = getNullabilityCompletenessCheckFileID(S, loc: pointerLoc); |
4571 | if (file.isInvalid()) |
4572 | return; |
4573 | |
4574 | // If we haven't seen any type nullability in this file, we won't warn now |
4575 | // about anything. |
4576 | FileNullability &fileNullability = S.NullabilityMap[file]; |
4577 | if (!fileNullability.SawTypeNullability) { |
4578 | // If this is the first pointer declarator in the file, and the appropriate |
4579 | // warning is on, record it in case we need to diagnose it retroactively. |
4580 | diag::kind diagKind; |
4581 | if (pointerKind == SimplePointerKind::Array) |
4582 | diagKind = diag::warn_nullability_missing_array; |
4583 | else |
4584 | diagKind = diag::warn_nullability_missing; |
4585 | |
4586 | if (fileNullability.PointerLoc.isInvalid() && |
4587 | !S.Context.getDiagnostics().isIgnored(DiagID: diagKind, Loc: pointerLoc)) { |
4588 | fileNullability.PointerLoc = pointerLoc; |
4589 | fileNullability.PointerEndLoc = pointerEndLoc; |
4590 | fileNullability.PointerKind = static_cast<unsigned>(pointerKind); |
4591 | } |
4592 | |
4593 | return; |
4594 | } |
4595 | |
4596 | // Complain about missing nullability. |
4597 | emitNullabilityConsistencyWarning(S, PointerKind: pointerKind, PointerLoc: pointerLoc, PointerEndLoc: pointerEndLoc); |
4598 | } |
4599 | |
4600 | /// Marks that a nullability feature has been used in the file containing |
4601 | /// \p loc. |
4602 | /// |
4603 | /// If this file already had pointer types in it that were missing nullability, |
4604 | /// the first such instance is retroactively diagnosed. |
4605 | /// |
4606 | /// \sa checkNullabilityConsistency |
4607 | static void recordNullabilitySeen(Sema &S, SourceLocation loc) { |
4608 | FileID file = getNullabilityCompletenessCheckFileID(S, loc); |
4609 | if (file.isInvalid()) |
4610 | return; |
4611 | |
4612 | FileNullability &fileNullability = S.NullabilityMap[file]; |
4613 | if (fileNullability.SawTypeNullability) |
4614 | return; |
4615 | fileNullability.SawTypeNullability = true; |
4616 | |
4617 | // If we haven't seen any type nullability before, now we have. Retroactively |
4618 | // diagnose the first unannotated pointer, if there was one. |
4619 | if (fileNullability.PointerLoc.isInvalid()) |
4620 | return; |
4621 | |
4622 | auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind); |
4623 | emitNullabilityConsistencyWarning(S, PointerKind: kind, PointerLoc: fileNullability.PointerLoc, |
4624 | PointerEndLoc: fileNullability.PointerEndLoc); |
4625 | } |
4626 | |
4627 | /// Returns true if any of the declarator chunks before \p endIndex include a |
4628 | /// level of indirection: array, pointer, reference, or pointer-to-member. |
4629 | /// |
4630 | /// Because declarator chunks are stored in outer-to-inner order, testing |
4631 | /// every chunk before \p endIndex is testing all chunks that embed the current |
4632 | /// chunk as part of their type. |
4633 | /// |
4634 | /// It is legal to pass the result of Declarator::getNumTypeObjects() as the |
4635 | /// end index, in which case all chunks are tested. |
4636 | static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) { |
4637 | unsigned i = endIndex; |
4638 | while (i != 0) { |
4639 | // Walk outwards along the declarator chunks. |
4640 | --i; |
4641 | const DeclaratorChunk &DC = D.getTypeObject(i); |
4642 | switch (DC.Kind) { |
4643 | case DeclaratorChunk::Paren: |
4644 | break; |
4645 | case DeclaratorChunk::Array: |
4646 | case DeclaratorChunk::Pointer: |
4647 | case DeclaratorChunk::Reference: |
4648 | case DeclaratorChunk::MemberPointer: |
4649 | return true; |
4650 | case DeclaratorChunk::Function: |
4651 | case DeclaratorChunk::BlockPointer: |
4652 | case DeclaratorChunk::Pipe: |
4653 | // These are invalid anyway, so just ignore. |
4654 | break; |
4655 | } |
4656 | } |
4657 | return false; |
4658 | } |
4659 | |
4660 | static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) { |
4661 | return (Chunk.Kind == DeclaratorChunk::Pointer || |
4662 | Chunk.Kind == DeclaratorChunk::Array); |
4663 | } |
4664 | |
4665 | template<typename AttrT> |
4666 | static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) { |
4667 | AL.setUsedAsTypeAttr(); |
4668 | return ::new (Ctx) AttrT(Ctx, AL); |
4669 | } |
4670 | |
4671 | static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, |
4672 | NullabilityKind NK) { |
4673 | switch (NK) { |
4674 | case NullabilityKind::NonNull: |
4675 | return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr); |
4676 | |
4677 | case NullabilityKind::Nullable: |
4678 | return createSimpleAttr<TypeNullableAttr>(Ctx, Attr); |
4679 | |
4680 | case NullabilityKind::NullableResult: |
4681 | return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr); |
4682 | |
4683 | case NullabilityKind::Unspecified: |
4684 | return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr); |
4685 | } |
4686 | llvm_unreachable("unknown NullabilityKind" ); |
4687 | } |
4688 | |
4689 | // Diagnose whether this is a case with the multiple addr spaces. |
4690 | // Returns true if this is an invalid case. |
4691 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified |
4692 | // by qualifiers for two or more different address spaces." |
4693 | static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, |
4694 | LangAS ASNew, |
4695 | SourceLocation AttrLoc) { |
4696 | if (ASOld != LangAS::Default) { |
4697 | if (ASOld != ASNew) { |
4698 | S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); |
4699 | return true; |
4700 | } |
4701 | // Emit a warning if they are identical; it's likely unintended. |
4702 | S.Diag(AttrLoc, |
4703 | diag::warn_attribute_address_multiple_identical_qualifiers); |
4704 | } |
4705 | return false; |
4706 | } |
4707 | |
4708 | static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state, |
4709 | QualType declSpecType, |
4710 | TypeSourceInfo *TInfo) { |
4711 | // The TypeSourceInfo that this function returns will not be a null type. |
4712 | // If there is an error, this function will fill in a dummy type as fallback. |
4713 | QualType T = declSpecType; |
4714 | Declarator &D = state.getDeclarator(); |
4715 | Sema &S = state.getSema(); |
4716 | ASTContext &Context = S.Context; |
4717 | const LangOptions &LangOpts = S.getLangOpts(); |
4718 | |
4719 | // The name we're declaring, if any. |
4720 | DeclarationName Name; |
4721 | if (D.getIdentifier()) |
4722 | Name = D.getIdentifier(); |
4723 | |
4724 | // Does this declaration declare a typedef-name? |
4725 | bool IsTypedefName = |
4726 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef || |
4727 | D.getContext() == DeclaratorContext::AliasDecl || |
4728 | D.getContext() == DeclaratorContext::AliasTemplate; |
4729 | |
4730 | // Does T refer to a function type with a cv-qualifier or a ref-qualifier? |
4731 | bool IsQualifiedFunction = T->isFunctionProtoType() && |
4732 | (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() || |
4733 | T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None); |
4734 | |
4735 | // If T is 'decltype(auto)', the only declarators we can have are parens |
4736 | // and at most one function declarator if this is a function declaration. |
4737 | // If T is a deduced class template specialization type, we can have no |
4738 | // declarator chunks at all. |
4739 | if (auto *DT = T->getAs<DeducedType>()) { |
4740 | const AutoType *AT = T->getAs<AutoType>(); |
4741 | bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(Val: DT); |
4742 | if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) { |
4743 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { |
4744 | unsigned Index = E - I - 1; |
4745 | DeclaratorChunk &DeclChunk = D.getTypeObject(i: Index); |
4746 | unsigned DiagId = IsClassTemplateDeduction |
4747 | ? diag::err_deduced_class_template_compound_type |
4748 | : diag::err_decltype_auto_compound_type; |
4749 | unsigned DiagKind = 0; |
4750 | switch (DeclChunk.Kind) { |
4751 | case DeclaratorChunk::Paren: |
4752 | // FIXME: Rejecting this is a little silly. |
4753 | if (IsClassTemplateDeduction) { |
4754 | DiagKind = 4; |
4755 | break; |
4756 | } |
4757 | continue; |
4758 | case DeclaratorChunk::Function: { |
4759 | if (IsClassTemplateDeduction) { |
4760 | DiagKind = 3; |
4761 | break; |
4762 | } |
4763 | unsigned FnIndex; |
4764 | if (D.isFunctionDeclarationContext() && |
4765 | D.isFunctionDeclarator(idx&: FnIndex) && FnIndex == Index) |
4766 | continue; |
4767 | DiagId = diag::err_decltype_auto_function_declarator_not_declaration; |
4768 | break; |
4769 | } |
4770 | case DeclaratorChunk::Pointer: |
4771 | case DeclaratorChunk::BlockPointer: |
4772 | case DeclaratorChunk::MemberPointer: |
4773 | DiagKind = 0; |
4774 | break; |
4775 | case DeclaratorChunk::Reference: |
4776 | DiagKind = 1; |
4777 | break; |
4778 | case DeclaratorChunk::Array: |
4779 | DiagKind = 2; |
4780 | break; |
4781 | case DeclaratorChunk::Pipe: |
4782 | break; |
4783 | } |
4784 | |
4785 | S.Diag(Loc: DeclChunk.Loc, DiagID: DiagId) << DiagKind; |
4786 | D.setInvalidType(true); |
4787 | break; |
4788 | } |
4789 | } |
4790 | } |
4791 | |
4792 | // Determine whether we should infer _Nonnull on pointer types. |
4793 | std::optional<NullabilityKind> inferNullability; |
4794 | bool inferNullabilityCS = false; |
4795 | bool inferNullabilityInnerOnly = false; |
4796 | bool inferNullabilityInnerOnlyComplete = false; |
4797 | |
4798 | // Are we in an assume-nonnull region? |
4799 | bool inAssumeNonNullRegion = false; |
4800 | SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc(); |
4801 | if (assumeNonNullLoc.isValid()) { |
4802 | inAssumeNonNullRegion = true; |
4803 | recordNullabilitySeen(S, loc: assumeNonNullLoc); |
4804 | } |
4805 | |
4806 | // Whether to complain about missing nullability specifiers or not. |
4807 | enum { |
4808 | /// Never complain. |
4809 | CAMN_No, |
4810 | /// Complain on the inner pointers (but not the outermost |
4811 | /// pointer). |
4812 | CAMN_InnerPointers, |
4813 | /// Complain about any pointers that don't have nullability |
4814 | /// specified or inferred. |
4815 | CAMN_Yes |
4816 | } complainAboutMissingNullability = CAMN_No; |
4817 | unsigned NumPointersRemaining = 0; |
4818 | auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None; |
4819 | |
4820 | if (IsTypedefName) { |
4821 | // For typedefs, we do not infer any nullability (the default), |
4822 | // and we only complain about missing nullability specifiers on |
4823 | // inner pointers. |
4824 | complainAboutMissingNullability = CAMN_InnerPointers; |
4825 | |
4826 | if (T->canHaveNullability(/*ResultIfUnknown*/ false) && |
4827 | !T->getNullability()) { |
4828 | // Note that we allow but don't require nullability on dependent types. |
4829 | ++NumPointersRemaining; |
4830 | } |
4831 | |
4832 | for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) { |
4833 | DeclaratorChunk &chunk = D.getTypeObject(i); |
4834 | switch (chunk.Kind) { |
4835 | case DeclaratorChunk::Array: |
4836 | case DeclaratorChunk::Function: |
4837 | case DeclaratorChunk::Pipe: |
4838 | break; |
4839 | |
4840 | case DeclaratorChunk::BlockPointer: |
4841 | case DeclaratorChunk::MemberPointer: |
4842 | ++NumPointersRemaining; |
4843 | break; |
4844 | |
4845 | case DeclaratorChunk::Paren: |
4846 | case DeclaratorChunk::Reference: |
4847 | continue; |
4848 | |
4849 | case DeclaratorChunk::Pointer: |
4850 | ++NumPointersRemaining; |
4851 | continue; |
4852 | } |
4853 | } |
4854 | } else { |
4855 | bool isFunctionOrMethod = false; |
4856 | switch (auto context = state.getDeclarator().getContext()) { |
4857 | case DeclaratorContext::ObjCParameter: |
4858 | case DeclaratorContext::ObjCResult: |
4859 | case DeclaratorContext::Prototype: |
4860 | case DeclaratorContext::TrailingReturn: |
4861 | case DeclaratorContext::TrailingReturnVar: |
4862 | isFunctionOrMethod = true; |
4863 | [[fallthrough]]; |
4864 | |
4865 | case DeclaratorContext::Member: |
4866 | if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) { |
4867 | complainAboutMissingNullability = CAMN_No; |
4868 | break; |
4869 | } |
4870 | |
4871 | // Weak properties are inferred to be nullable. |
4872 | if (state.getDeclarator().isObjCWeakProperty()) { |
4873 | // Weak properties cannot be nonnull, and should not complain about |
4874 | // missing nullable attributes during completeness checks. |
4875 | complainAboutMissingNullability = CAMN_No; |
4876 | if (inAssumeNonNullRegion) { |
4877 | inferNullability = NullabilityKind::Nullable; |
4878 | } |
4879 | break; |
4880 | } |
4881 | |
4882 | [[fallthrough]]; |
4883 | |
4884 | case DeclaratorContext::File: |
4885 | case DeclaratorContext::KNRTypeList: { |
4886 | complainAboutMissingNullability = CAMN_Yes; |
4887 | |
4888 | // Nullability inference depends on the type and declarator. |
4889 | auto wrappingKind = PointerWrappingDeclaratorKind::None; |
4890 | switch (classifyPointerDeclarator(S, type: T, declarator&: D, wrappingKind)) { |
4891 | case PointerDeclaratorKind::NonPointer: |
4892 | case PointerDeclaratorKind::MultiLevelPointer: |
4893 | // Cannot infer nullability. |
4894 | break; |
4895 | |
4896 | case PointerDeclaratorKind::SingleLevelPointer: |
4897 | // Infer _Nonnull if we are in an assumes-nonnull region. |
4898 | if (inAssumeNonNullRegion) { |
4899 | complainAboutInferringWithinChunk = wrappingKind; |
4900 | inferNullability = NullabilityKind::NonNull; |
4901 | inferNullabilityCS = (context == DeclaratorContext::ObjCParameter || |
4902 | context == DeclaratorContext::ObjCResult); |
4903 | } |
4904 | break; |
4905 | |
4906 | case PointerDeclaratorKind::CFErrorRefPointer: |
4907 | case PointerDeclaratorKind::NSErrorPointerPointer: |
4908 | // Within a function or method signature, infer _Nullable at both |
4909 | // levels. |
4910 | if (isFunctionOrMethod && inAssumeNonNullRegion) |
4911 | inferNullability = NullabilityKind::Nullable; |
4912 | break; |
4913 | |
4914 | case PointerDeclaratorKind::MaybePointerToCFRef: |
4915 | if (isFunctionOrMethod) { |
4916 | // On pointer-to-pointer parameters marked cf_returns_retained or |
4917 | // cf_returns_not_retained, if the outer pointer is explicit then |
4918 | // infer the inner pointer as _Nullable. |
4919 | auto hasCFReturnsAttr = |
4920 | [](const ParsedAttributesView &AttrList) -> bool { |
4921 | return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) || |
4922 | AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained); |
4923 | }; |
4924 | if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) { |
4925 | if (hasCFReturnsAttr(D.getDeclarationAttributes()) || |
4926 | hasCFReturnsAttr(D.getAttributes()) || |
4927 | hasCFReturnsAttr(InnermostChunk->getAttrs()) || |
4928 | hasCFReturnsAttr(D.getDeclSpec().getAttributes())) { |
4929 | inferNullability = NullabilityKind::Nullable; |
4930 | inferNullabilityInnerOnly = true; |
4931 | } |
4932 | } |
4933 | } |
4934 | break; |
4935 | } |
4936 | break; |
4937 | } |
4938 | |
4939 | case DeclaratorContext::ConversionId: |
4940 | complainAboutMissingNullability = CAMN_Yes; |
4941 | break; |
4942 | |
4943 | case DeclaratorContext::AliasDecl: |
4944 | case DeclaratorContext::AliasTemplate: |
4945 | case DeclaratorContext::Block: |
4946 | case DeclaratorContext::BlockLiteral: |
4947 | case DeclaratorContext::Condition: |
4948 | case DeclaratorContext::CXXCatch: |
4949 | case DeclaratorContext::CXXNew: |
4950 | case DeclaratorContext::ForInit: |
4951 | case DeclaratorContext::SelectionInit: |
4952 | case DeclaratorContext::LambdaExpr: |
4953 | case DeclaratorContext::LambdaExprParameter: |
4954 | case DeclaratorContext::ObjCCatch: |
4955 | case DeclaratorContext::TemplateParam: |
4956 | case DeclaratorContext::TemplateArg: |
4957 | case DeclaratorContext::TemplateTypeArg: |
4958 | case DeclaratorContext::TypeName: |
4959 | case DeclaratorContext::FunctionalCast: |
4960 | case DeclaratorContext::RequiresExpr: |
4961 | case DeclaratorContext::Association: |
4962 | // Don't infer in these contexts. |
4963 | break; |
4964 | } |
4965 | } |
4966 | |
4967 | // Local function that returns true if its argument looks like a va_list. |
4968 | auto isVaList = [&S](QualType T) -> bool { |
4969 | auto *typedefTy = T->getAs<TypedefType>(); |
4970 | if (!typedefTy) |
4971 | return false; |
4972 | TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl(); |
4973 | do { |
4974 | if (typedefTy->getDecl() == vaListTypedef) |
4975 | return true; |
4976 | if (auto *name = typedefTy->getDecl()->getIdentifier()) |
4977 | if (name->isStr("va_list" )) |
4978 | return true; |
4979 | typedefTy = typedefTy->desugar()->getAs<TypedefType>(); |
4980 | } while (typedefTy); |
4981 | return false; |
4982 | }; |
4983 | |
4984 | // Local function that checks the nullability for a given pointer declarator. |
4985 | // Returns true if _Nonnull was inferred. |
4986 | auto inferPointerNullability = |
4987 | [&](SimplePointerKind pointerKind, SourceLocation pointerLoc, |
4988 | SourceLocation pointerEndLoc, |
4989 | ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * { |
4990 | // We've seen a pointer. |
4991 | if (NumPointersRemaining > 0) |
4992 | --NumPointersRemaining; |
4993 | |
4994 | // If a nullability attribute is present, there's nothing to do. |
4995 | if (hasNullabilityAttr(attrs)) |
4996 | return nullptr; |
4997 | |
4998 | // If we're supposed to infer nullability, do so now. |
4999 | if (inferNullability && !inferNullabilityInnerOnlyComplete) { |
5000 | ParsedAttr::Form form = |
5001 | inferNullabilityCS |
5002 | ? ParsedAttr::Form::ContextSensitiveKeyword() |
5003 | : ParsedAttr::Form::Keyword(IsAlignas: false /*IsAlignAs*/, |
5004 | IsRegularKeywordAttribute: false /*IsRegularKeywordAttribute*/); |
5005 | ParsedAttr *nullabilityAttr = Pool.create( |
5006 | attrName: S.getNullabilityKeyword(nullability: *inferNullability), attrRange: SourceRange(pointerLoc), |
5007 | scopeName: nullptr, scopeLoc: SourceLocation(), args: nullptr, numArgs: 0, form); |
5008 | |
5009 | attrs.addAtEnd(newAttr: nullabilityAttr); |
5010 | |
5011 | if (inferNullabilityCS) { |
5012 | state.getDeclarator().getMutableDeclSpec().getObjCQualifiers() |
5013 | ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability); |
5014 | } |
5015 | |
5016 | if (pointerLoc.isValid() && |
5017 | complainAboutInferringWithinChunk != |
5018 | PointerWrappingDeclaratorKind::None) { |
5019 | auto Diag = |
5020 | S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type); |
5021 | Diag << static_cast<int>(complainAboutInferringWithinChunk); |
5022 | fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull); |
5023 | } |
5024 | |
5025 | if (inferNullabilityInnerOnly) |
5026 | inferNullabilityInnerOnlyComplete = true; |
5027 | return nullabilityAttr; |
5028 | } |
5029 | |
5030 | // If we're supposed to complain about missing nullability, do so |
5031 | // now if it's truly missing. |
5032 | switch (complainAboutMissingNullability) { |
5033 | case CAMN_No: |
5034 | break; |
5035 | |
5036 | case CAMN_InnerPointers: |
5037 | if (NumPointersRemaining == 0) |
5038 | break; |
5039 | [[fallthrough]]; |
5040 | |
5041 | case CAMN_Yes: |
5042 | checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc); |
5043 | } |
5044 | return nullptr; |
5045 | }; |
5046 | |
5047 | // If the type itself could have nullability but does not, infer pointer |
5048 | // nullability and perform consistency checking. |
5049 | if (S.CodeSynthesisContexts.empty()) { |
5050 | if (T->canHaveNullability(/*ResultIfUnknown*/ false) && |
5051 | !T->getNullability()) { |
5052 | if (isVaList(T)) { |
5053 | // Record that we've seen a pointer, but do nothing else. |
5054 | if (NumPointersRemaining > 0) |
5055 | --NumPointersRemaining; |
5056 | } else { |
5057 | SimplePointerKind pointerKind = SimplePointerKind::Pointer; |
5058 | if (T->isBlockPointerType()) |
5059 | pointerKind = SimplePointerKind::BlockPointer; |
5060 | else if (T->isMemberPointerType()) |
5061 | pointerKind = SimplePointerKind::MemberPointer; |
5062 | |
5063 | if (auto *attr = inferPointerNullability( |
5064 | pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(), |
5065 | D.getDeclSpec().getEndLoc(), |
5066 | D.getMutableDeclSpec().getAttributes(), |
5067 | D.getMutableDeclSpec().getAttributePool())) { |
5068 | T = state.getAttributedType( |
5069 | A: createNullabilityAttr(Ctx&: Context, Attr&: *attr, NK: *inferNullability), ModifiedType: T, EquivType: T); |
5070 | } |
5071 | } |
5072 | } |
5073 | |
5074 | if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() && |
5075 | !T->getNullability() && !isVaList(T) && D.isPrototypeContext() && |
5076 | !hasOuterPointerLikeChunk(D, endIndex: D.getNumTypeObjects())) { |
5077 | checkNullabilityConsistency(S, pointerKind: SimplePointerKind::Array, |
5078 | pointerLoc: D.getDeclSpec().getTypeSpecTypeLoc()); |
5079 | } |
5080 | } |
5081 | |
5082 | bool ExpectNoDerefChunk = |
5083 | state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref); |
5084 | |
5085 | // Walk the DeclTypeInfo, building the recursive type as we go. |
5086 | // DeclTypeInfos are ordered from the identifier out, which is |
5087 | // opposite of what we want :). |
5088 | |
5089 | // Track if the produced type matches the structure of the declarator. |
5090 | // This is used later to decide if we can fill `TypeLoc` from |
5091 | // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from |
5092 | // an error by replacing the type with `int`. |
5093 | bool AreDeclaratorChunksValid = true; |
5094 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { |
5095 | unsigned chunkIndex = e - i - 1; |
5096 | state.setCurrentChunkIndex(chunkIndex); |
5097 | DeclaratorChunk &DeclType = D.getTypeObject(i: chunkIndex); |
5098 | IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren; |
5099 | switch (DeclType.Kind) { |
5100 | case DeclaratorChunk::Paren: |
5101 | if (i == 0) |
5102 | warnAboutRedundantParens(S, D, T); |
5103 | T = S.BuildParenType(T); |
5104 | break; |
5105 | case DeclaratorChunk::BlockPointer: |
5106 | // If blocks are disabled, emit an error. |
5107 | if (!LangOpts.Blocks) |
5108 | S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL; |
5109 | |
5110 | // Handle pointer nullability. |
5111 | inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc, |
5112 | DeclType.EndLoc, DeclType.getAttrs(), |
5113 | state.getDeclarator().getAttributePool()); |
5114 | |
5115 | T = S.BuildBlockPointerType(T, Loc: D.getIdentifierLoc(), Entity: Name); |
5116 | if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) { |
5117 | // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly |
5118 | // qualified with const. |
5119 | if (LangOpts.OpenCL) |
5120 | DeclType.Cls.TypeQuals |= DeclSpec::TQ_const; |
5121 | T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Cls.TypeQuals); |
5122 | } |
5123 | break; |
5124 | case DeclaratorChunk::Pointer: |
5125 | // Verify that we're not building a pointer to pointer to function with |
5126 | // exception specification. |
5127 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { |
5128 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); |
5129 | D.setInvalidType(true); |
5130 | // Build the type anyway. |
5131 | } |
5132 | |
5133 | // Handle pointer nullability |
5134 | inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc, |
5135 | DeclType.EndLoc, DeclType.getAttrs(), |
5136 | state.getDeclarator().getAttributePool()); |
5137 | |
5138 | if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) { |
5139 | T = Context.getObjCObjectPointerType(OIT: T); |
5140 | if (DeclType.Ptr.TypeQuals) |
5141 | T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Ptr.TypeQuals); |
5142 | break; |
5143 | } |
5144 | |
5145 | // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used. |
5146 | // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used. |
5147 | // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed. |
5148 | if (LangOpts.OpenCL) { |
5149 | if (T->isImageType() || T->isSamplerT() || T->isPipeType() || |
5150 | T->isBlockPointerType()) { |
5151 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T; |
5152 | D.setInvalidType(true); |
5153 | } |
5154 | } |
5155 | |
5156 | T = S.BuildPointerType(T, Loc: DeclType.Loc, Entity: Name); |
5157 | if (DeclType.Ptr.TypeQuals) |
5158 | T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Ptr.TypeQuals); |
5159 | break; |
5160 | case DeclaratorChunk::Reference: { |
5161 | // Verify that we're not building a reference to pointer to function with |
5162 | // exception specification. |
5163 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { |
5164 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); |
5165 | D.setInvalidType(true); |
5166 | // Build the type anyway. |
5167 | } |
5168 | T = S.BuildReferenceType(T, SpelledAsLValue: DeclType.Ref.LValueRef, Loc: DeclType.Loc, Entity: Name); |
5169 | |
5170 | if (DeclType.Ref.HasRestrict) |
5171 | T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: Qualifiers::Restrict); |
5172 | break; |
5173 | } |
5174 | case DeclaratorChunk::Array: { |
5175 | // Verify that we're not building an array of pointers to function with |
5176 | // exception specification. |
5177 | if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) { |
5178 | S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); |
5179 | D.setInvalidType(true); |
5180 | // Build the type anyway. |
5181 | } |
5182 | DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; |
5183 | Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); |
5184 | ArraySizeModifier ASM; |
5185 | |
5186 | // Microsoft property fields can have multiple sizeless array chunks |
5187 | // (i.e. int x[][][]). Skip all of these except one to avoid creating |
5188 | // bad incomplete array types. |
5189 | if (chunkIndex != 0 && !ArraySize && |
5190 | D.getDeclSpec().getAttributes().hasMSPropertyAttr()) { |
5191 | // This is a sizeless chunk. If the next is also, skip this one. |
5192 | DeclaratorChunk &NextDeclType = D.getTypeObject(i: chunkIndex - 1); |
5193 | if (NextDeclType.Kind == DeclaratorChunk::Array && |
5194 | !NextDeclType.Arr.NumElts) |
5195 | break; |
5196 | } |
5197 | |
5198 | if (ATI.isStar) |
5199 | ASM = ArraySizeModifier::Star; |
5200 | else if (ATI.hasStatic) |
5201 | ASM = ArraySizeModifier::Static; |
5202 | else |
5203 | ASM = ArraySizeModifier::Normal; |
5204 | if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) { |
5205 | // FIXME: This check isn't quite right: it allows star in prototypes |
5206 | // for function definitions, and disallows some edge cases detailed |
5207 | // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html |
5208 | S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype); |
5209 | ASM = ArraySizeModifier::Normal; |
5210 | D.setInvalidType(true); |
5211 | } |
5212 | |
5213 | // C99 6.7.5.2p1: The optional type qualifiers and the keyword static |
5214 | // shall appear only in a declaration of a function parameter with an |
5215 | // array type, ... |
5216 | if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) { |
5217 | if (!(D.isPrototypeContext() || |
5218 | D.getContext() == DeclaratorContext::KNRTypeList)) { |
5219 | S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) |
5220 | << (ASM == ArraySizeModifier::Static ? "'static'" |
5221 | : "type qualifier" ); |
5222 | // Remove the 'static' and the type qualifiers. |
5223 | if (ASM == ArraySizeModifier::Static) |
5224 | ASM = ArraySizeModifier::Normal; |
5225 | ATI.TypeQuals = 0; |
5226 | D.setInvalidType(true); |
5227 | } |
5228 | |
5229 | // C99 6.7.5.2p1: ... and then only in the outermost array type |
5230 | // derivation. |
5231 | if (hasOuterPointerLikeChunk(D, endIndex: chunkIndex)) { |
5232 | S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) |
5233 | << (ASM == ArraySizeModifier::Static ? "'static'" |
5234 | : "type qualifier" ); |
5235 | if (ASM == ArraySizeModifier::Static) |
5236 | ASM = ArraySizeModifier::Normal; |
5237 | ATI.TypeQuals = 0; |
5238 | D.setInvalidType(true); |
5239 | } |
5240 | } |
5241 | |
5242 | // Array parameters can be marked nullable as well, although it's not |
5243 | // necessary if they're marked 'static'. |
5244 | if (complainAboutMissingNullability == CAMN_Yes && |
5245 | !hasNullabilityAttr(attrs: DeclType.getAttrs()) && |
5246 | ASM != ArraySizeModifier::Static && D.isPrototypeContext() && |
5247 | !hasOuterPointerLikeChunk(D, endIndex: chunkIndex)) { |
5248 | checkNullabilityConsistency(S, pointerKind: SimplePointerKind::Array, pointerLoc: DeclType.Loc); |
5249 | } |
5250 | |
5251 | T = S.BuildArrayType(T, ASM, ArraySize, Quals: ATI.TypeQuals, |
5252 | Brackets: SourceRange(DeclType.Loc, DeclType.EndLoc), Entity: Name); |
5253 | break; |
5254 | } |
5255 | case DeclaratorChunk::Function: { |
5256 | // If the function declarator has a prototype (i.e. it is not () and |
5257 | // does not have a K&R-style identifier list), then the arguments are part |
5258 | // of the type, otherwise the argument list is (). |
5259 | DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; |
5260 | IsQualifiedFunction = |
5261 | FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier(); |
5262 | |
5263 | // Check for auto functions and trailing return type and adjust the |
5264 | // return type accordingly. |
5265 | if (!D.isInvalidType()) { |
5266 | // trailing-return-type is only required if we're declaring a function, |
5267 | // and not, for instance, a pointer to a function. |
5268 | if (D.getDeclSpec().hasAutoTypeSpec() && |
5269 | !FTI.hasTrailingReturnType() && chunkIndex == 0) { |
5270 | if (!S.getLangOpts().CPlusPlus14) { |
5271 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), |
5272 | D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto |
5273 | ? diag::err_auto_missing_trailing_return |
5274 | : diag::err_deduced_return_type); |
5275 | T = Context.IntTy; |
5276 | D.setInvalidType(true); |
5277 | AreDeclaratorChunksValid = false; |
5278 | } else { |
5279 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), |
5280 | diag::warn_cxx11_compat_deduced_return_type); |
5281 | } |
5282 | } else if (FTI.hasTrailingReturnType()) { |
5283 | // T must be exactly 'auto' at this point. See CWG issue 681. |
5284 | if (isa<ParenType>(Val: T)) { |
5285 | S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens) |
5286 | << T << D.getSourceRange(); |
5287 | D.setInvalidType(true); |
5288 | // FIXME: recover and fill decls in `TypeLoc`s. |
5289 | AreDeclaratorChunksValid = false; |
5290 | } else if (D.getName().getKind() == |
5291 | UnqualifiedIdKind::IK_DeductionGuideName) { |
5292 | if (T != Context.DependentTy) { |
5293 | S.Diag(D.getDeclSpec().getBeginLoc(), |
5294 | diag::err_deduction_guide_with_complex_decl) |
5295 | << D.getSourceRange(); |
5296 | D.setInvalidType(true); |
5297 | // FIXME: recover and fill decls in `TypeLoc`s. |
5298 | AreDeclaratorChunksValid = false; |
5299 | } |
5300 | } else if (D.getContext() != DeclaratorContext::LambdaExpr && |
5301 | (T.hasQualifiers() || !isa<AutoType>(Val: T) || |
5302 | cast<AutoType>(Val&: T)->getKeyword() != |
5303 | AutoTypeKeyword::Auto || |
5304 | cast<AutoType>(Val&: T)->isConstrained())) { |
5305 | S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(), |
5306 | diag::err_trailing_return_without_auto) |
5307 | << T << D.getDeclSpec().getSourceRange(); |
5308 | D.setInvalidType(true); |
5309 | // FIXME: recover and fill decls in `TypeLoc`s. |
5310 | AreDeclaratorChunksValid = false; |
5311 | } |
5312 | T = S.GetTypeFromParser(Ty: FTI.getTrailingReturnType(), TInfo: &TInfo); |
5313 | if (T.isNull()) { |
5314 | // An error occurred parsing the trailing return type. |
5315 | T = Context.IntTy; |
5316 | D.setInvalidType(true); |
5317 | } else if (AutoType *Auto = T->getContainedAutoType()) { |
5318 | // If the trailing return type contains an `auto`, we may need to |
5319 | // invent a template parameter for it, for cases like |
5320 | // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`. |
5321 | InventedTemplateParameterInfo *InventedParamInfo = nullptr; |
5322 | if (D.getContext() == DeclaratorContext::Prototype) |
5323 | InventedParamInfo = &S.InventedParameterInfos.back(); |
5324 | else if (D.getContext() == DeclaratorContext::LambdaExprParameter) |
5325 | InventedParamInfo = S.getCurLambda(); |
5326 | if (InventedParamInfo) { |
5327 | std::tie(args&: T, args&: TInfo) = InventTemplateParameter( |
5328 | state, T, TrailingTSI: TInfo, Auto, Info&: *InventedParamInfo); |
5329 | } |
5330 | } |
5331 | } else { |
5332 | // This function type is not the type of the entity being declared, |
5333 | // so checking the 'auto' is not the responsibility of this chunk. |
5334 | } |
5335 | } |
5336 | |
5337 | // C99 6.7.5.3p1: The return type may not be a function or array type. |
5338 | // For conversion functions, we'll diagnose this particular error later. |
5339 | if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) && |
5340 | (D.getName().getKind() != |
5341 | UnqualifiedIdKind::IK_ConversionFunctionId)) { |
5342 | unsigned diagID = diag::err_func_returning_array_function; |
5343 | // Last processing chunk in block context means this function chunk |
5344 | // represents the block. |
5345 | if (chunkIndex == 0 && |
5346 | D.getContext() == DeclaratorContext::BlockLiteral) |
5347 | diagID = diag::err_block_returning_array_function; |
5348 | S.Diag(Loc: DeclType.Loc, DiagID: diagID) << T->isFunctionType() << T; |
5349 | T = Context.IntTy; |
5350 | D.setInvalidType(true); |
5351 | AreDeclaratorChunksValid = false; |
5352 | } |
5353 | |
5354 | // Do not allow returning half FP value. |
5355 | // FIXME: This really should be in BuildFunctionType. |
5356 | if (T->isHalfType()) { |
5357 | if (S.getLangOpts().OpenCL) { |
5358 | if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , |
5359 | LO: S.getLangOpts())) { |
5360 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) |
5361 | << T << 0 /*pointer hint*/; |
5362 | D.setInvalidType(true); |
5363 | } |
5364 | } else if (!S.getLangOpts().NativeHalfArgsAndReturns && |
5365 | !S.Context.getTargetInfo().allowHalfArgsAndReturns()) { |
5366 | S.Diag(D.getIdentifierLoc(), |
5367 | diag::err_parameters_retval_cannot_have_fp16_type) << 1; |
5368 | D.setInvalidType(true); |
5369 | } |
5370 | } |
5371 | |
5372 | if (LangOpts.OpenCL) { |
5373 | // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a |
5374 | // function. |
5375 | if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() || |
5376 | T->isPipeType()) { |
5377 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return) |
5378 | << T << 1 /*hint off*/; |
5379 | D.setInvalidType(true); |
5380 | } |
5381 | // OpenCL doesn't support variadic functions and blocks |
5382 | // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf. |
5383 | // We also allow here any toolchain reserved identifiers. |
5384 | if (FTI.isVariadic && |
5385 | !S.getOpenCLOptions().isAvailableOption( |
5386 | Ext: "__cl_clang_variadic_functions" , LO: S.getLangOpts()) && |
5387 | !(D.getIdentifier() && |
5388 | ((D.getIdentifier()->getName() == "printf" && |
5389 | LangOpts.getOpenCLCompatibleVersion() >= 120) || |
5390 | D.getIdentifier()->getName().starts_with(Prefix: "__" )))) { |
5391 | S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function); |
5392 | D.setInvalidType(true); |
5393 | } |
5394 | } |
5395 | |
5396 | // Methods cannot return interface types. All ObjC objects are |
5397 | // passed by reference. |
5398 | if (T->isObjCObjectType()) { |
5399 | SourceLocation DiagLoc, FixitLoc; |
5400 | if (TInfo) { |
5401 | DiagLoc = TInfo->getTypeLoc().getBeginLoc(); |
5402 | FixitLoc = S.getLocForEndOfToken(Loc: TInfo->getTypeLoc().getEndLoc()); |
5403 | } else { |
5404 | DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); |
5405 | FixitLoc = S.getLocForEndOfToken(Loc: D.getDeclSpec().getEndLoc()); |
5406 | } |
5407 | S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value) |
5408 | << 0 << T |
5409 | << FixItHint::CreateInsertion(FixitLoc, "*" ); |
5410 | |
5411 | T = Context.getObjCObjectPointerType(OIT: T); |
5412 | if (TInfo) { |
5413 | TypeLocBuilder TLB; |
5414 | TLB.pushFullCopy(L: TInfo->getTypeLoc()); |
5415 | ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T); |
5416 | TLoc.setStarLoc(FixitLoc); |
5417 | TInfo = TLB.getTypeSourceInfo(Context, T); |
5418 | } else { |
5419 | AreDeclaratorChunksValid = false; |
5420 | } |
5421 | |
5422 | D.setInvalidType(true); |
5423 | } |
5424 | |
5425 | // cv-qualifiers on return types are pointless except when the type is a |
5426 | // class type in C++. |
5427 | if ((T.getCVRQualifiers() || T->isAtomicType()) && |
5428 | !(S.getLangOpts().CPlusPlus && |
5429 | (T->isDependentType() || T->isRecordType()))) { |
5430 | if (T->isVoidType() && !S.getLangOpts().CPlusPlus && |
5431 | D.getFunctionDefinitionKind() == |
5432 | FunctionDefinitionKind::Definition) { |
5433 | // [6.9.1/3] qualified void return is invalid on a C |
5434 | // function definition. Apparently ok on declarations and |
5435 | // in C++ though (!) |
5436 | S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T; |
5437 | } else |
5438 | diagnoseRedundantReturnTypeQualifiers(S, RetTy: T, D, FunctionChunkIndex: chunkIndex); |
5439 | |
5440 | // C++2a [dcl.fct]p12: |
5441 | // A volatile-qualified return type is deprecated |
5442 | if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20) |
5443 | S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T; |
5444 | } |
5445 | |
5446 | // Objective-C ARC ownership qualifiers are ignored on the function |
5447 | // return type (by type canonicalization). Complain if this attribute |
5448 | // was written here. |
5449 | if (T.getQualifiers().hasObjCLifetime()) { |
5450 | SourceLocation AttrLoc; |
5451 | if (chunkIndex + 1 < D.getNumTypeObjects()) { |
5452 | DeclaratorChunk ReturnTypeChunk = D.getTypeObject(i: chunkIndex + 1); |
5453 | for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) { |
5454 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { |
5455 | AttrLoc = AL.getLoc(); |
5456 | break; |
5457 | } |
5458 | } |
5459 | } |
5460 | if (AttrLoc.isInvalid()) { |
5461 | for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) { |
5462 | if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) { |
5463 | AttrLoc = AL.getLoc(); |
5464 | break; |
5465 | } |
5466 | } |
5467 | } |
5468 | |
5469 | if (AttrLoc.isValid()) { |
5470 | // The ownership attributes are almost always written via |
5471 | // the predefined |
5472 | // __strong/__weak/__autoreleasing/__unsafe_unretained. |
5473 | if (AttrLoc.isMacroID()) |
5474 | AttrLoc = |
5475 | S.SourceMgr.getImmediateExpansionRange(Loc: AttrLoc).getBegin(); |
5476 | |
5477 | S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type) |
5478 | << T.getQualifiers().getObjCLifetime(); |
5479 | } |
5480 | } |
5481 | |
5482 | if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) { |
5483 | // C++ [dcl.fct]p6: |
5484 | // Types shall not be defined in return or parameter types. |
5485 | TagDecl *Tag = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl()); |
5486 | S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) |
5487 | << Context.getTypeDeclType(Tag); |
5488 | } |
5489 | |
5490 | // Exception specs are not allowed in typedefs. Complain, but add it |
5491 | // anyway. |
5492 | if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17) |
5493 | S.Diag(FTI.getExceptionSpecLocBeg(), |
5494 | diag::err_exception_spec_in_typedef) |
5495 | << (D.getContext() == DeclaratorContext::AliasDecl || |
5496 | D.getContext() == DeclaratorContext::AliasTemplate); |
5497 | |
5498 | // If we see "T var();" or "T var(T());" at block scope, it is probably |
5499 | // an attempt to initialize a variable, not a function declaration. |
5500 | if (FTI.isAmbiguous) |
5501 | warnAboutAmbiguousFunction(S, D, DeclType, RT: T); |
5502 | |
5503 | FunctionType::ExtInfo EI( |
5504 | getCCForDeclaratorChunk(S, D, AttrList: DeclType.getAttrs(), FTI, ChunkIndex: chunkIndex)); |
5505 | |
5506 | // OpenCL disallows functions without a prototype, but it doesn't enforce |
5507 | // strict prototypes as in C23 because it allows a function definition to |
5508 | // have an identifier list. See OpenCL 3.0 6.11/g for more details. |
5509 | if (!FTI.NumParams && !FTI.isVariadic && |
5510 | !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) { |
5511 | // Simple void foo(), where the incoming T is the result type. |
5512 | T = Context.getFunctionNoProtoType(ResultTy: T, Info: EI); |
5513 | } else { |
5514 | // We allow a zero-parameter variadic function in C if the |
5515 | // function is marked with the "overloadable" attribute. Scan |
5516 | // for this attribute now. We also allow it in C23 per WG14 N2975. |
5517 | if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) { |
5518 | if (LangOpts.C23) |
5519 | S.Diag(FTI.getEllipsisLoc(), |
5520 | diag::warn_c17_compat_ellipsis_only_parameter); |
5521 | else if (!D.getDeclarationAttributes().hasAttribute( |
5522 | ParsedAttr::AT_Overloadable) && |
5523 | !D.getAttributes().hasAttribute( |
5524 | ParsedAttr::AT_Overloadable) && |
5525 | !D.getDeclSpec().getAttributes().hasAttribute( |
5526 | ParsedAttr::AT_Overloadable)) |
5527 | S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param); |
5528 | } |
5529 | |
5530 | if (FTI.NumParams && FTI.Params[0].Param == nullptr) { |
5531 | // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function |
5532 | // definition. |
5533 | S.Diag(FTI.Params[0].IdentLoc, |
5534 | diag::err_ident_list_in_fn_declaration); |
5535 | D.setInvalidType(true); |
5536 | // Recover by creating a K&R-style function type, if possible. |
5537 | T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) |
5538 | ? Context.getFunctionNoProtoType(ResultTy: T, Info: EI) |
5539 | : Context.IntTy; |
5540 | AreDeclaratorChunksValid = false; |
5541 | break; |
5542 | } |
5543 | |
5544 | FunctionProtoType::ExtProtoInfo EPI; |
5545 | EPI.ExtInfo = EI; |
5546 | EPI.Variadic = FTI.isVariadic; |
5547 | EPI.EllipsisLoc = FTI.getEllipsisLoc(); |
5548 | EPI.HasTrailingReturn = FTI.hasTrailingReturnType(); |
5549 | EPI.TypeQuals.addCVRUQualifiers( |
5550 | mask: FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers() |
5551 | : 0); |
5552 | EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None |
5553 | : FTI.RefQualifierIsLValueRef? RQ_LValue |
5554 | : RQ_RValue; |
5555 | |
5556 | // Otherwise, we have a function with a parameter list that is |
5557 | // potentially variadic. |
5558 | SmallVector<QualType, 16> ParamTys; |
5559 | ParamTys.reserve(N: FTI.NumParams); |
5560 | |
5561 | SmallVector<FunctionProtoType::ExtParameterInfo, 16> |
5562 | ExtParameterInfos(FTI.NumParams); |
5563 | bool HasAnyInterestingExtParameterInfos = false; |
5564 | |
5565 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { |
5566 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param); |
5567 | QualType ParamTy = Param->getType(); |
5568 | assert(!ParamTy.isNull() && "Couldn't parse type?" ); |
5569 | |
5570 | // Look for 'void'. void is allowed only as a single parameter to a |
5571 | // function with no other parameters (C99 6.7.5.3p10). We record |
5572 | // int(void) as a FunctionProtoType with an empty parameter list. |
5573 | if (ParamTy->isVoidType()) { |
5574 | // If this is something like 'float(int, void)', reject it. 'void' |
5575 | // is an incomplete type (C99 6.2.5p19) and function decls cannot |
5576 | // have parameters of incomplete type. |
5577 | if (FTI.NumParams != 1 || FTI.isVariadic) { |
5578 | S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param); |
5579 | ParamTy = Context.IntTy; |
5580 | Param->setType(ParamTy); |
5581 | } else if (FTI.Params[i].Ident) { |
5582 | // Reject, but continue to parse 'int(void abc)'. |
5583 | S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type); |
5584 | ParamTy = Context.IntTy; |
5585 | Param->setType(ParamTy); |
5586 | } else { |
5587 | // Reject, but continue to parse 'float(const void)'. |
5588 | if (ParamTy.hasQualifiers()) |
5589 | S.Diag(DeclType.Loc, diag::err_void_param_qualified); |
5590 | |
5591 | // Do not add 'void' to the list. |
5592 | break; |
5593 | } |
5594 | } else if (ParamTy->isHalfType()) { |
5595 | // Disallow half FP parameters. |
5596 | // FIXME: This really should be in BuildFunctionType. |
5597 | if (S.getLangOpts().OpenCL) { |
5598 | if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16" , |
5599 | LO: S.getLangOpts())) { |
5600 | S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) |
5601 | << ParamTy << 0; |
5602 | D.setInvalidType(); |
5603 | Param->setInvalidDecl(); |
5604 | } |
5605 | } else if (!S.getLangOpts().NativeHalfArgsAndReturns && |
5606 | !S.Context.getTargetInfo().allowHalfArgsAndReturns()) { |
5607 | S.Diag(Param->getLocation(), |
5608 | diag::err_parameters_retval_cannot_have_fp16_type) << 0; |
5609 | D.setInvalidType(); |
5610 | } |
5611 | } else if (!FTI.hasPrototype) { |
5612 | if (Context.isPromotableIntegerType(T: ParamTy)) { |
5613 | ParamTy = Context.getPromotedIntegerType(PromotableType: ParamTy); |
5614 | Param->setKNRPromoted(true); |
5615 | } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) { |
5616 | if (BTy->getKind() == BuiltinType::Float) { |
5617 | ParamTy = Context.DoubleTy; |
5618 | Param->setKNRPromoted(true); |
5619 | } |
5620 | } |
5621 | } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) { |
5622 | // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function. |
5623 | S.Diag(Param->getLocation(), diag::err_opencl_invalid_param) |
5624 | << ParamTy << 1 /*hint off*/; |
5625 | D.setInvalidType(); |
5626 | } |
5627 | |
5628 | if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) { |
5629 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(consumed: true); |
5630 | HasAnyInterestingExtParameterInfos = true; |
5631 | } |
5632 | |
5633 | if (auto attr = Param->getAttr<ParameterABIAttr>()) { |
5634 | ExtParameterInfos[i] = |
5635 | ExtParameterInfos[i].withABI(kind: attr->getABI()); |
5636 | HasAnyInterestingExtParameterInfos = true; |
5637 | } |
5638 | |
5639 | if (Param->hasAttr<PassObjectSizeAttr>()) { |
5640 | ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize(); |
5641 | HasAnyInterestingExtParameterInfos = true; |
5642 | } |
5643 | |
5644 | if (Param->hasAttr<NoEscapeAttr>()) { |
5645 | ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(NoEscape: true); |
5646 | HasAnyInterestingExtParameterInfos = true; |
5647 | } |
5648 | |
5649 | ParamTys.push_back(Elt: ParamTy); |
5650 | } |
5651 | |
5652 | if (HasAnyInterestingExtParameterInfos) { |
5653 | EPI.ExtParameterInfos = ExtParameterInfos.data(); |
5654 | checkExtParameterInfos(S, paramTypes: ParamTys, EPI, |
5655 | getParamLoc: [&](unsigned i) { return FTI.Params[i].Param->getLocation(); }); |
5656 | } |
5657 | |
5658 | SmallVector<QualType, 4> Exceptions; |
5659 | SmallVector<ParsedType, 2> DynamicExceptions; |
5660 | SmallVector<SourceRange, 2> DynamicExceptionRanges; |
5661 | Expr *NoexceptExpr = nullptr; |
5662 | |
5663 | if (FTI.getExceptionSpecType() == EST_Dynamic) { |
5664 | // FIXME: It's rather inefficient to have to split into two vectors |
5665 | // here. |
5666 | unsigned N = FTI.getNumExceptions(); |
5667 | DynamicExceptions.reserve(N); |
5668 | DynamicExceptionRanges.reserve(N); |
5669 | for (unsigned I = 0; I != N; ++I) { |
5670 | DynamicExceptions.push_back(Elt: FTI.Exceptions[I].Ty); |
5671 | DynamicExceptionRanges.push_back(Elt: FTI.Exceptions[I].Range); |
5672 | } |
5673 | } else if (isComputedNoexcept(ESpecType: FTI.getExceptionSpecType())) { |
5674 | NoexceptExpr = FTI.NoexceptExpr; |
5675 | } |
5676 | |
5677 | S.checkExceptionSpecification(IsTopLevel: D.isFunctionDeclarationContext(), |
5678 | EST: FTI.getExceptionSpecType(), |
5679 | DynamicExceptions, |
5680 | DynamicExceptionRanges, |
5681 | NoexceptExpr, |
5682 | Exceptions, |
5683 | ESI&: EPI.ExceptionSpec); |
5684 | |
5685 | // FIXME: Set address space from attrs for C++ mode here. |
5686 | // OpenCLCPlusPlus: A class member function has an address space. |
5687 | auto IsClassMember = [&]() { |
5688 | return (!state.getDeclarator().getCXXScopeSpec().isEmpty() && |
5689 | state.getDeclarator() |
5690 | .getCXXScopeSpec() |
5691 | .getScopeRep() |
5692 | ->getKind() == NestedNameSpecifier::TypeSpec) || |
5693 | state.getDeclarator().getContext() == |
5694 | DeclaratorContext::Member || |
5695 | state.getDeclarator().getContext() == |
5696 | DeclaratorContext::LambdaExpr; |
5697 | }; |
5698 | |
5699 | if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) { |
5700 | LangAS ASIdx = LangAS::Default; |
5701 | // Take address space attr if any and mark as invalid to avoid adding |
5702 | // them later while creating QualType. |
5703 | if (FTI.MethodQualifiers) |
5704 | for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) { |
5705 | LangAS ASIdxNew = attr.asOpenCLLangAS(); |
5706 | if (DiagnoseMultipleAddrSpaceAttributes(S, ASOld: ASIdx, ASNew: ASIdxNew, |
5707 | AttrLoc: attr.getLoc())) |
5708 | D.setInvalidType(true); |
5709 | else |
5710 | ASIdx = ASIdxNew; |
5711 | } |
5712 | // If a class member function's address space is not set, set it to |
5713 | // __generic. |
5714 | LangAS AS = |
5715 | (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace() |
5716 | : ASIdx); |
5717 | EPI.TypeQuals.addAddressSpace(space: AS); |
5718 | } |
5719 | T = Context.getFunctionType(ResultTy: T, Args: ParamTys, EPI); |
5720 | } |
5721 | break; |
5722 | } |
5723 | case DeclaratorChunk::MemberPointer: { |
5724 | // The scope spec must refer to a class, or be dependent. |
5725 | CXXScopeSpec &SS = DeclType.Mem.Scope(); |
5726 | QualType ClsType; |
5727 | |
5728 | // Handle pointer nullability. |
5729 | inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc, |
5730 | DeclType.EndLoc, DeclType.getAttrs(), |
5731 | state.getDeclarator().getAttributePool()); |
5732 | |
5733 | if (SS.isInvalid()) { |
5734 | // Avoid emitting extra errors if we already errored on the scope. |
5735 | D.setInvalidType(true); |
5736 | } else if (S.isDependentScopeSpecifier(SS) || |
5737 | isa_and_nonnull<CXXRecordDecl>(Val: S.computeDeclContext(SS))) { |
5738 | NestedNameSpecifier *NNS = SS.getScopeRep(); |
5739 | NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); |
5740 | switch (NNS->getKind()) { |
5741 | case NestedNameSpecifier::Identifier: |
5742 | ClsType = Context.getDependentNameType( |
5743 | Keyword: ElaboratedTypeKeyword::None, NNS: NNSPrefix, Name: NNS->getAsIdentifier()); |
5744 | break; |
5745 | |
5746 | case NestedNameSpecifier::Namespace: |
5747 | case NestedNameSpecifier::NamespaceAlias: |
5748 | case NestedNameSpecifier::Global: |
5749 | case NestedNameSpecifier::Super: |
5750 | llvm_unreachable("Nested-name-specifier must name a type" ); |
5751 | |
5752 | case NestedNameSpecifier::TypeSpec: |
5753 | case NestedNameSpecifier::TypeSpecWithTemplate: |
5754 | ClsType = QualType(NNS->getAsType(), 0); |
5755 | // Note: if the NNS has a prefix and ClsType is a nondependent |
5756 | // TemplateSpecializationType, then the NNS prefix is NOT included |
5757 | // in ClsType; hence we wrap ClsType into an ElaboratedType. |
5758 | // NOTE: in particular, no wrap occurs if ClsType already is an |
5759 | // Elaborated, DependentName, or DependentTemplateSpecialization. |
5760 | if (isa<TemplateSpecializationType>(Val: NNS->getAsType())) |
5761 | ClsType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, |
5762 | NNS: NNSPrefix, NamedType: ClsType); |
5763 | break; |
5764 | } |
5765 | } else { |
5766 | S.Diag(DeclType.Mem.Scope().getBeginLoc(), |
5767 | diag::err_illegal_decl_mempointer_in_nonclass) |
5768 | << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name" ) |
5769 | << DeclType.Mem.Scope().getRange(); |
5770 | D.setInvalidType(true); |
5771 | } |
5772 | |
5773 | if (!ClsType.isNull()) |
5774 | T = S.BuildMemberPointerType(T, Class: ClsType, Loc: DeclType.Loc, |
5775 | Entity: D.getIdentifier()); |
5776 | else |
5777 | AreDeclaratorChunksValid = false; |
5778 | |
5779 | if (T.isNull()) { |
5780 | T = Context.IntTy; |
5781 | D.setInvalidType(true); |
5782 | AreDeclaratorChunksValid = false; |
5783 | } else if (DeclType.Mem.TypeQuals) { |
5784 | T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Mem.TypeQuals); |
5785 | } |
5786 | break; |
5787 | } |
5788 | |
5789 | case DeclaratorChunk::Pipe: { |
5790 | T = S.BuildReadPipeType(T, Loc: DeclType.Loc); |
5791 | processTypeAttrs(state, type&: T, TAL: TAL_DeclSpec, |
5792 | attrs: D.getMutableDeclSpec().getAttributes()); |
5793 | break; |
5794 | } |
5795 | } |
5796 | |
5797 | if (T.isNull()) { |
5798 | D.setInvalidType(true); |
5799 | T = Context.IntTy; |
5800 | AreDeclaratorChunksValid = false; |
5801 | } |
5802 | |
5803 | // See if there are any attributes on this declarator chunk. |
5804 | processTypeAttrs(state, type&: T, TAL: TAL_DeclChunk, attrs: DeclType.getAttrs(), |
5805 | CFT: S.IdentifyCUDATarget(Attrs: D.getAttributes())); |
5806 | |
5807 | if (DeclType.Kind != DeclaratorChunk::Paren) { |
5808 | if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType)) |
5809 | S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array); |
5810 | |
5811 | ExpectNoDerefChunk = state.didParseNoDeref(); |
5812 | } |
5813 | } |
5814 | |
5815 | if (ExpectNoDerefChunk) |
5816 | S.Diag(state.getDeclarator().getBeginLoc(), |
5817 | diag::warn_noderef_on_non_pointer_or_array); |
5818 | |
5819 | // GNU warning -Wstrict-prototypes |
5820 | // Warn if a function declaration or definition is without a prototype. |
5821 | // This warning is issued for all kinds of unprototyped function |
5822 | // declarations (i.e. function type typedef, function pointer etc.) |
5823 | // C99 6.7.5.3p14: |
5824 | // The empty list in a function declarator that is not part of a definition |
5825 | // of that function specifies that no information about the number or types |
5826 | // of the parameters is supplied. |
5827 | // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of |
5828 | // function declarations whose behavior changes in C23. |
5829 | if (!LangOpts.requiresStrictPrototypes()) { |
5830 | bool IsBlock = false; |
5831 | for (const DeclaratorChunk &DeclType : D.type_objects()) { |
5832 | switch (DeclType.Kind) { |
5833 | case DeclaratorChunk::BlockPointer: |
5834 | IsBlock = true; |
5835 | break; |
5836 | case DeclaratorChunk::Function: { |
5837 | const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; |
5838 | // We suppress the warning when there's no LParen location, as this |
5839 | // indicates the declaration was an implicit declaration, which gets |
5840 | // warned about separately via -Wimplicit-function-declaration. We also |
5841 | // suppress the warning when we know the function has a prototype. |
5842 | if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic && |
5843 | FTI.getLParenLoc().isValid()) |
5844 | S.Diag(DeclType.Loc, diag::warn_strict_prototypes) |
5845 | << IsBlock |
5846 | << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void" ); |
5847 | IsBlock = false; |
5848 | break; |
5849 | } |
5850 | default: |
5851 | break; |
5852 | } |
5853 | } |
5854 | } |
5855 | |
5856 | assert(!T.isNull() && "T must not be null after this point" ); |
5857 | |
5858 | if (LangOpts.CPlusPlus && T->isFunctionType()) { |
5859 | const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); |
5860 | assert(FnTy && "Why oh why is there not a FunctionProtoType here?" ); |
5861 | |
5862 | // C++ 8.3.5p4: |
5863 | // A cv-qualifier-seq shall only be part of the function type |
5864 | // for a nonstatic member function, the function type to which a pointer |
5865 | // to member refers, or the top-level function type of a function typedef |
5866 | // declaration. |
5867 | // |
5868 | // Core issue 547 also allows cv-qualifiers on function types that are |
5869 | // top-level template type arguments. |
5870 | enum { |
5871 | NonMember, |
5872 | Member, |
5873 | ExplicitObjectMember, |
5874 | DeductionGuide |
5875 | } Kind = NonMember; |
5876 | if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) |
5877 | Kind = DeductionGuide; |
5878 | else if (!D.getCXXScopeSpec().isSet()) { |
5879 | if ((D.getContext() == DeclaratorContext::Member || |
5880 | D.getContext() == DeclaratorContext::LambdaExpr) && |
5881 | !D.getDeclSpec().isFriendSpecified()) |
5882 | Kind = Member; |
5883 | } else { |
5884 | DeclContext *DC = S.computeDeclContext(SS: D.getCXXScopeSpec()); |
5885 | if (!DC || DC->isRecord()) |
5886 | Kind = Member; |
5887 | } |
5888 | |
5889 | if (Kind == Member) { |
5890 | unsigned I; |
5891 | if (D.isFunctionDeclarator(idx&: I)) { |
5892 | const DeclaratorChunk &Chunk = D.getTypeObject(i: I); |
5893 | if (Chunk.Fun.NumParams) { |
5894 | auto *P = dyn_cast_or_null<ParmVarDecl>(Val: Chunk.Fun.Params->Param); |
5895 | if (P && P->isExplicitObjectParameter()) |
5896 | Kind = ExplicitObjectMember; |
5897 | } |
5898 | } |
5899 | } |
5900 | |
5901 | // C++11 [dcl.fct]p6 (w/DR1417): |
5902 | // An attempt to specify a function type with a cv-qualifier-seq or a |
5903 | // ref-qualifier (including by typedef-name) is ill-formed unless it is: |
5904 | // - the function type for a non-static member function, |
5905 | // - the function type to which a pointer to member refers, |
5906 | // - the top-level function type of a function typedef declaration or |
5907 | // alias-declaration, |
5908 | // - the type-id in the default argument of a type-parameter, or |
5909 | // - the type-id of a template-argument for a type-parameter |
5910 | // |
5911 | // C++23 [dcl.fct]p6 (P0847R7) |
5912 | // ... A member-declarator with an explicit-object-parameter-declaration |
5913 | // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be |
5914 | // declared static or virtual ... |
5915 | // |
5916 | // FIXME: Checking this here is insufficient. We accept-invalid on: |
5917 | // |
5918 | // template<typename T> struct S { void f(T); }; |
5919 | // S<int() const> s; |
5920 | // |
5921 | // ... for instance. |
5922 | if (IsQualifiedFunction && |
5923 | // Check for non-static member function and not and |
5924 | // explicit-object-parameter-declaration |
5925 | (Kind != Member || D.isExplicitObjectMemberFunction() || |
5926 | D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || |
5927 | (D.getContext() == clang::DeclaratorContext::Member && |
5928 | D.isStaticMember())) && |
5929 | !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg && |
5930 | D.getContext() != DeclaratorContext::TemplateTypeArg) { |
5931 | SourceLocation Loc = D.getBeginLoc(); |
5932 | SourceRange RemovalRange; |
5933 | unsigned I; |
5934 | if (D.isFunctionDeclarator(idx&: I)) { |
5935 | SmallVector<SourceLocation, 4> RemovalLocs; |
5936 | const DeclaratorChunk &Chunk = D.getTypeObject(i: I); |
5937 | assert(Chunk.Kind == DeclaratorChunk::Function); |
5938 | |
5939 | if (Chunk.Fun.hasRefQualifier()) |
5940 | RemovalLocs.push_back(Elt: Chunk.Fun.getRefQualifierLoc()); |
5941 | |
5942 | if (Chunk.Fun.hasMethodTypeQualifiers()) |
5943 | Chunk.Fun.MethodQualifiers->forEachQualifier( |
5944 | Handle: [&](DeclSpec::TQ TypeQual, StringRef QualName, |
5945 | SourceLocation SL) { RemovalLocs.push_back(Elt: SL); }); |
5946 | |
5947 | if (!RemovalLocs.empty()) { |
5948 | llvm::sort(C&: RemovalLocs, |
5949 | Comp: BeforeThanCompare<SourceLocation>(S.getSourceManager())); |
5950 | RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back()); |
5951 | Loc = RemovalLocs.front(); |
5952 | } |
5953 | } |
5954 | |
5955 | S.Diag(Loc, diag::err_invalid_qualified_function_type) |
5956 | << Kind << D.isFunctionDeclarator() << T |
5957 | << getFunctionQualifiersAsString(FnTy) |
5958 | << FixItHint::CreateRemoval(RemovalRange); |
5959 | |
5960 | // Strip the cv-qualifiers and ref-qualifiers from the type. |
5961 | FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); |
5962 | EPI.TypeQuals.removeCVRQualifiers(); |
5963 | EPI.RefQualifier = RQ_None; |
5964 | |
5965 | T = Context.getFunctionType(ResultTy: FnTy->getReturnType(), Args: FnTy->getParamTypes(), |
5966 | EPI); |
5967 | // Rebuild any parens around the identifier in the function type. |
5968 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { |
5969 | if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren) |
5970 | break; |
5971 | T = S.BuildParenType(T); |
5972 | } |
5973 | } |
5974 | } |
5975 | |
5976 | // Apply any undistributed attributes from the declaration or declarator. |
5977 | ParsedAttributesView NonSlidingAttrs; |
5978 | for (ParsedAttr &AL : D.getDeclarationAttributes()) { |
5979 | if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) { |
5980 | NonSlidingAttrs.addAtEnd(newAttr: &AL); |
5981 | } |
5982 | } |
5983 | processTypeAttrs(state, type&: T, TAL: TAL_DeclName, attrs: NonSlidingAttrs); |
5984 | processTypeAttrs(state, type&: T, TAL: TAL_DeclName, attrs: D.getAttributes()); |
5985 | |
5986 | // Diagnose any ignored type attributes. |
5987 | state.diagnoseIgnoredTypeAttrs(type: T); |
5988 | |
5989 | // C++0x [dcl.constexpr]p9: |
5990 | // A constexpr specifier used in an object declaration declares the object |
5991 | // as const. |
5992 | if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr && |
5993 | T->isObjectType()) |
5994 | T.addConst(); |
5995 | |
5996 | // C++2a [dcl.fct]p4: |
5997 | // A parameter with volatile-qualified type is deprecated |
5998 | if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 && |
5999 | (D.getContext() == DeclaratorContext::Prototype || |
6000 | D.getContext() == DeclaratorContext::LambdaExprParameter)) |
6001 | S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T; |
6002 | |
6003 | // If there was an ellipsis in the declarator, the declaration declares a |
6004 | // parameter pack whose type may be a pack expansion type. |
6005 | if (D.hasEllipsis()) { |
6006 | // C++0x [dcl.fct]p13: |
6007 | // A declarator-id or abstract-declarator containing an ellipsis shall |
6008 | // only be used in a parameter-declaration. Such a parameter-declaration |
6009 | // is a parameter pack (14.5.3). [...] |
6010 | switch (D.getContext()) { |
6011 | case DeclaratorContext::Prototype: |
6012 | case DeclaratorContext::LambdaExprParameter: |
6013 | case DeclaratorContext::RequiresExpr: |
6014 | // C++0x [dcl.fct]p13: |
6015 | // [...] When it is part of a parameter-declaration-clause, the |
6016 | // parameter pack is a function parameter pack (14.5.3). The type T |
6017 | // of the declarator-id of the function parameter pack shall contain |
6018 | // a template parameter pack; each template parameter pack in T is |
6019 | // expanded by the function parameter pack. |
6020 | // |
6021 | // We represent function parameter packs as function parameters whose |
6022 | // type is a pack expansion. |
6023 | if (!T->containsUnexpandedParameterPack() && |
6024 | (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) { |
6025 | S.Diag(D.getEllipsisLoc(), |
6026 | diag::err_function_parameter_pack_without_parameter_packs) |
6027 | << T << D.getSourceRange(); |
6028 | D.setEllipsisLoc(SourceLocation()); |
6029 | } else { |
6030 | T = Context.getPackExpansionType(Pattern: T, NumExpansions: std::nullopt, |
6031 | /*ExpectPackInType=*/false); |
6032 | } |
6033 | break; |
6034 | case DeclaratorContext::TemplateParam: |
6035 | // C++0x [temp.param]p15: |
6036 | // If a template-parameter is a [...] is a parameter-declaration that |
6037 | // declares a parameter pack (8.3.5), then the template-parameter is a |
6038 | // template parameter pack (14.5.3). |
6039 | // |
6040 | // Note: core issue 778 clarifies that, if there are any unexpanded |
6041 | // parameter packs in the type of the non-type template parameter, then |
6042 | // it expands those parameter packs. |
6043 | if (T->containsUnexpandedParameterPack()) |
6044 | T = Context.getPackExpansionType(Pattern: T, NumExpansions: std::nullopt); |
6045 | else |
6046 | S.Diag(D.getEllipsisLoc(), |
6047 | LangOpts.CPlusPlus11 |
6048 | ? diag::warn_cxx98_compat_variadic_templates |
6049 | : diag::ext_variadic_templates); |
6050 | break; |
6051 | |
6052 | case DeclaratorContext::File: |
6053 | case DeclaratorContext::KNRTypeList: |
6054 | case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here? |
6055 | case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here? |
6056 | case DeclaratorContext::TypeName: |
6057 | case DeclaratorContext::FunctionalCast: |
6058 | case DeclaratorContext::CXXNew: |
6059 | case DeclaratorContext::AliasDecl: |
6060 | case DeclaratorContext::AliasTemplate: |
6061 | case DeclaratorContext::Member: |
6062 | case DeclaratorContext::Block: |
6063 | case DeclaratorContext::ForInit: |
6064 | case DeclaratorContext::SelectionInit: |
6065 | case DeclaratorContext::Condition: |
6066 | case DeclaratorContext::CXXCatch: |
6067 | case DeclaratorContext::ObjCCatch: |
6068 | case DeclaratorContext::BlockLiteral: |
6069 | case DeclaratorContext::LambdaExpr: |
6070 | case DeclaratorContext::ConversionId: |
6071 | case DeclaratorContext::TrailingReturn: |
6072 | case DeclaratorContext::TrailingReturnVar: |
6073 | case DeclaratorContext::TemplateArg: |
6074 | case DeclaratorContext::TemplateTypeArg: |
6075 | case DeclaratorContext::Association: |
6076 | // FIXME: We may want to allow parameter packs in block-literal contexts |
6077 | // in the future. |
6078 | S.Diag(D.getEllipsisLoc(), |
6079 | diag::err_ellipsis_in_declarator_not_parameter); |
6080 | D.setEllipsisLoc(SourceLocation()); |
6081 | break; |
6082 | } |
6083 | } |
6084 | |
6085 | assert(!T.isNull() && "T must not be null at the end of this function" ); |
6086 | if (!AreDeclaratorChunksValid) |
6087 | return Context.getTrivialTypeSourceInfo(T); |
6088 | return GetTypeSourceInfoForDeclarator(State&: state, T, ReturnTypeInfo: TInfo); |
6089 | } |
6090 | |
6091 | /// GetTypeForDeclarator - Convert the type for the specified |
6092 | /// declarator to Type instances. |
6093 | /// |
6094 | /// The result of this call will never be null, but the associated |
6095 | /// type may be a null type if there's an unrecoverable error. |
6096 | TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D) { |
6097 | // Determine the type of the declarator. Not all forms of declarator |
6098 | // have a type. |
6099 | |
6100 | TypeProcessingState state(*this, D); |
6101 | |
6102 | TypeSourceInfo *ReturnTypeInfo = nullptr; |
6103 | QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); |
6104 | if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount) |
6105 | inferARCWriteback(state, declSpecType&: T); |
6106 | |
6107 | return GetFullTypeForDeclarator(state, declSpecType: T, TInfo: ReturnTypeInfo); |
6108 | } |
6109 | |
6110 | static void transferARCOwnershipToDeclSpec(Sema &S, |
6111 | QualType &declSpecTy, |
6112 | Qualifiers::ObjCLifetime ownership) { |
6113 | if (declSpecTy->isObjCRetainableType() && |
6114 | declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) { |
6115 | Qualifiers qs; |
6116 | qs.addObjCLifetime(type: ownership); |
6117 | declSpecTy = S.Context.getQualifiedType(T: declSpecTy, Qs: qs); |
6118 | } |
6119 | } |
6120 | |
6121 | static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, |
6122 | Qualifiers::ObjCLifetime ownership, |
6123 | unsigned chunkIndex) { |
6124 | Sema &S = state.getSema(); |
6125 | Declarator &D = state.getDeclarator(); |
6126 | |
6127 | // Look for an explicit lifetime attribute. |
6128 | DeclaratorChunk &chunk = D.getTypeObject(i: chunkIndex); |
6129 | if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership)) |
6130 | return; |
6131 | |
6132 | const char *attrStr = nullptr; |
6133 | switch (ownership) { |
6134 | case Qualifiers::OCL_None: llvm_unreachable("no ownership!" ); |
6135 | case Qualifiers::OCL_ExplicitNone: attrStr = "none" ; break; |
6136 | case Qualifiers::OCL_Strong: attrStr = "strong" ; break; |
6137 | case Qualifiers::OCL_Weak: attrStr = "weak" ; break; |
6138 | case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing" ; break; |
6139 | } |
6140 | |
6141 | IdentifierLoc *Arg = new (S.Context) IdentifierLoc; |
6142 | Arg->Ident = &S.Context.Idents.get(Name: attrStr); |
6143 | Arg->Loc = SourceLocation(); |
6144 | |
6145 | ArgsUnion Args(Arg); |
6146 | |
6147 | // If there wasn't one, add one (with an invalid source location |
6148 | // so that we don't make an AttributedType for it). |
6149 | ParsedAttr *attr = D.getAttributePool().create( |
6150 | attrName: &S.Context.Idents.get(Name: "objc_ownership" ), attrRange: SourceLocation(), |
6151 | /*scope*/ scopeName: nullptr, scopeLoc: SourceLocation(), |
6152 | /*args*/ &Args, numArgs: 1, form: ParsedAttr::Form::GNU()); |
6153 | chunk.getAttrs().addAtEnd(newAttr: attr); |
6154 | // TODO: mark whether we did this inference? |
6155 | } |
6156 | |
6157 | /// Used for transferring ownership in casts resulting in l-values. |
6158 | static void transferARCOwnership(TypeProcessingState &state, |
6159 | QualType &declSpecTy, |
6160 | Qualifiers::ObjCLifetime ownership) { |
6161 | Sema &S = state.getSema(); |
6162 | Declarator &D = state.getDeclarator(); |
6163 | |
6164 | int inner = -1; |
6165 | bool hasIndirection = false; |
6166 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { |
6167 | DeclaratorChunk &chunk = D.getTypeObject(i); |
6168 | switch (chunk.Kind) { |
6169 | case DeclaratorChunk::Paren: |
6170 | // Ignore parens. |
6171 | break; |
6172 | |
6173 | case DeclaratorChunk::Array: |
6174 | case DeclaratorChunk::Reference: |
6175 | case DeclaratorChunk::Pointer: |
6176 | if (inner != -1) |
6177 | hasIndirection = true; |
6178 | inner = i; |
6179 | break; |
6180 | |
6181 | case DeclaratorChunk::BlockPointer: |
6182 | if (inner != -1) |
6183 | transferARCOwnershipToDeclaratorChunk(state, ownership, chunkIndex: i); |
6184 | return; |
6185 | |
6186 | case DeclaratorChunk::Function: |
6187 | case DeclaratorChunk::MemberPointer: |
6188 | case DeclaratorChunk::Pipe: |
6189 | return; |
6190 | } |
6191 | } |
6192 | |
6193 | if (inner == -1) |
6194 | return; |
6195 | |
6196 | DeclaratorChunk &chunk = D.getTypeObject(i: inner); |
6197 | if (chunk.Kind == DeclaratorChunk::Pointer) { |
6198 | if (declSpecTy->isObjCRetainableType()) |
6199 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); |
6200 | if (declSpecTy->isObjCObjectType() && hasIndirection) |
6201 | return transferARCOwnershipToDeclaratorChunk(state, ownership, chunkIndex: inner); |
6202 | } else { |
6203 | assert(chunk.Kind == DeclaratorChunk::Array || |
6204 | chunk.Kind == DeclaratorChunk::Reference); |
6205 | return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership); |
6206 | } |
6207 | } |
6208 | |
6209 | TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) { |
6210 | TypeProcessingState state(*this, D); |
6211 | |
6212 | TypeSourceInfo *ReturnTypeInfo = nullptr; |
6213 | QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo); |
6214 | |
6215 | if (getLangOpts().ObjC) { |
6216 | Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(T: FromTy); |
6217 | if (ownership != Qualifiers::OCL_None) |
6218 | transferARCOwnership(state, declSpecTy, ownership); |
6219 | } |
6220 | |
6221 | return GetFullTypeForDeclarator(state, declSpecType: declSpecTy, TInfo: ReturnTypeInfo); |
6222 | } |
6223 | |
6224 | static void fillAttributedTypeLoc(AttributedTypeLoc TL, |
6225 | TypeProcessingState &State) { |
6226 | TL.setAttr(State.takeAttrForAttributedType(AT: TL.getTypePtr())); |
6227 | } |
6228 | |
6229 | static void fillMatrixTypeLoc(MatrixTypeLoc MTL, |
6230 | const ParsedAttributesView &Attrs) { |
6231 | for (const ParsedAttr &AL : Attrs) { |
6232 | if (AL.getKind() == ParsedAttr::AT_MatrixType) { |
6233 | MTL.setAttrNameLoc(AL.getLoc()); |
6234 | MTL.setAttrRowOperand(AL.getArgAsExpr(Arg: 0)); |
6235 | MTL.setAttrColumnOperand(AL.getArgAsExpr(Arg: 1)); |
6236 | MTL.setAttrOperandParensRange(SourceRange()); |
6237 | return; |
6238 | } |
6239 | } |
6240 | |
6241 | llvm_unreachable("no matrix_type attribute found at the expected location!" ); |
6242 | } |
6243 | |
6244 | namespace { |
6245 | class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { |
6246 | Sema &SemaRef; |
6247 | ASTContext &Context; |
6248 | TypeProcessingState &State; |
6249 | const DeclSpec &DS; |
6250 | |
6251 | public: |
6252 | TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State, |
6253 | const DeclSpec &DS) |
6254 | : SemaRef(S), Context(Context), State(State), DS(DS) {} |
6255 | |
6256 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { |
6257 | Visit(TyLoc: TL.getModifiedLoc()); |
6258 | fillAttributedTypeLoc(TL, State); |
6259 | } |
6260 | void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { |
6261 | Visit(TyLoc: TL.getWrappedLoc()); |
6262 | } |
6263 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { |
6264 | Visit(TyLoc: TL.getInnerLoc()); |
6265 | TL.setExpansionLoc( |
6266 | State.getExpansionLocForMacroQualifiedType(MQT: TL.getTypePtr())); |
6267 | } |
6268 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { |
6269 | Visit(TyLoc: TL.getUnqualifiedLoc()); |
6270 | } |
6271 | // Allow to fill pointee's type locations, e.g., |
6272 | // int __attr * __attr * __attr *p; |
6273 | void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); } |
6274 | void VisitTypedefTypeLoc(TypedefTypeLoc TL) { |
6275 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); |
6276 | } |
6277 | void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { |
6278 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); |
6279 | // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires |
6280 | // addition field. What we have is good enough for display of location |
6281 | // of 'fixit' on interface name. |
6282 | TL.setNameEndLoc(DS.getEndLoc()); |
6283 | } |
6284 | void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { |
6285 | TypeSourceInfo *RepTInfo = nullptr; |
6286 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &RepTInfo); |
6287 | TL.copy(RepTInfo->getTypeLoc()); |
6288 | } |
6289 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { |
6290 | TypeSourceInfo *RepTInfo = nullptr; |
6291 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &RepTInfo); |
6292 | TL.copy(RepTInfo->getTypeLoc()); |
6293 | } |
6294 | void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { |
6295 | TypeSourceInfo *TInfo = nullptr; |
6296 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo); |
6297 | |
6298 | // If we got no declarator info from previous Sema routines, |
6299 | // just fill with the typespec loc. |
6300 | if (!TInfo) { |
6301 | TL.initialize(Context, DS.getTypeSpecTypeNameLoc()); |
6302 | return; |
6303 | } |
6304 | |
6305 | TypeLoc OldTL = TInfo->getTypeLoc(); |
6306 | if (TInfo->getType()->getAs<ElaboratedType>()) { |
6307 | ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>(); |
6308 | TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc() |
6309 | .castAs<TemplateSpecializationTypeLoc>(); |
6310 | TL.copy(Loc: NamedTL); |
6311 | } else { |
6312 | TL.copy(Loc: OldTL.castAs<TemplateSpecializationTypeLoc>()); |
6313 | assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc()); |
6314 | } |
6315 | |
6316 | } |
6317 | void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { |
6318 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr || |
6319 | DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr); |
6320 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); |
6321 | TL.setParensRange(DS.getTypeofParensRange()); |
6322 | } |
6323 | void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { |
6324 | assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType || |
6325 | DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType); |
6326 | TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); |
6327 | TL.setParensRange(DS.getTypeofParensRange()); |
6328 | assert(DS.getRepAsType()); |
6329 | TypeSourceInfo *TInfo = nullptr; |
6330 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo); |
6331 | TL.setUnmodifiedTInfo(TInfo); |
6332 | } |
6333 | void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { |
6334 | assert(DS.getTypeSpecType() == DeclSpec::TST_decltype); |
6335 | TL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); |
6336 | TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); |
6337 | } |
6338 | void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) { |
6339 | assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing); |
6340 | TL.setEllipsisLoc(DS.getEllipsisLoc()); |
6341 | } |
6342 | void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { |
6343 | assert(DS.isTransformTypeTrait(DS.getTypeSpecType())); |
6344 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); |
6345 | TL.setParensRange(DS.getTypeofParensRange()); |
6346 | assert(DS.getRepAsType()); |
6347 | TypeSourceInfo *TInfo = nullptr; |
6348 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo); |
6349 | TL.setUnderlyingTInfo(TInfo); |
6350 | } |
6351 | void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { |
6352 | // By default, use the source location of the type specifier. |
6353 | TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); |
6354 | if (TL.needsExtraLocalData()) { |
6355 | // Set info for the written builtin specifiers. |
6356 | TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); |
6357 | // Try to have a meaningful source location. |
6358 | if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified) |
6359 | TL.expandBuiltinRange(Range: DS.getTypeSpecSignLoc()); |
6360 | if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified) |
6361 | TL.expandBuiltinRange(Range: DS.getTypeSpecWidthRange()); |
6362 | } |
6363 | } |
6364 | void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { |
6365 | if (DS.getTypeSpecType() == TST_typename) { |
6366 | TypeSourceInfo *TInfo = nullptr; |
6367 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo); |
6368 | if (TInfo) |
6369 | if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) { |
6370 | TL.copy(Loc: ETL); |
6371 | return; |
6372 | } |
6373 | } |
6374 | const ElaboratedType *T = TL.getTypePtr(); |
6375 | TL.setElaboratedKeywordLoc(T->getKeyword() != ElaboratedTypeKeyword::None |
6376 | ? DS.getTypeSpecTypeLoc() |
6377 | : SourceLocation()); |
6378 | const CXXScopeSpec& SS = DS.getTypeSpecScope(); |
6379 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
6380 | Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); |
6381 | } |
6382 | void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { |
6383 | assert(DS.getTypeSpecType() == TST_typename); |
6384 | TypeSourceInfo *TInfo = nullptr; |
6385 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo); |
6386 | assert(TInfo); |
6387 | TL.copy(Loc: TInfo->getTypeLoc().castAs<DependentNameTypeLoc>()); |
6388 | } |
6389 | void VisitDependentTemplateSpecializationTypeLoc( |
6390 | DependentTemplateSpecializationTypeLoc TL) { |
6391 | assert(DS.getTypeSpecType() == TST_typename); |
6392 | TypeSourceInfo *TInfo = nullptr; |
6393 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo); |
6394 | assert(TInfo); |
6395 | TL.copy( |
6396 | Loc: TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>()); |
6397 | } |
6398 | void VisitAutoTypeLoc(AutoTypeLoc TL) { |
6399 | assert(DS.getTypeSpecType() == TST_auto || |
6400 | DS.getTypeSpecType() == TST_decltype_auto || |
6401 | DS.getTypeSpecType() == TST_auto_type || |
6402 | DS.getTypeSpecType() == TST_unspecified); |
6403 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); |
6404 | if (DS.getTypeSpecType() == TST_decltype_auto) |
6405 | TL.setRParenLoc(DS.getTypeofParensRange().getEnd()); |
6406 | if (!DS.isConstrainedAuto()) |
6407 | return; |
6408 | TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId(); |
6409 | if (!TemplateId) |
6410 | return; |
6411 | |
6412 | NestedNameSpecifierLoc NNS = |
6413 | (DS.getTypeSpecScope().isNotEmpty() |
6414 | ? DS.getTypeSpecScope().getWithLocInContext(Context) |
6415 | : NestedNameSpecifierLoc()); |
6416 | TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc, |
6417 | TemplateId->RAngleLoc); |
6418 | if (TemplateId->NumArgs > 0) { |
6419 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
6420 | TemplateId->NumArgs); |
6421 | SemaRef.translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgsInfo); |
6422 | } |
6423 | DeclarationNameInfo DNI = DeclarationNameInfo( |
6424 | TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(), |
6425 | TemplateId->TemplateNameLoc); |
6426 | auto *CR = ConceptReference::Create( |
6427 | C: Context, NNS, TemplateKWLoc: TemplateId->TemplateKWLoc, ConceptNameInfo: DNI, |
6428 | /*FoundDecl=*/nullptr, |
6429 | /*NamedDecl=*/NamedConcept: TL.getTypePtr()->getTypeConstraintConcept(), |
6430 | ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgsInfo)); |
6431 | TL.setConceptReference(CR); |
6432 | } |
6433 | void VisitTagTypeLoc(TagTypeLoc TL) { |
6434 | TL.setNameLoc(DS.getTypeSpecTypeNameLoc()); |
6435 | } |
6436 | void VisitAtomicTypeLoc(AtomicTypeLoc TL) { |
6437 | // An AtomicTypeLoc can come from either an _Atomic(...) type specifier |
6438 | // or an _Atomic qualifier. |
6439 | if (DS.getTypeSpecType() == DeclSpec::TST_atomic) { |
6440 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); |
6441 | TL.setParensRange(DS.getTypeofParensRange()); |
6442 | |
6443 | TypeSourceInfo *TInfo = nullptr; |
6444 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo); |
6445 | assert(TInfo); |
6446 | TL.getValueLoc().initializeFullCopy(Other: TInfo->getTypeLoc()); |
6447 | } else { |
6448 | TL.setKWLoc(DS.getAtomicSpecLoc()); |
6449 | // No parens, to indicate this was spelled as an _Atomic qualifier. |
6450 | TL.setParensRange(SourceRange()); |
6451 | Visit(TyLoc: TL.getValueLoc()); |
6452 | } |
6453 | } |
6454 | |
6455 | void VisitPipeTypeLoc(PipeTypeLoc TL) { |
6456 | TL.setKWLoc(DS.getTypeSpecTypeLoc()); |
6457 | |
6458 | TypeSourceInfo *TInfo = nullptr; |
6459 | Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo); |
6460 | TL.getValueLoc().initializeFullCopy(Other: TInfo->getTypeLoc()); |
6461 | } |
6462 | |
6463 | void VisitExtIntTypeLoc(BitIntTypeLoc TL) { |
6464 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); |
6465 | } |
6466 | |
6467 | void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) { |
6468 | TL.setNameLoc(DS.getTypeSpecTypeLoc()); |
6469 | } |
6470 | |
6471 | void VisitTypeLoc(TypeLoc TL) { |
6472 | // FIXME: add other typespec types and change this to an assert. |
6473 | TL.initialize(Context, Loc: DS.getTypeSpecTypeLoc()); |
6474 | } |
6475 | }; |
6476 | |
6477 | class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { |
6478 | ASTContext &Context; |
6479 | TypeProcessingState &State; |
6480 | const DeclaratorChunk &Chunk; |
6481 | |
6482 | public: |
6483 | DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State, |
6484 | const DeclaratorChunk &Chunk) |
6485 | : Context(Context), State(State), Chunk(Chunk) {} |
6486 | |
6487 | void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { |
6488 | llvm_unreachable("qualified type locs not expected here!" ); |
6489 | } |
6490 | void VisitDecayedTypeLoc(DecayedTypeLoc TL) { |
6491 | llvm_unreachable("decayed type locs not expected here!" ); |
6492 | } |
6493 | |
6494 | void VisitAttributedTypeLoc(AttributedTypeLoc TL) { |
6495 | fillAttributedTypeLoc(TL, State); |
6496 | } |
6497 | void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) { |
6498 | // nothing |
6499 | } |
6500 | void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { |
6501 | // nothing |
6502 | } |
6503 | void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { |
6504 | assert(Chunk.Kind == DeclaratorChunk::BlockPointer); |
6505 | TL.setCaretLoc(Chunk.Loc); |
6506 | } |
6507 | void VisitPointerTypeLoc(PointerTypeLoc TL) { |
6508 | assert(Chunk.Kind == DeclaratorChunk::Pointer); |
6509 | TL.setStarLoc(Chunk.Loc); |
6510 | } |
6511 | void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { |
6512 | assert(Chunk.Kind == DeclaratorChunk::Pointer); |
6513 | TL.setStarLoc(Chunk.Loc); |
6514 | } |
6515 | void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { |
6516 | assert(Chunk.Kind == DeclaratorChunk::MemberPointer); |
6517 | const CXXScopeSpec& SS = Chunk.Mem.Scope(); |
6518 | NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context); |
6519 | |
6520 | const Type* ClsTy = TL.getClass(); |
6521 | QualType ClsQT = QualType(ClsTy, 0); |
6522 | TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(T: ClsQT, Size: 0); |
6523 | // Now copy source location info into the type loc component. |
6524 | TypeLoc ClsTL = ClsTInfo->getTypeLoc(); |
6525 | switch (NNSLoc.getNestedNameSpecifier()->getKind()) { |
6526 | case NestedNameSpecifier::Identifier: |
6527 | assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc" ); |
6528 | { |
6529 | DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>(); |
6530 | DNTLoc.setElaboratedKeywordLoc(SourceLocation()); |
6531 | DNTLoc.setQualifierLoc(NNSLoc.getPrefix()); |
6532 | DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc()); |
6533 | } |
6534 | break; |
6535 | |
6536 | case NestedNameSpecifier::TypeSpec: |
6537 | case NestedNameSpecifier::TypeSpecWithTemplate: |
6538 | if (isa<ElaboratedType>(Val: ClsTy)) { |
6539 | ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>(); |
6540 | ETLoc.setElaboratedKeywordLoc(SourceLocation()); |
6541 | ETLoc.setQualifierLoc(NNSLoc.getPrefix()); |
6542 | TypeLoc NamedTL = ETLoc.getNamedTypeLoc(); |
6543 | NamedTL.initializeFullCopy(Other: NNSLoc.getTypeLoc()); |
6544 | } else { |
6545 | ClsTL.initializeFullCopy(Other: NNSLoc.getTypeLoc()); |
6546 | } |
6547 | break; |
6548 | |
6549 | case NestedNameSpecifier::Namespace: |
6550 | case NestedNameSpecifier::NamespaceAlias: |
6551 | case NestedNameSpecifier::Global: |
6552 | case NestedNameSpecifier::Super: |
6553 | llvm_unreachable("Nested-name-specifier must name a type" ); |
6554 | } |
6555 | |
6556 | // Finally fill in MemberPointerLocInfo fields. |
6557 | TL.setStarLoc(Chunk.Mem.StarLoc); |
6558 | TL.setClassTInfo(ClsTInfo); |
6559 | } |
6560 | void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { |
6561 | assert(Chunk.Kind == DeclaratorChunk::Reference); |
6562 | // 'Amp' is misleading: this might have been originally |
6563 | /// spelled with AmpAmp. |
6564 | TL.setAmpLoc(Chunk.Loc); |
6565 | } |
6566 | void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { |
6567 | assert(Chunk.Kind == DeclaratorChunk::Reference); |
6568 | assert(!Chunk.Ref.LValueRef); |
6569 | TL.setAmpAmpLoc(Chunk.Loc); |
6570 | } |
6571 | void VisitArrayTypeLoc(ArrayTypeLoc TL) { |
6572 | assert(Chunk.Kind == DeclaratorChunk::Array); |
6573 | TL.setLBracketLoc(Chunk.Loc); |
6574 | TL.setRBracketLoc(Chunk.EndLoc); |
6575 | TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); |
6576 | } |
6577 | void VisitFunctionTypeLoc(FunctionTypeLoc TL) { |
6578 | assert(Chunk.Kind == DeclaratorChunk::Function); |
6579 | TL.setLocalRangeBegin(Chunk.Loc); |
6580 | TL.setLocalRangeEnd(Chunk.EndLoc); |
6581 | |
6582 | const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; |
6583 | TL.setLParenLoc(FTI.getLParenLoc()); |
6584 | TL.setRParenLoc(FTI.getRParenLoc()); |
6585 | for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) { |
6586 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param); |
6587 | TL.setParam(i: tpi++, VD: Param); |
6588 | } |
6589 | TL.setExceptionSpecRange(FTI.getExceptionSpecRange()); |
6590 | } |
6591 | void VisitParenTypeLoc(ParenTypeLoc TL) { |
6592 | assert(Chunk.Kind == DeclaratorChunk::Paren); |
6593 | TL.setLParenLoc(Chunk.Loc); |
6594 | TL.setRParenLoc(Chunk.EndLoc); |
6595 | } |
6596 | void VisitPipeTypeLoc(PipeTypeLoc TL) { |
6597 | assert(Chunk.Kind == DeclaratorChunk::Pipe); |
6598 | TL.setKWLoc(Chunk.Loc); |
6599 | } |
6600 | void VisitBitIntTypeLoc(BitIntTypeLoc TL) { |
6601 | TL.setNameLoc(Chunk.Loc); |
6602 | } |
6603 | void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { |
6604 | TL.setExpansionLoc(Chunk.Loc); |
6605 | } |
6606 | void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); } |
6607 | void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) { |
6608 | TL.setNameLoc(Chunk.Loc); |
6609 | } |
6610 | void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { |
6611 | TL.setNameLoc(Chunk.Loc); |
6612 | } |
6613 | void |
6614 | VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) { |
6615 | TL.setNameLoc(Chunk.Loc); |
6616 | } |
6617 | void VisitMatrixTypeLoc(MatrixTypeLoc TL) { |
6618 | fillMatrixTypeLoc(MTL: TL, Attrs: Chunk.getAttrs()); |
6619 | } |
6620 | |
6621 | void VisitTypeLoc(TypeLoc TL) { |
6622 | llvm_unreachable("unsupported TypeLoc kind in declarator!" ); |
6623 | } |
6624 | }; |
6625 | } // end anonymous namespace |
6626 | |
6627 | static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) { |
6628 | SourceLocation Loc; |
6629 | switch (Chunk.Kind) { |
6630 | case DeclaratorChunk::Function: |
6631 | case DeclaratorChunk::Array: |
6632 | case DeclaratorChunk::Paren: |
6633 | case DeclaratorChunk::Pipe: |
6634 | llvm_unreachable("cannot be _Atomic qualified" ); |
6635 | |
6636 | case DeclaratorChunk::Pointer: |
6637 | Loc = Chunk.Ptr.AtomicQualLoc; |
6638 | break; |
6639 | |
6640 | case DeclaratorChunk::BlockPointer: |
6641 | case DeclaratorChunk::Reference: |
6642 | case DeclaratorChunk::MemberPointer: |
6643 | // FIXME: Provide a source location for the _Atomic keyword. |
6644 | break; |
6645 | } |
6646 | |
6647 | ATL.setKWLoc(Loc); |
6648 | ATL.setParensRange(SourceRange()); |
6649 | } |
6650 | |
6651 | static void |
6652 | fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, |
6653 | const ParsedAttributesView &Attrs) { |
6654 | for (const ParsedAttr &AL : Attrs) { |
6655 | if (AL.getKind() == ParsedAttr::AT_AddressSpace) { |
6656 | DASTL.setAttrNameLoc(AL.getLoc()); |
6657 | DASTL.setAttrExprOperand(AL.getArgAsExpr(Arg: 0)); |
6658 | DASTL.setAttrOperandParensRange(SourceRange()); |
6659 | return; |
6660 | } |
6661 | } |
6662 | |
6663 | llvm_unreachable( |
6664 | "no address_space attribute found at the expected location!" ); |
6665 | } |
6666 | |
6667 | /// Create and instantiate a TypeSourceInfo with type source information. |
6668 | /// |
6669 | /// \param T QualType referring to the type as written in source code. |
6670 | /// |
6671 | /// \param ReturnTypeInfo For declarators whose return type does not show |
6672 | /// up in the normal place in the declaration specifiers (such as a C++ |
6673 | /// conversion function), this pointer will refer to a type source information |
6674 | /// for that return type. |
6675 | static TypeSourceInfo * |
6676 | GetTypeSourceInfoForDeclarator(TypeProcessingState &State, |
6677 | QualType T, TypeSourceInfo *ReturnTypeInfo) { |
6678 | Sema &S = State.getSema(); |
6679 | Declarator &D = State.getDeclarator(); |
6680 | |
6681 | TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T); |
6682 | UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); |
6683 | |
6684 | // Handle parameter packs whose type is a pack expansion. |
6685 | if (isa<PackExpansionType>(Val: T)) { |
6686 | CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc()); |
6687 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); |
6688 | } |
6689 | |
6690 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { |
6691 | // Microsoft property fields can have multiple sizeless array chunks |
6692 | // (i.e. int x[][][]). Don't create more than one level of incomplete array. |
6693 | if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 && |
6694 | D.getDeclSpec().getAttributes().hasMSPropertyAttr()) |
6695 | continue; |
6696 | |
6697 | // An AtomicTypeLoc might be produced by an atomic qualifier in this |
6698 | // declarator chunk. |
6699 | if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) { |
6700 | fillAtomicQualLoc(ATL, Chunk: D.getTypeObject(i)); |
6701 | CurrTL = ATL.getValueLoc().getUnqualifiedLoc(); |
6702 | } |
6703 | |
6704 | bool HasDesugaredTypeLoc = true; |
6705 | while (HasDesugaredTypeLoc) { |
6706 | switch (CurrTL.getTypeLocClass()) { |
6707 | case TypeLoc::MacroQualified: { |
6708 | auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>(); |
6709 | TL.setExpansionLoc( |
6710 | State.getExpansionLocForMacroQualifiedType(MQT: TL.getTypePtr())); |
6711 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); |
6712 | break; |
6713 | } |
6714 | |
6715 | case TypeLoc::Attributed: { |
6716 | auto TL = CurrTL.castAs<AttributedTypeLoc>(); |
6717 | fillAttributedTypeLoc(TL, State); |
6718 | CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc(); |
6719 | break; |
6720 | } |
6721 | |
6722 | case TypeLoc::Adjusted: |
6723 | case TypeLoc::BTFTagAttributed: { |
6724 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); |
6725 | break; |
6726 | } |
6727 | |
6728 | case TypeLoc::DependentAddressSpace: { |
6729 | auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>(); |
6730 | fillDependentAddressSpaceTypeLoc(DASTL: TL, Attrs: D.getTypeObject(i).getAttrs()); |
6731 | CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc(); |
6732 | break; |
6733 | } |
6734 | |
6735 | default: |
6736 | HasDesugaredTypeLoc = false; |
6737 | break; |
6738 | } |
6739 | } |
6740 | |
6741 | DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(TyLoc: CurrTL); |
6742 | CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); |
6743 | } |
6744 | |
6745 | // If we have different source information for the return type, use |
6746 | // that. This really only applies to C++ conversion functions. |
6747 | if (ReturnTypeInfo) { |
6748 | TypeLoc TL = ReturnTypeInfo->getTypeLoc(); |
6749 | assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); |
6750 | memcpy(dest: CurrTL.getOpaqueData(), src: TL.getOpaqueData(), n: TL.getFullDataSize()); |
6751 | } else { |
6752 | TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(TyLoc: CurrTL); |
6753 | } |
6754 | |
6755 | return TInfo; |
6756 | } |
6757 | |
6758 | /// Create a LocInfoType to hold the given QualType and TypeSourceInfo. |
6759 | ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) { |
6760 | // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser |
6761 | // and Sema during declaration parsing. Try deallocating/caching them when |
6762 | // it's appropriate, instead of allocating them and keeping them around. |
6763 | LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(Size: sizeof(LocInfoType), |
6764 | Alignment: alignof(LocInfoType)); |
6765 | new (LocT) LocInfoType(T, TInfo); |
6766 | assert(LocT->getTypeClass() != T->getTypeClass() && |
6767 | "LocInfoType's TypeClass conflicts with an existing Type class" ); |
6768 | return ParsedType::make(P: QualType(LocT, 0)); |
6769 | } |
6770 | |
6771 | void LocInfoType::getAsStringInternal(std::string &Str, |
6772 | const PrintingPolicy &Policy) const { |
6773 | llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*" |
6774 | " was used directly instead of getting the QualType through" |
6775 | " GetTypeFromParser" ); |
6776 | } |
6777 | |
6778 | TypeResult Sema::ActOnTypeName(Declarator &D) { |
6779 | // C99 6.7.6: Type names have no identifier. This is already validated by |
6780 | // the parser. |
6781 | assert(D.getIdentifier() == nullptr && |
6782 | "Type name should have no identifier!" ); |
6783 | |
6784 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
6785 | QualType T = TInfo->getType(); |
6786 | if (D.isInvalidType()) |
6787 | return true; |
6788 | |
6789 | // Make sure there are no unused decl attributes on the declarator. |
6790 | // We don't want to do this for ObjC parameters because we're going |
6791 | // to apply them to the actual parameter declaration. |
6792 | // Likewise, we don't want to do this for alias declarations, because |
6793 | // we are actually going to build a declaration from this eventually. |
6794 | if (D.getContext() != DeclaratorContext::ObjCParameter && |
6795 | D.getContext() != DeclaratorContext::AliasDecl && |
6796 | D.getContext() != DeclaratorContext::AliasTemplate) |
6797 | checkUnusedDeclAttributes(D); |
6798 | |
6799 | if (getLangOpts().CPlusPlus) { |
6800 | // Check that there are no default arguments (C++ only). |
6801 | CheckExtraCXXDefaultArguments(D); |
6802 | } |
6803 | |
6804 | return CreateParsedType(T, TInfo); |
6805 | } |
6806 | |
6807 | ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) { |
6808 | QualType T = Context.getObjCInstanceType(); |
6809 | TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc); |
6810 | return CreateParsedType(T, TInfo); |
6811 | } |
6812 | |
6813 | //===----------------------------------------------------------------------===// |
6814 | // Type Attribute Processing |
6815 | //===----------------------------------------------------------------------===// |
6816 | |
6817 | /// Build an AddressSpace index from a constant expression and diagnose any |
6818 | /// errors related to invalid address_spaces. Returns true on successfully |
6819 | /// building an AddressSpace index. |
6820 | static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, |
6821 | const Expr *AddrSpace, |
6822 | SourceLocation AttrLoc) { |
6823 | if (!AddrSpace->isValueDependent()) { |
6824 | std::optional<llvm::APSInt> OptAddrSpace = |
6825 | AddrSpace->getIntegerConstantExpr(Ctx: S.Context); |
6826 | if (!OptAddrSpace) { |
6827 | S.Diag(AttrLoc, diag::err_attribute_argument_type) |
6828 | << "'address_space'" << AANT_ArgumentIntegerConstant |
6829 | << AddrSpace->getSourceRange(); |
6830 | return false; |
6831 | } |
6832 | llvm::APSInt &addrSpace = *OptAddrSpace; |
6833 | |
6834 | // Bounds checking. |
6835 | if (addrSpace.isSigned()) { |
6836 | if (addrSpace.isNegative()) { |
6837 | S.Diag(AttrLoc, diag::err_attribute_address_space_negative) |
6838 | << AddrSpace->getSourceRange(); |
6839 | return false; |
6840 | } |
6841 | addrSpace.setIsSigned(false); |
6842 | } |
6843 | |
6844 | llvm::APSInt max(addrSpace.getBitWidth()); |
6845 | max = |
6846 | Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace; |
6847 | |
6848 | if (addrSpace > max) { |
6849 | S.Diag(AttrLoc, diag::err_attribute_address_space_too_high) |
6850 | << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange(); |
6851 | return false; |
6852 | } |
6853 | |
6854 | ASIdx = |
6855 | getLangASFromTargetAS(TargetAS: static_cast<unsigned>(addrSpace.getZExtValue())); |
6856 | return true; |
6857 | } |
6858 | |
6859 | // Default value for DependentAddressSpaceTypes |
6860 | ASIdx = LangAS::Default; |
6861 | return true; |
6862 | } |
6863 | |
6864 | /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression |
6865 | /// is uninstantiated. If instantiated it will apply the appropriate address |
6866 | /// space to the type. This function allows dependent template variables to be |
6867 | /// used in conjunction with the address_space attribute |
6868 | QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, |
6869 | SourceLocation AttrLoc) { |
6870 | if (!AddrSpace->isValueDependent()) { |
6871 | if (DiagnoseMultipleAddrSpaceAttributes(S&: *this, ASOld: T.getAddressSpace(), ASNew: ASIdx, |
6872 | AttrLoc)) |
6873 | return QualType(); |
6874 | |
6875 | return Context.getAddrSpaceQualType(T, AddressSpace: ASIdx); |
6876 | } |
6877 | |
6878 | // A check with similar intentions as checking if a type already has an |
6879 | // address space except for on a dependent types, basically if the |
6880 | // current type is already a DependentAddressSpaceType then its already |
6881 | // lined up to have another address space on it and we can't have |
6882 | // multiple address spaces on the one pointer indirection |
6883 | if (T->getAs<DependentAddressSpaceType>()) { |
6884 | Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers); |
6885 | return QualType(); |
6886 | } |
6887 | |
6888 | return Context.getDependentAddressSpaceType(PointeeType: T, AddrSpaceExpr: AddrSpace, AttrLoc); |
6889 | } |
6890 | |
6891 | QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, |
6892 | SourceLocation AttrLoc) { |
6893 | LangAS ASIdx; |
6894 | if (!BuildAddressSpaceIndex(S&: *this, ASIdx, AddrSpace, AttrLoc)) |
6895 | return QualType(); |
6896 | return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc); |
6897 | } |
6898 | |
6899 | static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, |
6900 | TypeProcessingState &State) { |
6901 | Sema &S = State.getSema(); |
6902 | |
6903 | // Check the number of attribute arguments. |
6904 | if (Attr.getNumArgs() != 1) { |
6905 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) |
6906 | << Attr << 1; |
6907 | Attr.setInvalid(); |
6908 | return; |
6909 | } |
6910 | |
6911 | // Ensure the argument is a string. |
6912 | auto *StrLiteral = dyn_cast<StringLiteral>(Val: Attr.getArgAsExpr(Arg: 0)); |
6913 | if (!StrLiteral) { |
6914 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) |
6915 | << Attr << AANT_ArgumentString; |
6916 | Attr.setInvalid(); |
6917 | return; |
6918 | } |
6919 | |
6920 | ASTContext &Ctx = S.Context; |
6921 | StringRef BTFTypeTag = StrLiteral->getString(); |
6922 | Type = State.getBTFTagAttributedType( |
6923 | ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type); |
6924 | } |
6925 | |
6926 | /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the |
6927 | /// specified type. The attribute contains 1 argument, the id of the address |
6928 | /// space for the type. |
6929 | static void HandleAddressSpaceTypeAttribute(QualType &Type, |
6930 | const ParsedAttr &Attr, |
6931 | TypeProcessingState &State) { |
6932 | Sema &S = State.getSema(); |
6933 | |
6934 | // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be |
6935 | // qualified by an address-space qualifier." |
6936 | if (Type->isFunctionType()) { |
6937 | S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type); |
6938 | Attr.setInvalid(); |
6939 | return; |
6940 | } |
6941 | |
6942 | LangAS ASIdx; |
6943 | if (Attr.getKind() == ParsedAttr::AT_AddressSpace) { |
6944 | |
6945 | // Check the attribute arguments. |
6946 | if (Attr.getNumArgs() != 1) { |
6947 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr |
6948 | << 1; |
6949 | Attr.setInvalid(); |
6950 | return; |
6951 | } |
6952 | |
6953 | Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(Arg: 0)); |
6954 | LangAS ASIdx; |
6955 | if (!BuildAddressSpaceIndex(S, ASIdx, AddrSpace: ASArgExpr, AttrLoc: Attr.getLoc())) { |
6956 | Attr.setInvalid(); |
6957 | return; |
6958 | } |
6959 | |
6960 | ASTContext &Ctx = S.Context; |
6961 | auto *ASAttr = |
6962 | ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx)); |
6963 | |
6964 | // If the expression is not value dependent (not templated), then we can |
6965 | // apply the address space qualifiers just to the equivalent type. |
6966 | // Otherwise, we make an AttributedType with the modified and equivalent |
6967 | // type the same, and wrap it in a DependentAddressSpaceType. When this |
6968 | // dependent type is resolved, the qualifier is added to the equivalent type |
6969 | // later. |
6970 | QualType T; |
6971 | if (!ASArgExpr->isValueDependent()) { |
6972 | QualType EquivType = |
6973 | S.BuildAddressSpaceAttr(T&: Type, ASIdx, AddrSpace: ASArgExpr, AttrLoc: Attr.getLoc()); |
6974 | if (EquivType.isNull()) { |
6975 | Attr.setInvalid(); |
6976 | return; |
6977 | } |
6978 | T = State.getAttributedType(A: ASAttr, ModifiedType: Type, EquivType); |
6979 | } else { |
6980 | T = State.getAttributedType(A: ASAttr, ModifiedType: Type, EquivType: Type); |
6981 | T = S.BuildAddressSpaceAttr(T, ASIdx, AddrSpace: ASArgExpr, AttrLoc: Attr.getLoc()); |
6982 | } |
6983 | |
6984 | if (!T.isNull()) |
6985 | Type = T; |
6986 | else |
6987 | Attr.setInvalid(); |
6988 | } else { |
6989 | // The keyword-based type attributes imply which address space to use. |
6990 | ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS() |
6991 | : Attr.asOpenCLLangAS(); |
6992 | if (S.getLangOpts().HLSL) |
6993 | ASIdx = Attr.asHLSLLangAS(); |
6994 | |
6995 | if (ASIdx == LangAS::Default) |
6996 | llvm_unreachable("Invalid address space" ); |
6997 | |
6998 | if (DiagnoseMultipleAddrSpaceAttributes(S, ASOld: Type.getAddressSpace(), ASNew: ASIdx, |
6999 | AttrLoc: Attr.getLoc())) { |
7000 | Attr.setInvalid(); |
7001 | return; |
7002 | } |
7003 | |
7004 | Type = S.Context.getAddrSpaceQualType(T: Type, AddressSpace: ASIdx); |
7005 | } |
7006 | } |
7007 | |
7008 | /// handleObjCOwnershipTypeAttr - Process an objc_ownership |
7009 | /// attribute on the specified type. |
7010 | /// |
7011 | /// Returns 'true' if the attribute was handled. |
7012 | static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, |
7013 | ParsedAttr &attr, QualType &type) { |
7014 | bool NonObjCPointer = false; |
7015 | |
7016 | if (!type->isDependentType() && !type->isUndeducedType()) { |
7017 | if (const PointerType *ptr = type->getAs<PointerType>()) { |
7018 | QualType pointee = ptr->getPointeeType(); |
7019 | if (pointee->isObjCRetainableType() || pointee->isPointerType()) |
7020 | return false; |
7021 | // It is important not to lose the source info that there was an attribute |
7022 | // applied to non-objc pointer. We will create an attributed type but |
7023 | // its type will be the same as the original type. |
7024 | NonObjCPointer = true; |
7025 | } else if (!type->isObjCRetainableType()) { |
7026 | return false; |
7027 | } |
7028 | |
7029 | // Don't accept an ownership attribute in the declspec if it would |
7030 | // just be the return type of a block pointer. |
7031 | if (state.isProcessingDeclSpec()) { |
7032 | Declarator &D = state.getDeclarator(); |
7033 | if (maybeMovePastReturnType(declarator&: D, i: D.getNumTypeObjects(), |
7034 | /*onlyBlockPointers=*/true)) |
7035 | return false; |
7036 | } |
7037 | } |
7038 | |
7039 | Sema &S = state.getSema(); |
7040 | SourceLocation AttrLoc = attr.getLoc(); |
7041 | if (AttrLoc.isMacroID()) |
7042 | AttrLoc = |
7043 | S.getSourceManager().getImmediateExpansionRange(Loc: AttrLoc).getBegin(); |
7044 | |
7045 | if (!attr.isArgIdent(Arg: 0)) { |
7046 | S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr |
7047 | << AANT_ArgumentString; |
7048 | attr.setInvalid(); |
7049 | return true; |
7050 | } |
7051 | |
7052 | IdentifierInfo *II = attr.getArgAsIdent(Arg: 0)->Ident; |
7053 | Qualifiers::ObjCLifetime lifetime; |
7054 | if (II->isStr(Str: "none" )) |
7055 | lifetime = Qualifiers::OCL_ExplicitNone; |
7056 | else if (II->isStr(Str: "strong" )) |
7057 | lifetime = Qualifiers::OCL_Strong; |
7058 | else if (II->isStr(Str: "weak" )) |
7059 | lifetime = Qualifiers::OCL_Weak; |
7060 | else if (II->isStr(Str: "autoreleasing" )) |
7061 | lifetime = Qualifiers::OCL_Autoreleasing; |
7062 | else { |
7063 | S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II; |
7064 | attr.setInvalid(); |
7065 | return true; |
7066 | } |
7067 | |
7068 | // Just ignore lifetime attributes other than __weak and __unsafe_unretained |
7069 | // outside of ARC mode. |
7070 | if (!S.getLangOpts().ObjCAutoRefCount && |
7071 | lifetime != Qualifiers::OCL_Weak && |
7072 | lifetime != Qualifiers::OCL_ExplicitNone) { |
7073 | return true; |
7074 | } |
7075 | |
7076 | SplitQualType underlyingType = type.split(); |
7077 | |
7078 | // Check for redundant/conflicting ownership qualifiers. |
7079 | if (Qualifiers::ObjCLifetime previousLifetime |
7080 | = type.getQualifiers().getObjCLifetime()) { |
7081 | // If it's written directly, that's an error. |
7082 | if (S.Context.hasDirectOwnershipQualifier(Ty: type)) { |
7083 | S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant) |
7084 | << type; |
7085 | return true; |
7086 | } |
7087 | |
7088 | // Otherwise, if the qualifiers actually conflict, pull sugar off |
7089 | // and remove the ObjCLifetime qualifiers. |
7090 | if (previousLifetime != lifetime) { |
7091 | // It's possible to have multiple local ObjCLifetime qualifiers. We |
7092 | // can't stop after we reach a type that is directly qualified. |
7093 | const Type *prevTy = nullptr; |
7094 | while (!prevTy || prevTy != underlyingType.Ty) { |
7095 | prevTy = underlyingType.Ty; |
7096 | underlyingType = underlyingType.getSingleStepDesugaredType(); |
7097 | } |
7098 | underlyingType.Quals.removeObjCLifetime(); |
7099 | } |
7100 | } |
7101 | |
7102 | underlyingType.Quals.addObjCLifetime(type: lifetime); |
7103 | |
7104 | if (NonObjCPointer) { |
7105 | StringRef name = attr.getAttrName()->getName(); |
7106 | switch (lifetime) { |
7107 | case Qualifiers::OCL_None: |
7108 | case Qualifiers::OCL_ExplicitNone: |
7109 | break; |
7110 | case Qualifiers::OCL_Strong: name = "__strong" ; break; |
7111 | case Qualifiers::OCL_Weak: name = "__weak" ; break; |
7112 | case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing" ; break; |
7113 | } |
7114 | S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name |
7115 | << TDS_ObjCObjOrBlock << type; |
7116 | } |
7117 | |
7118 | // Don't actually add the __unsafe_unretained qualifier in non-ARC files, |
7119 | // because having both 'T' and '__unsafe_unretained T' exist in the type |
7120 | // system causes unfortunate widespread consistency problems. (For example, |
7121 | // they're not considered compatible types, and we mangle them identicially |
7122 | // as template arguments.) These problems are all individually fixable, |
7123 | // but it's easier to just not add the qualifier and instead sniff it out |
7124 | // in specific places using isObjCInertUnsafeUnretainedType(). |
7125 | // |
7126 | // Doing this does means we miss some trivial consistency checks that |
7127 | // would've triggered in ARC, but that's better than trying to solve all |
7128 | // the coexistence problems with __unsafe_unretained. |
7129 | if (!S.getLangOpts().ObjCAutoRefCount && |
7130 | lifetime == Qualifiers::OCL_ExplicitNone) { |
7131 | type = state.getAttributedType( |
7132 | createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr), |
7133 | type, type); |
7134 | return true; |
7135 | } |
7136 | |
7137 | QualType origType = type; |
7138 | if (!NonObjCPointer) |
7139 | type = S.Context.getQualifiedType(split: underlyingType); |
7140 | |
7141 | // If we have a valid source location for the attribute, use an |
7142 | // AttributedType instead. |
7143 | if (AttrLoc.isValid()) { |
7144 | type = state.getAttributedType(::new (S.Context) |
7145 | ObjCOwnershipAttr(S.Context, attr, II), |
7146 | origType, type); |
7147 | } |
7148 | |
7149 | auto diagnoseOrDelay = [](Sema &S, SourceLocation loc, |
7150 | unsigned diagnostic, QualType type) { |
7151 | if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { |
7152 | S.DelayedDiagnostics.add( |
7153 | diag: sema::DelayedDiagnostic::makeForbiddenType( |
7154 | loc: S.getSourceManager().getExpansionLoc(Loc: loc), |
7155 | diagnostic, type, /*ignored*/ argument: 0)); |
7156 | } else { |
7157 | S.Diag(Loc: loc, DiagID: diagnostic); |
7158 | } |
7159 | }; |
7160 | |
7161 | // Sometimes, __weak isn't allowed. |
7162 | if (lifetime == Qualifiers::OCL_Weak && |
7163 | !S.getLangOpts().ObjCWeak && !NonObjCPointer) { |
7164 | |
7165 | // Use a specialized diagnostic if the runtime just doesn't support them. |
7166 | unsigned diagnostic = |
7167 | (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled |
7168 | : diag::err_arc_weak_no_runtime); |
7169 | |
7170 | // In any case, delay the diagnostic until we know what we're parsing. |
7171 | diagnoseOrDelay(S, AttrLoc, diagnostic, type); |
7172 | |
7173 | attr.setInvalid(); |
7174 | return true; |
7175 | } |
7176 | |
7177 | // Forbid __weak for class objects marked as |
7178 | // objc_arc_weak_reference_unavailable |
7179 | if (lifetime == Qualifiers::OCL_Weak) { |
7180 | if (const ObjCObjectPointerType *ObjT = |
7181 | type->getAs<ObjCObjectPointerType>()) { |
7182 | if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) { |
7183 | if (Class->isArcWeakrefUnavailable()) { |
7184 | S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class); |
7185 | S.Diag(ObjT->getInterfaceDecl()->getLocation(), |
7186 | diag::note_class_declared); |
7187 | } |
7188 | } |
7189 | } |
7190 | } |
7191 | |
7192 | return true; |
7193 | } |
7194 | |
7195 | /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type |
7196 | /// attribute on the specified type. Returns true to indicate that |
7197 | /// the attribute was handled, false to indicate that the type does |
7198 | /// not permit the attribute. |
7199 | static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, |
7200 | QualType &type) { |
7201 | Sema &S = state.getSema(); |
7202 | |
7203 | // Delay if this isn't some kind of pointer. |
7204 | if (!type->isPointerType() && |
7205 | !type->isObjCObjectPointerType() && |
7206 | !type->isBlockPointerType()) |
7207 | return false; |
7208 | |
7209 | if (type.getObjCGCAttr() != Qualifiers::GCNone) { |
7210 | S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc); |
7211 | attr.setInvalid(); |
7212 | return true; |
7213 | } |
7214 | |
7215 | // Check the attribute arguments. |
7216 | if (!attr.isArgIdent(Arg: 0)) { |
7217 | S.Diag(attr.getLoc(), diag::err_attribute_argument_type) |
7218 | << attr << AANT_ArgumentString; |
7219 | attr.setInvalid(); |
7220 | return true; |
7221 | } |
7222 | Qualifiers::GC GCAttr; |
7223 | if (attr.getNumArgs() > 1) { |
7224 | S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr |
7225 | << 1; |
7226 | attr.setInvalid(); |
7227 | return true; |
7228 | } |
7229 | |
7230 | IdentifierInfo *II = attr.getArgAsIdent(Arg: 0)->Ident; |
7231 | if (II->isStr(Str: "weak" )) |
7232 | GCAttr = Qualifiers::Weak; |
7233 | else if (II->isStr(Str: "strong" )) |
7234 | GCAttr = Qualifiers::Strong; |
7235 | else { |
7236 | S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported) |
7237 | << attr << II; |
7238 | attr.setInvalid(); |
7239 | return true; |
7240 | } |
7241 | |
7242 | QualType origType = type; |
7243 | type = S.Context.getObjCGCQualType(T: origType, gcAttr: GCAttr); |
7244 | |
7245 | // Make an attributed type to preserve the source information. |
7246 | if (attr.getLoc().isValid()) |
7247 | type = state.getAttributedType( |
7248 | ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type); |
7249 | |
7250 | return true; |
7251 | } |
7252 | |
7253 | namespace { |
7254 | /// A helper class to unwrap a type down to a function for the |
7255 | /// purposes of applying attributes there. |
7256 | /// |
7257 | /// Use: |
7258 | /// FunctionTypeUnwrapper unwrapped(SemaRef, T); |
7259 | /// if (unwrapped.isFunctionType()) { |
7260 | /// const FunctionType *fn = unwrapped.get(); |
7261 | /// // change fn somehow |
7262 | /// T = unwrapped.wrap(fn); |
7263 | /// } |
7264 | struct FunctionTypeUnwrapper { |
7265 | enum WrapKind { |
7266 | Desugar, |
7267 | Attributed, |
7268 | Parens, |
7269 | Array, |
7270 | Pointer, |
7271 | BlockPointer, |
7272 | Reference, |
7273 | MemberPointer, |
7274 | MacroQualified, |
7275 | }; |
7276 | |
7277 | QualType Original; |
7278 | const FunctionType *Fn; |
7279 | SmallVector<unsigned char /*WrapKind*/, 8> Stack; |
7280 | |
7281 | FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) { |
7282 | while (true) { |
7283 | const Type *Ty = T.getTypePtr(); |
7284 | if (isa<FunctionType>(Val: Ty)) { |
7285 | Fn = cast<FunctionType>(Val: Ty); |
7286 | return; |
7287 | } else if (isa<ParenType>(Val: Ty)) { |
7288 | T = cast<ParenType>(Val: Ty)->getInnerType(); |
7289 | Stack.push_back(Elt: Parens); |
7290 | } else if (isa<ConstantArrayType>(Val: Ty) || isa<VariableArrayType>(Val: Ty) || |
7291 | isa<IncompleteArrayType>(Val: Ty)) { |
7292 | T = cast<ArrayType>(Val: Ty)->getElementType(); |
7293 | Stack.push_back(Elt: Array); |
7294 | } else if (isa<PointerType>(Val: Ty)) { |
7295 | T = cast<PointerType>(Val: Ty)->getPointeeType(); |
7296 | Stack.push_back(Elt: Pointer); |
7297 | } else if (isa<BlockPointerType>(Val: Ty)) { |
7298 | T = cast<BlockPointerType>(Val: Ty)->getPointeeType(); |
7299 | Stack.push_back(Elt: BlockPointer); |
7300 | } else if (isa<MemberPointerType>(Val: Ty)) { |
7301 | T = cast<MemberPointerType>(Val: Ty)->getPointeeType(); |
7302 | Stack.push_back(Elt: MemberPointer); |
7303 | } else if (isa<ReferenceType>(Val: Ty)) { |
7304 | T = cast<ReferenceType>(Val: Ty)->getPointeeType(); |
7305 | Stack.push_back(Elt: Reference); |
7306 | } else if (isa<AttributedType>(Val: Ty)) { |
7307 | T = cast<AttributedType>(Val: Ty)->getEquivalentType(); |
7308 | Stack.push_back(Elt: Attributed); |
7309 | } else if (isa<MacroQualifiedType>(Val: Ty)) { |
7310 | T = cast<MacroQualifiedType>(Val: Ty)->getUnderlyingType(); |
7311 | Stack.push_back(Elt: MacroQualified); |
7312 | } else { |
7313 | const Type *DTy = Ty->getUnqualifiedDesugaredType(); |
7314 | if (Ty == DTy) { |
7315 | Fn = nullptr; |
7316 | return; |
7317 | } |
7318 | |
7319 | T = QualType(DTy, 0); |
7320 | Stack.push_back(Elt: Desugar); |
7321 | } |
7322 | } |
7323 | } |
7324 | |
7325 | bool isFunctionType() const { return (Fn != nullptr); } |
7326 | const FunctionType *get() const { return Fn; } |
7327 | |
7328 | QualType wrap(Sema &S, const FunctionType *New) { |
7329 | // If T wasn't modified from the unwrapped type, do nothing. |
7330 | if (New == get()) return Original; |
7331 | |
7332 | Fn = New; |
7333 | return wrap(S.Context, Original, 0); |
7334 | } |
7335 | |
7336 | private: |
7337 | QualType wrap(ASTContext &C, QualType Old, unsigned I) { |
7338 | if (I == Stack.size()) |
7339 | return C.getQualifiedType(Fn, Old.getQualifiers()); |
7340 | |
7341 | // Build up the inner type, applying the qualifiers from the old |
7342 | // type to the new type. |
7343 | SplitQualType SplitOld = Old.split(); |
7344 | |
7345 | // As a special case, tail-recurse if there are no qualifiers. |
7346 | if (SplitOld.Quals.empty()) |
7347 | return wrap(C, Old: SplitOld.Ty, I); |
7348 | return C.getQualifiedType(T: wrap(C, Old: SplitOld.Ty, I), Qs: SplitOld.Quals); |
7349 | } |
7350 | |
7351 | QualType wrap(ASTContext &C, const Type *Old, unsigned I) { |
7352 | if (I == Stack.size()) return QualType(Fn, 0); |
7353 | |
7354 | switch (static_cast<WrapKind>(Stack[I++])) { |
7355 | case Desugar: |
7356 | // This is the point at which we potentially lose source |
7357 | // information. |
7358 | return wrap(C, Old: Old->getUnqualifiedDesugaredType(), I); |
7359 | |
7360 | case Attributed: |
7361 | return wrap(C, Old: cast<AttributedType>(Val: Old)->getEquivalentType(), I); |
7362 | |
7363 | case Parens: { |
7364 | QualType New = wrap(C, Old: cast<ParenType>(Val: Old)->getInnerType(), I); |
7365 | return C.getParenType(NamedType: New); |
7366 | } |
7367 | |
7368 | case MacroQualified: |
7369 | return wrap(C, Old: cast<MacroQualifiedType>(Val: Old)->getUnderlyingType(), I); |
7370 | |
7371 | case Array: { |
7372 | if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: Old)) { |
7373 | QualType New = wrap(C, CAT->getElementType(), I); |
7374 | return C.getConstantArrayType(EltTy: New, ArySize: CAT->getSize(), SizeExpr: CAT->getSizeExpr(), |
7375 | ASM: CAT->getSizeModifier(), |
7376 | IndexTypeQuals: CAT->getIndexTypeCVRQualifiers()); |
7377 | } |
7378 | |
7379 | if (const auto *VAT = dyn_cast<VariableArrayType>(Val: Old)) { |
7380 | QualType New = wrap(C, VAT->getElementType(), I); |
7381 | return C.getVariableArrayType( |
7382 | EltTy: New, NumElts: VAT->getSizeExpr(), ASM: VAT->getSizeModifier(), |
7383 | IndexTypeQuals: VAT->getIndexTypeCVRQualifiers(), Brackets: VAT->getBracketsRange()); |
7384 | } |
7385 | |
7386 | const auto *IAT = cast<IncompleteArrayType>(Val: Old); |
7387 | QualType New = wrap(C, IAT->getElementType(), I); |
7388 | return C.getIncompleteArrayType(EltTy: New, ASM: IAT->getSizeModifier(), |
7389 | IndexTypeQuals: IAT->getIndexTypeCVRQualifiers()); |
7390 | } |
7391 | |
7392 | case Pointer: { |
7393 | QualType New = wrap(C, Old: cast<PointerType>(Val: Old)->getPointeeType(), I); |
7394 | return C.getPointerType(T: New); |
7395 | } |
7396 | |
7397 | case BlockPointer: { |
7398 | QualType New = wrap(C, Old: cast<BlockPointerType>(Val: Old)->getPointeeType(),I); |
7399 | return C.getBlockPointerType(T: New); |
7400 | } |
7401 | |
7402 | case MemberPointer: { |
7403 | const MemberPointerType *OldMPT = cast<MemberPointerType>(Val: Old); |
7404 | QualType New = wrap(C, Old: OldMPT->getPointeeType(), I); |
7405 | return C.getMemberPointerType(T: New, Cls: OldMPT->getClass()); |
7406 | } |
7407 | |
7408 | case Reference: { |
7409 | const ReferenceType *OldRef = cast<ReferenceType>(Val: Old); |
7410 | QualType New = wrap(C, Old: OldRef->getPointeeType(), I); |
7411 | if (isa<LValueReferenceType>(Val: OldRef)) |
7412 | return C.getLValueReferenceType(T: New, SpelledAsLValue: OldRef->isSpelledAsLValue()); |
7413 | else |
7414 | return C.getRValueReferenceType(T: New); |
7415 | } |
7416 | } |
7417 | |
7418 | llvm_unreachable("unknown wrapping kind" ); |
7419 | } |
7420 | }; |
7421 | } // end anonymous namespace |
7422 | |
7423 | static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State, |
7424 | ParsedAttr &PAttr, QualType &Type) { |
7425 | Sema &S = State.getSema(); |
7426 | |
7427 | Attr *A; |
7428 | switch (PAttr.getKind()) { |
7429 | default: llvm_unreachable("Unknown attribute kind" ); |
7430 | case ParsedAttr::AT_Ptr32: |
7431 | A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr); |
7432 | break; |
7433 | case ParsedAttr::AT_Ptr64: |
7434 | A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr); |
7435 | break; |
7436 | case ParsedAttr::AT_SPtr: |
7437 | A = createSimpleAttr<SPtrAttr>(S.Context, PAttr); |
7438 | break; |
7439 | case ParsedAttr::AT_UPtr: |
7440 | A = createSimpleAttr<UPtrAttr>(S.Context, PAttr); |
7441 | break; |
7442 | } |
7443 | |
7444 | std::bitset<attr::LastAttr> Attrs; |
7445 | QualType Desugared = Type; |
7446 | for (;;) { |
7447 | if (const TypedefType *TT = dyn_cast<TypedefType>(Val&: Desugared)) { |
7448 | Desugared = TT->desugar(); |
7449 | continue; |
7450 | } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Val&: Desugared)) { |
7451 | Desugared = ET->desugar(); |
7452 | continue; |
7453 | } |
7454 | const AttributedType *AT = dyn_cast<AttributedType>(Val&: Desugared); |
7455 | if (!AT) |
7456 | break; |
7457 | Attrs[AT->getAttrKind()] = true; |
7458 | Desugared = AT->getModifiedType(); |
7459 | } |
7460 | |
7461 | // You cannot specify duplicate type attributes, so if the attribute has |
7462 | // already been applied, flag it. |
7463 | attr::Kind NewAttrKind = A->getKind(); |
7464 | if (Attrs[NewAttrKind]) { |
7465 | S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; |
7466 | return true; |
7467 | } |
7468 | Attrs[NewAttrKind] = true; |
7469 | |
7470 | // You cannot have both __sptr and __uptr on the same type, nor can you |
7471 | // have __ptr32 and __ptr64. |
7472 | if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) { |
7473 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) |
7474 | << "'__ptr32'" |
7475 | << "'__ptr64'" << /*isRegularKeyword=*/0; |
7476 | return true; |
7477 | } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) { |
7478 | S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible) |
7479 | << "'__sptr'" |
7480 | << "'__uptr'" << /*isRegularKeyword=*/0; |
7481 | return true; |
7482 | } |
7483 | |
7484 | // Check the raw (i.e., desugared) Canonical type to see if it |
7485 | // is a pointer type. |
7486 | if (!isa<PointerType>(Val: Desugared)) { |
7487 | // Pointer type qualifiers can only operate on pointer types, but not |
7488 | // pointer-to-member types. |
7489 | if (Type->isMemberPointerType()) |
7490 | S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr; |
7491 | else |
7492 | S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0; |
7493 | return true; |
7494 | } |
7495 | |
7496 | // Add address space to type based on its attributes. |
7497 | LangAS ASIdx = LangAS::Default; |
7498 | uint64_t PtrWidth = |
7499 | S.Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default); |
7500 | if (PtrWidth == 32) { |
7501 | if (Attrs[attr::Ptr64]) |
7502 | ASIdx = LangAS::ptr64; |
7503 | else if (Attrs[attr::UPtr]) |
7504 | ASIdx = LangAS::ptr32_uptr; |
7505 | } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) { |
7506 | if (Attrs[attr::UPtr]) |
7507 | ASIdx = LangAS::ptr32_uptr; |
7508 | else |
7509 | ASIdx = LangAS::ptr32_sptr; |
7510 | } |
7511 | |
7512 | QualType Pointee = Type->getPointeeType(); |
7513 | if (ASIdx != LangAS::Default) |
7514 | Pointee = S.Context.getAddrSpaceQualType( |
7515 | T: S.Context.removeAddrSpaceQualType(T: Pointee), AddressSpace: ASIdx); |
7516 | Type = State.getAttributedType(A, ModifiedType: Type, EquivType: S.Context.getPointerType(T: Pointee)); |
7517 | return false; |
7518 | } |
7519 | |
7520 | static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State, |
7521 | QualType &QT, ParsedAttr &PAttr) { |
7522 | assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref); |
7523 | |
7524 | Sema &S = State.getSema(); |
7525 | Attr *A = createSimpleAttr<WebAssemblyFuncrefAttr>(S.Context, PAttr); |
7526 | |
7527 | std::bitset<attr::LastAttr> Attrs; |
7528 | attr::Kind NewAttrKind = A->getKind(); |
7529 | const auto *AT = dyn_cast<AttributedType>(Val&: QT); |
7530 | while (AT) { |
7531 | Attrs[AT->getAttrKind()] = true; |
7532 | AT = dyn_cast<AttributedType>(Val: AT->getModifiedType()); |
7533 | } |
7534 | |
7535 | // You cannot specify duplicate type attributes, so if the attribute has |
7536 | // already been applied, flag it. |
7537 | if (Attrs[NewAttrKind]) { |
7538 | S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr; |
7539 | return true; |
7540 | } |
7541 | |
7542 | // Add address space to type based on its attributes. |
7543 | LangAS ASIdx = LangAS::wasm_funcref; |
7544 | QualType Pointee = QT->getPointeeType(); |
7545 | Pointee = S.Context.getAddrSpaceQualType( |
7546 | T: S.Context.removeAddrSpaceQualType(T: Pointee), AddressSpace: ASIdx); |
7547 | QT = State.getAttributedType(A, ModifiedType: QT, EquivType: S.Context.getPointerType(T: Pointee)); |
7548 | return false; |
7549 | } |
7550 | |
7551 | /// Rebuild an attributed type without the nullability attribute on it. |
7552 | static QualType rebuildAttributedTypeWithoutNullability(ASTContext &Ctx, |
7553 | QualType Type) { |
7554 | auto Attributed = dyn_cast<AttributedType>(Val: Type.getTypePtr()); |
7555 | if (!Attributed) |
7556 | return Type; |
7557 | |
7558 | // Skip the nullability attribute; we're done. |
7559 | if (Attributed->getImmediateNullability()) |
7560 | return Attributed->getModifiedType(); |
7561 | |
7562 | // Build the modified type. |
7563 | QualType Modified = rebuildAttributedTypeWithoutNullability( |
7564 | Ctx, Type: Attributed->getModifiedType()); |
7565 | assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr()); |
7566 | return Ctx.getAttributedType(attrKind: Attributed->getAttrKind(), modifiedType: Modified, |
7567 | equivalentType: Attributed->getEquivalentType()); |
7568 | } |
7569 | |
7570 | /// Map a nullability attribute kind to a nullability kind. |
7571 | static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) { |
7572 | switch (kind) { |
7573 | case ParsedAttr::AT_TypeNonNull: |
7574 | return NullabilityKind::NonNull; |
7575 | |
7576 | case ParsedAttr::AT_TypeNullable: |
7577 | return NullabilityKind::Nullable; |
7578 | |
7579 | case ParsedAttr::AT_TypeNullableResult: |
7580 | return NullabilityKind::NullableResult; |
7581 | |
7582 | case ParsedAttr::AT_TypeNullUnspecified: |
7583 | return NullabilityKind::Unspecified; |
7584 | |
7585 | default: |
7586 | llvm_unreachable("not a nullability attribute kind" ); |
7587 | } |
7588 | } |
7589 | |
7590 | static bool CheckNullabilityTypeSpecifier( |
7591 | Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT, |
7592 | NullabilityKind Nullability, SourceLocation NullabilityLoc, |
7593 | bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) { |
7594 | bool Implicit = (State == nullptr); |
7595 | if (!Implicit) |
7596 | recordNullabilitySeen(S, loc: NullabilityLoc); |
7597 | |
7598 | // Check for existing nullability attributes on the type. |
7599 | QualType Desugared = QT; |
7600 | while (auto *Attributed = dyn_cast<AttributedType>(Val: Desugared.getTypePtr())) { |
7601 | // Check whether there is already a null |
7602 | if (auto ExistingNullability = Attributed->getImmediateNullability()) { |
7603 | // Duplicated nullability. |
7604 | if (Nullability == *ExistingNullability) { |
7605 | if (Implicit) |
7606 | break; |
7607 | |
7608 | S.Diag(NullabilityLoc, diag::warn_nullability_duplicate) |
7609 | << DiagNullabilityKind(Nullability, IsContextSensitive) |
7610 | << FixItHint::CreateRemoval(NullabilityLoc); |
7611 | |
7612 | break; |
7613 | } |
7614 | |
7615 | if (!OverrideExisting) { |
7616 | // Conflicting nullability. |
7617 | S.Diag(NullabilityLoc, diag::err_nullability_conflicting) |
7618 | << DiagNullabilityKind(Nullability, IsContextSensitive) |
7619 | << DiagNullabilityKind(*ExistingNullability, false); |
7620 | return true; |
7621 | } |
7622 | |
7623 | // Rebuild the attributed type, dropping the existing nullability. |
7624 | QT = rebuildAttributedTypeWithoutNullability(Ctx&: S.Context, Type: QT); |
7625 | } |
7626 | |
7627 | Desugared = Attributed->getModifiedType(); |
7628 | } |
7629 | |
7630 | // If there is already a different nullability specifier, complain. |
7631 | // This (unlike the code above) looks through typedefs that might |
7632 | // have nullability specifiers on them, which means we cannot |
7633 | // provide a useful Fix-It. |
7634 | if (auto ExistingNullability = Desugared->getNullability()) { |
7635 | if (Nullability != *ExistingNullability && !Implicit) { |
7636 | S.Diag(NullabilityLoc, diag::err_nullability_conflicting) |
7637 | << DiagNullabilityKind(Nullability, IsContextSensitive) |
7638 | << DiagNullabilityKind(*ExistingNullability, false); |
7639 | |
7640 | // Try to find the typedef with the existing nullability specifier. |
7641 | if (auto TT = Desugared->getAs<TypedefType>()) { |
7642 | TypedefNameDecl *typedefDecl = TT->getDecl(); |
7643 | QualType underlyingType = typedefDecl->getUnderlyingType(); |
7644 | if (auto typedefNullability = |
7645 | AttributedType::stripOuterNullability(T&: underlyingType)) { |
7646 | if (*typedefNullability == *ExistingNullability) { |
7647 | S.Diag(typedefDecl->getLocation(), diag::note_nullability_here) |
7648 | << DiagNullabilityKind(*ExistingNullability, false); |
7649 | } |
7650 | } |
7651 | } |
7652 | |
7653 | return true; |
7654 | } |
7655 | } |
7656 | |
7657 | // If this definitely isn't a pointer type, reject the specifier. |
7658 | if (!Desugared->canHaveNullability() && |
7659 | !(AllowOnArrayType && Desugared->isArrayType())) { |
7660 | if (!Implicit) |
7661 | S.Diag(NullabilityLoc, diag::err_nullability_nonpointer) |
7662 | << DiagNullabilityKind(Nullability, IsContextSensitive) << QT; |
7663 | |
7664 | return true; |
7665 | } |
7666 | |
7667 | // For the context-sensitive keywords/Objective-C property |
7668 | // attributes, require that the type be a single-level pointer. |
7669 | if (IsContextSensitive) { |
7670 | // Make sure that the pointee isn't itself a pointer type. |
7671 | const Type *pointeeType = nullptr; |
7672 | if (Desugared->isArrayType()) |
7673 | pointeeType = Desugared->getArrayElementTypeNoTypeQual(); |
7674 | else if (Desugared->isAnyPointerType()) |
7675 | pointeeType = Desugared->getPointeeType().getTypePtr(); |
7676 | |
7677 | if (pointeeType && (pointeeType->isAnyPointerType() || |
7678 | pointeeType->isObjCObjectPointerType() || |
7679 | pointeeType->isMemberPointerType())) { |
7680 | S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel) |
7681 | << DiagNullabilityKind(Nullability, true) << QT; |
7682 | S.Diag(NullabilityLoc, diag::note_nullability_type_specifier) |
7683 | << DiagNullabilityKind(Nullability, false) << QT |
7684 | << FixItHint::CreateReplacement(NullabilityLoc, |
7685 | getNullabilitySpelling(Nullability)); |
7686 | return true; |
7687 | } |
7688 | } |
7689 | |
7690 | // Form the attributed type. |
7691 | if (State) { |
7692 | assert(PAttr); |
7693 | Attr *A = createNullabilityAttr(Ctx&: S.Context, Attr&: *PAttr, NK: Nullability); |
7694 | QT = State->getAttributedType(A, ModifiedType: QT, EquivType: QT); |
7695 | } else { |
7696 | attr::Kind attrKind = AttributedType::getNullabilityAttrKind(kind: Nullability); |
7697 | QT = S.Context.getAttributedType(attrKind, modifiedType: QT, equivalentType: QT); |
7698 | } |
7699 | return false; |
7700 | } |
7701 | |
7702 | static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State, |
7703 | QualType &Type, ParsedAttr &Attr, |
7704 | bool AllowOnArrayType) { |
7705 | NullabilityKind Nullability = mapNullabilityAttrKind(kind: Attr.getKind()); |
7706 | SourceLocation NullabilityLoc = Attr.getLoc(); |
7707 | bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute(); |
7708 | |
7709 | return CheckNullabilityTypeSpecifier(S&: State.getSema(), State: &State, PAttr: &Attr, QT&: Type, |
7710 | Nullability, NullabilityLoc, |
7711 | IsContextSensitive, AllowOnArrayType, |
7712 | /*overrideExisting*/ OverrideExisting: false); |
7713 | } |
7714 | |
7715 | bool Sema::CheckImplicitNullabilityTypeSpecifier(QualType &Type, |
7716 | NullabilityKind Nullability, |
7717 | SourceLocation DiagLoc, |
7718 | bool AllowArrayTypes, |
7719 | bool OverrideExisting) { |
7720 | return CheckNullabilityTypeSpecifier( |
7721 | S&: *this, State: nullptr, PAttr: nullptr, QT&: Type, Nullability, NullabilityLoc: DiagLoc, |
7722 | /*isContextSensitive*/ IsContextSensitive: false, AllowOnArrayType: AllowArrayTypes, OverrideExisting); |
7723 | } |
7724 | |
7725 | /// Check the application of the Objective-C '__kindof' qualifier to |
7726 | /// the given type. |
7727 | static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, |
7728 | ParsedAttr &attr) { |
7729 | Sema &S = state.getSema(); |
7730 | |
7731 | if (isa<ObjCTypeParamType>(Val: type)) { |
7732 | // Build the attributed type to record where __kindof occurred. |
7733 | type = state.getAttributedType( |
7734 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type); |
7735 | return false; |
7736 | } |
7737 | |
7738 | // Find out if it's an Objective-C object or object pointer type; |
7739 | const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>(); |
7740 | const ObjCObjectType *objType = ptrType ? ptrType->getObjectType() |
7741 | : type->getAs<ObjCObjectType>(); |
7742 | |
7743 | // If not, we can't apply __kindof. |
7744 | if (!objType) { |
7745 | // FIXME: Handle dependent types that aren't yet object types. |
7746 | S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject) |
7747 | << type; |
7748 | return true; |
7749 | } |
7750 | |
7751 | // Rebuild the "equivalent" type, which pushes __kindof down into |
7752 | // the object type. |
7753 | // There is no need to apply kindof on an unqualified id type. |
7754 | QualType equivType = S.Context.getObjCObjectType( |
7755 | objType->getBaseType(), objType->getTypeArgsAsWritten(), |
7756 | objType->getProtocols(), |
7757 | /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); |
7758 | |
7759 | // If we started with an object pointer type, rebuild it. |
7760 | if (ptrType) { |
7761 | equivType = S.Context.getObjCObjectPointerType(OIT: equivType); |
7762 | if (auto nullability = type->getNullability()) { |
7763 | // We create a nullability attribute from the __kindof attribute. |
7764 | // Make sure that will make sense. |
7765 | assert(attr.getAttributeSpellingListIndex() == 0 && |
7766 | "multiple spellings for __kindof?" ); |
7767 | Attr *A = createNullabilityAttr(Ctx&: S.Context, Attr&: attr, NK: *nullability); |
7768 | A->setImplicit(true); |
7769 | equivType = state.getAttributedType(A, ModifiedType: equivType, EquivType: equivType); |
7770 | } |
7771 | } |
7772 | |
7773 | // Build the attributed type to record where __kindof occurred. |
7774 | type = state.getAttributedType( |
7775 | createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType); |
7776 | return false; |
7777 | } |
7778 | |
7779 | /// Distribute a nullability type attribute that cannot be applied to |
7780 | /// the type specifier to a pointer, block pointer, or member pointer |
7781 | /// declarator, complaining if necessary. |
7782 | /// |
7783 | /// \returns true if the nullability annotation was distributed, false |
7784 | /// otherwise. |
7785 | static bool distributeNullabilityTypeAttr(TypeProcessingState &state, |
7786 | QualType type, ParsedAttr &attr) { |
7787 | Declarator &declarator = state.getDeclarator(); |
7788 | |
7789 | /// Attempt to move the attribute to the specified chunk. |
7790 | auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool { |
7791 | // If there is already a nullability attribute there, don't add |
7792 | // one. |
7793 | if (hasNullabilityAttr(attrs: chunk.getAttrs())) |
7794 | return false; |
7795 | |
7796 | // Complain about the nullability qualifier being in the wrong |
7797 | // place. |
7798 | enum { |
7799 | PK_Pointer, |
7800 | PK_BlockPointer, |
7801 | PK_MemberPointer, |
7802 | PK_FunctionPointer, |
7803 | PK_MemberFunctionPointer, |
7804 | } pointerKind |
7805 | = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer |
7806 | : PK_Pointer) |
7807 | : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer |
7808 | : inFunction? PK_MemberFunctionPointer : PK_MemberPointer; |
7809 | |
7810 | auto diag = state.getSema().Diag(attr.getLoc(), |
7811 | diag::warn_nullability_declspec) |
7812 | << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()), |
7813 | attr.isContextSensitiveKeywordAttribute()) |
7814 | << type |
7815 | << static_cast<unsigned>(pointerKind); |
7816 | |
7817 | // FIXME: MemberPointer chunks don't carry the location of the *. |
7818 | if (chunk.Kind != DeclaratorChunk::MemberPointer) { |
7819 | diag << FixItHint::CreateRemoval(RemoveRange: attr.getLoc()) |
7820 | << FixItHint::CreateInsertion( |
7821 | InsertionLoc: state.getSema().getPreprocessor().getLocForEndOfToken( |
7822 | Loc: chunk.Loc), |
7823 | Code: " " + attr.getAttrName()->getName().str() + " " ); |
7824 | } |
7825 | |
7826 | moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(), |
7827 | toList&: chunk.getAttrs()); |
7828 | return true; |
7829 | }; |
7830 | |
7831 | // Move it to the outermost pointer, member pointer, or block |
7832 | // pointer declarator. |
7833 | for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) { |
7834 | DeclaratorChunk &chunk = declarator.getTypeObject(i: i-1); |
7835 | switch (chunk.Kind) { |
7836 | case DeclaratorChunk::Pointer: |
7837 | case DeclaratorChunk::BlockPointer: |
7838 | case DeclaratorChunk::MemberPointer: |
7839 | return moveToChunk(chunk, false); |
7840 | |
7841 | case DeclaratorChunk::Paren: |
7842 | case DeclaratorChunk::Array: |
7843 | continue; |
7844 | |
7845 | case DeclaratorChunk::Function: |
7846 | // Try to move past the return type to a function/block/member |
7847 | // function pointer. |
7848 | if (DeclaratorChunk *dest = maybeMovePastReturnType( |
7849 | declarator, i, |
7850 | /*onlyBlockPointers=*/false)) { |
7851 | return moveToChunk(*dest, true); |
7852 | } |
7853 | |
7854 | return false; |
7855 | |
7856 | // Don't walk through these. |
7857 | case DeclaratorChunk::Reference: |
7858 | case DeclaratorChunk::Pipe: |
7859 | return false; |
7860 | } |
7861 | } |
7862 | |
7863 | return false; |
7864 | } |
7865 | |
7866 | static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) { |
7867 | assert(!Attr.isInvalid()); |
7868 | switch (Attr.getKind()) { |
7869 | default: |
7870 | llvm_unreachable("not a calling convention attribute" ); |
7871 | case ParsedAttr::AT_CDecl: |
7872 | return createSimpleAttr<CDeclAttr>(Ctx, Attr); |
7873 | case ParsedAttr::AT_FastCall: |
7874 | return createSimpleAttr<FastCallAttr>(Ctx, Attr); |
7875 | case ParsedAttr::AT_StdCall: |
7876 | return createSimpleAttr<StdCallAttr>(Ctx, Attr); |
7877 | case ParsedAttr::AT_ThisCall: |
7878 | return createSimpleAttr<ThisCallAttr>(Ctx, Attr); |
7879 | case ParsedAttr::AT_RegCall: |
7880 | return createSimpleAttr<RegCallAttr>(Ctx, Attr); |
7881 | case ParsedAttr::AT_Pascal: |
7882 | return createSimpleAttr<PascalAttr>(Ctx, Attr); |
7883 | case ParsedAttr::AT_SwiftCall: |
7884 | return createSimpleAttr<SwiftCallAttr>(Ctx, Attr); |
7885 | case ParsedAttr::AT_SwiftAsyncCall: |
7886 | return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr); |
7887 | case ParsedAttr::AT_VectorCall: |
7888 | return createSimpleAttr<VectorCallAttr>(Ctx, Attr); |
7889 | case ParsedAttr::AT_AArch64VectorPcs: |
7890 | return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr); |
7891 | case ParsedAttr::AT_AArch64SVEPcs: |
7892 | return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr); |
7893 | case ParsedAttr::AT_ArmStreaming: |
7894 | return createSimpleAttr<ArmStreamingAttr>(Ctx, Attr); |
7895 | case ParsedAttr::AT_AMDGPUKernelCall: |
7896 | return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr); |
7897 | case ParsedAttr::AT_Pcs: { |
7898 | // The attribute may have had a fixit applied where we treated an |
7899 | // identifier as a string literal. The contents of the string are valid, |
7900 | // but the form may not be. |
7901 | StringRef Str; |
7902 | if (Attr.isArgExpr(Arg: 0)) |
7903 | Str = cast<StringLiteral>(Val: Attr.getArgAsExpr(Arg: 0))->getString(); |
7904 | else |
7905 | Str = Attr.getArgAsIdent(Arg: 0)->Ident->getName(); |
7906 | PcsAttr::PCSType Type; |
7907 | if (!PcsAttr::ConvertStrToPCSType(Str, Type)) |
7908 | llvm_unreachable("already validated the attribute" ); |
7909 | return ::new (Ctx) PcsAttr(Ctx, Attr, Type); |
7910 | } |
7911 | case ParsedAttr::AT_IntelOclBicc: |
7912 | return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr); |
7913 | case ParsedAttr::AT_MSABI: |
7914 | return createSimpleAttr<MSABIAttr>(Ctx, Attr); |
7915 | case ParsedAttr::AT_SysVABI: |
7916 | return createSimpleAttr<SysVABIAttr>(Ctx, Attr); |
7917 | case ParsedAttr::AT_PreserveMost: |
7918 | return createSimpleAttr<PreserveMostAttr>(Ctx, Attr); |
7919 | case ParsedAttr::AT_PreserveAll: |
7920 | return createSimpleAttr<PreserveAllAttr>(Ctx, Attr); |
7921 | case ParsedAttr::AT_M68kRTD: |
7922 | return createSimpleAttr<M68kRTDAttr>(Ctx, Attr); |
7923 | case ParsedAttr::AT_PreserveNone: |
7924 | return createSimpleAttr<PreserveNoneAttr>(Ctx, Attr); |
7925 | } |
7926 | llvm_unreachable("unexpected attribute kind!" ); |
7927 | } |
7928 | |
7929 | static bool checkMutualExclusion(TypeProcessingState &state, |
7930 | const FunctionProtoType::ExtProtoInfo &EPI, |
7931 | ParsedAttr &Attr, |
7932 | AttributeCommonInfo::Kind OtherKind) { |
7933 | auto OtherAttr = std::find_if( |
7934 | first: state.getCurrentAttributes().begin(), last: state.getCurrentAttributes().end(), |
7935 | pred: [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; }); |
7936 | if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid()) |
7937 | return false; |
7938 | |
7939 | Sema &S = state.getSema(); |
7940 | S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) |
7941 | << *OtherAttr << Attr |
7942 | << (OtherAttr->isRegularKeywordAttribute() || |
7943 | Attr.isRegularKeywordAttribute()); |
7944 | S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute); |
7945 | Attr.setInvalid(); |
7946 | return true; |
7947 | } |
7948 | |
7949 | static bool handleArmStateAttribute(Sema &S, |
7950 | FunctionProtoType::ExtProtoInfo &EPI, |
7951 | ParsedAttr &Attr, |
7952 | FunctionType::ArmStateValue State) { |
7953 | if (!Attr.getNumArgs()) { |
7954 | S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr; |
7955 | Attr.setInvalid(); |
7956 | return true; |
7957 | } |
7958 | |
7959 | for (unsigned I = 0; I < Attr.getNumArgs(); ++I) { |
7960 | StringRef StateName; |
7961 | SourceLocation LiteralLoc; |
7962 | if (!S.checkStringLiteralArgumentAttr(Attr, ArgNum: I, Str&: StateName, ArgLocation: &LiteralLoc)) |
7963 | return true; |
7964 | |
7965 | unsigned Shift; |
7966 | FunctionType::ArmStateValue ExistingState; |
7967 | if (StateName == "za" ) { |
7968 | Shift = FunctionType::SME_ZAShift; |
7969 | ExistingState = FunctionType::getArmZAState(AttrBits: EPI.AArch64SMEAttributes); |
7970 | } else if (StateName == "zt0" ) { |
7971 | Shift = FunctionType::SME_ZT0Shift; |
7972 | ExistingState = FunctionType::getArmZT0State(AttrBits: EPI.AArch64SMEAttributes); |
7973 | } else { |
7974 | S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName; |
7975 | Attr.setInvalid(); |
7976 | return true; |
7977 | } |
7978 | |
7979 | // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S) |
7980 | // are all mutually exclusive for the same S, so check if there are |
7981 | // conflicting attributes. |
7982 | if (ExistingState != FunctionType::ARM_None && ExistingState != State) { |
7983 | S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state) |
7984 | << StateName; |
7985 | Attr.setInvalid(); |
7986 | return true; |
7987 | } |
7988 | |
7989 | EPI.setArmSMEAttribute( |
7990 | Kind: (FunctionType::AArch64SMETypeAttributes)((State << Shift))); |
7991 | } |
7992 | return false; |
7993 | } |
7994 | |
7995 | /// Process an individual function attribute. Returns true to |
7996 | /// indicate that the attribute was handled, false if it wasn't. |
7997 | static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, |
7998 | QualType &type, |
7999 | Sema::CUDAFunctionTarget CFT) { |
8000 | Sema &S = state.getSema(); |
8001 | |
8002 | FunctionTypeUnwrapper unwrapped(S, type); |
8003 | |
8004 | if (attr.getKind() == ParsedAttr::AT_NoReturn) { |
8005 | if (S.CheckAttrNoArgs(CurrAttr: attr)) |
8006 | return true; |
8007 | |
8008 | // Delay if this is not a function type. |
8009 | if (!unwrapped.isFunctionType()) |
8010 | return false; |
8011 | |
8012 | // Otherwise we can process right away. |
8013 | FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(noReturn: true); |
8014 | type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI)); |
8015 | return true; |
8016 | } |
8017 | |
8018 | if (attr.getKind() == ParsedAttr::AT_CmseNSCall) { |
8019 | // Delay if this is not a function type. |
8020 | if (!unwrapped.isFunctionType()) |
8021 | return false; |
8022 | |
8023 | // Ignore if we don't have CMSE enabled. |
8024 | if (!S.getLangOpts().Cmse) { |
8025 | S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr; |
8026 | attr.setInvalid(); |
8027 | return true; |
8028 | } |
8029 | |
8030 | // Otherwise we can process right away. |
8031 | FunctionType::ExtInfo EI = |
8032 | unwrapped.get()->getExtInfo().withCmseNSCall(cmseNSCall: true); |
8033 | type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI)); |
8034 | return true; |
8035 | } |
8036 | |
8037 | // ns_returns_retained is not always a type attribute, but if we got |
8038 | // here, we're treating it as one right now. |
8039 | if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) { |
8040 | if (attr.getNumArgs()) return true; |
8041 | |
8042 | // Delay if this is not a function type. |
8043 | if (!unwrapped.isFunctionType()) |
8044 | return false; |
8045 | |
8046 | // Check whether the return type is reasonable. |
8047 | if (S.checkNSReturnsRetainedReturnType(loc: attr.getLoc(), |
8048 | type: unwrapped.get()->getReturnType())) |
8049 | return true; |
8050 | |
8051 | // Only actually change the underlying type in ARC builds. |
8052 | QualType origType = type; |
8053 | if (state.getSema().getLangOpts().ObjCAutoRefCount) { |
8054 | FunctionType::ExtInfo EI |
8055 | = unwrapped.get()->getExtInfo().withProducesResult(producesResult: true); |
8056 | type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI)); |
8057 | } |
8058 | type = state.getAttributedType( |
8059 | createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr), |
8060 | origType, type); |
8061 | return true; |
8062 | } |
8063 | |
8064 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) { |
8065 | if (S.CheckAttrTarget(CurrAttr: attr) || S.CheckAttrNoArgs(CurrAttr: attr)) |
8066 | return true; |
8067 | |
8068 | // Delay if this is not a function type. |
8069 | if (!unwrapped.isFunctionType()) |
8070 | return false; |
8071 | |
8072 | FunctionType::ExtInfo EI = |
8073 | unwrapped.get()->getExtInfo().withNoCallerSavedRegs(noCallerSavedRegs: true); |
8074 | type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI)); |
8075 | return true; |
8076 | } |
8077 | |
8078 | if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) { |
8079 | if (!S.getLangOpts().CFProtectionBranch) { |
8080 | S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored); |
8081 | attr.setInvalid(); |
8082 | return true; |
8083 | } |
8084 | |
8085 | if (S.CheckAttrTarget(CurrAttr: attr) || S.CheckAttrNoArgs(CurrAttr: attr)) |
8086 | return true; |
8087 | |
8088 | // If this is not a function type, warning will be asserted by subject |
8089 | // check. |
8090 | if (!unwrapped.isFunctionType()) |
8091 | return true; |
8092 | |
8093 | FunctionType::ExtInfo EI = |
8094 | unwrapped.get()->getExtInfo().withNoCfCheck(noCfCheck: true); |
8095 | type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI)); |
8096 | return true; |
8097 | } |
8098 | |
8099 | if (attr.getKind() == ParsedAttr::AT_Regparm) { |
8100 | unsigned value; |
8101 | if (S.CheckRegparmAttr(attr, value)) |
8102 | return true; |
8103 | |
8104 | // Delay if this is not a function type. |
8105 | if (!unwrapped.isFunctionType()) |
8106 | return false; |
8107 | |
8108 | // Diagnose regparm with fastcall. |
8109 | const FunctionType *fn = unwrapped.get(); |
8110 | CallingConv CC = fn->getCallConv(); |
8111 | if (CC == CC_X86FastCall) { |
8112 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) |
8113 | << FunctionType::getNameForCallConv(CC) << "regparm" |
8114 | << attr.isRegularKeywordAttribute(); |
8115 | attr.setInvalid(); |
8116 | return true; |
8117 | } |
8118 | |
8119 | FunctionType::ExtInfo EI = |
8120 | unwrapped.get()->getExtInfo().withRegParm(RegParm: value); |
8121 | type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI)); |
8122 | return true; |
8123 | } |
8124 | |
8125 | if (attr.getKind() == ParsedAttr::AT_ArmStreaming || |
8126 | attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible || |
8127 | attr.getKind() == ParsedAttr::AT_ArmPreserves || |
8128 | attr.getKind() == ParsedAttr::AT_ArmIn || |
8129 | attr.getKind() == ParsedAttr::AT_ArmOut || |
8130 | attr.getKind() == ParsedAttr::AT_ArmInOut) { |
8131 | if (S.CheckAttrTarget(CurrAttr: attr)) |
8132 | return true; |
8133 | |
8134 | if (attr.getKind() == ParsedAttr::AT_ArmStreaming || |
8135 | attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible) |
8136 | if (S.CheckAttrNoArgs(CurrAttr: attr)) |
8137 | return true; |
8138 | |
8139 | if (!unwrapped.isFunctionType()) |
8140 | return false; |
8141 | |
8142 | const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>(); |
8143 | if (!FnTy) { |
8144 | // SME ACLE attributes are not supported on K&R-style unprototyped C |
8145 | // functions. |
8146 | S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) << |
8147 | attr << attr.isRegularKeywordAttribute() << ExpectedFunctionWithProtoType; |
8148 | attr.setInvalid(); |
8149 | return false; |
8150 | } |
8151 | |
8152 | FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo(); |
8153 | switch (attr.getKind()) { |
8154 | case ParsedAttr::AT_ArmStreaming: |
8155 | if (checkMutualExclusion(state, EPI, attr, |
8156 | ParsedAttr::AT_ArmStreamingCompatible)) |
8157 | return true; |
8158 | EPI.setArmSMEAttribute(Kind: FunctionType::SME_PStateSMEnabledMask); |
8159 | break; |
8160 | case ParsedAttr::AT_ArmStreamingCompatible: |
8161 | if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming)) |
8162 | return true; |
8163 | EPI.setArmSMEAttribute(Kind: FunctionType::SME_PStateSMCompatibleMask); |
8164 | break; |
8165 | case ParsedAttr::AT_ArmPreserves: |
8166 | if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_Preserves)) |
8167 | return true; |
8168 | break; |
8169 | case ParsedAttr::AT_ArmIn: |
8170 | if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_In)) |
8171 | return true; |
8172 | break; |
8173 | case ParsedAttr::AT_ArmOut: |
8174 | if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_Out)) |
8175 | return true; |
8176 | break; |
8177 | case ParsedAttr::AT_ArmInOut: |
8178 | if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_InOut)) |
8179 | return true; |
8180 | break; |
8181 | default: |
8182 | llvm_unreachable("Unsupported attribute" ); |
8183 | } |
8184 | |
8185 | QualType newtype = S.Context.getFunctionType(ResultTy: FnTy->getReturnType(), |
8186 | Args: FnTy->getParamTypes(), EPI); |
8187 | type = unwrapped.wrap(S, New: newtype->getAs<FunctionType>()); |
8188 | return true; |
8189 | } |
8190 | |
8191 | if (attr.getKind() == ParsedAttr::AT_NoThrow) { |
8192 | // Delay if this is not a function type. |
8193 | if (!unwrapped.isFunctionType()) |
8194 | return false; |
8195 | |
8196 | if (S.CheckAttrNoArgs(CurrAttr: attr)) { |
8197 | attr.setInvalid(); |
8198 | return true; |
8199 | } |
8200 | |
8201 | // Otherwise we can process right away. |
8202 | auto *Proto = unwrapped.get()->castAs<FunctionProtoType>(); |
8203 | |
8204 | // MSVC ignores nothrow if it is in conflict with an explicit exception |
8205 | // specification. |
8206 | if (Proto->hasExceptionSpec()) { |
8207 | switch (Proto->getExceptionSpecType()) { |
8208 | case EST_None: |
8209 | llvm_unreachable("This doesn't have an exception spec!" ); |
8210 | |
8211 | case EST_DynamicNone: |
8212 | case EST_BasicNoexcept: |
8213 | case EST_NoexceptTrue: |
8214 | case EST_NoThrow: |
8215 | // Exception spec doesn't conflict with nothrow, so don't warn. |
8216 | [[fallthrough]]; |
8217 | case EST_Unparsed: |
8218 | case EST_Uninstantiated: |
8219 | case EST_DependentNoexcept: |
8220 | case EST_Unevaluated: |
8221 | // We don't have enough information to properly determine if there is a |
8222 | // conflict, so suppress the warning. |
8223 | break; |
8224 | case EST_Dynamic: |
8225 | case EST_MSAny: |
8226 | case EST_NoexceptFalse: |
8227 | S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored); |
8228 | break; |
8229 | } |
8230 | return true; |
8231 | } |
8232 | |
8233 | type = unwrapped.wrap( |
8234 | S, New: S.Context |
8235 | .getFunctionTypeWithExceptionSpec( |
8236 | Orig: QualType{Proto, 0}, |
8237 | ESI: FunctionProtoType::ExceptionSpecInfo{EST_NoThrow}) |
8238 | ->getAs<FunctionType>()); |
8239 | return true; |
8240 | } |
8241 | |
8242 | // Delay if the type didn't work out to a function. |
8243 | if (!unwrapped.isFunctionType()) return false; |
8244 | |
8245 | // Otherwise, a calling convention. |
8246 | CallingConv CC; |
8247 | if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/FD: nullptr, CFT)) |
8248 | return true; |
8249 | |
8250 | const FunctionType *fn = unwrapped.get(); |
8251 | CallingConv CCOld = fn->getCallConv(); |
8252 | Attr *CCAttr = getCCTypeAttr(Ctx&: S.Context, Attr&: attr); |
8253 | |
8254 | if (CCOld != CC) { |
8255 | // Error out on when there's already an attribute on the type |
8256 | // and the CCs don't match. |
8257 | if (S.getCallingConvAttributedType(T: type)) { |
8258 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) |
8259 | << FunctionType::getNameForCallConv(CC) |
8260 | << FunctionType::getNameForCallConv(CCOld) |
8261 | << attr.isRegularKeywordAttribute(); |
8262 | attr.setInvalid(); |
8263 | return true; |
8264 | } |
8265 | } |
8266 | |
8267 | // Diagnose use of variadic functions with calling conventions that |
8268 | // don't support them (e.g. because they're callee-cleanup). |
8269 | // We delay warning about this on unprototyped function declarations |
8270 | // until after redeclaration checking, just in case we pick up a |
8271 | // prototype that way. And apparently we also "delay" warning about |
8272 | // unprototyped function types in general, despite not necessarily having |
8273 | // much ability to diagnose it later. |
8274 | if (!supportsVariadicCall(CC)) { |
8275 | const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(Val: fn); |
8276 | if (FnP && FnP->isVariadic()) { |
8277 | // stdcall and fastcall are ignored with a warning for GCC and MS |
8278 | // compatibility. |
8279 | if (CC == CC_X86StdCall || CC == CC_X86FastCall) |
8280 | return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported) |
8281 | << FunctionType::getNameForCallConv(CC) |
8282 | << (int)Sema::CallingConventionIgnoredReason::VariadicFunction; |
8283 | |
8284 | attr.setInvalid(); |
8285 | return S.Diag(attr.getLoc(), diag::err_cconv_varargs) |
8286 | << FunctionType::getNameForCallConv(CC); |
8287 | } |
8288 | } |
8289 | |
8290 | // Also diagnose fastcall with regparm. |
8291 | if (CC == CC_X86FastCall && fn->getHasRegParm()) { |
8292 | S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible) |
8293 | << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall) |
8294 | << attr.isRegularKeywordAttribute(); |
8295 | attr.setInvalid(); |
8296 | return true; |
8297 | } |
8298 | |
8299 | // Modify the CC from the wrapped function type, wrap it all back, and then |
8300 | // wrap the whole thing in an AttributedType as written. The modified type |
8301 | // might have a different CC if we ignored the attribute. |
8302 | QualType Equivalent; |
8303 | if (CCOld == CC) { |
8304 | Equivalent = type; |
8305 | } else { |
8306 | auto EI = unwrapped.get()->getExtInfo().withCallingConv(cc: CC); |
8307 | Equivalent = |
8308 | unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI)); |
8309 | } |
8310 | type = state.getAttributedType(A: CCAttr, ModifiedType: type, EquivType: Equivalent); |
8311 | return true; |
8312 | } |
8313 | |
8314 | bool Sema::hasExplicitCallingConv(QualType T) { |
8315 | const AttributedType *AT; |
8316 | |
8317 | // Stop if we'd be stripping off a typedef sugar node to reach the |
8318 | // AttributedType. |
8319 | while ((AT = T->getAs<AttributedType>()) && |
8320 | AT->getAs<TypedefType>() == T->getAs<TypedefType>()) { |
8321 | if (AT->isCallingConv()) |
8322 | return true; |
8323 | T = AT->getModifiedType(); |
8324 | } |
8325 | return false; |
8326 | } |
8327 | |
8328 | void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer, |
8329 | bool IsCtorOrDtor, SourceLocation Loc) { |
8330 | FunctionTypeUnwrapper Unwrapped(*this, T); |
8331 | const FunctionType *FT = Unwrapped.get(); |
8332 | bool IsVariadic = (isa<FunctionProtoType>(Val: FT) && |
8333 | cast<FunctionProtoType>(Val: FT)->isVariadic()); |
8334 | CallingConv CurCC = FT->getCallConv(); |
8335 | CallingConv ToCC = |
8336 | Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod: HasThisPointer); |
8337 | |
8338 | if (CurCC == ToCC) |
8339 | return; |
8340 | |
8341 | // MS compiler ignores explicit calling convention attributes on structors. We |
8342 | // should do the same. |
8343 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) { |
8344 | // Issue a warning on ignored calling convention -- except of __stdcall. |
8345 | // Again, this is what MS compiler does. |
8346 | if (CurCC != CC_X86StdCall) |
8347 | Diag(Loc, diag::warn_cconv_unsupported) |
8348 | << FunctionType::getNameForCallConv(CurCC) |
8349 | << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor; |
8350 | // Default adjustment. |
8351 | } else { |
8352 | // Only adjust types with the default convention. For example, on Windows |
8353 | // we should adjust a __cdecl type to __thiscall for instance methods, and a |
8354 | // __thiscall type to __cdecl for static methods. |
8355 | CallingConv DefaultCC = |
8356 | Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod: !HasThisPointer); |
8357 | |
8358 | if (CurCC != DefaultCC) |
8359 | return; |
8360 | |
8361 | if (hasExplicitCallingConv(T)) |
8362 | return; |
8363 | } |
8364 | |
8365 | FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: ToCC)); |
8366 | QualType Wrapped = Unwrapped.wrap(S&: *this, New: FT); |
8367 | T = Context.getAdjustedType(Orig: T, New: Wrapped); |
8368 | } |
8369 | |
8370 | /// HandleVectorSizeAttribute - this attribute is only applicable to integral |
8371 | /// and float scalars, although arrays, pointers, and function return values are |
8372 | /// allowed in conjunction with this construct. Aggregates with this attribute |
8373 | /// are invalid, even if they are of the same size as a corresponding scalar. |
8374 | /// The raw attribute should contain precisely 1 argument, the vector size for |
8375 | /// the variable, measured in bytes. If curType and rawAttr are well formed, |
8376 | /// this routine will return a new vector type. |
8377 | static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, |
8378 | Sema &S) { |
8379 | // Check the attribute arguments. |
8380 | if (Attr.getNumArgs() != 1) { |
8381 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr |
8382 | << 1; |
8383 | Attr.setInvalid(); |
8384 | return; |
8385 | } |
8386 | |
8387 | Expr *SizeExpr = Attr.getArgAsExpr(Arg: 0); |
8388 | QualType T = S.BuildVectorType(CurType, SizeExpr, AttrLoc: Attr.getLoc()); |
8389 | if (!T.isNull()) |
8390 | CurType = T; |
8391 | else |
8392 | Attr.setInvalid(); |
8393 | } |
8394 | |
8395 | /// Process the OpenCL-like ext_vector_type attribute when it occurs on |
8396 | /// a type. |
8397 | static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, |
8398 | Sema &S) { |
8399 | // check the attribute arguments. |
8400 | if (Attr.getNumArgs() != 1) { |
8401 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr |
8402 | << 1; |
8403 | return; |
8404 | } |
8405 | |
8406 | Expr *SizeExpr = Attr.getArgAsExpr(Arg: 0); |
8407 | QualType T = S.BuildExtVectorType(T: CurType, ArraySize: SizeExpr, AttrLoc: Attr.getLoc()); |
8408 | if (!T.isNull()) |
8409 | CurType = T; |
8410 | } |
8411 | |
8412 | static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) { |
8413 | const BuiltinType *BTy = Ty->getAs<BuiltinType>(); |
8414 | if (!BTy) |
8415 | return false; |
8416 | |
8417 | llvm::Triple Triple = S.Context.getTargetInfo().getTriple(); |
8418 | |
8419 | // Signed poly is mathematically wrong, but has been baked into some ABIs by |
8420 | // now. |
8421 | bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 || |
8422 | Triple.getArch() == llvm::Triple::aarch64_32 || |
8423 | Triple.getArch() == llvm::Triple::aarch64_be; |
8424 | if (VecKind == VectorKind::NeonPoly) { |
8425 | if (IsPolyUnsigned) { |
8426 | // AArch64 polynomial vectors are unsigned. |
8427 | return BTy->getKind() == BuiltinType::UChar || |
8428 | BTy->getKind() == BuiltinType::UShort || |
8429 | BTy->getKind() == BuiltinType::ULong || |
8430 | BTy->getKind() == BuiltinType::ULongLong; |
8431 | } else { |
8432 | // AArch32 polynomial vectors are signed. |
8433 | return BTy->getKind() == BuiltinType::SChar || |
8434 | BTy->getKind() == BuiltinType::Short || |
8435 | BTy->getKind() == BuiltinType::LongLong; |
8436 | } |
8437 | } |
8438 | |
8439 | // Non-polynomial vector types: the usual suspects are allowed, as well as |
8440 | // float64_t on AArch64. |
8441 | if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) && |
8442 | BTy->getKind() == BuiltinType::Double) |
8443 | return true; |
8444 | |
8445 | return BTy->getKind() == BuiltinType::SChar || |
8446 | BTy->getKind() == BuiltinType::UChar || |
8447 | BTy->getKind() == BuiltinType::Short || |
8448 | BTy->getKind() == BuiltinType::UShort || |
8449 | BTy->getKind() == BuiltinType::Int || |
8450 | BTy->getKind() == BuiltinType::UInt || |
8451 | BTy->getKind() == BuiltinType::Long || |
8452 | BTy->getKind() == BuiltinType::ULong || |
8453 | BTy->getKind() == BuiltinType::LongLong || |
8454 | BTy->getKind() == BuiltinType::ULongLong || |
8455 | BTy->getKind() == BuiltinType::Float || |
8456 | BTy->getKind() == BuiltinType::Half || |
8457 | BTy->getKind() == BuiltinType::BFloat16; |
8458 | } |
8459 | |
8460 | static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, |
8461 | llvm::APSInt &Result) { |
8462 | const auto *AttrExpr = Attr.getArgAsExpr(Arg: 0); |
8463 | if (!AttrExpr->isTypeDependent()) { |
8464 | if (std::optional<llvm::APSInt> Res = |
8465 | AttrExpr->getIntegerConstantExpr(Ctx: S.Context)) { |
8466 | Result = *Res; |
8467 | return true; |
8468 | } |
8469 | } |
8470 | S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) |
8471 | << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange(); |
8472 | Attr.setInvalid(); |
8473 | return false; |
8474 | } |
8475 | |
8476 | /// HandleNeonVectorTypeAttr - The "neon_vector_type" and |
8477 | /// "neon_polyvector_type" attributes are used to create vector types that |
8478 | /// are mangled according to ARM's ABI. Otherwise, these types are identical |
8479 | /// to those created with the "vector_size" attribute. Unlike "vector_size" |
8480 | /// the argument to these Neon attributes is the number of vector elements, |
8481 | /// not the vector size in bytes. The vector width and element type must |
8482 | /// match one of the standard Neon vector types. |
8483 | static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, |
8484 | Sema &S, VectorKind VecKind) { |
8485 | bool IsTargetCUDAAndHostARM = false; |
8486 | if (S.getLangOpts().CUDAIsDevice) { |
8487 | const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo(); |
8488 | IsTargetCUDAAndHostARM = |
8489 | AuxTI && (AuxTI->getTriple().isAArch64() || AuxTI->getTriple().isARM()); |
8490 | } |
8491 | |
8492 | // Target must have NEON (or MVE, whose vectors are similar enough |
8493 | // not to need a separate attribute) |
8494 | if (!(S.Context.getTargetInfo().hasFeature(Feature: "neon" ) || |
8495 | S.Context.getTargetInfo().hasFeature(Feature: "mve" ) || |
8496 | S.Context.getTargetInfo().hasFeature(Feature: "sve" ) || |
8497 | S.Context.getTargetInfo().hasFeature(Feature: "sme" ) || |
8498 | IsTargetCUDAAndHostARM) && |
8499 | VecKind == VectorKind::Neon) { |
8500 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) |
8501 | << Attr << "'neon', 'mve', 'sve' or 'sme'" ; |
8502 | Attr.setInvalid(); |
8503 | return; |
8504 | } |
8505 | if (!(S.Context.getTargetInfo().hasFeature(Feature: "neon" ) || |
8506 | S.Context.getTargetInfo().hasFeature(Feature: "mve" ) || |
8507 | IsTargetCUDAAndHostARM) && |
8508 | VecKind == VectorKind::NeonPoly) { |
8509 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) |
8510 | << Attr << "'neon' or 'mve'" ; |
8511 | Attr.setInvalid(); |
8512 | return; |
8513 | } |
8514 | |
8515 | // Check the attribute arguments. |
8516 | if (Attr.getNumArgs() != 1) { |
8517 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) |
8518 | << Attr << 1; |
8519 | Attr.setInvalid(); |
8520 | return; |
8521 | } |
8522 | // The number of elements must be an ICE. |
8523 | llvm::APSInt numEltsInt(32); |
8524 | if (!verifyValidIntegerConstantExpr(S, Attr, Result&: numEltsInt)) |
8525 | return; |
8526 | |
8527 | // Only certain element types are supported for Neon vectors. |
8528 | if (!isPermittedNeonBaseType(Ty&: CurType, VecKind, S) && |
8529 | !IsTargetCUDAAndHostARM) { |
8530 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; |
8531 | Attr.setInvalid(); |
8532 | return; |
8533 | } |
8534 | |
8535 | // The total size of the vector must be 64 or 128 bits. |
8536 | unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(T: CurType)); |
8537 | unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue()); |
8538 | unsigned vecSize = typeSize * numElts; |
8539 | if (vecSize != 64 && vecSize != 128) { |
8540 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType; |
8541 | Attr.setInvalid(); |
8542 | return; |
8543 | } |
8544 | |
8545 | CurType = S.Context.getVectorType(VectorType: CurType, NumElts: numElts, VecKind); |
8546 | } |
8547 | |
8548 | /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is |
8549 | /// used to create fixed-length versions of sizeless SVE types defined by |
8550 | /// the ACLE, such as svint32_t and svbool_t. |
8551 | static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, |
8552 | Sema &S) { |
8553 | // Target must have SVE. |
8554 | if (!S.Context.getTargetInfo().hasFeature(Feature: "sve" )) { |
8555 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'" ; |
8556 | Attr.setInvalid(); |
8557 | return; |
8558 | } |
8559 | |
8560 | // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or |
8561 | // if <bits>+ syntax is used. |
8562 | if (!S.getLangOpts().VScaleMin || |
8563 | S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) { |
8564 | S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported) |
8565 | << Attr; |
8566 | Attr.setInvalid(); |
8567 | return; |
8568 | } |
8569 | |
8570 | // Check the attribute arguments. |
8571 | if (Attr.getNumArgs() != 1) { |
8572 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) |
8573 | << Attr << 1; |
8574 | Attr.setInvalid(); |
8575 | return; |
8576 | } |
8577 | |
8578 | // The vector size must be an integer constant expression. |
8579 | llvm::APSInt SveVectorSizeInBits(32); |
8580 | if (!verifyValidIntegerConstantExpr(S, Attr, Result&: SveVectorSizeInBits)) |
8581 | return; |
8582 | |
8583 | unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue()); |
8584 | |
8585 | // The attribute vector size must match -msve-vector-bits. |
8586 | if (VecSize != S.getLangOpts().VScaleMin * 128) { |
8587 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size) |
8588 | << VecSize << S.getLangOpts().VScaleMin * 128; |
8589 | Attr.setInvalid(); |
8590 | return; |
8591 | } |
8592 | |
8593 | // Attribute can only be attached to a single SVE vector or predicate type. |
8594 | if (!CurType->isSveVLSBuiltinType()) { |
8595 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type) |
8596 | << Attr << CurType; |
8597 | Attr.setInvalid(); |
8598 | return; |
8599 | } |
8600 | |
8601 | const auto *BT = CurType->castAs<BuiltinType>(); |
8602 | |
8603 | QualType EltType = CurType->getSveEltType(Ctx: S.Context); |
8604 | unsigned TypeSize = S.Context.getTypeSize(T: EltType); |
8605 | VectorKind VecKind = VectorKind::SveFixedLengthData; |
8606 | if (BT->getKind() == BuiltinType::SveBool) { |
8607 | // Predicates are represented as i8. |
8608 | VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth(); |
8609 | VecKind = VectorKind::SveFixedLengthPredicate; |
8610 | } else |
8611 | VecSize /= TypeSize; |
8612 | CurType = S.Context.getVectorType(VectorType: EltType, NumElts: VecSize, VecKind); |
8613 | } |
8614 | |
8615 | static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, |
8616 | QualType &CurType, |
8617 | ParsedAttr &Attr) { |
8618 | const VectorType *VT = dyn_cast<VectorType>(Val&: CurType); |
8619 | if (!VT || VT->getVectorKind() != VectorKind::Neon) { |
8620 | State.getSema().Diag(Attr.getLoc(), |
8621 | diag::err_attribute_arm_mve_polymorphism); |
8622 | Attr.setInvalid(); |
8623 | return; |
8624 | } |
8625 | |
8626 | CurType = |
8627 | State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>( |
8628 | State.getSema().Context, Attr), |
8629 | CurType, CurType); |
8630 | } |
8631 | |
8632 | /// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is |
8633 | /// used to create fixed-length versions of sizeless RVV types such as |
8634 | /// vint8m1_t_t. |
8635 | static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType, |
8636 | ParsedAttr &Attr, Sema &S) { |
8637 | // Target must have vector extension. |
8638 | if (!S.Context.getTargetInfo().hasFeature(Feature: "zve32x" )) { |
8639 | S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) |
8640 | << Attr << "'zve32x'" ; |
8641 | Attr.setInvalid(); |
8642 | return; |
8643 | } |
8644 | |
8645 | auto VScale = S.Context.getTargetInfo().getVScaleRange(LangOpts: S.getLangOpts()); |
8646 | if (!VScale || !VScale->first || VScale->first != VScale->second) { |
8647 | S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported) |
8648 | << Attr; |
8649 | Attr.setInvalid(); |
8650 | return; |
8651 | } |
8652 | |
8653 | // Check the attribute arguments. |
8654 | if (Attr.getNumArgs() != 1) { |
8655 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) |
8656 | << Attr << 1; |
8657 | Attr.setInvalid(); |
8658 | return; |
8659 | } |
8660 | |
8661 | // The vector size must be an integer constant expression. |
8662 | llvm::APSInt RVVVectorSizeInBits(32); |
8663 | if (!verifyValidIntegerConstantExpr(S, Attr, Result&: RVVVectorSizeInBits)) |
8664 | return; |
8665 | |
8666 | // Attribute can only be attached to a single RVV vector type. |
8667 | if (!CurType->isRVVVLSBuiltinType()) { |
8668 | S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type) |
8669 | << Attr << CurType; |
8670 | Attr.setInvalid(); |
8671 | return; |
8672 | } |
8673 | |
8674 | unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue()); |
8675 | |
8676 | ASTContext::BuiltinVectorTypeInfo Info = |
8677 | S.Context.getBuiltinVectorTypeInfo(VecTy: CurType->castAs<BuiltinType>()); |
8678 | unsigned MinElts = Info.EC.getKnownMinValue(); |
8679 | |
8680 | VectorKind VecKind = VectorKind::RVVFixedLengthData; |
8681 | unsigned ExpectedSize = VScale->first * MinElts; |
8682 | QualType EltType = CurType->getRVVEltType(Ctx: S.Context); |
8683 | unsigned EltSize = S.Context.getTypeSize(T: EltType); |
8684 | unsigned NumElts; |
8685 | if (Info.ElementType == S.Context.BoolTy) { |
8686 | NumElts = VecSize / S.Context.getCharWidth(); |
8687 | VecKind = VectorKind::RVVFixedLengthMask; |
8688 | } else { |
8689 | ExpectedSize *= EltSize; |
8690 | NumElts = VecSize / EltSize; |
8691 | } |
8692 | |
8693 | // The attribute vector size must match -mrvv-vector-bits. |
8694 | if (ExpectedSize % 8 != 0 || VecSize != ExpectedSize) { |
8695 | S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size) |
8696 | << VecSize << ExpectedSize; |
8697 | Attr.setInvalid(); |
8698 | return; |
8699 | } |
8700 | |
8701 | CurType = S.Context.getVectorType(VectorType: EltType, NumElts, VecKind); |
8702 | } |
8703 | |
8704 | /// Handle OpenCL Access Qualifier Attribute. |
8705 | static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, |
8706 | Sema &S) { |
8707 | // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type. |
8708 | if (!(CurType->isImageType() || CurType->isPipeType())) { |
8709 | S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier); |
8710 | Attr.setInvalid(); |
8711 | return; |
8712 | } |
8713 | |
8714 | if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) { |
8715 | QualType BaseTy = TypedefTy->desugar(); |
8716 | |
8717 | std::string PrevAccessQual; |
8718 | if (BaseTy->isPipeType()) { |
8719 | if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) { |
8720 | OpenCLAccessAttr *Attr = |
8721 | TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>(); |
8722 | PrevAccessQual = Attr->getSpelling(); |
8723 | } else { |
8724 | PrevAccessQual = "read_only" ; |
8725 | } |
8726 | } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) { |
8727 | |
8728 | switch (ImgType->getKind()) { |
8729 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
8730 | case BuiltinType::Id: \ |
8731 | PrevAccessQual = #Access; \ |
8732 | break; |
8733 | #include "clang/Basic/OpenCLImageTypes.def" |
8734 | default: |
8735 | llvm_unreachable("Unable to find corresponding image type." ); |
8736 | } |
8737 | } else { |
8738 | llvm_unreachable("unexpected type" ); |
8739 | } |
8740 | StringRef AttrName = Attr.getAttrName()->getName(); |
8741 | if (PrevAccessQual == AttrName.ltrim(Chars: "_" )) { |
8742 | // Duplicated qualifiers |
8743 | S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec) |
8744 | << AttrName << Attr.getRange(); |
8745 | } else { |
8746 | // Contradicting qualifiers |
8747 | S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers); |
8748 | } |
8749 | |
8750 | S.Diag(TypedefTy->getDecl()->getBeginLoc(), |
8751 | diag::note_opencl_typedef_access_qualifier) << PrevAccessQual; |
8752 | } else if (CurType->isPipeType()) { |
8753 | if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) { |
8754 | QualType ElemType = CurType->castAs<PipeType>()->getElementType(); |
8755 | CurType = S.Context.getWritePipeType(T: ElemType); |
8756 | } |
8757 | } |
8758 | } |
8759 | |
8760 | /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type |
8761 | static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, |
8762 | Sema &S) { |
8763 | if (!S.getLangOpts().MatrixTypes) { |
8764 | S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled); |
8765 | return; |
8766 | } |
8767 | |
8768 | if (Attr.getNumArgs() != 2) { |
8769 | S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) |
8770 | << Attr << 2; |
8771 | return; |
8772 | } |
8773 | |
8774 | Expr *RowsExpr = Attr.getArgAsExpr(Arg: 0); |
8775 | Expr *ColsExpr = Attr.getArgAsExpr(Arg: 1); |
8776 | QualType T = S.BuildMatrixType(ElementTy: CurType, NumRows: RowsExpr, NumCols: ColsExpr, AttrLoc: Attr.getLoc()); |
8777 | if (!T.isNull()) |
8778 | CurType = T; |
8779 | } |
8780 | |
8781 | static void HandleAnnotateTypeAttr(TypeProcessingState &State, |
8782 | QualType &CurType, const ParsedAttr &PA) { |
8783 | Sema &S = State.getSema(); |
8784 | |
8785 | if (PA.getNumArgs() < 1) { |
8786 | S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1; |
8787 | return; |
8788 | } |
8789 | |
8790 | // Make sure that there is a string literal as the annotation's first |
8791 | // argument. |
8792 | StringRef Str; |
8793 | if (!S.checkStringLiteralArgumentAttr(Attr: PA, ArgNum: 0, Str)) |
8794 | return; |
8795 | |
8796 | llvm::SmallVector<Expr *, 4> Args; |
8797 | Args.reserve(N: PA.getNumArgs() - 1); |
8798 | for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) { |
8799 | assert(!PA.isArgIdent(Idx)); |
8800 | Args.push_back(Elt: PA.getArgAsExpr(Arg: Idx)); |
8801 | } |
8802 | if (!S.ConstantFoldAttrArgs(CI: PA, Args)) |
8803 | return; |
8804 | auto *AnnotateTypeAttr = |
8805 | AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA); |
8806 | CurType = State.getAttributedType(A: AnnotateTypeAttr, ModifiedType: CurType, EquivType: CurType); |
8807 | } |
8808 | |
8809 | static void HandleLifetimeBoundAttr(TypeProcessingState &State, |
8810 | QualType &CurType, |
8811 | ParsedAttr &Attr) { |
8812 | if (State.getDeclarator().isDeclarationOfFunction()) { |
8813 | CurType = State.getAttributedType( |
8814 | createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr), |
8815 | CurType, CurType); |
8816 | } |
8817 | } |
8818 | |
8819 | static void HandleHLSLParamModifierAttr(QualType &CurType, |
8820 | const ParsedAttr &Attr, Sema &S) { |
8821 | // Don't apply this attribute to template dependent types. It is applied on |
8822 | // substitution during template instantiation. |
8823 | if (CurType->isDependentType()) |
8824 | return; |
8825 | if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout || |
8826 | Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) |
8827 | CurType = S.getASTContext().getLValueReferenceType(T: CurType); |
8828 | } |
8829 | |
8830 | static void processTypeAttrs(TypeProcessingState &state, QualType &type, |
8831 | TypeAttrLocation TAL, |
8832 | const ParsedAttributesView &attrs, |
8833 | Sema::CUDAFunctionTarget CFT) { |
8834 | |
8835 | state.setParsedNoDeref(false); |
8836 | if (attrs.empty()) |
8837 | return; |
8838 | |
8839 | // Scan through and apply attributes to this type where it makes sense. Some |
8840 | // attributes (such as __address_space__, __vector_size__, etc) apply to the |
8841 | // type, but others can be present in the type specifiers even though they |
8842 | // apply to the decl. Here we apply type attributes and ignore the rest. |
8843 | |
8844 | // This loop modifies the list pretty frequently, but we still need to make |
8845 | // sure we visit every element once. Copy the attributes list, and iterate |
8846 | // over that. |
8847 | ParsedAttributesView AttrsCopy{attrs}; |
8848 | for (ParsedAttr &attr : AttrsCopy) { |
8849 | |
8850 | // Skip attributes that were marked to be invalid. |
8851 | if (attr.isInvalid()) |
8852 | continue; |
8853 | |
8854 | if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) { |
8855 | // [[gnu::...]] attributes are treated as declaration attributes, so may |
8856 | // not appertain to a DeclaratorChunk. If we handle them as type |
8857 | // attributes, accept them in that position and diagnose the GCC |
8858 | // incompatibility. |
8859 | if (attr.isGNUScope()) { |
8860 | assert(attr.isStandardAttributeSyntax()); |
8861 | bool IsTypeAttr = attr.isTypeAttr(); |
8862 | if (TAL == TAL_DeclChunk) { |
8863 | state.getSema().Diag(attr.getLoc(), |
8864 | IsTypeAttr |
8865 | ? diag::warn_gcc_ignores_type_attr |
8866 | : diag::warn_cxx11_gnu_attribute_on_type) |
8867 | << attr; |
8868 | if (!IsTypeAttr) |
8869 | continue; |
8870 | } |
8871 | } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk && |
8872 | !attr.isTypeAttr()) { |
8873 | // Otherwise, only consider type processing for a C++11 attribute if |
8874 | // - it has actually been applied to a type (decl-specifier-seq or |
8875 | // declarator chunk), or |
8876 | // - it is a type attribute, irrespective of where it was applied (so |
8877 | // that we can support the legacy behavior of some type attributes |
8878 | // that can be applied to the declaration name). |
8879 | continue; |
8880 | } |
8881 | } |
8882 | |
8883 | // If this is an attribute we can handle, do so now, |
8884 | // otherwise, add it to the FnAttrs list for rechaining. |
8885 | switch (attr.getKind()) { |
8886 | default: |
8887 | // A [[]] attribute on a declarator chunk must appertain to a type. |
8888 | if ((attr.isStandardAttributeSyntax() || |
8889 | attr.isRegularKeywordAttribute()) && |
8890 | TAL == TAL_DeclChunk) { |
8891 | state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr) |
8892 | << attr << attr.isRegularKeywordAttribute(); |
8893 | attr.setUsedAsTypeAttr(); |
8894 | } |
8895 | break; |
8896 | |
8897 | case ParsedAttr::UnknownAttribute: |
8898 | if (attr.isStandardAttributeSyntax()) { |
8899 | state.getSema().Diag(attr.getLoc(), |
8900 | diag::warn_unknown_attribute_ignored) |
8901 | << attr << attr.getRange(); |
8902 | // Mark the attribute as invalid so we don't emit the same diagnostic |
8903 | // multiple times. |
8904 | attr.setInvalid(); |
8905 | } |
8906 | break; |
8907 | |
8908 | case ParsedAttr::IgnoredAttribute: |
8909 | break; |
8910 | |
8911 | case ParsedAttr::AT_BTFTypeTag: |
8912 | HandleBTFTypeTagAttribute(Type&: type, Attr: attr, State&: state); |
8913 | attr.setUsedAsTypeAttr(); |
8914 | break; |
8915 | |
8916 | case ParsedAttr::AT_MayAlias: |
8917 | // FIXME: This attribute needs to actually be handled, but if we ignore |
8918 | // it it breaks large amounts of Linux software. |
8919 | attr.setUsedAsTypeAttr(); |
8920 | break; |
8921 | case ParsedAttr::AT_OpenCLPrivateAddressSpace: |
8922 | case ParsedAttr::AT_OpenCLGlobalAddressSpace: |
8923 | case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace: |
8924 | case ParsedAttr::AT_OpenCLGlobalHostAddressSpace: |
8925 | case ParsedAttr::AT_OpenCLLocalAddressSpace: |
8926 | case ParsedAttr::AT_OpenCLConstantAddressSpace: |
8927 | case ParsedAttr::AT_OpenCLGenericAddressSpace: |
8928 | case ParsedAttr::AT_HLSLGroupSharedAddressSpace: |
8929 | case ParsedAttr::AT_AddressSpace: |
8930 | HandleAddressSpaceTypeAttribute(Type&: type, Attr: attr, State&: state); |
8931 | attr.setUsedAsTypeAttr(); |
8932 | break; |
8933 | OBJC_POINTER_TYPE_ATTRS_CASELIST: |
8934 | if (!handleObjCPointerTypeAttr(state, attr, type)) |
8935 | distributeObjCPointerTypeAttr(state, attr, type); |
8936 | attr.setUsedAsTypeAttr(); |
8937 | break; |
8938 | case ParsedAttr::AT_VectorSize: |
8939 | HandleVectorSizeAttr(CurType&: type, Attr: attr, S&: state.getSema()); |
8940 | attr.setUsedAsTypeAttr(); |
8941 | break; |
8942 | case ParsedAttr::AT_ExtVectorType: |
8943 | HandleExtVectorTypeAttr(CurType&: type, Attr: attr, S&: state.getSema()); |
8944 | attr.setUsedAsTypeAttr(); |
8945 | break; |
8946 | case ParsedAttr::AT_NeonVectorType: |
8947 | HandleNeonVectorTypeAttr(CurType&: type, Attr: attr, S&: state.getSema(), VecKind: VectorKind::Neon); |
8948 | attr.setUsedAsTypeAttr(); |
8949 | break; |
8950 | case ParsedAttr::AT_NeonPolyVectorType: |
8951 | HandleNeonVectorTypeAttr(CurType&: type, Attr: attr, S&: state.getSema(), |
8952 | VecKind: VectorKind::NeonPoly); |
8953 | attr.setUsedAsTypeAttr(); |
8954 | break; |
8955 | case ParsedAttr::AT_ArmSveVectorBits: |
8956 | HandleArmSveVectorBitsTypeAttr(CurType&: type, Attr&: attr, S&: state.getSema()); |
8957 | attr.setUsedAsTypeAttr(); |
8958 | break; |
8959 | case ParsedAttr::AT_ArmMveStrictPolymorphism: { |
8960 | HandleArmMveStrictPolymorphismAttr(State&: state, CurType&: type, Attr&: attr); |
8961 | attr.setUsedAsTypeAttr(); |
8962 | break; |
8963 | } |
8964 | case ParsedAttr::AT_RISCVRVVVectorBits: |
8965 | HandleRISCVRVVVectorBitsTypeAttr(CurType&: type, Attr&: attr, S&: state.getSema()); |
8966 | attr.setUsedAsTypeAttr(); |
8967 | break; |
8968 | case ParsedAttr::AT_OpenCLAccess: |
8969 | HandleOpenCLAccessAttr(CurType&: type, Attr: attr, S&: state.getSema()); |
8970 | attr.setUsedAsTypeAttr(); |
8971 | break; |
8972 | case ParsedAttr::AT_LifetimeBound: |
8973 | if (TAL == TAL_DeclChunk) |
8974 | HandleLifetimeBoundAttr(State&: state, CurType&: type, Attr&: attr); |
8975 | break; |
8976 | |
8977 | case ParsedAttr::AT_NoDeref: { |
8978 | // FIXME: `noderef` currently doesn't work correctly in [[]] syntax. |
8979 | // See https://github.com/llvm/llvm-project/issues/55790 for details. |
8980 | // For the time being, we simply emit a warning that the attribute is |
8981 | // ignored. |
8982 | if (attr.isStandardAttributeSyntax()) { |
8983 | state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored) |
8984 | << attr; |
8985 | break; |
8986 | } |
8987 | ASTContext &Ctx = state.getSema().Context; |
8988 | type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr), |
8989 | type, type); |
8990 | attr.setUsedAsTypeAttr(); |
8991 | state.setParsedNoDeref(true); |
8992 | break; |
8993 | } |
8994 | |
8995 | case ParsedAttr::AT_MatrixType: |
8996 | HandleMatrixTypeAttr(CurType&: type, Attr: attr, S&: state.getSema()); |
8997 | attr.setUsedAsTypeAttr(); |
8998 | break; |
8999 | |
9000 | case ParsedAttr::AT_WebAssemblyFuncref: { |
9001 | if (!HandleWebAssemblyFuncrefAttr(State&: state, QT&: type, PAttr&: attr)) |
9002 | attr.setUsedAsTypeAttr(); |
9003 | break; |
9004 | } |
9005 | |
9006 | case ParsedAttr::AT_HLSLParamModifier: { |
9007 | HandleHLSLParamModifierAttr(CurType&: type, Attr: attr, S&: state.getSema()); |
9008 | attr.setUsedAsTypeAttr(); |
9009 | break; |
9010 | } |
9011 | |
9012 | MS_TYPE_ATTRS_CASELIST: |
9013 | if (!handleMSPointerTypeQualifierAttr(State&: state, PAttr&: attr, Type&: type)) |
9014 | attr.setUsedAsTypeAttr(); |
9015 | break; |
9016 | |
9017 | |
9018 | NULLABILITY_TYPE_ATTRS_CASELIST: |
9019 | // Either add nullability here or try to distribute it. We |
9020 | // don't want to distribute the nullability specifier past any |
9021 | // dependent type, because that complicates the user model. |
9022 | if (type->canHaveNullability() || type->isDependentType() || |
9023 | type->isArrayType() || |
9024 | !distributeNullabilityTypeAttr(state, type, attr)) { |
9025 | unsigned endIndex; |
9026 | if (TAL == TAL_DeclChunk) |
9027 | endIndex = state.getCurrentChunkIndex(); |
9028 | else |
9029 | endIndex = state.getDeclarator().getNumTypeObjects(); |
9030 | bool allowOnArrayType = |
9031 | state.getDeclarator().isPrototypeContext() && |
9032 | !hasOuterPointerLikeChunk(D: state.getDeclarator(), endIndex); |
9033 | if (CheckNullabilityTypeSpecifier(State&: state, Type&: type, Attr&: attr, |
9034 | AllowOnArrayType: allowOnArrayType)) { |
9035 | attr.setInvalid(); |
9036 | } |
9037 | |
9038 | attr.setUsedAsTypeAttr(); |
9039 | } |
9040 | break; |
9041 | |
9042 | case ParsedAttr::AT_ObjCKindOf: |
9043 | // '__kindof' must be part of the decl-specifiers. |
9044 | switch (TAL) { |
9045 | case TAL_DeclSpec: |
9046 | break; |
9047 | |
9048 | case TAL_DeclChunk: |
9049 | case TAL_DeclName: |
9050 | state.getSema().Diag(attr.getLoc(), |
9051 | diag::err_objc_kindof_wrong_position) |
9052 | << FixItHint::CreateRemoval(attr.getLoc()) |
9053 | << FixItHint::CreateInsertion( |
9054 | state.getDeclarator().getDeclSpec().getBeginLoc(), |
9055 | "__kindof " ); |
9056 | break; |
9057 | } |
9058 | |
9059 | // Apply it regardless. |
9060 | if (checkObjCKindOfType(state, type, attr)) |
9061 | attr.setInvalid(); |
9062 | break; |
9063 | |
9064 | case ParsedAttr::AT_NoThrow: |
9065 | // Exception Specifications aren't generally supported in C mode throughout |
9066 | // clang, so revert to attribute-based handling for C. |
9067 | if (!state.getSema().getLangOpts().CPlusPlus) |
9068 | break; |
9069 | [[fallthrough]]; |
9070 | FUNCTION_TYPE_ATTRS_CASELIST: |
9071 | attr.setUsedAsTypeAttr(); |
9072 | |
9073 | // Attributes with standard syntax have strict rules for what they |
9074 | // appertain to and hence should not use the "distribution" logic below. |
9075 | if (attr.isStandardAttributeSyntax() || |
9076 | attr.isRegularKeywordAttribute()) { |
9077 | if (!handleFunctionTypeAttr(state, attr, type, CFT)) { |
9078 | diagnoseBadTypeAttribute(S&: state.getSema(), attr, type); |
9079 | attr.setInvalid(); |
9080 | } |
9081 | break; |
9082 | } |
9083 | |
9084 | // Never process function type attributes as part of the |
9085 | // declaration-specifiers. |
9086 | if (TAL == TAL_DeclSpec) |
9087 | distributeFunctionTypeAttrFromDeclSpec(state, attr, declSpecType&: type, CFT); |
9088 | |
9089 | // Otherwise, handle the possible delays. |
9090 | else if (!handleFunctionTypeAttr(state, attr, type, CFT)) |
9091 | distributeFunctionTypeAttr(state, attr, type); |
9092 | break; |
9093 | case ParsedAttr::AT_AcquireHandle: { |
9094 | if (!type->isFunctionType()) |
9095 | return; |
9096 | |
9097 | if (attr.getNumArgs() != 1) { |
9098 | state.getSema().Diag(attr.getLoc(), |
9099 | diag::err_attribute_wrong_number_arguments) |
9100 | << attr << 1; |
9101 | attr.setInvalid(); |
9102 | return; |
9103 | } |
9104 | |
9105 | StringRef HandleType; |
9106 | if (!state.getSema().checkStringLiteralArgumentAttr(Attr: attr, ArgNum: 0, Str&: HandleType)) |
9107 | return; |
9108 | type = state.getAttributedType( |
9109 | AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr), |
9110 | type, type); |
9111 | attr.setUsedAsTypeAttr(); |
9112 | break; |
9113 | } |
9114 | case ParsedAttr::AT_AnnotateType: { |
9115 | HandleAnnotateTypeAttr(State&: state, CurType&: type, PA: attr); |
9116 | attr.setUsedAsTypeAttr(); |
9117 | break; |
9118 | } |
9119 | } |
9120 | |
9121 | // Handle attributes that are defined in a macro. We do not want this to be |
9122 | // applied to ObjC builtin attributes. |
9123 | if (isa<AttributedType>(type) && attr.hasMacroIdentifier() && |
9124 | !type.getQualifiers().hasObjCLifetime() && |
9125 | !type.getQualifiers().hasObjCGCAttr() && |
9126 | attr.getKind() != ParsedAttr::AT_ObjCGC && |
9127 | attr.getKind() != ParsedAttr::AT_ObjCOwnership) { |
9128 | const IdentifierInfo *MacroII = attr.getMacroIdentifier(); |
9129 | type = state.getSema().Context.getMacroQualifiedType(UnderlyingTy: type, MacroII); |
9130 | state.setExpansionLocForMacroQualifiedType( |
9131 | MQT: cast<MacroQualifiedType>(Val: type.getTypePtr()), |
9132 | Loc: attr.getMacroExpansionLoc()); |
9133 | } |
9134 | } |
9135 | } |
9136 | |
9137 | void Sema::completeExprArrayBound(Expr *E) { |
9138 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) { |
9139 | if (VarDecl *Var = dyn_cast<VarDecl>(Val: DRE->getDecl())) { |
9140 | if (isTemplateInstantiation(Kind: Var->getTemplateSpecializationKind())) { |
9141 | auto *Def = Var->getDefinition(); |
9142 | if (!Def) { |
9143 | SourceLocation PointOfInstantiation = E->getExprLoc(); |
9144 | runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] { |
9145 | InstantiateVariableDefinition(PointOfInstantiation, Var); |
9146 | }); |
9147 | Def = Var->getDefinition(); |
9148 | |
9149 | // If we don't already have a point of instantiation, and we managed |
9150 | // to instantiate a definition, this is the point of instantiation. |
9151 | // Otherwise, we don't request an end-of-TU instantiation, so this is |
9152 | // not a point of instantiation. |
9153 | // FIXME: Is this really the right behavior? |
9154 | if (Var->getPointOfInstantiation().isInvalid() && Def) { |
9155 | assert(Var->getTemplateSpecializationKind() == |
9156 | TSK_ImplicitInstantiation && |
9157 | "explicit instantiation with no point of instantiation" ); |
9158 | Var->setTemplateSpecializationKind( |
9159 | TSK: Var->getTemplateSpecializationKind(), PointOfInstantiation); |
9160 | } |
9161 | } |
9162 | |
9163 | // Update the type to the definition's type both here and within the |
9164 | // expression. |
9165 | if (Def) { |
9166 | DRE->setDecl(Def); |
9167 | QualType T = Def->getType(); |
9168 | DRE->setType(T); |
9169 | // FIXME: Update the type on all intervening expressions. |
9170 | E->setType(T); |
9171 | } |
9172 | |
9173 | // We still go on to try to complete the type independently, as it |
9174 | // may also require instantiations or diagnostics if it remains |
9175 | // incomplete. |
9176 | } |
9177 | } |
9178 | } |
9179 | } |
9180 | |
9181 | QualType Sema::getCompletedType(Expr *E) { |
9182 | // Incomplete array types may be completed by the initializer attached to |
9183 | // their definitions. For static data members of class templates and for |
9184 | // variable templates, we need to instantiate the definition to get this |
9185 | // initializer and complete the type. |
9186 | if (E->getType()->isIncompleteArrayType()) |
9187 | completeExprArrayBound(E); |
9188 | |
9189 | // FIXME: Are there other cases which require instantiating something other |
9190 | // than the type to complete the type of an expression? |
9191 | |
9192 | return E->getType(); |
9193 | } |
9194 | |
9195 | /// Ensure that the type of the given expression is complete. |
9196 | /// |
9197 | /// This routine checks whether the expression \p E has a complete type. If the |
9198 | /// expression refers to an instantiable construct, that instantiation is |
9199 | /// performed as needed to complete its type. Furthermore |
9200 | /// Sema::RequireCompleteType is called for the expression's type (or in the |
9201 | /// case of a reference type, the referred-to type). |
9202 | /// |
9203 | /// \param E The expression whose type is required to be complete. |
9204 | /// \param Kind Selects which completeness rules should be applied. |
9205 | /// \param Diagnoser The object that will emit a diagnostic if the type is |
9206 | /// incomplete. |
9207 | /// |
9208 | /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false |
9209 | /// otherwise. |
9210 | bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, |
9211 | TypeDiagnoser &Diagnoser) { |
9212 | return RequireCompleteType(Loc: E->getExprLoc(), T: getCompletedType(E), Kind, |
9213 | Diagnoser); |
9214 | } |
9215 | |
9216 | bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) { |
9217 | BoundTypeDiagnoser<> Diagnoser(DiagID); |
9218 | return RequireCompleteExprType(E, Kind: CompleteTypeKind::Default, Diagnoser); |
9219 | } |
9220 | |
9221 | /// Ensure that the type T is a complete type. |
9222 | /// |
9223 | /// This routine checks whether the type @p T is complete in any |
9224 | /// context where a complete type is required. If @p T is a complete |
9225 | /// type, returns false. If @p T is a class template specialization, |
9226 | /// this routine then attempts to perform class template |
9227 | /// instantiation. If instantiation fails, or if @p T is incomplete |
9228 | /// and cannot be completed, issues the diagnostic @p diag (giving it |
9229 | /// the type @p T) and returns true. |
9230 | /// |
9231 | /// @param Loc The location in the source that the incomplete type |
9232 | /// diagnostic should refer to. |
9233 | /// |
9234 | /// @param T The type that this routine is examining for completeness. |
9235 | /// |
9236 | /// @param Kind Selects which completeness rules should be applied. |
9237 | /// |
9238 | /// @returns @c true if @p T is incomplete and a diagnostic was emitted, |
9239 | /// @c false otherwise. |
9240 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, |
9241 | CompleteTypeKind Kind, |
9242 | TypeDiagnoser &Diagnoser) { |
9243 | if (RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: &Diagnoser)) |
9244 | return true; |
9245 | if (const TagType *Tag = T->getAs<TagType>()) { |
9246 | if (!Tag->getDecl()->isCompleteDefinitionRequired()) { |
9247 | Tag->getDecl()->setCompleteDefinitionRequired(); |
9248 | Consumer.HandleTagDeclRequiredDefinition(D: Tag->getDecl()); |
9249 | } |
9250 | } |
9251 | return false; |
9252 | } |
9253 | |
9254 | bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) { |
9255 | llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls; |
9256 | if (!Suggested) |
9257 | return false; |
9258 | |
9259 | // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext |
9260 | // and isolate from other C++ specific checks. |
9261 | StructuralEquivalenceContext Ctx( |
9262 | D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls, |
9263 | StructuralEquivalenceKind::Default, |
9264 | false /*StrictTypeSpelling*/, true /*Complain*/, |
9265 | true /*ErrorOnTagTypeMismatch*/); |
9266 | return Ctx.IsEquivalent(D1: D, D2: Suggested); |
9267 | } |
9268 | |
9269 | bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, |
9270 | AcceptableKind Kind, bool OnlyNeedComplete) { |
9271 | // Easy case: if we don't have modules, all declarations are visible. |
9272 | if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility) |
9273 | return true; |
9274 | |
9275 | // If this definition was instantiated from a template, map back to the |
9276 | // pattern from which it was instantiated. |
9277 | if (isa<TagDecl>(Val: D) && cast<TagDecl>(Val: D)->isBeingDefined()) { |
9278 | // We're in the middle of defining it; this definition should be treated |
9279 | // as visible. |
9280 | return true; |
9281 | } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) { |
9282 | if (auto *Pattern = RD->getTemplateInstantiationPattern()) |
9283 | RD = Pattern; |
9284 | D = RD->getDefinition(); |
9285 | } else if (auto *ED = dyn_cast<EnumDecl>(Val: D)) { |
9286 | if (auto *Pattern = ED->getTemplateInstantiationPattern()) |
9287 | ED = Pattern; |
9288 | if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) { |
9289 | // If the enum has a fixed underlying type, it may have been forward |
9290 | // declared. In -fms-compatibility, `enum Foo;` will also forward declare |
9291 | // the enum and assign it the underlying type of `int`. Since we're only |
9292 | // looking for a complete type (not a definition), any visible declaration |
9293 | // of it will do. |
9294 | *Suggested = nullptr; |
9295 | for (auto *Redecl : ED->redecls()) { |
9296 | if (isAcceptable(Redecl, Kind)) |
9297 | return true; |
9298 | if (Redecl->isThisDeclarationADefinition() || |
9299 | (Redecl->isCanonicalDecl() && !*Suggested)) |
9300 | *Suggested = Redecl; |
9301 | } |
9302 | |
9303 | return false; |
9304 | } |
9305 | D = ED->getDefinition(); |
9306 | } else if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
9307 | if (auto *Pattern = FD->getTemplateInstantiationPattern()) |
9308 | FD = Pattern; |
9309 | D = FD->getDefinition(); |
9310 | } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) { |
9311 | if (auto *Pattern = VD->getTemplateInstantiationPattern()) |
9312 | VD = Pattern; |
9313 | D = VD->getDefinition(); |
9314 | } |
9315 | |
9316 | assert(D && "missing definition for pattern of instantiated definition" ); |
9317 | |
9318 | *Suggested = D; |
9319 | |
9320 | auto DefinitionIsAcceptable = [&] { |
9321 | // The (primary) definition might be in a visible module. |
9322 | if (isAcceptable(D, Kind)) |
9323 | return true; |
9324 | |
9325 | // A visible module might have a merged definition instead. |
9326 | if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(Def: D) |
9327 | : hasVisibleMergedDefinition(Def: D)) { |
9328 | if (CodeSynthesisContexts.empty() && |
9329 | !getLangOpts().ModulesLocalVisibility) { |
9330 | // Cache the fact that this definition is implicitly visible because |
9331 | // there is a visible merged definition. |
9332 | D->setVisibleDespiteOwningModule(); |
9333 | } |
9334 | return true; |
9335 | } |
9336 | |
9337 | return false; |
9338 | }; |
9339 | |
9340 | if (DefinitionIsAcceptable()) |
9341 | return true; |
9342 | |
9343 | // The external source may have additional definitions of this entity that are |
9344 | // visible, so complete the redeclaration chain now and ask again. |
9345 | if (auto *Source = Context.getExternalSource()) { |
9346 | Source->CompleteRedeclChain(D); |
9347 | return DefinitionIsAcceptable(); |
9348 | } |
9349 | |
9350 | return false; |
9351 | } |
9352 | |
9353 | /// Determine whether there is any declaration of \p D that was ever a |
9354 | /// definition (perhaps before module merging) and is currently visible. |
9355 | /// \param D The definition of the entity. |
9356 | /// \param Suggested Filled in with the declaration that should be made visible |
9357 | /// in order to provide a definition of this entity. |
9358 | /// \param OnlyNeedComplete If \c true, we only need the type to be complete, |
9359 | /// not defined. This only matters for enums with a fixed underlying |
9360 | /// type, since in all other cases, a type is complete if and only if it |
9361 | /// is defined. |
9362 | bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, |
9363 | bool OnlyNeedComplete) { |
9364 | return hasAcceptableDefinition(D, Suggested, Kind: Sema::AcceptableKind::Visible, |
9365 | OnlyNeedComplete); |
9366 | } |
9367 | |
9368 | /// Determine whether there is any declaration of \p D that was ever a |
9369 | /// definition (perhaps before module merging) and is currently |
9370 | /// reachable. |
9371 | /// \param D The definition of the entity. |
9372 | /// \param Suggested Filled in with the declaration that should be made |
9373 | /// reachable |
9374 | /// in order to provide a definition of this entity. |
9375 | /// \param OnlyNeedComplete If \c true, we only need the type to be complete, |
9376 | /// not defined. This only matters for enums with a fixed underlying |
9377 | /// type, since in all other cases, a type is complete if and only if it |
9378 | /// is defined. |
9379 | bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, |
9380 | bool OnlyNeedComplete) { |
9381 | return hasAcceptableDefinition(D, Suggested, Kind: Sema::AcceptableKind::Reachable, |
9382 | OnlyNeedComplete); |
9383 | } |
9384 | |
9385 | /// Locks in the inheritance model for the given class and all of its bases. |
9386 | static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) { |
9387 | RD = RD->getMostRecentNonInjectedDecl(); |
9388 | if (!RD->hasAttr<MSInheritanceAttr>()) { |
9389 | MSInheritanceModel IM; |
9390 | bool BestCase = false; |
9391 | switch (S.MSPointerToMemberRepresentationMethod) { |
9392 | case LangOptions::PPTMK_BestCase: |
9393 | BestCase = true; |
9394 | IM = RD->calculateInheritanceModel(); |
9395 | break; |
9396 | case LangOptions::PPTMK_FullGeneralitySingleInheritance: |
9397 | IM = MSInheritanceModel::Single; |
9398 | break; |
9399 | case LangOptions::PPTMK_FullGeneralityMultipleInheritance: |
9400 | IM = MSInheritanceModel::Multiple; |
9401 | break; |
9402 | case LangOptions::PPTMK_FullGeneralityVirtualInheritance: |
9403 | IM = MSInheritanceModel::Unspecified; |
9404 | break; |
9405 | } |
9406 | |
9407 | SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid() |
9408 | ? S.ImplicitMSInheritanceAttrLoc |
9409 | : RD->getSourceRange(); |
9410 | RD->addAttr(MSInheritanceAttr::CreateImplicit( |
9411 | S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM))); |
9412 | S.Consumer.AssignInheritanceModel(RD); |
9413 | } |
9414 | } |
9415 | |
9416 | /// The implementation of RequireCompleteType |
9417 | bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T, |
9418 | CompleteTypeKind Kind, |
9419 | TypeDiagnoser *Diagnoser) { |
9420 | // FIXME: Add this assertion to make sure we always get instantiation points. |
9421 | // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); |
9422 | // FIXME: Add this assertion to help us flush out problems with |
9423 | // checking for dependent types and type-dependent expressions. |
9424 | // |
9425 | // assert(!T->isDependentType() && |
9426 | // "Can't ask whether a dependent type is complete"); |
9427 | |
9428 | if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) { |
9429 | if (!MPTy->getClass()->isDependentType()) { |
9430 | if (getLangOpts().CompleteMemberPointers && |
9431 | !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() && |
9432 | RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind, |
9433 | diag::err_memptr_incomplete)) |
9434 | return true; |
9435 | |
9436 | // We lock in the inheritance model once somebody has asked us to ensure |
9437 | // that a pointer-to-member type is complete. |
9438 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
9439 | (void)isCompleteType(Loc, T: QualType(MPTy->getClass(), 0)); |
9440 | assignInheritanceModel(S&: *this, RD: MPTy->getMostRecentCXXRecordDecl()); |
9441 | } |
9442 | } |
9443 | } |
9444 | |
9445 | NamedDecl *Def = nullptr; |
9446 | bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless); |
9447 | bool Incomplete = (T->isIncompleteType(Def: &Def) || |
9448 | (!AcceptSizeless && T->isSizelessBuiltinType())); |
9449 | |
9450 | // Check that any necessary explicit specializations are visible. For an |
9451 | // enum, we just need the declaration, so don't check this. |
9452 | if (Def && !isa<EnumDecl>(Val: Def)) |
9453 | checkSpecializationReachability(Loc, Spec: Def); |
9454 | |
9455 | // If we have a complete type, we're done. |
9456 | if (!Incomplete) { |
9457 | NamedDecl *Suggested = nullptr; |
9458 | if (Def && |
9459 | !hasReachableDefinition(D: Def, Suggested: &Suggested, /*OnlyNeedComplete=*/true)) { |
9460 | // If the user is going to see an error here, recover by making the |
9461 | // definition visible. |
9462 | bool TreatAsComplete = Diagnoser && !isSFINAEContext(); |
9463 | if (Diagnoser && Suggested) |
9464 | diagnoseMissingImport(Loc, Decl: Suggested, MIK: MissingImportKind::Definition, |
9465 | /*Recover*/ TreatAsComplete); |
9466 | return !TreatAsComplete; |
9467 | } else if (Def && !TemplateInstCallbacks.empty()) { |
9468 | CodeSynthesisContext TempInst; |
9469 | TempInst.Kind = CodeSynthesisContext::Memoization; |
9470 | TempInst.Template = Def; |
9471 | TempInst.Entity = Def; |
9472 | TempInst.PointOfInstantiation = Loc; |
9473 | atTemplateBegin(Callbacks&: TemplateInstCallbacks, TheSema: *this, Inst: TempInst); |
9474 | atTemplateEnd(Callbacks&: TemplateInstCallbacks, TheSema: *this, Inst: TempInst); |
9475 | } |
9476 | |
9477 | return false; |
9478 | } |
9479 | |
9480 | TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: Def); |
9481 | ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Val: Def); |
9482 | |
9483 | // Give the external source a chance to provide a definition of the type. |
9484 | // This is kept separate from completing the redeclaration chain so that |
9485 | // external sources such as LLDB can avoid synthesizing a type definition |
9486 | // unless it's actually needed. |
9487 | if (Tag || IFace) { |
9488 | // Avoid diagnosing invalid decls as incomplete. |
9489 | if (Def->isInvalidDecl()) |
9490 | return true; |
9491 | |
9492 | // Give the external AST source a chance to complete the type. |
9493 | if (auto *Source = Context.getExternalSource()) { |
9494 | if (Tag && Tag->hasExternalLexicalStorage()) |
9495 | Source->CompleteType(Tag); |
9496 | if (IFace && IFace->hasExternalLexicalStorage()) |
9497 | Source->CompleteType(Class: IFace); |
9498 | // If the external source completed the type, go through the motions |
9499 | // again to ensure we're allowed to use the completed type. |
9500 | if (!T->isIncompleteType()) |
9501 | return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); |
9502 | } |
9503 | } |
9504 | |
9505 | // If we have a class template specialization or a class member of a |
9506 | // class template specialization, or an array with known size of such, |
9507 | // try to instantiate it. |
9508 | if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Val: Tag)) { |
9509 | bool Instantiated = false; |
9510 | bool Diagnosed = false; |
9511 | if (RD->isDependentContext()) { |
9512 | // Don't try to instantiate a dependent class (eg, a member template of |
9513 | // an instantiated class template specialization). |
9514 | // FIXME: Can this ever happen? |
9515 | } else if (auto *ClassTemplateSpec = |
9516 | dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) { |
9517 | if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { |
9518 | runWithSufficientStackSpace(Loc, Fn: [&] { |
9519 | Diagnosed = InstantiateClassTemplateSpecialization( |
9520 | PointOfInstantiation: Loc, ClassTemplateSpec, TSK: TSK_ImplicitInstantiation, |
9521 | /*Complain=*/Diagnoser); |
9522 | }); |
9523 | Instantiated = true; |
9524 | } |
9525 | } else { |
9526 | CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass(); |
9527 | if (!RD->isBeingDefined() && Pattern) { |
9528 | MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo(); |
9529 | assert(MSI && "Missing member specialization information?" ); |
9530 | // This record was instantiated from a class within a template. |
9531 | if (MSI->getTemplateSpecializationKind() != |
9532 | TSK_ExplicitSpecialization) { |
9533 | runWithSufficientStackSpace(Loc, Fn: [&] { |
9534 | Diagnosed = InstantiateClass(PointOfInstantiation: Loc, Instantiation: RD, Pattern, |
9535 | TemplateArgs: getTemplateInstantiationArgs(RD), |
9536 | TSK: TSK_ImplicitInstantiation, |
9537 | /*Complain=*/Diagnoser); |
9538 | }); |
9539 | Instantiated = true; |
9540 | } |
9541 | } |
9542 | } |
9543 | |
9544 | if (Instantiated) { |
9545 | // Instantiate* might have already complained that the template is not |
9546 | // defined, if we asked it to. |
9547 | if (Diagnoser && Diagnosed) |
9548 | return true; |
9549 | // If we instantiated a definition, check that it's usable, even if |
9550 | // instantiation produced an error, so that repeated calls to this |
9551 | // function give consistent answers. |
9552 | if (!T->isIncompleteType()) |
9553 | return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser); |
9554 | } |
9555 | } |
9556 | |
9557 | // FIXME: If we didn't instantiate a definition because of an explicit |
9558 | // specialization declaration, check that it's visible. |
9559 | |
9560 | if (!Diagnoser) |
9561 | return true; |
9562 | |
9563 | Diagnoser->diagnose(S&: *this, Loc, T); |
9564 | |
9565 | // If the type was a forward declaration of a class/struct/union |
9566 | // type, produce a note. |
9567 | if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid()) |
9568 | Diag(Tag->getLocation(), |
9569 | Tag->isBeingDefined() ? diag::note_type_being_defined |
9570 | : diag::note_forward_declaration) |
9571 | << Context.getTagDeclType(Tag); |
9572 | |
9573 | // If the Objective-C class was a forward declaration, produce a note. |
9574 | if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid()) |
9575 | Diag(IFace->getLocation(), diag::note_forward_class); |
9576 | |
9577 | // If we have external information that we can use to suggest a fix, |
9578 | // produce a note. |
9579 | if (ExternalSource) |
9580 | ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T); |
9581 | |
9582 | return true; |
9583 | } |
9584 | |
9585 | bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, |
9586 | CompleteTypeKind Kind, unsigned DiagID) { |
9587 | BoundTypeDiagnoser<> Diagnoser(DiagID); |
9588 | return RequireCompleteType(Loc, T, Kind, Diagnoser); |
9589 | } |
9590 | |
9591 | /// Get diagnostic %select index for tag kind for |
9592 | /// literal type diagnostic message. |
9593 | /// WARNING: Indexes apply to particular diagnostics only! |
9594 | /// |
9595 | /// \returns diagnostic %select index. |
9596 | static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) { |
9597 | switch (Tag) { |
9598 | case TagTypeKind::Struct: |
9599 | return 0; |
9600 | case TagTypeKind::Interface: |
9601 | return 1; |
9602 | case TagTypeKind::Class: |
9603 | return 2; |
9604 | default: llvm_unreachable("Invalid tag kind for literal type diagnostic!" ); |
9605 | } |
9606 | } |
9607 | |
9608 | /// Ensure that the type T is a literal type. |
9609 | /// |
9610 | /// This routine checks whether the type @p T is a literal type. If @p T is an |
9611 | /// incomplete type, an attempt is made to complete it. If @p T is a literal |
9612 | /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, |
9613 | /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving |
9614 | /// it the type @p T), along with notes explaining why the type is not a |
9615 | /// literal type, and returns true. |
9616 | /// |
9617 | /// @param Loc The location in the source that the non-literal type |
9618 | /// diagnostic should refer to. |
9619 | /// |
9620 | /// @param T The type that this routine is examining for literalness. |
9621 | /// |
9622 | /// @param Diagnoser Emits a diagnostic if T is not a literal type. |
9623 | /// |
9624 | /// @returns @c true if @p T is not a literal type and a diagnostic was emitted, |
9625 | /// @c false otherwise. |
9626 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, |
9627 | TypeDiagnoser &Diagnoser) { |
9628 | assert(!T->isDependentType() && "type should not be dependent" ); |
9629 | |
9630 | QualType ElemType = Context.getBaseElementType(QT: T); |
9631 | if ((isCompleteType(Loc, T: ElemType) || ElemType->isVoidType()) && |
9632 | T->isLiteralType(Ctx: Context)) |
9633 | return false; |
9634 | |
9635 | Diagnoser.diagnose(S&: *this, Loc, T); |
9636 | |
9637 | if (T->isVariableArrayType()) |
9638 | return true; |
9639 | |
9640 | const RecordType *RT = ElemType->getAs<RecordType>(); |
9641 | if (!RT) |
9642 | return true; |
9643 | |
9644 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: RT->getDecl()); |
9645 | |
9646 | // A partially-defined class type can't be a literal type, because a literal |
9647 | // class type must have a trivial destructor (which can't be checked until |
9648 | // the class definition is complete). |
9649 | if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T)) |
9650 | return true; |
9651 | |
9652 | // [expr.prim.lambda]p3: |
9653 | // This class type is [not] a literal type. |
9654 | if (RD->isLambda() && !getLangOpts().CPlusPlus17) { |
9655 | Diag(RD->getLocation(), diag::note_non_literal_lambda); |
9656 | return true; |
9657 | } |
9658 | |
9659 | // If the class has virtual base classes, then it's not an aggregate, and |
9660 | // cannot have any constexpr constructors or a trivial default constructor, |
9661 | // so is non-literal. This is better to diagnose than the resulting absence |
9662 | // of constexpr constructors. |
9663 | if (RD->getNumVBases()) { |
9664 | Diag(RD->getLocation(), diag::note_non_literal_virtual_base) |
9665 | << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); |
9666 | for (const auto &I : RD->vbases()) |
9667 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) |
9668 | << I.getSourceRange(); |
9669 | } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() && |
9670 | !RD->hasTrivialDefaultConstructor()) { |
9671 | Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD; |
9672 | } else if (RD->hasNonLiteralTypeFieldsOrBases()) { |
9673 | for (const auto &I : RD->bases()) { |
9674 | if (!I.getType()->isLiteralType(Ctx: Context)) { |
9675 | Diag(I.getBeginLoc(), diag::note_non_literal_base_class) |
9676 | << RD << I.getType() << I.getSourceRange(); |
9677 | return true; |
9678 | } |
9679 | } |
9680 | for (const auto *I : RD->fields()) { |
9681 | if (!I->getType()->isLiteralType(Context) || |
9682 | I->getType().isVolatileQualified()) { |
9683 | Diag(I->getLocation(), diag::note_non_literal_field) |
9684 | << RD << I << I->getType() |
9685 | << I->getType().isVolatileQualified(); |
9686 | return true; |
9687 | } |
9688 | } |
9689 | } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor() |
9690 | : !RD->hasTrivialDestructor()) { |
9691 | // All fields and bases are of literal types, so have trivial or constexpr |
9692 | // destructors. If this class's destructor is non-trivial / non-constexpr, |
9693 | // it must be user-declared. |
9694 | CXXDestructorDecl *Dtor = RD->getDestructor(); |
9695 | assert(Dtor && "class has literal fields and bases but no dtor?" ); |
9696 | if (!Dtor) |
9697 | return true; |
9698 | |
9699 | if (getLangOpts().CPlusPlus20) { |
9700 | Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor) |
9701 | << RD; |
9702 | } else { |
9703 | Diag(Dtor->getLocation(), Dtor->isUserProvided() |
9704 | ? diag::note_non_literal_user_provided_dtor |
9705 | : diag::note_non_literal_nontrivial_dtor) |
9706 | << RD; |
9707 | if (!Dtor->isUserProvided()) |
9708 | SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI, |
9709 | /*Diagnose*/ true); |
9710 | } |
9711 | } |
9712 | |
9713 | return true; |
9714 | } |
9715 | |
9716 | bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) { |
9717 | BoundTypeDiagnoser<> Diagnoser(DiagID); |
9718 | return RequireLiteralType(Loc, T, Diagnoser); |
9719 | } |
9720 | |
9721 | /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified |
9722 | /// by the nested-name-specifier contained in SS, and that is (re)declared by |
9723 | /// OwnedTagDecl, which is nullptr if this is not a (re)declaration. |
9724 | QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, |
9725 | const CXXScopeSpec &SS, QualType T, |
9726 | TagDecl *OwnedTagDecl) { |
9727 | if (T.isNull()) |
9728 | return T; |
9729 | return Context.getElaboratedType( |
9730 | Keyword, NNS: SS.isValid() ? SS.getScopeRep() : nullptr, NamedType: T, OwnedTagDecl); |
9731 | } |
9732 | |
9733 | QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) { |
9734 | assert(!E->hasPlaceholderType() && "unexpected placeholder" ); |
9735 | |
9736 | if (!getLangOpts().CPlusPlus && E->refersToBitField()) |
9737 | Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) |
9738 | << (Kind == TypeOfKind::Unqualified ? 3 : 2); |
9739 | |
9740 | if (!E->isTypeDependent()) { |
9741 | QualType T = E->getType(); |
9742 | if (const TagType *TT = T->getAs<TagType>()) |
9743 | DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc()); |
9744 | } |
9745 | return Context.getTypeOfExprType(E, Kind); |
9746 | } |
9747 | |
9748 | /// getDecltypeForExpr - Given an expr, will return the decltype for |
9749 | /// that expression, according to the rules in C++11 |
9750 | /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18. |
9751 | QualType Sema::getDecltypeForExpr(Expr *E) { |
9752 | if (E->isTypeDependent()) |
9753 | return Context.DependentTy; |
9754 | |
9755 | Expr *IDExpr = E; |
9756 | if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(Val: E)) |
9757 | IDExpr = ImplCastExpr->getSubExpr(); |
9758 | |
9759 | if (auto *PackExpr = dyn_cast<PackIndexingExpr>(Val: E)) |
9760 | IDExpr = PackExpr->getSelectedExpr(); |
9761 | |
9762 | // C++11 [dcl.type.simple]p4: |
9763 | // The type denoted by decltype(e) is defined as follows: |
9764 | |
9765 | // C++20: |
9766 | // - if E is an unparenthesized id-expression naming a non-type |
9767 | // template-parameter (13.2), decltype(E) is the type of the |
9768 | // template-parameter after performing any necessary type deduction |
9769 | // Note that this does not pick up the implicit 'const' for a template |
9770 | // parameter object. This rule makes no difference before C++20 so we apply |
9771 | // it unconditionally. |
9772 | if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(Val: IDExpr)) |
9773 | return SNTTPE->getParameterType(Ctx: Context); |
9774 | |
9775 | // - if e is an unparenthesized id-expression or an unparenthesized class |
9776 | // member access (5.2.5), decltype(e) is the type of the entity named |
9777 | // by e. If there is no such entity, or if e names a set of overloaded |
9778 | // functions, the program is ill-formed; |
9779 | // |
9780 | // We apply the same rules for Objective-C ivar and property references. |
9781 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: IDExpr)) { |
9782 | const ValueDecl *VD = DRE->getDecl(); |
9783 | QualType T = VD->getType(); |
9784 | return isa<TemplateParamObjectDecl>(Val: VD) ? T.getUnqualifiedType() : T; |
9785 | } |
9786 | if (const auto *ME = dyn_cast<MemberExpr>(Val: IDExpr)) { |
9787 | if (const auto *VD = ME->getMemberDecl()) |
9788 | if (isa<FieldDecl>(Val: VD) || isa<VarDecl>(Val: VD)) |
9789 | return VD->getType(); |
9790 | } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(Val: IDExpr)) { |
9791 | return IR->getDecl()->getType(); |
9792 | } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(Val: IDExpr)) { |
9793 | if (PR->isExplicitProperty()) |
9794 | return PR->getExplicitProperty()->getType(); |
9795 | } else if (const auto *PE = dyn_cast<PredefinedExpr>(Val: IDExpr)) { |
9796 | return PE->getType(); |
9797 | } |
9798 | |
9799 | // C++11 [expr.lambda.prim]p18: |
9800 | // Every occurrence of decltype((x)) where x is a possibly |
9801 | // parenthesized id-expression that names an entity of automatic |
9802 | // storage duration is treated as if x were transformed into an |
9803 | // access to a corresponding data member of the closure type that |
9804 | // would have been declared if x were an odr-use of the denoted |
9805 | // entity. |
9806 | if (getCurLambda() && isa<ParenExpr>(Val: IDExpr)) { |
9807 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: IDExpr->IgnoreParens())) { |
9808 | if (auto *Var = dyn_cast<VarDecl>(Val: DRE->getDecl())) { |
9809 | QualType T = getCapturedDeclRefType(Var, DRE->getLocation()); |
9810 | if (!T.isNull()) |
9811 | return Context.getLValueReferenceType(T); |
9812 | } |
9813 | } |
9814 | } |
9815 | |
9816 | return Context.getReferenceQualifiedType(e: E); |
9817 | } |
9818 | |
9819 | QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) { |
9820 | assert(!E->hasPlaceholderType() && "unexpected placeholder" ); |
9821 | |
9822 | if (AsUnevaluated && CodeSynthesisContexts.empty() && |
9823 | !E->isInstantiationDependent() && E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) { |
9824 | // The expression operand for decltype is in an unevaluated expression |
9825 | // context, so side effects could result in unintended consequences. |
9826 | // Exclude instantiation-dependent expressions, because 'decltype' is often |
9827 | // used to build SFINAE gadgets. |
9828 | Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); |
9829 | } |
9830 | return Context.getDecltypeType(e: E, UnderlyingType: getDecltypeForExpr(E)); |
9831 | } |
9832 | |
9833 | QualType Sema::ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, |
9834 | SourceLocation Loc, |
9835 | SourceLocation EllipsisLoc) { |
9836 | if (!IndexExpr) |
9837 | return QualType(); |
9838 | |
9839 | // Diagnose unexpanded packs but continue to improve recovery. |
9840 | if (!Pattern->containsUnexpandedParameterPack()) |
9841 | Diag(Loc, diag::err_expected_name_of_pack) << Pattern; |
9842 | |
9843 | QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc); |
9844 | |
9845 | if (!Type.isNull()) |
9846 | Diag(Loc, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing |
9847 | : diag::ext_pack_indexing); |
9848 | return Type; |
9849 | } |
9850 | |
9851 | QualType Sema::BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, |
9852 | SourceLocation Loc, |
9853 | SourceLocation EllipsisLoc, |
9854 | bool FullySubstituted, |
9855 | ArrayRef<QualType> Expansions) { |
9856 | |
9857 | std::optional<int64_t> Index; |
9858 | if (FullySubstituted && !IndexExpr->isValueDependent() && |
9859 | !IndexExpr->isTypeDependent()) { |
9860 | llvm::APSInt Value(Context.getIntWidth(T: Context.getSizeType())); |
9861 | ExprResult Res = CheckConvertedConstantExpression( |
9862 | From: IndexExpr, T: Context.getSizeType(), Value, CCE: CCEK_ArrayBound); |
9863 | if (!Res.isUsable()) |
9864 | return QualType(); |
9865 | Index = Value.getExtValue(); |
9866 | IndexExpr = Res.get(); |
9867 | } |
9868 | |
9869 | if (FullySubstituted && Index) { |
9870 | if (*Index < 0 || *Index >= int64_t(Expansions.size())) { |
9871 | Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound) |
9872 | << *Index << Pattern << Expansions.size(); |
9873 | return QualType(); |
9874 | } |
9875 | } |
9876 | |
9877 | return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted, |
9878 | Expansions, Index: Index.value_or(u: -1)); |
9879 | } |
9880 | |
9881 | static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType, |
9882 | SourceLocation Loc) { |
9883 | assert(BaseType->isEnumeralType()); |
9884 | EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl(); |
9885 | assert(ED && "EnumType has no EnumDecl" ); |
9886 | |
9887 | S.DiagnoseUseOfDecl(ED, Loc); |
9888 | |
9889 | QualType Underlying = ED->getIntegerType(); |
9890 | assert(!Underlying.isNull()); |
9891 | |
9892 | return Underlying; |
9893 | } |
9894 | |
9895 | QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType, |
9896 | SourceLocation Loc) { |
9897 | if (!BaseType->isEnumeralType()) { |
9898 | Diag(Loc, diag::err_only_enums_have_underlying_types); |
9899 | return QualType(); |
9900 | } |
9901 | |
9902 | // The enum could be incomplete if we're parsing its definition or |
9903 | // recovering from an error. |
9904 | NamedDecl *FwdDecl = nullptr; |
9905 | if (BaseType->isIncompleteType(Def: &FwdDecl)) { |
9906 | Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType; |
9907 | Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl; |
9908 | return QualType(); |
9909 | } |
9910 | |
9911 | return GetEnumUnderlyingType(S&: *this, BaseType, Loc); |
9912 | } |
9913 | |
9914 | QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) { |
9915 | QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType() |
9916 | ? BuildPointerType(T: BaseType.getNonReferenceType(), Loc, |
9917 | Entity: DeclarationName()) |
9918 | : BaseType; |
9919 | |
9920 | return Pointer.isNull() ? QualType() : Pointer; |
9921 | } |
9922 | |
9923 | QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) { |
9924 | // We don't want block pointers or ObjectiveC's id type. |
9925 | if (!BaseType->isAnyPointerType() || BaseType->isObjCIdType()) |
9926 | return BaseType; |
9927 | |
9928 | return BaseType->getPointeeType(); |
9929 | } |
9930 | |
9931 | QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) { |
9932 | QualType Underlying = BaseType.getNonReferenceType(); |
9933 | if (Underlying->isArrayType()) |
9934 | return Context.getDecayedType(T: Underlying); |
9935 | |
9936 | if (Underlying->isFunctionType()) |
9937 | return BuiltinAddPointer(BaseType, Loc); |
9938 | |
9939 | SplitQualType Split = Underlying.getSplitUnqualifiedType(); |
9940 | // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is |
9941 | // in the same group of qualifiers as 'const' and 'volatile', we're extending |
9942 | // '__decay(T)' so that it removes all qualifiers. |
9943 | Split.Quals.removeCVRQualifiers(); |
9944 | return Context.getQualifiedType(split: Split); |
9945 | } |
9946 | |
9947 | QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind, |
9948 | SourceLocation Loc) { |
9949 | assert(LangOpts.CPlusPlus); |
9950 | QualType Reference = |
9951 | BaseType.isReferenceable() |
9952 | ? BuildReferenceType(T: BaseType, |
9953 | SpelledAsLValue: UKind == UnaryTransformType::AddLvalueReference, |
9954 | Loc, Entity: DeclarationName()) |
9955 | : BaseType; |
9956 | return Reference.isNull() ? QualType() : Reference; |
9957 | } |
9958 | |
9959 | QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, |
9960 | SourceLocation Loc) { |
9961 | if (UKind == UnaryTransformType::RemoveAllExtents) |
9962 | return Context.getBaseElementType(QT: BaseType); |
9963 | |
9964 | if (const auto *AT = Context.getAsArrayType(T: BaseType)) |
9965 | return AT->getElementType(); |
9966 | |
9967 | return BaseType; |
9968 | } |
9969 | |
9970 | QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind, |
9971 | SourceLocation Loc) { |
9972 | assert(LangOpts.CPlusPlus); |
9973 | QualType T = BaseType.getNonReferenceType(); |
9974 | if (UKind == UTTKind::RemoveCVRef && |
9975 | (T.isConstQualified() || T.isVolatileQualified())) { |
9976 | Qualifiers Quals; |
9977 | QualType Unqual = Context.getUnqualifiedArrayType(T, Quals); |
9978 | Quals.removeConst(); |
9979 | Quals.removeVolatile(); |
9980 | T = Context.getQualifiedType(T: Unqual, Qs: Quals); |
9981 | } |
9982 | return T; |
9983 | } |
9984 | |
9985 | QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, |
9986 | SourceLocation Loc) { |
9987 | if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) || |
9988 | BaseType->isFunctionType()) |
9989 | return BaseType; |
9990 | |
9991 | Qualifiers Quals; |
9992 | QualType Unqual = Context.getUnqualifiedArrayType(T: BaseType, Quals); |
9993 | |
9994 | if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV) |
9995 | Quals.removeConst(); |
9996 | if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV) |
9997 | Quals.removeVolatile(); |
9998 | if (UKind == UTTKind::RemoveRestrict) |
9999 | Quals.removeRestrict(); |
10000 | |
10001 | return Context.getQualifiedType(T: Unqual, Qs: Quals); |
10002 | } |
10003 | |
10004 | static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType, |
10005 | bool IsMakeSigned, |
10006 | SourceLocation Loc) { |
10007 | if (BaseType->isEnumeralType()) { |
10008 | QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc); |
10009 | if (auto *BitInt = dyn_cast<BitIntType>(Val&: Underlying)) { |
10010 | unsigned int Bits = BitInt->getNumBits(); |
10011 | if (Bits > 1) |
10012 | return S.Context.getBitIntType(Unsigned: !IsMakeSigned, NumBits: Bits); |
10013 | |
10014 | S.Diag(Loc, diag::err_make_signed_integral_only) |
10015 | << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying; |
10016 | return QualType(); |
10017 | } |
10018 | if (Underlying->isBooleanType()) { |
10019 | S.Diag(Loc, diag::err_make_signed_integral_only) |
10020 | << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1 |
10021 | << Underlying; |
10022 | return QualType(); |
10023 | } |
10024 | } |
10025 | |
10026 | bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type(); |
10027 | std::array<CanQualType *, 6> AllSignedIntegers = { |
10028 | &S.Context.SignedCharTy, &S.Context.ShortTy, &S.Context.IntTy, |
10029 | &S.Context.LongTy, &S.Context.LongLongTy, &S.Context.Int128Ty}; |
10030 | ArrayRef<CanQualType *> AvailableSignedIntegers( |
10031 | AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported); |
10032 | std::array<CanQualType *, 6> AllUnsignedIntegers = { |
10033 | &S.Context.UnsignedCharTy, &S.Context.UnsignedShortTy, |
10034 | &S.Context.UnsignedIntTy, &S.Context.UnsignedLongTy, |
10035 | &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty}; |
10036 | ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(), |
10037 | AllUnsignedIntegers.size() - |
10038 | Int128Unsupported); |
10039 | ArrayRef<CanQualType *> *Consider = |
10040 | IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers; |
10041 | |
10042 | uint64_t BaseSize = S.Context.getTypeSize(T: BaseType); |
10043 | auto *Result = |
10044 | llvm::find_if(Range&: *Consider, P: [&S, BaseSize](const CanQual<Type> *T) { |
10045 | return BaseSize == S.Context.getTypeSize(T: T->getTypePtr()); |
10046 | }); |
10047 | |
10048 | assert(Result != Consider->end()); |
10049 | return QualType((*Result)->getTypePtr(), 0); |
10050 | } |
10051 | |
10052 | QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, |
10053 | SourceLocation Loc) { |
10054 | bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned; |
10055 | if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) || |
10056 | BaseType->isBooleanType() || |
10057 | (BaseType->isBitIntType() && |
10058 | BaseType->getAs<BitIntType>()->getNumBits() < 2)) { |
10059 | Diag(Loc, diag::err_make_signed_integral_only) |
10060 | << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0; |
10061 | return QualType(); |
10062 | } |
10063 | |
10064 | bool IsNonIntIntegral = |
10065 | BaseType->isChar16Type() || BaseType->isChar32Type() || |
10066 | BaseType->isWideCharType() || BaseType->isEnumeralType(); |
10067 | |
10068 | QualType Underlying = |
10069 | IsNonIntIntegral |
10070 | ? ChangeIntegralSignedness(S&: *this, BaseType, IsMakeSigned, Loc) |
10071 | : IsMakeSigned ? Context.getCorrespondingSignedType(T: BaseType) |
10072 | : Context.getCorrespondingUnsignedType(T: BaseType); |
10073 | if (Underlying.isNull()) |
10074 | return Underlying; |
10075 | return Context.getQualifiedType(T: Underlying, Qs: BaseType.getQualifiers()); |
10076 | } |
10077 | |
10078 | QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind, |
10079 | SourceLocation Loc) { |
10080 | if (BaseType->isDependentType()) |
10081 | return Context.getUnaryTransformType(BaseType, UnderlyingType: BaseType, UKind); |
10082 | QualType Result; |
10083 | switch (UKind) { |
10084 | case UnaryTransformType::EnumUnderlyingType: { |
10085 | Result = BuiltinEnumUnderlyingType(BaseType, Loc); |
10086 | break; |
10087 | } |
10088 | case UnaryTransformType::AddPointer: { |
10089 | Result = BuiltinAddPointer(BaseType, Loc); |
10090 | break; |
10091 | } |
10092 | case UnaryTransformType::RemovePointer: { |
10093 | Result = BuiltinRemovePointer(BaseType, Loc); |
10094 | break; |
10095 | } |
10096 | case UnaryTransformType::Decay: { |
10097 | Result = BuiltinDecay(BaseType, Loc); |
10098 | break; |
10099 | } |
10100 | case UnaryTransformType::AddLvalueReference: |
10101 | case UnaryTransformType::AddRvalueReference: { |
10102 | Result = BuiltinAddReference(BaseType, UKind, Loc); |
10103 | break; |
10104 | } |
10105 | case UnaryTransformType::RemoveAllExtents: |
10106 | case UnaryTransformType::RemoveExtent: { |
10107 | Result = BuiltinRemoveExtent(BaseType, UKind, Loc); |
10108 | break; |
10109 | } |
10110 | case UnaryTransformType::RemoveCVRef: |
10111 | case UnaryTransformType::RemoveReference: { |
10112 | Result = BuiltinRemoveReference(BaseType, UKind, Loc); |
10113 | break; |
10114 | } |
10115 | case UnaryTransformType::RemoveConst: |
10116 | case UnaryTransformType::RemoveCV: |
10117 | case UnaryTransformType::RemoveRestrict: |
10118 | case UnaryTransformType::RemoveVolatile: { |
10119 | Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc); |
10120 | break; |
10121 | } |
10122 | case UnaryTransformType::MakeSigned: |
10123 | case UnaryTransformType::MakeUnsigned: { |
10124 | Result = BuiltinChangeSignedness(BaseType, UKind, Loc); |
10125 | break; |
10126 | } |
10127 | } |
10128 | |
10129 | return !Result.isNull() |
10130 | ? Context.getUnaryTransformType(BaseType, UnderlyingType: Result, UKind) |
10131 | : Result; |
10132 | } |
10133 | |
10134 | QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) { |
10135 | if (!isDependentOrGNUAutoType(T)) { |
10136 | // FIXME: It isn't entirely clear whether incomplete atomic types |
10137 | // are allowed or not; for simplicity, ban them for the moment. |
10138 | if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0)) |
10139 | return QualType(); |
10140 | |
10141 | int DisallowedKind = -1; |
10142 | if (T->isArrayType()) |
10143 | DisallowedKind = 1; |
10144 | else if (T->isFunctionType()) |
10145 | DisallowedKind = 2; |
10146 | else if (T->isReferenceType()) |
10147 | DisallowedKind = 3; |
10148 | else if (T->isAtomicType()) |
10149 | DisallowedKind = 4; |
10150 | else if (T.hasQualifiers()) |
10151 | DisallowedKind = 5; |
10152 | else if (T->isSizelessType()) |
10153 | DisallowedKind = 6; |
10154 | else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus) |
10155 | // Some other non-trivially-copyable type (probably a C++ class) |
10156 | DisallowedKind = 7; |
10157 | else if (T->isBitIntType()) |
10158 | DisallowedKind = 8; |
10159 | else if (getLangOpts().C23 && T->isUndeducedAutoType()) |
10160 | // _Atomic auto is prohibited in C23 |
10161 | DisallowedKind = 9; |
10162 | |
10163 | if (DisallowedKind != -1) { |
10164 | Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T; |
10165 | return QualType(); |
10166 | } |
10167 | |
10168 | // FIXME: Do we need any handling for ARC here? |
10169 | } |
10170 | |
10171 | // Build the pointer type. |
10172 | return Context.getAtomicType(T); |
10173 | } |
10174 | |